yaml_utils.py 1.1 KB

123456789101112131415161718192021222324252627
  1. # Safely load fast C Yaml loader/dumper if they are available
  2. try:
  3. from yaml import CSafeLoader as Loader
  4. except ImportError:
  5. from yaml import SafeLoader as Loader # type: ignore[assignment, misc]
  6. try:
  7. from yaml import CSafeDumper as Dumper
  8. except ImportError:
  9. from yaml import SafeDumper as Dumper # type: ignore[assignment, misc]
  10. YamlDumper = Dumper
  11. # A custom loader for YAML that errors on duplicate keys.
  12. # This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165
  13. class YamlLoader(Loader):
  14. def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
  15. mapping = []
  16. for key_node, value_node in node.value:
  17. key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call]
  18. if key in mapping:
  19. raise AssertionError(
  20. f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}"
  21. )
  22. mapping.append(key)
  23. mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
  24. return mapping