B
B
Boris192018-04-05 20:26:40
Python
Boris19, 2018-04-05 20:26:40

How to move aliases to another file?

Yaml has alias support.
For example:

references:
    value1: &reference "Don't repeat yourself!"  
    value2: *reference

Those. You can refer to an element. But here's the problem, I want to put these aliases in a separate file so that for several yaml files at once, you can specify all aliases by default.
I didn’t find ready-made solutions, I tried to make my crutch with loading a file by adding a constructor (Loader.add_constructor), but it seems that the links are replaced earlier, because the execution did not reach the constructor and dropped out with the error found undefined alias
Maybe someone has come across this and found a solution, please help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-04-05
@Boris19

The YAML specification does not support any relationship between documents. Moreover, it explicitly postulates that each document is independent. But there are libraries that ignore this.

import sys
from ruamel.std.pathlib import Path
from ruamel.yaml import YAML, version_info

yaml = YAML(typ='safe', pure=True)
yaml.default_flow_style = False

def my_compose_document(self):
    self.parser.get_event()
    node = self.compose_node(None, None)
    self.parser.get_event()
    return node

yaml.Composer.compose_document = my_compose_document

def yaml_include(loader, node):
    y = loader.loader
    yaml = YAML(typ=y.typ, pure=y.pure)
    yaml.composer.anchors = loader.composer.anchors
    return yaml.load(Path(node.value))

yaml.Constructor.add_constructor("!include", yaml_include)

data = yaml.load(Path('warehouse.yaml'))
yaml.dump(data, sys.stdout)

specific:
  spec1:
    <<: *obj1
  spec2:
    <<: *obj1
    key1: 10

warehouse:
  obj1: &obj1
    key1: 1
    key2: 2
specific: !include specific.yaml

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question