Fix crash in dedent when blank lines are passed

This commit is contained in:
Mislav Marohnić 2020-07-16 16:09:47 +02:00
parent 3db8bc654a
commit 4e15982046
2 changed files with 23 additions and 14 deletions

View file

@ -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, " "))
}

View file

@ -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)
}
}
}