Skip to content

Instantly share code, notes, and snippets.

@tgarc
Last active April 28, 2017 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgarc/fc9978b4227478441c87e83e78e1602d to your computer and use it in GitHub Desktop.
Save tgarc/fc9978b4227478441c87e83e78e1602d to your computer and use it in GitHub Desktop.
Load a yaml stream (src) and merge it with another yaml stream (dst) allowing *dst* to use aliases defined in *src*.
import sys
import yaml
def merge_load(src, dst, loadfunc=yaml.load, **kwargs):
'''\
Load a yaml stream (src) and merge it with another yaml stream
(dst) allowing *dst* to use aliases defined in *src*.
Other Parameters
----------------
**kwargs
Keyword arguments to pass to loadfunc
'''
# For convenience, allow dst to be None
if dst is None: return loadfunc(src, **kwargs)
srcanchors = { x.anchor: x for x in yaml.parse(src)
if getattr(x, 'anchor', None) is not None}
dstanchors = { x.value for x in yaml.scan(dst)
if isinstance(x, yaml.tokens.AnchorToken) }
dstevents = []
for event in yaml.parse(dst):
if not isinstance(event, yaml.events.AliasEvent) \
or event.anchor in dstanchors \
or event.anchor not in srcanchors:
dstevents.append(event)
continue
dstevents.append(srcanchors[event.anchor])
dstevents[-1].anchor = None
override = loadfunc(yaml.emit(dstevents), **kwargs)
dst = loadfunc(src, **kwargs)
if override:
dst.update(override)
return dst
print merge_load(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment