Skip to content

Commit

Permalink
Add wrapLines function
Browse files Browse the repository at this point in the history
  • Loading branch information
Silvio Böhler committed Nov 21, 2024
1 parent 26c30f0 commit 48d7454
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/syntax/printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,28 @@ func (p *Printer) Format(f directives.File) error {
_, err := p.Write([]byte(text[pos:]))
return err
}

func wrapLines(width int, text string) []string {
fields := strings.Fields(text)
var res []string
var b strings.Builder

for len(fields) > 0 {
lineLength := utf8.RuneCountInString(fields[0])
b.WriteString(fields[0])
fields = fields[1:]
for len(fields) > 0 {
fieldLength := utf8.RuneCountInString(fields[0])
if lineLength+fieldLength+1 > width {
break
}
lineLength += 1 + utf8.RuneCountInString(fields[0])
b.WriteRune(' ')
b.WriteString(fields[0])
fields = fields[1:]
}
res = append(res, b.String())
b.Reset()
}
return res
}
44 changes: 44 additions & 0 deletions lib/syntax/printer/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,47 @@ func TestFormat(t *testing.T) {
func lines(ss ...string) string {
return strings.Join(ss, "\n") + "\n"
}

func TestWrapLines(t *testing.T) {
tests := []struct {
width int
input string
want []string
}{
{
width: 5,
input: "foo bar baz",
want: []string{"foo", "bar", "baz"},
},
{
width: 5,
input: "foo barbarbar baz",
want: []string{"foo", "barbarbar", "baz"},
},
{
width: 7,
input: "foo bar baz",
want: []string{"foo bar", "baz"},
},
{
width: 11,
input: "foo bar baz",
want: []string{"foo bar baz"},
},
{
width: 5,
input: " ",
},
}

for _, test := range tests {
t.Run(test.input, func(t *testing.T) {

got := wrapLines(test.width, test.input)

if diff := cmp.Diff(test.want, got); diff != "" {
t.Fatalf("wrapLines(%d, %s) returned unexpected diff (-want/+got)\n%s", test.width, test.input, diff)
}
})
}
}

0 comments on commit 48d7454

Please sign in to comment.