Added yaml constructor that get the realpath of a file
This commit is contained in:
20
tools/render
20
tools/render
@@ -83,9 +83,23 @@ def template_constructor(environment: Environment):
|
||||
return inner
|
||||
|
||||
|
||||
def get_loader():
|
||||
def realpath_constructor(directory: pathlib.Path):
|
||||
def inner(loader: yaml.SafeLoader, node: yaml.nodes.ScalarNode):
|
||||
try:
|
||||
realpath = directory.joinpath(loader.construct_scalar(node)).resolve(
|
||||
strict=True
|
||||
)
|
||||
return str(realpath)
|
||||
except Exception:
|
||||
raise yaml.MarkedYAMLError("Failed to get real path", node.start_mark)
|
||||
|
||||
return inner
|
||||
|
||||
|
||||
def get_loader(directory: pathlib.Path):
|
||||
"""Add special constructors to yaml loader"""
|
||||
loader = yaml.SafeLoader
|
||||
loader.add_constructor("!realpath", realpath_constructor(directory))
|
||||
loader.add_constructor("!schematic", schematic_constructor)
|
||||
loader.add_constructor("!patch", template_constructor(PATCHES))
|
||||
|
||||
@@ -97,7 +111,7 @@ def get_defaults(directory: pathlib.Path, root: pathlib.Path):
|
||||
"""Compute the defaults from the provided directory and parents."""
|
||||
try:
|
||||
with open(directory.joinpath("_defaults.yaml")) as fyaml:
|
||||
yml_data = yaml.load(fyaml, Loader=get_loader())
|
||||
yml_data = yaml.load(fyaml, Loader=get_loader(directory))
|
||||
except OSError:
|
||||
yml_data = {}
|
||||
|
||||
@@ -122,7 +136,7 @@ def main():
|
||||
filename = str(fullname.relative_to(NODES).parent) + "/" + fullname.stem
|
||||
|
||||
with open(fullname) as fyaml:
|
||||
yml_data = yaml.load(fyaml, Loader=get_loader())
|
||||
yml_data = yaml.load(fyaml, Loader=get_loader(fullname.parent))
|
||||
yml_data = get_defaults(fullname.parent, NODES) | yml_data
|
||||
yml_data["hostname"] = fullname.stem
|
||||
yml_data["filename"] = filename
|
||||
|
||||
Reference in New Issue
Block a user