How to automatically re-indent a YAML file? -
let's consider example:
--- foo: alice: female bob: male bar: - node: 42 name: none - node: 43 name: none
if decide reindent , start this:
--- foo: alice: female bob: male bar: - node: 42 name: none - node: 43 name: none
i don't have enough information it. vim's attempt this:
--- foo: alice: female bob: male bar: - node: 42 name: none - node: 43 name: none
ansible cannot make well:
--- foo: alice: female bob: male bar: - node: 42 name: none - node: 43 name: none
i think possible workaround add blank line when indentation increased:
--- foo: alice: female bob: male bar: - node: 42 name: none - node: 43 name: none
in opinion, main problem yaml people still fighting tabs, spaces , indent size. large yaml files edited several people, resulting file cannot parsed anymore. 2 solutions see are:
- use tabs , force tabs identation case makefiles
- the above solution
what seem want making sure yaml files uniformly indented (e.g. before being checked revision control system). idea of dedenting , re-indenting not work lose information if flatten structure. this:
foo: alice: female bob: male
consists of 2 mappings: mapping 1 key , value mapping of 2 keys 2 values.
this:
foo: alice: female bob: male
is 1 mapping 3 keys, , key foo
has value null scalar (also writable, apart empty string, ~
, null
, null
in yaml files).
most yaml parsers lose information when reading in file internal data: - comments dropped - key ordering not preserved mappings - spaces around scalars not preserved
the ruamel.yaml python package (of author) enhancemed parser allows round-tripping yaml file data , yaml preserve more of original information. preserve comments , key ordering, drops e.g. spacing around single line scalars.
this round-tripping stabilizes on second round-trip , can used reindent yaml file. yaml
utility included in package can used without need program things yourself:
yaml round-trip your_file.yml --verbose
(round-trip
can shortened rt
) check whether , how file change. shows unified diff if change. based on can decide save file if stabilizes:
yaml round-trip your_file.yml --save
the output example.yml
:
--- foo: alice: female # verified bob: male bar: - node: 42 name: none - node: 43 name: none
would be:
example.yml: stabilzes on second round trip, ok without comments --- example.yml +++ round trip yaml @@ -1,9 +1,9 @@ --- foo: alice: female # verified - bob: male + bob: male bar: -- node: 42 +- node: 42 name: none -- node: 43 - name: none +- node: 43 + name: none
and when saved like:
--- foo: alice: female # verified bob: male bar: - node: 42 name: none - node: 43 name: none
the indentation level default 2, can set option yaml
.
Comments
Post a Comment