summaryrefslogtreecommitdiff
path: root/src/pyssg/yaml_parser.py
diff options
context:
space:
mode:
authorDavid Luevano Alvarado <david@luevano.xyz>2022-12-04 15:06:48 -0600
committerDavid Luevano Alvarado <david@luevano.xyz>2022-12-04 15:06:48 -0600
commit0bc00ce9352ba843d62c189b68e0e07724cc4b58 (patch)
tree7cfb33a04649f6860f2d29cf0ec124a0f4aa7e3a /src/pyssg/yaml_parser.py
parent5794ce299e0283ed98e102ee1faaeaf86206f588 (diff)
migrate from INI to YAML, breaks compatibility
config file and template files need to be converted to the new format to use with YAML config
Diffstat (limited to 'src/pyssg/yaml_parser.py')
-rw-r--r--src/pyssg/yaml_parser.py45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/pyssg/yaml_parser.py b/src/pyssg/yaml_parser.py
new file mode 100644
index 0000000..48c2eec
--- /dev/null
+++ b/src/pyssg/yaml_parser.py
@@ -0,0 +1,45 @@
+import yaml
+from yaml import SafeLoader
+from yaml.nodes import SequenceNode
+from io import TextIOWrapper
+from importlib.resources import path as rpath
+from logging import Logger, getLogger
+
+log: Logger = getLogger(__name__)
+
+
+# required to concat values in yaml using !join [value, value, ...]
+def __join_constructor(loader: SafeLoader, node: SequenceNode) -> str:
+ seq = loader.construct_sequence(node)
+ return ''.join([str(i) for i in seq])
+log.warning('adding the custom join constructor to yaml.SafeLoader')
+SafeLoader.add_constructor('!join', __join_constructor)
+
+
+# "file" is either a path or the yaml content itself
+def __read_raw_yaml(file: TextIOWrapper) -> list[dict]:
+ all_docs: list[dict] = []
+ all_docs_gen = yaml.safe_load_all(file)
+ for doc in all_docs_gen:
+ all_docs.append(doc)
+
+ return all_docs
+
+
+def get_parsed_yaml(resource: str, package: str='') -> list[dict]:
+ all_yaml_docs: list[dict] = []
+ if package == '':
+ log.debug('no package specified, reading file "%s"', resource)
+ with open(resource, 'r') as f:
+ all_yaml_docs = __read_raw_yaml(f)
+ else:
+ log.debug('package "%s" specified, reading resource "%s"',
+ package, resource)
+ with rpath(package, resource) as p:
+ with open(p, 'r') as f:
+ all_yaml_docs = __read_raw_yaml(f)
+
+ log.info('found %s document(s) for configuration "%s"',
+ len(all_yaml_docs), f'{package}.{resource}' if package != '' else resource)
+
+ return all_yaml_docs