55package v1beta1_test
66
77import (
8- "bufio"
98 "fmt"
109 "regexp"
1110 "strings"
@@ -32,11 +31,14 @@ var leadingTabs = regexp.MustCompile(`^\t+`)
3231// dedentLines finds the shortest leading whitespace of every line in data and then removes it from every line.
3332// When tabWidth is positive, leading tabs are converted to spaces first.
3433func dedentLines (data string , tabWidth int ) string {
34+ if len (data ) < 1 {
35+ return ""
36+ }
37+
3538 var lines = make ([]string , 0 , 20 )
3639 var lowest , highest string
3740
38- for s := bufio .NewScanner (strings .NewReader (data )); s .Scan (); {
39- line := s .Text ()
41+ for line := range strings .Lines (data ) {
4042 tabs := leadingTabs .FindString (line )
4143
4244 // Replace any leading tabs with spaces when tabWidth is positive.
@@ -71,16 +73,12 @@ func dedentLines(data string, tabWidth int) string {
7173 if len (lines [i ]) > width {
7274 lines [i ] = lines [i ][width :]
7375 } else {
74- lines [i ] = ""
76+ lines [i ] = "\n "
7577 }
7678 }
7779 }
7880
79- result := strings .Join (lines , "\n " )
80- if len (lines ) > 0 {
81- result += "\n "
82- }
83- return result
81+ return strings .TrimSuffix (strings .Join (lines , "" ), "\n " ) + "\n "
8482}
8583
8684func TestDedentLines (t * testing.T ) {
@@ -127,6 +125,9 @@ func TestDedentLines(t *testing.T) {
127125 {input : " " , expected : "\n " },
128126 {input : "\t " , expected : "\n " },
129127 {input : "\t \t " , expected : "\n " },
128+
129+ // blank lines preserved
130+ {input : " ~\n \n ~\n " , expected : "~\n \n ~\n " },
130131 } {
131132 t .Run (fmt .Sprintf ("%v:%#v" , tc .width , tc .input ), func (t * testing.T ) {
132133 assert .DeepEqual (t , dedentLines (tc .input , tc .width ), tc .expected )
0 commit comments