File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff 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+ }
Original file line number Diff line number Diff 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\n bar" , "--foo\n --bar" },
87+ {"foo\n bar\n " , "--foo\n --bar\n " },
88+ {"foo\n \n bar\n " , "--foo\n --\n --bar\n " },
89+ }
90+ for _ , tc := range testCases {
91+ require .Equal (t , tc [1 ], Indent ("--" , tc [0 ]))
92+ }
93+ }
You can’t perform that action at this time.
0 commit comments