From 777991543190396d46532c5b511cd63d946a025a Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Thu, 14 Sep 2017 09:29:05 -0700 Subject: [PATCH] Remove use of sprintf in formatter 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. --- format/format.go | 19 +++++++++---------- format/testfiles/test.rego | 2 +- format/testfiles/test.rego.formatted | 2 +- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/format/format.go b/format/format.go index 16b206bd2e..f5d1785930 100644 --- a/format/format.go +++ b/format/format.go @@ -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(", ") @@ -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. @@ -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() } diff --git a/format/testfiles/test.rego b/format/testfiles/test.rego index 85941b50e9..d3ee1d3a93 100644 --- a/format/testfiles/test.rego +++ b/format/testfiles/test.rego @@ -53,7 +53,7 @@ fn(x) = y { } long(x) = true { - x = "foo" + x = "foo %host" } short(x) { diff --git a/format/testfiles/test.rego.formatted b/format/testfiles/test.rego.formatted index e2b6cdef22..850cdfd93f 100644 --- a/format/testfiles/test.rego.formatted +++ b/format/testfiles/test.rego.formatted @@ -58,7 +58,7 @@ fn(x) = y { } long(x) { - x = "foo" + x = "foo %host" } short(x) {