diff --git a/command/help.go b/command/help.go index 9e013e711..04121785f 100644 --- a/command/help.go +++ b/command/help.go @@ -164,28 +164,26 @@ func rpad(s string, padding int) string { func dedent(s string) string { lines := strings.Split(s, "\n") - - n := int(^uint(0) >> 1) + minIndent := -1 for _, l := range lines { if len(l) == 0 { continue } - if c := countLeadingSpaces(l); c < n { - n = c + indent := len(l) - len(strings.TrimLeft(l, " ")) + if minIndent == -1 || indent < minIndent { + minIndent = indent } } - var buf bytes.Buffer - - for _, l := range lines { - fmt.Fprintln(&buf, strings.TrimPrefix(l, strings.Repeat(" ", n))) + if minIndent <= 0 { + return s } + var buf bytes.Buffer + for _, l := range lines { + fmt.Fprintln(&buf, strings.TrimPrefix(l, strings.Repeat(" ", minIndent))) + } return strings.TrimSuffix(buf.String(), "\n") } - -func countLeadingSpaces(s string) int { - return len(s) - len(strings.TrimLeft(s, " ")) -} diff --git a/command/help_test.go b/command/help_test.go index 8010ceb59..64c412ab2 100644 --- a/command/help_test.go +++ b/command/help_test.go @@ -27,9 +27,20 @@ func TestDedent(t *testing.T) { input: " line 1\n line 2\n line 3\n\n", expected: "line 1\nline 2\nline 3\n\n", }, + { + input: "\n\n\n\n\n\n", + expected: "\n\n\n\n\n\n", + }, + { + input: "", + expected: "", + }, } - for _, kase := range cases { - eq(t, dedent(kase.input), kase.expected) + for _, tt := range cases { + got := dedent(tt.input) + if got != tt.expected { + t.Errorf("expected: %q, got: %q", tt.expected, got) + } } }