Skip to content

Commit 13e918a

Browse files
authored
Make UseSingleQuote compliant with the YAML spec (#647)
* Make UseSingleQuote compliant with the YAML spec * Make it self-explanatory
1 parent 3992548 commit 13e918a

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

encode_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ func TestEncoder(t *testing.T) {
704704
},
705705
// Quote style
706706
{
707-
`v: '\'a\'b'` + "\n",
707+
`v: '''a''b'` + "\n",
708708
map[string]string{"v": `'a'b`},
709709
[]yaml.EncodeOption{
710710
yaml.UseSingleQuote(true),
@@ -717,6 +717,13 @@ func TestEncoder(t *testing.T) {
717717
yaml.UseSingleQuote(false),
718718
},
719719
},
720+
{
721+
`a: '\.yaml'` + "\n",
722+
map[string]string{"a": `\.yaml`},
723+
[]yaml.EncodeOption{
724+
yaml.UseSingleQuote(true),
725+
},
726+
},
720727
}
721728
for _, test := range tests {
722729
t.Run(test.source, func(t *testing.T) {

stdlib_quote.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,18 @@ func appendQuotedWith(buf []byte, s string, quote byte) []byte {
5353

5454
func appendEscapedRune(buf []byte, r rune, quote byte) []byte {
5555
var runeTmp [utf8.UTFMax]byte
56-
if r == rune(quote) || r == '\\' { // always backslashed
57-
buf = append(buf, '\\')
56+
// goccy/go-yaml patch on top of the standard library's appendEscapedRune function.
57+
//
58+
// We use this to implement the YAML single-quoted string, where the only escape sequence is '', which represents a single quote.
59+
// The below snippet from the standard library is for escaping e.g. \ with \\, which is not what we want for the single-quoted string.
60+
//
61+
// if r == rune(quote) || r == '\\' { // always backslashed
62+
// buf = append(buf, '\\')
63+
// buf = append(buf, byte(r))
64+
// return buf
65+
// }
66+
if r == rune(quote) {
67+
buf = append(buf, byte(r))
5868
buf = append(buf, byte(r))
5969
return buf
6070
}

0 commit comments

Comments
 (0)