Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use %q to quote struct tag values #83

Merged
merged 1 commit into from Nov 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 14 additions & 2 deletions jen/examples_test.go
@@ -1,9 +1,8 @@
package jen_test

import (
"fmt"

"bytes"
"fmt"

. "github.com/dave/jennifer/jen"
)
Expand Down Expand Up @@ -1295,6 +1294,19 @@ func ExampleTag() {
// }
}

func ExampleTag_withQuotesAndNewline() {
c := Type().Id("foo").Struct(
Id("A").String().Tag(map[string]string{"json": "a"}),
Id("B").Int().Tag(map[string]string{"json": "b", "bar": "the value of\nthe\"bar\" tag"}),
)
fmt.Printf("%#v", c)
// Output:
// type foo struct {
// A string `json:"a"`
// B int `bar:"the value of\nthe \"bar\" tag" json:"b"`
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, we would get B int "bar:\"the value of\nthe\"bar\" tag\" json:\"b\""

Notice that the quotes around bar are escaped at the same level as the quotes for the tag value, meaning the reflect.StructTag.Get parser will recognize the first quote after opening as the end of the value.

// }
}

func ExampleNull_and_nil() {
c := Func().Id("foo").Params(
nil,
Expand Down
2 changes: 1 addition & 1 deletion jen/tag.go
Expand Up @@ -59,7 +59,7 @@ func (t tag) render(f *File, w io.Writer, s *Statement) error {
if len(str) > 0 {
str += " "
}
str += fmt.Sprintf(`%s:"%s"`, k, v)
str += fmt.Sprintf(`%s:%q`, k, v)
}

if strconv.CanBackquote(str) {
Expand Down