File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed
Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change @@ -123,3 +123,45 @@ func Indent(prepend, str string) string {
123123 }
124124 return b .String ()
125125}
126+
127+ // UnwrapText reformats wrapped lines by replacing single newlines with spaces,
128+ // while preserving blank-line paragraph breaks. This allows defining long
129+ // strings in a readable fashion.
130+ //
131+ // More specifically:
132+ // - the input string is broken up into lines;
133+ // - each line is trimmed of leading and trailing whitespace;
134+ // - leading or trailing empty lines are discarded;
135+ // - each run of non-empty lines is joined into a single line, with a space
136+ // separator;
137+ // - resulting single lines are joined with a blank line in-between.
138+ //
139+ // For example:
140+ // UnwrapText(`
141+ //
142+ // This is a paragraph that
143+ // is wrapped on multiple lines.
144+ //
145+ // This is another paragraph.
146+ //
147+ // `)
148+ // returns
149+ // "This is a paragraph that is wrapped on multiple lines.\n\nThis is another paragraph."
150+ func UnwrapText (input string ) string {
151+ var buf strings.Builder
152+
153+ var separator string
154+ for _ , l := range strings .Split (input , "\n " ) {
155+ l = strings .TrimSpace (l )
156+ if l == "" {
157+ separator = "\n \n "
158+ } else {
159+ if buf .Len () > 0 {
160+ buf .WriteString (separator )
161+ }
162+ buf .WriteString (l )
163+ separator = " "
164+ }
165+ }
166+ return buf .String ()
167+ }
Original file line number Diff line number Diff line change @@ -91,3 +91,37 @@ func TestIndent(t *testing.T) {
9191 require .Equal (t , tc [1 ], Indent ("--" , tc [0 ]))
9292 }
9393}
94+
95+ func TestUnwrapText (t * testing.T ) {
96+ expected := "This is a single line string. It looks fine."
97+
98+ require .Equal (t , expected , UnwrapText (`This
99+ is a single line string.
100+ It looks fine.` ))
101+
102+ require .Equal (t , expected , UnwrapText (`
103+
104+
105+ This
106+ is a single line string.
107+ It looks
108+ fine.
109+
110+ ` ))
111+
112+ expected = "This is a paragraph that is wrapped on multiple lines.\n \n This is another paragraph."
113+ require .Equal (t , expected , UnwrapText (`This is a paragraph that
114+ is wrapped on multiple lines.
115+
116+ This is another
117+ paragraph.` ))
118+
119+ require .Equal (t , expected , UnwrapText (`
120+
121+ This is a paragraph that
122+ is wrapped on multiple lines.
123+
124+ This is another paragraph.
125+
126+ ` ))
127+ }
You can’t perform that action at this time.
0 commit comments