Skip to content

Commit

Permalink
Make UseSingleQuote compliant with the YAML spec (#647)
Browse files Browse the repository at this point in the history
* Make UseSingleQuote compliant with the YAML spec

* Make it self-explanatory
  • Loading branch information
mumoshu authored Feb 12, 2025
1 parent 3992548 commit 13e918a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
9 changes: 8 additions & 1 deletion encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ func TestEncoder(t *testing.T) {
},
// Quote style
{
`v: '\'a\'b'` + "\n",
`v: '''a''b'` + "\n",
map[string]string{"v": `'a'b`},
[]yaml.EncodeOption{
yaml.UseSingleQuote(true),
Expand All @@ -717,6 +717,13 @@ func TestEncoder(t *testing.T) {
yaml.UseSingleQuote(false),
},
},
{
`a: '\.yaml'` + "\n",
map[string]string{"a": `\.yaml`},
[]yaml.EncodeOption{
yaml.UseSingleQuote(true),
},
},
}
for _, test := range tests {
t.Run(test.source, func(t *testing.T) {
Expand Down
14 changes: 12 additions & 2 deletions stdlib_quote.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,18 @@ func appendQuotedWith(buf []byte, s string, quote byte) []byte {

func appendEscapedRune(buf []byte, r rune, quote byte) []byte {
var runeTmp [utf8.UTFMax]byte
if r == rune(quote) || r == '\\' { // always backslashed
buf = append(buf, '\\')
// goccy/go-yaml patch on top of the standard library's appendEscapedRune function.
//
// We use this to implement the YAML single-quoted string, where the only escape sequence is '', which represents a single quote.
// The below snippet from the standard library is for escaping e.g. \ with \\, which is not what we want for the single-quoted string.
//
// if r == rune(quote) || r == '\\' { // always backslashed
// buf = append(buf, '\\')
// buf = append(buf, byte(r))
// return buf
// }
if r == rune(quote) {
buf = append(buf, byte(r))
buf = append(buf, byte(r))
return buf
}
Expand Down

0 comments on commit 13e918a

Please sign in to comment.