Skip to content

Commit

Permalink
Refactor wrap() and add test for empty line
Browse files Browse the repository at this point in the history
  • Loading branch information
abitrolly committed Oct 4, 2022
1 parent 359e5a8 commit 15b2789
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
23 changes: 10 additions & 13 deletions help.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,31 +468,28 @@ func nindent(spaces int, v string) string {
}

func wrap(input string, offset int, wrapAt int) string {
var sb strings.Builder
var ss []string

lines := strings.Split(input, "\n")

padding := strings.Repeat(" ", offset)

for i, line := range lines {
if line == "" {
sb.WriteString("\n")
continue
}

// the first line is not indented
if i != 0 {
sb.WriteString(padding)
}
ss = append(ss, line)
} else {
wrapped := wrapLine(line, offset, wrapAt, padding)
if i == 0 {
ss = append(ss, wrapped)
} else {
ss = append(ss, padding+wrapped)

sb.WriteString(wrapLine(line, offset, wrapAt, padding))
}

if i != len(lines)-1 {
sb.WriteString("\n")
}
}

return sb.String()
return strings.Join(ss, "\n")
}

func wrapLine(input string, offset int, wrapAt int, padding string) string {
Expand Down
7 changes: 7 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,13 @@ func TestDefaultCompleteWithFlags(t *testing.T) {
}
}

func TestWrap(t *testing.T) {
emptywrap := wrap("", 4, 16)
if emptywrap != "" {
t.Errorf("Wrapping empty line should return empty line. Got '%s'.", emptywrap)
}
}

func TestWrappedHelp(t *testing.T) {

// Reset HelpPrinter after this test.
Expand Down

0 comments on commit 15b2789

Please sign in to comment.