gendir 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ """YAML template configuration loader for ``gendir``."""
2
+
3
+ from pathlib import Path
4
+ from dataclasses import dataclass, field
5
+ from typing import List, Optional
6
+ import yaml
7
+
8
+ from .TemplateNode import TemplateNode
9
+ from .TemplateInput import TemplateInput
10
+ from .settings import default_encoding
11
+
12
+ @dataclass
13
+ class TemplateConfig:
14
+ """Top-level configuration parsed from a YAML template file.
15
+
16
+ Attributes:
17
+ target_parent: Default parent directory relative to the current working
18
+ directory when no explicit category is provided.
19
+ structure: Top-level list of :class:`TemplateNode` entries to generate.
20
+ inputs: Optional list of :class:`TemplateInput` entries describing
21
+ variables to prompt for when missing or invalid.
22
+ """
23
+
24
+ target_parent: Path
25
+ structure: List[TemplateNode]
26
+ inputs: List[TemplateInput] = field(default_factory=list)
27
+
28
+ @classmethod
29
+ def from_yaml(cls, file_path) -> 'TemplateConfig':
30
+ """Load and parse a :class:`TemplateConfig` from a YAML file.
31
+
32
+ Supports both ``inputs`` and ``input`` top-level keys for declarative
33
+ interactive prompts.
34
+
35
+ Args:
36
+ file_path: Path-like object pointing to a YAML template file.
37
+
38
+ Returns:
39
+ A populated :class:`TemplateConfig` instance.
40
+ """
41
+ with open(file_path, "r", encoding=default_encoding) as f:
42
+ raw = yaml.safe_load(f) or {}
43
+
44
+ raw_inputs = []
45
+ for key in ("inputs", "input"):
46
+ entries = raw.get(key)
47
+ if isinstance(entries, dict):
48
+ raw_inputs.append(entries)
49
+ elif isinstance(entries, list):
50
+ raw_inputs.extend(entries)
51
+
52
+ return cls(
53
+ target_parent=Path(raw.get("target_parent", "default")),
54
+ structure=[TemplateNode.from_dict(node) for node in (raw.get("structure") or [])],
55
+ inputs=[TemplateInput.from_dict(item) for item in raw_inputs],
56
+ )
@@ -0,0 +1,146 @@
1
+ """Interactive input specification and prompt helpers for ``gendir``."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Callable, List, Optional, Tuple
5
+
6
+
7
+ @dataclass
8
+ class TemplateInput:
9
+ """Declarative input prompt defined under ``inputs`` / ``input`` in YAML.
10
+
11
+ Attributes:
12
+ name: Context variable name populated by this input.
13
+ type: Input type for validation and parsing. Supported values are
14
+ ``"text"`` (default), ``"int"``, ``"float"`` / ``"number"``,
15
+ ``"bool"`` / ``"confirm"``, and ``"choice"`` / ``"select"``.
16
+ description: Optional human-readable description shown in the prompt.
17
+ default: Optional default value used when the user presses Enter.
18
+ required: If ``True``, empty input (with no default) re-prompts.
19
+ choices: Optional list of allowed values (used with ``choice`` or to
20
+ constrain ``text`` inputs).
21
+ """
22
+
23
+ name: str
24
+ type: str = "text"
25
+ description: Optional[str] = None
26
+ default: Optional[Any] = None
27
+ required: bool = False
28
+ choices: List[str] = field(default_factory=list)
29
+
30
+ @classmethod
31
+ def from_dict(cls, data: dict) -> 'TemplateInput':
32
+ """Construct a :class:`TemplateInput` from a parsed YAML mapping."""
33
+ raw_choices = data.get("choices") or []
34
+ return cls(
35
+ name=str(data["name"]).strip(),
36
+ type=str(data.get("type", "text")).strip().lower(),
37
+ description=data.get("description"),
38
+ default=data.get("default"),
39
+ required=bool(data.get("required", False)),
40
+ choices=[str(c) for c in raw_choices],
41
+ )
42
+
43
+ def _default_display(self) -> Optional[str]:
44
+ if self.default is None:
45
+ return None
46
+ if self.type in ("bool", "boolean", "confirm"):
47
+ if isinstance(self.default, bool):
48
+ return "y" if self.default else "n"
49
+ return str(self.default)
50
+ return str(self.default)
51
+
52
+ def format_prompt(self) -> str:
53
+ """Build an ``npm init``-style prompt string for this input."""
54
+ parts = [self.name]
55
+ meta: List[str] = []
56
+ if self.description:
57
+ meta.append(self.description)
58
+ if self.type in ("int", "integer", "float", "number"):
59
+ meta.append(self.type)
60
+ if meta:
61
+ parts.append(f"({', '.join(meta)})")
62
+
63
+ if self.type in ("bool", "boolean", "confirm"):
64
+ parts.append("[y/n]")
65
+ elif self.choices:
66
+ parts.append(f"[{'/'.join(self.choices)}]")
67
+
68
+ prompt = " ".join(parts) + ": "
69
+ default_text = self._default_display()
70
+ if default_text is not None:
71
+ prompt += f"({default_text}) "
72
+ return prompt
73
+
74
+ def parse_and_validate(self, raw_value: Any) -> Tuple[bool, Any, Optional[str]]:
75
+ """Validate and coerce ``raw_value`` according to this input's type.
76
+
77
+ Returns:
78
+ A tuple ``(is_valid, parsed_value, error_message)``.
79
+ """
80
+ text = "" if raw_value is None else str(raw_value).strip()
81
+
82
+ if text == "":
83
+ if self.default is not None:
84
+ if self.type in ("bool", "boolean", "confirm") and isinstance(self.default, bool):
85
+ return True, self.default, None
86
+ ok, parsed, _ = self.parse_and_validate(str(self.default))
87
+ return (True, parsed, None) if ok else (True, self.default, None)
88
+ if self.required:
89
+ return False, None, f"'{self.name}' is required."
90
+ return True, "", None
91
+
92
+ if self.type in ("int", "integer"):
93
+ try:
94
+ return True, int(text), None
95
+ except ValueError:
96
+ return False, None, "Expected an integer."
97
+
98
+ if self.type in ("float", "number"):
99
+ try:
100
+ return True, float(text), None
101
+ except ValueError:
102
+ return False, None, "Expected a number."
103
+
104
+ if self.type in ("bool", "boolean", "confirm"):
105
+ lowered = text.lower()
106
+ if lowered in ("y", "yes", "true", "1"):
107
+ return True, True, None
108
+ if lowered in ("n", "no", "false", "0"):
109
+ return True, False, None
110
+ return False, None, "Expected yes/no (y/n or true/false)."
111
+
112
+ if self.type in ("choice", "select"):
113
+ if not self.choices:
114
+ return True, text, None
115
+ if text in self.choices:
116
+ return True, text, None
117
+ if text.isdigit():
118
+ idx = int(text)
119
+ if 1 <= idx <= len(self.choices):
120
+ return True, self.choices[idx - 1], None
121
+ return False, None, f"Expected one of: {', '.join(self.choices)}."
122
+
123
+ # Default: text / string
124
+ if self.choices and text not in self.choices:
125
+ return False, None, f"Expected one of: {', '.join(self.choices)}."
126
+ return True, text, None
127
+
128
+ def prompt(self, input_func: Optional[Callable[[str], str]] = None) -> Any:
129
+ """Interactively prompt until a valid value is entered.
130
+
131
+ Falls back to the input's default (or ``""``) if stdin reaches EOF.
132
+ """
133
+ reader = input_func or input
134
+ prompt_str = self.format_prompt()
135
+ while True:
136
+ try:
137
+ answer = reader(prompt_str)
138
+ except EOFError:
139
+ print()
140
+ ok, value, _ = self.parse_and_validate("")
141
+ return value if ok else (self.default if self.default is not None else "")
142
+
143
+ ok, value, err = self.parse_and_validate(answer)
144
+ if ok:
145
+ return value
146
+ print(f"⚠️ {err}")
gendir/TemplateNode.py ADDED
@@ -0,0 +1,116 @@
1
+ """Tree node representation and filesystem generator for ``gendir``."""
2
+
3
+ import json
4
+ import shutil
5
+ from pathlib import Path
6
+ from dataclasses import dataclass, field
7
+ from typing import List, Optional
8
+
9
+ from .settings import default_encoding
10
+
11
+
12
+ class _EmptyValue:
13
+ """Placeholder object that renders as empty text for missing template vars."""
14
+
15
+ def __str__(self) -> str:
16
+ return ""
17
+
18
+ def __format__(self, format_spec: str) -> str:
19
+ return ""
20
+
21
+
22
+ class _SafeContext(dict):
23
+ """Formatting mapping that substitutes empty text for unspecified keys."""
24
+
25
+ def __missing__(self, key: str) -> _EmptyValue:
26
+ return _EmptyValue()
27
+
28
+
29
+ @dataclass
30
+ class TemplateNode:
31
+ """A single directory or file entry within a template structure.
32
+
33
+ Attributes:
34
+ type: Node kind, either ``"directory"`` or ``"file"``.
35
+ name: Entry name; supports Python ``str.format`` placeholders.
36
+ content: Inline file content as a format string or a ``dict``
37
+ (serialized as pretty-printed JSON). Ignored for directories or
38
+ when ``copy_from`` is set.
39
+ copy_from: Path relative to the template root pointing to an existing
40
+ file to copy verbatim. Takes precedence over ``content``.
41
+ contents: Nested child :class:`TemplateNode` items for directories.
42
+ """
43
+
44
+ type: str # "directory" or "file"
45
+ name: str
46
+ content: Optional[str] = None
47
+ copy_from: Optional[str] = None
48
+ contents: List['TemplateNode'] = field(default_factory=list)
49
+
50
+
51
+
52
+ @classmethod
53
+ def from_dict(cls, data: dict) -> 'TemplateNode':
54
+ """Recursively construct a :class:`TemplateNode` from a raw dictionary.
55
+
56
+ Args:
57
+ data: Mapping parsed from YAML containing at least ``"type"`` and
58
+ ``"name"`` keys.
59
+
60
+ Returns:
61
+ A :class:`TemplateNode` with any nested ``contents`` parsed.
62
+ """
63
+ # Recursively parse nested contents if it's a directory
64
+ raw_children = data.get("contents", [])
65
+ parsed_children = [cls.from_dict(child) for child in raw_children]
66
+
67
+ return cls(
68
+ type=data["type"],
69
+ name=data["name"],
70
+ content=data.get("content"),
71
+ copy_from=data.get("copy_from"),
72
+ contents=parsed_children
73
+ )
74
+
75
+ def generate(self, current: Path, context: dict, root:Path)->None:
76
+ """Recursively generate this node and its children on the filesystem.
77
+
78
+ Args:
79
+ current: Parent directory in which to create this node.
80
+ context: Mapping of template variables used for ``str.format``
81
+ substitution in names and inline string contents.
82
+ root: Base directory used to resolve relative ``copy_from`` paths.
83
+ """
84
+ safe_context = _SafeContext(context)
85
+ formatted_name = self.name.format_map(safe_context)
86
+ target:Path = current / formatted_name
87
+
88
+ if self.type == "directory":
89
+ target.mkdir(parents=True, exist_ok=True)
90
+ print(f"📁 Created directory:\t{target}")
91
+
92
+ for child in self.contents:
93
+ child.generate(target, context, root)
94
+
95
+ elif self.type == "file":
96
+ if self.copy_from:
97
+ src:Path=root/self.copy_from
98
+
99
+ if src.exists():
100
+ shutil.copy(src, target)
101
+ print(f"📄 Copied file from:\t{src}")
102
+ print(f"📄 Copied file to:\t{target}")
103
+
104
+ else:
105
+ target.touch()
106
+ print(f"⚠️ Source template\t'{src}' not found.")
107
+ print(f"⚠️ Created empty file:\t{target}")
108
+ else:
109
+ # Handle both raw strings and dictionary structures (like JSON notebooks)
110
+ if isinstance(self.content, dict):
111
+ file_content = json.dumps(self.content, indent=2)
112
+ else:
113
+ file_content = str(self.content or "").format_map(safe_context)
114
+
115
+ target.write_text(file_content, encoding=default_encoding)
116
+ print(f"📄 Created file:\t{target}")
gendir/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """gendir — Generate directory and file structures from YAML templates.
2
+
3
+ This package provides both a CLI (`gendir`) and a Python API for creating
4
+ repeatable folder hierarchies, populated text/JSON files, and copied static
5
+ assets defined in YAML template files.
6
+ """
gendir/cli.py ADDED
@@ -0,0 +1,193 @@
1
+ # PYTHON_ARGCOMPLETE_OK
2
+ """Command-line interface and shell completion helpers for ``gendir``."""
3
+
4
+ from argparse import Namespace, Action, ArgumentParser
5
+ from argcomplete import autocomplete
6
+ from pathlib import Path
7
+ from typing import Callable, Optional
8
+
9
+ from .settings import templates_dir_name, ignore
10
+ from .yaml_handler import handle_template
11
+
12
+ current_dir: Path = Path.cwd()
13
+
14
+ def find_repo_root(start_path: Path = None) -> Path:
15
+ """Walks up parent directories until it finds a .git directory or the templates directory"""
16
+ current: Path = (start_path or current_dir).resolve()
17
+ for parent in [current, *current.parents]:
18
+ if (parent / ".git").exists() or (parent / templates_dir_name).exists():
19
+ return parent
20
+ return current
21
+
22
+ root_d: Path = find_repo_root()
23
+ templates_dir: Path = root_d / templates_dir_name
24
+
25
+ def get_category_choies(prefix: str, parsed_args: Namespace, **kwargs: dict) -> list[str]:
26
+ """Scan current working directory for subdirectories as category suggestions."""
27
+ if not current_dir.exists():
28
+ return []
29
+
30
+ return [
31
+ d.name for d in current_dir.iterdir()
32
+ if d.is_dir()
33
+ and not d.name.startswith(".")
34
+ and d.name not in ignore
35
+ and d.name.startswith(prefix)
36
+ ]
37
+
38
+ def get_template_choices(prefix: str, parsed_args: Namespace, **kwargs: dict) -> list[str]:
39
+ """Dynamically scan the templates directory for available .yaml templates."""
40
+ if not templates_dir.exists():
41
+ return []
42
+ return [
43
+ path.stem for path in templates_dir.glob("*.yaml") if path.stem.startswith(prefix)
44
+ ]
45
+
46
+
47
+ def prompt_category(
48
+ suggestions: Optional[list[str]] = None,
49
+ input_func: Optional[Callable[[str], str]] = None,
50
+ ) -> Optional[str]:
51
+ """Interactively prompt for the ``category`` argument (``npm init`` style).
52
+
53
+ Returns ``None`` if the user presses Enter so the template's
54
+ ``target_parent`` default is used.
55
+ """
56
+ reader = input_func or input
57
+ hint_items = sorted(suggestions or [])
58
+ if hint_items:
59
+ preview = ", ".join(hint_items[:6])
60
+ if len(hint_items) > 6:
61
+ preview += ", ..."
62
+ prompt_str = f"category (existing: {preview}): (default) "
63
+ else:
64
+ prompt_str = "category: (default) "
65
+
66
+ try:
67
+ answer = reader(prompt_str).strip()
68
+ except EOFError:
69
+ print()
70
+ return None
71
+ return answer or None
72
+
73
+
74
+ def prompt_template(
75
+ templates_root: Path,
76
+ initial: Optional[str] = None,
77
+ input_func: Optional[Callable[[str], str]] = None,
78
+ ) -> Optional[Path]:
79
+ """Resolve or interactively prompt for a valid YAML template in ``templates_root``."""
80
+ reader = input_func or input
81
+ available = sorted(path.stem for path in templates_root.glob("*.yaml")) if templates_root.exists() else []
82
+
83
+ if initial is not None and initial.strip():
84
+ stem = initial.strip().removesuffix(".yaml")
85
+ candidate = templates_root / f"{stem}.yaml"
86
+ if candidate.exists():
87
+ return candidate
88
+ print(f"⚠️ Template '{initial}' not found in {templates_root}/.")
89
+
90
+ if not available:
91
+ print(f"❌ Error: No .yaml templates found in {templates_root}/")
92
+ return None
93
+
94
+ if len(available) == 1:
95
+ prompt_str = f"template name: ({available[0]}) "
96
+ else:
97
+ prompt_str = f"template name ({', '.join(available)}): "
98
+
99
+ while True:
100
+ try:
101
+ answer = reader(prompt_str).strip()
102
+ except EOFError:
103
+ print()
104
+ return None
105
+
106
+ if not answer and len(available) == 1:
107
+ answer = available[0]
108
+
109
+ if not answer:
110
+ print(f"⚠️ Please enter a template name (available: {', '.join(available)}).")
111
+ continue
112
+
113
+ stem = answer.removesuffix(".yaml")
114
+ candidate = templates_root / f"{stem}.yaml"
115
+ if candidate.exists():
116
+ return candidate
117
+ print(f"⚠️ Template '{answer}' not found. Available: {', '.join(available)}.")
118
+
119
+
120
+ def main():
121
+ parser = ArgumentParser(
122
+ description="CLI tool to generate structured folders from YAML templates"
123
+ )
124
+
125
+ category_arg: Action = parser.add_argument(
126
+ "category",
127
+ nargs="?",
128
+ default=None,
129
+ type=str,
130
+ help="Category or context (e.g., note, project, lab). Prompted if omitted."
131
+ )
132
+ category_arg.completer = get_category_choies
133
+
134
+ template_arg: Action = parser.add_argument(
135
+ "template",
136
+ nargs="?",
137
+ default=None,
138
+ type=str,
139
+ help="Template name matching a YAML file in the templates folder. Prompted if omitted or invalid."
140
+ )
141
+ template_arg.completer = get_template_choices
142
+
143
+ parser.add_argument(
144
+ "-v", "--var",
145
+ action="append",
146
+ default=[],
147
+ help="Extra template variables in key=value format (e.g., -v topic=auth -v version=2)"
148
+ )
149
+
150
+ parser.add_argument(
151
+ "-y", "--yes",
152
+ action="store_true",
153
+ help="Skip interactive prompts and use default or empty values"
154
+ )
155
+
156
+ autocomplete(parser)
157
+ args: Namespace = parser.parse_args()
158
+ interactive = not args.yes
159
+
160
+ try:
161
+ category = args.category.strip() if isinstance(args.category, str) else None
162
+ if not category and interactive:
163
+ category = prompt_category(get_category_choies("", args))
164
+
165
+ if interactive:
166
+ template_path = prompt_template(templates_dir, initial=args.template)
167
+ else:
168
+ if not args.template or not args.template.strip():
169
+ print("❌ Error: Template name is required when using --yes.")
170
+ return
171
+ stem = args.template.strip().removesuffix(".yaml")
172
+ template_path = templates_dir / f"{stem}.yaml"
173
+ if not template_path.exists():
174
+ print(f"❌ Error: Template '{args.template}.yaml' not found in {templates_dir}/")
175
+ return
176
+ except KeyboardInterrupt:
177
+ print("\n❌ Cancelled.")
178
+ return
179
+
180
+ if not template_path:
181
+ return
182
+
183
+ # Pass raw CLI arguments directly to the handler
184
+ handle_template(
185
+ template=template_path,
186
+ category=category,
187
+ var=args.var,
188
+ root=root_d,
189
+ interactive=interactive,
190
+ )
191
+
192
+ if __name__ == "__main__":
193
+ main()
gendir/settings.py ADDED
@@ -0,0 +1,16 @@
1
+ """Global configuration defaults for ``gendir``."""
2
+
3
+ default_encoding: str = "utf-8"
4
+ """Default character encoding used when reading templates and writing files."""
5
+
6
+ templates_dir_name: str = ".templates"
7
+ """Directory name searched for YAML templates and repository root detection."""
8
+
9
+ ignore: list[str] = [
10
+ ".venv",
11
+ "venv",
12
+ "__pycache__",
13
+ "build",
14
+ "dist"
15
+ ]
16
+ """Directory names excluded from CLI category tab-completion suggestions."""
gendir/yaml_handler.py ADDED
@@ -0,0 +1,99 @@
1
+ """High-level entry point for loading and executing YAML templates."""
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from typing import List, Union, Any
6
+
7
+ from .TemplateNode import TemplateNode
8
+ from .TemplateConfig import TemplateConfig
9
+
10
+ def handle_template(
11
+ template: Path = None,
12
+ category: Union[str, Path] = None,
13
+ var: List[str] = None,
14
+ root: Path = None,
15
+ interactive: bool = True,
16
+ ) -> bool:
17
+ """Load a YAML template and generate its directory structure on disk.
18
+
19
+ Args:
20
+ template: Path to the YAML template file.
21
+ category: Target parent directory (relative to the current working
22
+ directory, or an absolute path). Falls back to the template's
23
+ ``target_parent`` field when omitted.
24
+ var: Optional list of ``"key=value"`` strings added to the template
25
+ formatting context. Custom keys can override built-in variables
26
+ (``WEEK_NUM``, ``category``, ``root``).
27
+ root: Base directory used to resolve ``copy_from`` paths and stored in
28
+ the ``root`` context variable. Defaults to ``Path.cwd()``.
29
+ interactive: When ``True`` (default), interactively prompts for any
30
+ variables declared under ``inputs`` / ``input`` in the YAML file
31
+ that were not provided or failed validation.
32
+
33
+ Returns:
34
+ ``True`` if generation succeeded, or ``False`` if the template file
35
+ could not be found, failed to parse, or was cancelled by the user.
36
+ """
37
+
38
+ if not template or not template.exists():
39
+ print(f"❌ Error: Template path '{template}' does not exist.")
40
+ return False
41
+
42
+ try:
43
+ config: TemplateConfig = TemplateConfig.from_yaml(template)
44
+ except Exception as e:
45
+ print(f"❌ Error parsing template YAML: {e}")
46
+ return False
47
+
48
+ # Parse key=value override variables passed from the CLI
49
+ extra_vars: dict[str, Any] = {}
50
+ for item in (var or []):
51
+ if "=" in item:
52
+ key, val = item.split("=", 1)
53
+ extra_vars[key.strip()] = val.strip()
54
+ else:
55
+ print(f"⚠️ Warning: Ignored malformed variable '{item}' (expected key=value)")
56
+
57
+ # Validate and interactively prompt for variables declared in `inputs` / `input`
58
+ try:
59
+ for inp in config.inputs:
60
+ if inp.name in extra_vars and str(extra_vars[inp.name]).strip() != "":
61
+ ok, parsed, err = inp.parse_and_validate(extra_vars[inp.name])
62
+ if ok:
63
+ extra_vars[inp.name] = parsed
64
+ continue
65
+ print(f"⚠️ Invalid value '{extra_vars[inp.name]}' for '{inp.name}': {err}")
66
+ if interactive:
67
+ extra_vars[inp.name] = inp.prompt()
68
+ else:
69
+ ok_default, default_val, _ = inp.parse_and_validate("")
70
+ extra_vars[inp.name] = default_val if ok_default else ""
71
+ else:
72
+ if interactive:
73
+ extra_vars[inp.name] = inp.prompt()
74
+ else:
75
+ ok_default, default_val, _ = inp.parse_and_validate("")
76
+ extra_vars[inp.name] = default_val if ok_default else ""
77
+ except KeyboardInterrupt:
78
+ print("\n❌ Cancelled.")
79
+ return False
80
+
81
+ parent_dir = category or config.target_parent
82
+ base_path: Path = Path.cwd() / parent_dir
83
+ base_path.mkdir(parents=True, exist_ok=True)
84
+
85
+ # Build the full rendering context internally
86
+ context: dict[str, Any] = {
87
+ "WEEK_NUM": datetime.now().isocalendar()[1],
88
+ "category": str(parent_dir),
89
+ "root": root or Path.cwd(),
90
+ **extra_vars
91
+ }
92
+
93
+ print(f"🚀 Generating structure inside '{base_path.name}/'...")
94
+
95
+ for node in config.structure:
96
+ node.generate(base_path, context, root=(root or Path.cwd()))
97
+
98
+ print("✨ Generation complete!")
99
+ return True