|
| 1 | +""" |
| 2 | +========= |
| 3 | +Utilities |
| 4 | +========= |
| 5 | +
|
| 6 | +This module contains utility functions and classes for the layered_config_tree |
| 7 | +package. |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +from collections.abc import Hashable |
| 12 | +from pathlib import Path |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +import yaml |
| 16 | + |
| 17 | +from layered_config_tree import DuplicatedConfigurationError |
| 18 | + |
| 19 | + |
| 20 | +def load_yaml(data: str | Path) -> dict[str, Any]: |
| 21 | + """Loads a YAML filepath or string into a dictionary. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + data |
| 26 | + The YAML content to load. This can be a file path to a YAML file or a string |
| 27 | + containing YAML-formatted text. |
| 28 | +
|
| 29 | + Raises |
| 30 | + ------ |
| 31 | + ValueError |
| 32 | + If the loaded YAML content is not a dictionary. |
| 33 | +
|
| 34 | + Returns |
| 35 | + ------- |
| 36 | + A dictionary representation of the loaded YAML content. |
| 37 | +
|
| 38 | + Notes |
| 39 | + ----- |
| 40 | + If `data` is a Path object or a string that ends with ".yaml" or ".yml", it is |
| 41 | + treated as a filepath and this function loads the file. Otherwise, `data` is a |
| 42 | + string that does _not_ end in ".yaml" or ".yml" and it is treated as YAML-formatted |
| 43 | + text which is loaded directly into a dictionary. |
| 44 | + """ |
| 45 | + |
| 46 | + if (isinstance(data, str) and data.endswith((".yaml", ".yml"))) or isinstance(data, Path): |
| 47 | + # 'data' is a filepath to a yaml file (rather than a yaml string) |
| 48 | + with open(data) as f: |
| 49 | + data = f.read() |
| 50 | + data_dict: dict[str, Any] = yaml.load(data, Loader=SafeLoader) |
| 51 | + |
| 52 | + if not isinstance(data_dict, dict): |
| 53 | + raise ValueError( |
| 54 | + f"Loaded yaml file {data_dict} should be a dictionary but is type {type(data_dict)}" |
| 55 | + ) |
| 56 | + |
| 57 | + return data_dict |
| 58 | + |
| 59 | + |
| 60 | +class SafeLoader(yaml.SafeLoader): |
| 61 | + """A yaml.SafeLoader that restricts duplicate keys.""" |
| 62 | + |
| 63 | + def construct_mapping( |
| 64 | + self, node: yaml.MappingNode, deep: bool = False |
| 65 | + ) -> dict[Hashable, Any]: |
| 66 | + """Constructs the standard mapping after checking for duplicates. |
| 67 | +
|
| 68 | + Raises |
| 69 | + ------ |
| 70 | + DuplicateKeysInYAMLError |
| 71 | + If duplicate keys within the same level are detected in the YAML file |
| 72 | + being loaded. |
| 73 | +
|
| 74 | + Notes |
| 75 | + ----- |
| 76 | + A key is considered a duplicate only if it is the same as another key |
| 77 | + _at the same level in the YAML_. |
| 78 | +
|
| 79 | + This raises upon the _first_ duplicate key found; other duplicates may exist |
| 80 | + (in which case a new error will be raised upon re-loading of the YAML file |
| 81 | + once the duplicate is resolved). |
| 82 | + """ |
| 83 | + mapping = [] |
| 84 | + for key_node, _value_node in node.value: |
| 85 | + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] |
| 86 | + if key in mapping: |
| 87 | + raise DuplicatedConfigurationError( |
| 88 | + f"Duplicate key detected at same level of YAML: {key}. Resolve duplicates and try again.", |
| 89 | + name=f"duplicated_{key}", |
| 90 | + layer=None, |
| 91 | + source=None, |
| 92 | + value=None, |
| 93 | + ) |
| 94 | + mapping.append(key) |
| 95 | + return super().construct_mapping(node, deep) |
0 commit comments