dtolnay / serde-yaml

Strongly typed YAML library for Rust
Apache License 2.0
960 stars 157 forks source link

Quote YAML 1.1 bools during serialization #412

Open NiklasRosenstein opened 7 months ago

NiklasRosenstein commented 7 months ago

Closes #319

This PR handles pre-YAML 1.2 bool keywords (on, off, yes, no, etc.) during serialization to add single quotes which adds backwards compatibility when the serialized YAML is later loaded by a YAML parser for an older spec.

1.1 Reference: https://yaml.org/type/bool.html

Notable changes

Previous content This PR modifies `crate::de::parse_bool()` to treat `on/ON/yes/YES/off/OFF/no/NO` as bool as per the YAML 1.1 spec. The same change also causes string values with these values to be quoted, which fixes #319. I couldn't find whether `serde-yaml` aims to be compatible with a particular YAML spec version; the fact that it did not support on/off/etc. before suggest that it may be targeting YAML 1.2(.2?). Serializing these words with quotes is backwards compatible, however if we start to deserialize them as bool this may be breaking to consumers of `serde-yaml`. I would suggest to consider either 1. We introduce some kind of `YamlVersion` enum and default to `YamlVersion::V1_2`, which foregoes matching the on/off/etc. words 2. We pass a flag to `parse_bool()` during serialization so that we serialize treating these words as bool but don't during deserialization
NiklasRosenstein commented 7 months ago

Now I find the test_tag_resolution() test, which makes it pretty clear the crate is targeting YAML 1.2.2. I would still like to go forward with this PR, and at least ensure that the serialized result is backwards compatible with old YAML specs.

NiklasRosenstein commented 7 months ago

Ok, so now I just add a special case for handling the pre-YAML 1.2.2 keywords in the serializer. This avoids a breaking change on the deserializer while adding backwards compatibility to the serialized output.

uschi2000 commented 7 months ago

@NiklasRosenstein I suspect you'll have to find a way (cargo feature?) to make the behavior change opt-in. (Assuming here that @dtolnay isn't super keen on rolling out a change that will potentially break a lot of ossified/broken YAML users...) David?

uschi2000 commented 7 months ago

Also, what does this change mean for serde roundtrips? (ie, de(ser(yaml)) ?= yaml) (I'm not sure if there are any roundtrip guarantees at the moment.)