If you want to retain your source, you're best bet is to keep track of whether something changes and
not over write the source when not changes, as in your example.
ruamel.yaml
will always normalize output and if that is not what you want,
your only hope is to do exact string substitutions on the file, potentially
using the line information on the loaded data. I recommend against doing that,
and if you're retaining is for minizing diffs you should just byte the bullet
once, like what you would do when using some source formatter.
However if you work with YAML 1.1 only parsers although that version was
replaced more than 10 years ago, I can see that 12:00
instead of "12:00"
can
be a problem as those kind of strings are interpreted as sexagesimals.
In ruamel.yaml, you can either set the output to be YAML 1.1, and then 12:00
will be quoted, but you'll get a document header stating that it is conform to
the outdated version.
The other thing you can do is preserve any quotes using the .preserve_quotes
attribute:
import sys
import ruamel.yaml
yaml_str = """\
info_block:
enable: null
start: "12:00"
server_type: linux
"""
def my_represent_none(self, data):
return self.represent_scalar(u'tag:yaml.org,2002:null', u'null')
yaml = ruamel.yaml.YAML()
yaml.representer.add_representer(type(None), my_represent_none)
yaml.indent(mapping=2, sequence=2, offset=0)
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
which gives a complete retained version if combined with the alternative representer for the null node:
info_block:
enable: null
start: "12:00"
server_type: linux