Ejemplo n.º 1
0
def construct_env_tag(loader: yaml.Loader, node: yaml.Node) -> Any:
    """Assign value of ENV variable referenced at node."""
    default = None
    if isinstance(node, yaml.nodes.ScalarNode):
        vars = [loader.construct_scalar(node)]
    elif isinstance(node, yaml.nodes.SequenceNode):
        child_nodes = node.value
        if len(child_nodes) > 1:
            # default is resolved using YAML's (implicit) types.
            default = loader.construct_object(child_nodes[-1])
            child_nodes = child_nodes[:-1]
        # Env Vars are resolved as string values, ignoring (implicit) types.
        vars = [loader.construct_scalar(child) for child in child_nodes]
    else:
        raise yaml.constructor.ConstructorError(
            None, None,
            f'expected a scalar or sequence node, but found {node.id}',
            node.start_mark)

    for var in vars:
        if var in os.environ:
            value = os.environ[var]
            # Resolve value to Python type using YAML's implicit resolvers
            tag = loader.resolve(yaml.nodes.ScalarNode, value, (True, False))
            return loader.construct_object(yaml.nodes.ScalarNode(tag, value))

    return default
Ejemplo n.º 2
0
 def no_duplicates_constructor(loader: yaml.Loader,
                               node: yaml.Node,
                               deep: bool = False) -> Any:
     mapping: Dict[str, Any] = {}
     for key_node, value_node in node.value:
         key = loader.construct_object(key_node, deep=deep)
         value = loader.construct_object(value_node, deep=deep)
         if key in mapping:
             raise yaml.constructor.ConstructorError(
                 "while constructing a mapping",
                 node.start_mark,
                 f"found duplicate key {key}",
                 key_node.start_mark,
             )
         mapping[key] = value
     return loader.construct_mapping(node, deep)