-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrawl_loader.py
More file actions
41 lines (29 loc) · 1.15 KB
/
rawl_loader.py
File metadata and controls
41 lines (29 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import yaml
import os.path
class ExtLoaderMeta(type):
def __new__(metacls, __name__, __bases__, __dict__):
"""Add include constructer to class."""
# register the include constructor on the class
cls = super().__new__(metacls, __name__, __bases__, __dict__)
cls.add_constructor("!include", cls.construct_include)
return cls
class ExtLoader(yaml.Loader, metaclass=ExtLoaderMeta):
"""YAML Loader with `!include` constructor."""
def __init__(self, stream):
"""Initialise Loader."""
try:
self._root = os.path.split(stream.name)[0]
except AttributeError:
self._root = os.path.curdir
super().__init__(stream)
def construct_include(self, node):
"""Include file referenced at node."""
filename = os.path.abspath(
os.path.join(self._root, self.construct_scalar(node))
)
extension = os.path.splitext(filename)[1].lstrip(".")
with open(filename, "r") as f:
if extension in ("yaml", "yml"):
return yaml.load(f, ExtLoader)
else:
return "".join(f.readlines())