projectcats-cli 1.0.2__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.
pcat/templates.py ADDED
@@ -0,0 +1,223 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from pcat.config import load_config
8
+
9
+
10
+ def _sanitize_package_name(name: str) -> str:
11
+ cleaned = re.sub(r"[^a-zA-Z0-9_]+", "_", name.strip().lower()).strip("_")
12
+ if not cleaned:
13
+ cleaned = "pcat_project"
14
+ if cleaned[0].isdigit():
15
+ cleaned = f"pkg_{cleaned}"
16
+ return cleaned
17
+
18
+
19
+ def _render_placeholders(text: str, project_name: str, pkg_name: str) -> str:
20
+ return text.replace("{{name}}", project_name).replace("{{pkg_name}}", pkg_name)
21
+
22
+
23
+ def list_templates() -> list[tuple[str, str, str]]:
24
+ cfg = load_config()
25
+ items: list[tuple[str, str, str]] = [
26
+ ("py-cli", "builtin", "Python CLI project with pyproject.toml, package layout, and CLI entrypoint"),
27
+ ("script", "builtin", "Standalone Python script with main() and argument/input ready structure"),
28
+ ("mod", "builtin", "Modular package structure (__init__.py, core.py, README.md)"),
29
+ ("box", "builtin", "Isolated runner project template with main.py, requirements.txt, and pcatbox.json"),
30
+ ]
31
+ for tpl_name, tpl_path in sorted(cfg.custom_templates.items()):
32
+ items.append((tpl_name, "custom", tpl_path))
33
+ return items
34
+
35
+
36
+ def create_from_template(
37
+ project_name: str,
38
+ template_name: str | None = None,
39
+ output_dir: str | Path | None = None,
40
+ force: bool = False,
41
+ ) -> Path:
42
+ cfg = load_config()
43
+ tpl = (template_name or cfg.default_template or "py-cli").strip().lower()
44
+
45
+ clean_name = project_name.strip()
46
+ if not clean_name:
47
+ raise ValueError("Project name cannot be empty")
48
+
49
+ pkg_name = _sanitize_package_name(clean_name)
50
+ base_root = Path(output_dir).resolve() if output_dir is not None else Path.cwd().resolve()
51
+
52
+ if tpl in cfg.custom_templates:
53
+ src_tpl_dir = Path(cfg.custom_templates[tpl]).resolve()
54
+ if not src_tpl_dir.is_dir():
55
+ raise FileNotFoundError(f"Custom template '{tpl}' directory missing: {src_tpl_dir}")
56
+
57
+ target_dir = base_root / _render_placeholders(clean_name, clean_name, pkg_name)
58
+ if target_dir.exists() and any(target_dir.iterdir()) and not force:
59
+ raise FileExistsError(f"Target directory is not empty: {target_dir} (use --force)")
60
+ target_dir.mkdir(parents=True, exist_ok=True)
61
+
62
+ for root, dirs, files in os.walk(src_tpl_dir):
63
+ rel_root = Path(root).relative_to(src_tpl_dir)
64
+ rendered_rel_root = Path(
65
+ *(_render_placeholders(part, clean_name, pkg_name) for part in rel_root.parts)
66
+ )
67
+ dest_subdir = target_dir / rendered_rel_root
68
+ dest_subdir.mkdir(parents=True, exist_ok=True)
69
+
70
+ for fname in files:
71
+ src_file = Path(root) / fname
72
+ rendered_fname = _render_placeholders(fname, clean_name, pkg_name)
73
+ dest_file = dest_subdir / rendered_fname
74
+ raw_bytes = src_file.read_bytes()
75
+ try:
76
+ decoded = raw_bytes.decode("utf-8")
77
+ rendered_text = _render_placeholders(decoded, clean_name, pkg_name)
78
+ dest_file.write_text(rendered_text, encoding="utf-8", newline="\n")
79
+ except UnicodeDecodeError:
80
+ dest_file.write_bytes(raw_bytes)
81
+ return target_dir
82
+
83
+ builtin_names = {"py-cli", "script", "mod", "box"}
84
+ if tpl not in builtin_names:
85
+ known = sorted(builtin_names | set(cfg.custom_templates.keys()))
86
+ raise ValueError(f"Unknown template '{tpl}'. Available: {', '.join(known)}")
87
+
88
+ if tpl == "script":
89
+ target_file = base_root / f"{pkg_name}.py"
90
+ if target_file.exists() and not force:
91
+ raise FileExistsError(f"Target file already exists: {target_file} (use --force)")
92
+ target_file.parent.mkdir(parents=True, exist_ok=True)
93
+ content = (
94
+ "from __future__ import annotations\n\n"
95
+ "import sys\n\n\n"
96
+ "def main(argv: list[str] | None = None) -> int:\n"
97
+ " args = sys.argv[1:] if argv is None else argv\n"
98
+ f' print("{clean_name} started")\n'
99
+ ' if "--interactive" in args:\n'
100
+ ' val = input("Enter value: ").strip()\n'
101
+ ' print(f"Received: {val}")\n'
102
+ " return 0\n\n\n"
103
+ 'if __name__ == "__main__":\n'
104
+ " raise SystemExit(main())\n"
105
+ )
106
+ target_file.write_text(content, encoding="utf-8", newline="\n")
107
+ return target_file
108
+
109
+ target_dir = base_root / clean_name
110
+ if target_dir.exists() and any(target_dir.iterdir()) and not force:
111
+ raise FileExistsError(f"Target directory is not empty: {target_dir} (use --force)")
112
+ target_dir.mkdir(parents=True, exist_ok=True)
113
+
114
+ if tpl == "py-cli":
115
+ (target_dir / "src" / pkg_name).mkdir(parents=True, exist_ok=True)
116
+ (target_dir / "pyproject.toml").write_text(
117
+ "[build-system]\n"
118
+ 'requires = ["setuptools>=61.0"]\n'
119
+ 'build-backend = "setuptools.build_meta"\n\n'
120
+ "[project]\n"
121
+ f'name = "{pkg_name}"\n'
122
+ 'version = "0.1.0"\n'
123
+ 'description = "CLI project generated by pcat new"\n'
124
+ 'requires-python = ">=3.10"\n'
125
+ "dependencies = []\n\n"
126
+ "[project.scripts]\n"
127
+ f'{pkg_name} = "{pkg_name}.cli:main"\n\n'
128
+ "[tool.setuptools.packages.find]\n"
129
+ 'where = ["src"]\n',
130
+ encoding="utf-8",
131
+ newline="\n",
132
+ )
133
+ (target_dir / "src" / pkg_name / "__init__.py").write_text(
134
+ f'__version__ = "0.1.0"\n',
135
+ encoding="utf-8",
136
+ newline="\n",
137
+ )
138
+ (target_dir / "src" / pkg_name / "cli.py").write_text(
139
+ "from __future__ import annotations\n\n"
140
+ "import argparse\n"
141
+ "import sys\n\n\n"
142
+ "def main(argv: list[str] | None = None) -> int:\n"
143
+ " parser = argparse.ArgumentParser("
144
+ f'prog="{pkg_name}", description="{clean_name} CLI"'
145
+ ")\n"
146
+ ' parser.add_argument("--name", default="world", help="Target name")\n'
147
+ " ns = parser.parse_args(sys.argv[1:] if argv is None else argv)\n"
148
+ ' print(f"Hello, {ns.name}!")\n'
149
+ " return 0\n\n\n"
150
+ 'if __name__ == "__main__":\n'
151
+ " raise SystemExit(main())\n",
152
+ encoding="utf-8",
153
+ newline="\n",
154
+ )
155
+ return target_dir
156
+
157
+ if tpl == "mod":
158
+ mod_dir = target_dir / pkg_name
159
+ mod_dir.mkdir(parents=True, exist_ok=True)
160
+ (mod_dir / "__init__.py").write_text(
161
+ f'from .core import run_module\n\n__all__ = ["run_module"]\n',
162
+ encoding="utf-8",
163
+ newline="\n",
164
+ )
165
+ (mod_dir / "core.py").write_text(
166
+ "from __future__ import annotations\n\n\n"
167
+ 'def run_module(payload: str = "") -> str:\n'
168
+ f' return f"[{pkg_name}] processed: {{payload}}"\n',
169
+ encoding="utf-8",
170
+ newline="\n",
171
+ )
172
+ (target_dir / "README.md").write_text(
173
+ f"# {clean_name}\n\nModule package `{pkg_name}` created with `pcat new mod`.\n",
174
+ encoding="utf-8",
175
+ newline="\n",
176
+ )
177
+ return target_dir
178
+
179
+ # tpl == "box"
180
+ (target_dir / "pcatbox.json").write_text(
181
+ "{\n"
182
+ f' "name": "{clean_name}",\n'
183
+ ' "runtime": "python",\n'
184
+ ' "entry": "main.py",\n'
185
+ ' "env": {\n'
186
+ ' "PCAT_BOX": "1"\n'
187
+ " }\n"
188
+ "}\n",
189
+ encoding="utf-8",
190
+ newline="\n",
191
+ )
192
+ (target_dir / "requirements.txt").write_text("", encoding="utf-8", newline="\n")
193
+ (target_dir / "main.py").write_text(
194
+ "from __future__ import annotations\n\n"
195
+ "import os\n\n\n"
196
+ "def main() -> int:\n"
197
+ ' box_flag = os.environ.get("PCAT_BOX", "0")\n'
198
+ f' print(f"Running {clean_name} (PCAT_BOX={{box_flag}})")\n'
199
+ " return 0\n\n\n"
200
+ 'if __name__ == "__main__":\n'
201
+ " raise SystemExit(main())\n",
202
+ encoding="utf-8",
203
+ newline="\n",
204
+ )
205
+ return target_dir
206
+
207
+
208
+ def create_many_from_template(
209
+ names: list[str],
210
+ template_name: str | None = None,
211
+ output_dir: str | Path | None = None,
212
+ force: bool = False,
213
+ ) -> list[Path]:
214
+ created: list[Path] = []
215
+ for proj_name in names:
216
+ path = create_from_template(
217
+ project_name=proj_name,
218
+ template_name=template_name,
219
+ output_dir=output_dir,
220
+ force=force,
221
+ )
222
+ created.append(path)
223
+ return created