Skip to content

Commit c09df39

Browse files
beldenonsi
authored andcommittedDec 19, 2024
Properly encode CSV rows
Ensure CSV formatting properly encodes various edge-case values. We lean on `encoding/csv` from the go stdlib to do the work for us. In order to mix writing indentation with writing csv rows, we must csvWriter.Flush() after every csvWriter.Write(row).
1 parent 96a80fc commit c09df39

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed
 

‎ginkgo/outline/outline.go

+23-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package outline
22

33
import (
4+
"bytes"
5+
"encoding/csv"
46
"encoding/json"
57
"fmt"
68
"go/ast"
79
"go/token"
10+
"strconv"
811
"strings"
912

1013
"golang.org/x/tools/go/ast/inspector"
@@ -84,9 +87,11 @@ func (o *outline) String() string {
8487
// StringIndent returns a CSV-formated outline, but every line is indented by
8588
// one 'width' of spaces for every level of nesting.
8689
func (o *outline) StringIndent(width int) string {
87-
var b strings.Builder
90+
var b bytes.Buffer
8891
b.WriteString("Name,Text,Start,End,Spec,Focused,Pending,Labels\n")
8992

93+
csvWriter := csv.NewWriter(&b)
94+
9095
currentIndent := 0
9196
pre := func(n *ginkgoNode) {
9297
b.WriteString(fmt.Sprintf("%*s", currentIndent, ""))
@@ -96,8 +101,22 @@ func (o *outline) StringIndent(width int) string {
96101
} else {
97102
labels = strings.Join(n.Labels, ", ")
98103
}
99-
//enclosing labels in a double quoted comma separate listed so that when inmported into a CSV app the Labels column has comma separate strings
100-
b.WriteString(fmt.Sprintf("%s,%s,%d,%d,%t,%t,%t,\"%s\"\n", n.Name, n.Text, n.Start, n.End, n.Spec, n.Focused, n.Pending, labels))
104+
105+
row := []string{
106+
n.Name,
107+
n.Text,
108+
strconv.Itoa(n.Start),
109+
strconv.Itoa(n.End),
110+
strconv.FormatBool(n.Spec),
111+
strconv.FormatBool(n.Focused),
112+
strconv.FormatBool(n.Pending),
113+
labels,
114+
}
115+
csvWriter.Write(row)
116+
117+
// Ensure we write to `b' before the next `b.WriteString()', which might be adding indentation
118+
csvWriter.Flush()
119+
101120
currentIndent += width
102121
}
103122
post := func(n *ginkgoNode) {
@@ -106,5 +125,6 @@ func (o *outline) StringIndent(width int) string {
106125
for _, n := range o.Nodes {
107126
n.Walk(pre, post)
108127
}
128+
109129
return b.String()
110130
}

0 commit comments

Comments
 (0)
Please sign in to comment.