hermes_yaml.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """Shared YAML 1.1 policy for config, manifests, and frontmatter.
  2. Ruamel's native schema includes bare y/n booleans and rejects duplicate keys.
  3. Every operation owns its parser/emitter; instances must not be shared by threads.
  4. """
  5. from io import StringIO
  6. from typing import Any, IO, overload
  7. from ruamel.yaml import YAML
  8. from ruamel.yaml.error import YAMLError
  9. from ruamel.yaml.resolver import VersionedResolver
  10. class _Yaml11Resolver(VersionedResolver):
  11. # Quote strings like "off" without adding a %YAML directive to every config/snippet.
  12. @property
  13. def processing_version(self) -> tuple[int, int]:
  14. return (1, 1)
  15. def _load(document: str | bytes, *, pure: bool) -> Any:
  16. yaml = YAML(typ="safe", pure=pure)
  17. yaml.version = (1, 1)
  18. return yaml.load(document)
  19. def safe_load(stream: str | bytes | IO[str] | IO[bytes]) -> Any:
  20. """Read standard YAML data; existing configs use YAML 1.1 booleans.
  21. The pure parser defines what parses: Windows ARM64 has no C extension, and libyaml rejects
  22. documents the pure parser accepts (``[{url: http://h}]``), so a C rejection is re-read pure.
  23. """
  24. document = stream if isinstance(stream, (str, bytes)) else stream.read()
  25. try:
  26. return _load(document, pure=False)
  27. except YAMLError:
  28. return _load(document, pure=True)
  29. @overload
  30. def safe_dump(
  31. data: Any, stream: None = None, *, default_flow_style: bool = False,
  32. sort_keys: bool = True, allow_unicode: bool = True, width: int = 80,
  33. ) -> str: ...
  34. @overload
  35. def safe_dump(
  36. data: Any, stream: IO[str], *, default_flow_style: bool = False,
  37. sort_keys: bool = True, allow_unicode: bool = True, width: int = 80,
  38. ) -> None: ...
  39. def safe_dump(
  40. data: Any,
  41. stream: IO[str] | None = None,
  42. *,
  43. default_flow_style: bool = False,
  44. sort_keys: bool = True,
  45. allow_unicode: bool = True,
  46. width: int = 80,
  47. ) -> str | None:
  48. """Write standard YAML data with readable Unicode and indented block lists."""
  49. # The C emitter ignores sequence offsets and escapes astral Unicode.
  50. yaml = YAML(typ="safe", pure=True)
  51. yaml.Resolver = _Yaml11Resolver
  52. yaml.default_flow_style = default_flow_style
  53. yaml.allow_unicode = allow_unicode
  54. yaml.width = width
  55. yaml.sort_base_mapping_type_on_output = sort_keys
  56. yaml.indent(mapping=2, sequence=4, offset=2)
  57. if stream is not None:
  58. yaml.dump(data, stream)
  59. return None
  60. output = StringIO()
  61. yaml.dump(data, output)
  62. return output.getvalue()
  63. # ruamel's emitter can change a double-quoted value when it folds a long line right after an
  64. # escaped backslash (``D:\\Cent…`` → ``D:\\`` + bare newline): the fold reloads as a literal space
  65. # and a no-op save mutates the stored value (#119844). Config writes must be value-preserving, so
  66. # every round-trip emitter in the tree keeps scalars on one line instead of folding (``None``
  67. # does NOT disable folding on 0.18.x; only a large width does).
  68. ROUNDTRIP_YAML_WIDTH = 2**31 - 1
  69. def roundtrip_yaml() -> YAML:
  70. """Create a fresh comment/quote-preserving editor for user-authored YAML."""
  71. yaml = YAML(typ="rt")
  72. yaml.width = ROUNDTRIP_YAML_WIDTH
  73. yaml.Resolver = _Yaml11Resolver
  74. yaml.preserve_quotes = True
  75. yaml.allow_unicode = True
  76. yaml.default_flow_style = False
  77. yaml.indent(mapping=2, sequence=4, offset=2)
  78. return yaml