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 @@ -117,3 +117,45 @@ func Indent(prepend, str string) string {
117117 }
118118 return b .String ()
119119}
120+
121+ // UnwrapText reformats wrapped lines by replacing single newlines with spaces,
122+ // while preserving blank-line paragraph breaks. This allows defining long
123+ // strings in a readable fashion.
124+ //
125+ // More specifically:
126+ // - the input string is broken up into lines;
127+ // - each line is trimmed of leading and trailing whitespace;
128+ // - leading or trailing empty lines are discarded;
129+ // - each run of non-empty lines is joined into a single line, with a space
130+ // separator;
131+ // - resulting single lines are joined with a blank line in-between.
132+ //
133+ // For example:
134+ // UnwrapText(`
135+ //
136+ // This is a paragraph that
137+ // is wrapped on multiple lines.
138+ //
139+ // This is another paragraph.
140+ //
141+ // `)
142+ // returns
143+ // "This is a paragraph that is wrapped on multiple lines.\n\nThis is another paragraph."
144+ func UnwrapText (input string ) string {
145+ var buf strings.Builder
146+
147+ var separator string
148+ for _ , l := range strings .Split (input , "\n " ) {
149+ l = strings .TrimSpace (l )
150+ if l == "" {
151+ separator = "\n \n "
152+ } else {
153+ if buf .Len () > 0 {
154+ buf .WriteString (separator )
155+ }
156+ buf .WriteString (l )
157+ separator = " "
158+ }
159+ }
160+ return buf .String ()
161+ }
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