1
0
mirror of https://github.com/github/octodns.git synced 2024-05-11 05:55:00 +00:00

Add support for !include YAML directive

This commit is contained in:
Ross McFarland
2023-08-19 13:45:01 -07:00
parent e48759791c
commit c64e279dd2
9 changed files with 59 additions and 0 deletions

View File

@@ -2,6 +2,8 @@
#
#
from os.path import dirname, join
from natsort import natsort_keygen
from yaml import SafeDumper, SafeLoader, dump, load
from yaml.constructor import ConstructorError
@@ -23,7 +25,17 @@ class ContextLoader(SafeLoader):
def _construct(self, node):
return self._pairs(node)[0]
def include(self, node):
mark = self.get_mark()
directory = dirname(mark.name)
filename = join(directory, self.construct_scalar(node))
with open(filename, 'r') as fh:
return safe_load(fh, self.__class__)
ContextLoader.add_constructor('!include', ContextLoader.include)
ContextLoader.add_constructor(
ContextLoader.DEFAULT_MAPPING_TAG, ContextLoader._construct
)

View File

@@ -0,0 +1,5 @@
---
- 14
- 15
- 16
- 72

View File

@@ -0,0 +1,3 @@
---
k: v
z: 42

View File

@@ -0,0 +1 @@
---

View File

@@ -0,0 +1,2 @@
---
key: !include does-not-exist.yaml

View File

@@ -0,0 +1,8 @@
---
included-array: !include array.yaml
included-dict: !include dict.yaml
included-empty: !include empty.yaml
included-nested: !include nested.yaml
included-subdir: !include subdir/value.yaml
key: value
name: main

View File

@@ -0,0 +1,2 @@
---
!include subdir/value.yaml

View File

@@ -0,0 +1,2 @@
---
Hello World!

View File

@@ -62,3 +62,27 @@ class TestYaml(TestCase):
buf = StringIO()
safe_dump({'45a03129': 42, '45a0392a': 43}, buf)
self.assertEqual("---\n45a0392a: 43\n45a03129: 42\n", buf.getvalue())
def test_include(self):
with open('tests/config/include/main.yaml') as fh:
data = safe_load(fh)
self.assertEqual(
{
'included-array': [14, 15, 16, 72],
'included-dict': {'k': 'v', 'z': 42},
'included-empty': None,
'included-nested': 'Hello World!',
'included-subdir': 'Hello World!',
'key': 'value',
'name': 'main',
},
data,
)
with open('tests/config/include/include-doesnt-exist.yaml') as fh:
with self.assertRaises(FileNotFoundError) as ctx:
data = safe_load(fh)
self.assertEqual(
"[Errno 2] No such file or directory: 'tests/config/include/does-not-exist.yaml'",
str(ctx.exception),
)