Skip to content

Commit

Permalink
Marshal YAML 1.1 bool-like to strings (#583)
Browse files Browse the repository at this point in the history
We adhere to the YAML 1.2 for input, but only parsing "on", "off", and
friends, as strings rather than bools. When outputting however we will
ensure that we quote these cases. Failure to do so forces makes the
output ambiguous if it then to be parsed by a YAML 1.2 parser.
  • Loading branch information
tcolgate authored Mar 13, 2020
1 parent a6ecf24 commit 9f266ea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
17 changes: 16 additions & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,21 @@ func isBase60Float(s string) (result bool) {
// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)

// isOldBool returns whether s is bool notation as defined in YAML 1.1.
//
// We continue to force strings that YAML 1.1 would interpret as booleans to be
// rendered as quotes strings so that the marshalled output valid for YAML 1.1
// parsing.
func isOldBool(s string) (result bool) {
switch s {
case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON",
"n", "N", "no", "No", "NO", "off", "Off", "OFF":
return true
default:
return false
}
}

func (e *encoder) stringv(tag string, in reflect.Value) {
var style yaml_scalar_style_t
s := in.String()
Expand All @@ -319,7 +334,7 @@ func (e *encoder) stringv(tag string, in reflect.Value) {
// tag when encoded unquoted. If it doesn't,
// there's no need to quote it.
rtag, _ := resolve("", s)
canUsePlain = rtag == strTag && !isBase60Float(s)
canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s))
}
// Note: it's possible for user code to emit invalid YAML
// if they explicitly specify a tag and a string containing
Expand Down
6 changes: 6 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,12 @@ var marshalTests = []struct {
}, {
&struct{ A bool }{true},
"a: true\n",
}, {
&struct{ A string }{"true"},
"a: \"true\"\n",
}, {
&struct{ A string }{"off"},
"a: \"off\"\n",
},

// Conditional flag
Expand Down

0 comments on commit 9f266ea

Please sign in to comment.