diff --git a/nirman/yaml_parser.py b/nirman/yaml_parser.py new file mode 100644 index 0000000..2c1e8af --- /dev/null +++ b/nirman/yaml_parser.py @@ -0,0 +1,39 @@ +import yaml +from typing import Any, List, Tuple + + +def parse_yaml_tree(yaml_text: str) -> List[Tuple[int, str, bool]]: + data = yaml.safe_load(yaml_text) + tree: List[Tuple[int, str, bool]] = [] + + def walk(node: Any, depth: int): + if isinstance(node, dict): + for key, value in node.items(): + + # --- SPECIAL CASE: handle `files` as direct files --- + if key == "files": + if isinstance(value, list): + for item in value: + tree.append((depth, str(item), False)) + else: + tree.append((depth, str(value), False)) + continue + + # Normal dict key = folder + tree.append((depth, key, True)) + walk(value, depth + 1) + + elif isinstance(node, list): + for item in node: + if isinstance(item, dict): + for key, value in item.items(): + tree.append((depth, key, True)) + walk(value, depth + 1) + else: + tree.append((depth, str(item), False)) + + else: + tree.append((depth, str(node), False)) + + walk(data, 0) + return tree diff --git a/structure.yaml b/structure.yaml new file mode 100644 index 0000000..ba1827d --- /dev/null +++ b/structure.yaml @@ -0,0 +1,7 @@ +project: + src: + - main.py + - utils: + - helper.py + tests: + - test_main.py diff --git a/tests/test_yaml_parser.py b/tests/test_yaml_parser.py new file mode 100644 index 0000000..cba32bd --- /dev/null +++ b/tests/test_yaml_parser.py @@ -0,0 +1,31 @@ +import pytest +from nirman.yaml_parser import parse_yaml_tree + + +def test_simple_yaml_tree(): + yaml_data = """ +project: + src: + - main.py + - utils: + - helper.py + tests: + - test_main.py + files: + - README.md +""" + + expected = [ + (0, "project", True), + (1, "src", True), + (2, "main.py", False), + (2, "utils", True), + (3, "helper.py", False), + (1, "tests", True), + (2, "test_main.py", False), + (1, "README.md", False), + ] + + parsed = parse_yaml_tree(yaml_data) + assert parsed == expected +