I've been digging through documentation for the past two days and struggling to find any recent example of how to handle the ignore_aliases() call.
The config object is a python dict containing the list of dicts. The output below is generated if I disable the ignore_aliases() call.
if __name__ == '__main__':
team = TeamConfig("../TeamConfig.yml")
config = team.generateSonarConfig()
with open("../Test.yml", 'w') as f:
yml = YAML()
yml.indent(mapping=2, sequence=4, offset=2)
yml.Representer.ignore_aliases(yml, config)
yml.dump(config, f)
The indentation is great, and the order is preserved, I just need to remove the anchors and aliases:
templates:
- name: freedom
users:
- &id001
name: service-account2
permissions:
- browse
- read
- name: liberty
users:
- *id001
- *id002
- name: service-account3
permissions:
- browse
- read
- name: service-account4
permissions:
- browse
- read
any ideas?
First of all, I don't think the output you present is complete, as it is invalid
YAML and I certainly hope ruamel.yaml did not generate that as shown (if it
did file a bug report with the complete source).
I don't know where you got that example from but the method ignore_aliases()
is called with a data structure and should return True if any aliases should be
ignored. It is not something you call yourself. You can subclass the Representer or monkey-patch that on the RoundTripRepresenter.
The method in representer.py should take a data parameter and always return False:
import sys
from pathlib import Path
import ruamel.yaml
# your output minus the `- *id002` alias that has no corresponding anchor
in_file = Path('Test.yaml')
# monkey patch:
ruamel.yaml.representer.RoundTripRepresenter.ignore_aliases = lambda x, y: True
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(in_file)
yaml.dump(data, sys.stdout)
which gives:
templates:
- name: freedom
users:
- name: service-account2
permissions:
- browse
- read
- name: liberty
users:
- name: service-account2
permissions:
- browse
- read
- name: service-account3
permissions:
- browse
- read
- name: service-account4
permissions:
- browse
- read
Alternatively you can do the somewhat more verbose:
import sys
from pathlib import Path
import ruamel.yaml
# your output minus the `- *id002` alias that has no corresponding anchor
in_file = Path('Test.yaml')
class NonAliasingRTRepresenter(ruamel.yaml.representer.RoundTripRepresenter):
def ignore_aliases(self, data):
return True
yaml = ruamel.yaml.YAML()
yaml.Representer = NonAliasingRTRepresenter
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(in_file)
yaml.dump(data, sys.stdout)
which gives the same output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With