Skip to content

Commit d205a3f

Browse files
authored
Merge pull request #15 from RaduBerinde/crstrings-indent
crstrings: add Indent
2 parents b7c9be9 + 13b6fa2 commit d205a3f

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

crstrings/utils.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,23 @@ func Lines(s string) []string {
9797
}
9898
return strings.Split(s, "\n")
9999
}
100+
101+
// Indent prepends a string to every line of the given string.
102+
//
103+
// If the string ends in a newline, the resulting string also ends in a newline.
104+
func Indent(prepend, str string) string {
105+
lines := strings.Split(str, "\n")
106+
var b strings.Builder
107+
b.Grow(len(str) + len(lines)*len(prepend))
108+
for i, l := range lines {
109+
if i > 0 {
110+
b.WriteString("\n")
111+
}
112+
// Make sure we don't add an extra prepend after a trailing newline.
113+
if i < len(lines)-1 || l != "" {
114+
b.WriteString(prepend)
115+
b.WriteString(l)
116+
}
117+
}
118+
return b.String()
119+
}

crstrings/utils_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,18 @@ func TestLines(t *testing.T) {
7676
require.Equal(t, `[]`, fmt.Sprintf("%q", Lines("")))
7777
require.Equal(t, `[]`, fmt.Sprintf("%q", Lines("\n")))
7878
}
79+
80+
func TestIndent(t *testing.T) {
81+
testCases := [][2]string{
82+
{"", ""},
83+
{"foo", "--foo"},
84+
{"foo\n", "--foo\n"},
85+
{"foo\n\n", "--foo\n--\n"},
86+
{"foo\nbar", "--foo\n--bar"},
87+
{"foo\nbar\n", "--foo\n--bar\n"},
88+
{"foo\n\nbar\n", "--foo\n--\n--bar\n"},
89+
}
90+
for _, tc := range testCases {
91+
require.Equal(t, tc[1], Indent("--", tc[0]))
92+
}
93+
}

0 commit comments

Comments
 (0)