From 15b278907eb545b7ddd9cf60214202ed1f6dd950 Mon Sep 17 00:00:00 2001 From: Anatoli Babenia Date: Tue, 4 Oct 2022 13:13:52 +0300 Subject: [PATCH] Refactor `wrap()` and add test for empty line --- help.go | 23 ++++++++++------------- help_test.go | 7 +++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/help.go b/help.go index 5db6696..6929a22 100644 --- a/help.go +++ b/help.go @@ -468,7 +468,7 @@ 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") @@ -476,23 +476,20 @@ func wrap(input string, offset int, wrapAt int) string { 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 { diff --git a/help_test.go b/help_test.go index 9c99b98..d7cdfa2 100644 --- a/help_test.go +++ b/help_test.go @@ -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.