Skip to content

Commit

Permalink
Remove use of sprintf in formatter
Browse files Browse the repository at this point in the history
Do not format strings before writing them to output. String formatting
was only being used for concatenation and caused problems for Rego
strings that contain printf verbs.
  • Loading branch information
tsandall committed Sep 14, 2017
1 parent 80dfee8 commit 7779915
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
19 changes: 9 additions & 10 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,12 @@ func (w *writer) writeFunctionCall(t []*ast.Term, comments []*ast.Comment) []*as
fallthrough
case 2:
comments = w.writeTerm(t[1], comments)
w.write(" %s ", string(bi.Infix))
w.write(" " + string(bi.Infix) + " ")
return w.writeTerm(t[2], comments)
}
}

w.write("%s(", string(t[0].Value.(ast.String)))
w.write(string(t[0].Value.(ast.String)) + "(")
for _, v := range t[1 : len(t)-1] {
comments = w.writeTerm(v, comments)
w.write(", ")
Expand Down Expand Up @@ -425,7 +425,7 @@ func (w *writer) writeTerm(term *ast.Term, comments []*ast.Comment) []*ast.Comme
case ast.String:
if term.Location.Text[0] == '.' {
// This string was parsed from a ref, so preserve the value.
w.write(`"%s"`, string(x))
w.write(`"` + string(x) + `"`)
} else {
// To preserve raw strings, we need to output the original text,
// not what x.String() would give us.
Expand Down Expand Up @@ -901,18 +901,17 @@ func (w *writer) blankLine() {
w.write("\n")
}

// write formats the input string and writes it to the buffer.
func (w *writer) write(s string, a ...interface{}) {
w.buf.WriteString(fmt.Sprintf(s, a...))
// write the input string and writes it to the buffer.
func (w *writer) write(s string) {
w.buf.WriteString(s)
}

// writeLine writes the formatted string on a newly started line, then terminates
// the line.
func (w *writer) writeLine(s string, a ...interface{}) {
// writeLine writes the string on a newly started line, then terminate the line.
func (w *writer) writeLine(s string) {
if !w.inline {
w.startLine()
}
w.write(s, a...)
w.write(s)
w.endLine()
}

Expand Down
2 changes: 1 addition & 1 deletion format/testfiles/test.rego
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ fn(x) = y {
}

long(x) = true {
x = "foo"
x = "foo %host"
}

short(x) {
Expand Down
2 changes: 1 addition & 1 deletion format/testfiles/test.rego.formatted
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn(x) = y {
}

long(x) {
x = "foo"
x = "foo %host"
}

short(x) {
Expand Down

0 comments on commit 7779915

Please sign in to comment.