-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.py
More file actions
362 lines (293 loc) · 11.5 KB
/
init.py
File metadata and controls
362 lines (293 loc) · 11.5 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""Implementation of the init command.
Scaffolds a new project by running cdk init, uv init, copying template files,
installing dependencies, and making the initial commit.
"""
import re
import shutil
import subprocess
import sys
from importlib.resources import files
from pathlib import Path
import click
import tomlkit
from gds_idea_app_kit import (
GITHUB_ORG,
REPO_PREFIX,
__version__,
)
from gds_idea_app_kit.manifest import build_manifest, write_manifest
from gds_idea_app_kit.prerequisites import check_prerequisites
def _sanitize_app_name(name: str) -> str:
"""Sanitize and validate an app name for use as a DNS subdomain label.
The name will become part of a domain: {name}.gds-idea.click
Args:
name: The raw app name from the user.
Returns:
The cleaned app name.
Raises:
click.BadParameter: If the name is invalid.
"""
# Strip the repo prefix if the user accidentally included it
prefix = f"{REPO_PREFIX}-"
if name.startswith(prefix):
name = name[len(prefix) :]
# Lowercase
name = name.lower()
# Validate DNS label rules
if not name:
raise click.BadParameter("App name cannot be empty.")
if len(name) > 63:
raise click.BadParameter("App name must be 63 characters or fewer (DNS label limit).")
if not re.match(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$", name):
raise click.BadParameter(
"App name must contain only lowercase letters, numbers, and hyphens, "
"and must start and end with a letter or number."
)
if "--" in name:
raise click.BadParameter("App name must not contain consecutive hyphens (--).")
if name.isdigit():
raise click.BadParameter("App name must not be purely numeric.")
return name
def _get_templates_dir() -> Path:
"""Get the path to the bundled templates directory."""
return Path(str(files("gds_idea_app_kit") / "templates"))
def _apply_template_vars(content: str, variables: dict[str, str]) -> str:
"""Apply template variable substitution to content.
Replaces {{key}} with value for each entry in variables.
Args:
content: The template content with {{placeholders}}.
variables: Mapping of placeholder names to values.
Returns:
Content with all placeholders replaced.
"""
for key, value in variables.items():
content = content.replace(f"{{{{{key}}}}}", value)
return content
def _copy_template(src: Path, dest: Path, variables: dict[str, str] | None = None) -> None:
"""Copy a template file to a destination, optionally applying variable substitution.
Args:
src: Path to the source template file.
dest: Path to the destination file.
variables: Optional mapping of placeholder names to values.
"""
dest.parent.mkdir(parents=True, exist_ok=True)
content = src.read_text()
if variables:
content = _apply_template_vars(content, variables)
dest.write_text(content)
def _run_command(
cmd: list[str],
cwd: Path,
project_dir: Path | None = None,
) -> subprocess.CompletedProcess:
"""Run a subprocess command with error handling.
Args:
cmd: The command and arguments to run.
cwd: Working directory for the command.
project_dir: The project directory (for cleanup message on failure).
If not provided, uses cwd.
Returns:
The completed process result.
"""
cleanup_dir = project_dir or cwd
try:
return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True)
except FileNotFoundError:
if cmd[0] == "cdk":
click.echo("Error: 'cdk' is not installed.", err=True)
click.echo("", err=True)
click.echo("Install it with one of:", err=True)
click.echo(" npm install -g aws-cdk", err=True)
click.echo(" brew install aws-cdk", err=True)
else:
click.echo(f"Error: '{cmd[0]}' is not installed.", err=True)
sys.exit(1)
except subprocess.CalledProcessError as e:
click.echo(f"Error running: {' '.join(cmd)}", err=True)
if e.stderr:
click.echo(e.stderr, err=True)
click.echo("", err=True)
click.echo("To clean up the failed project:", err=True)
click.echo(f" rm -rf {cleanup_dir}", err=True)
sys.exit(1)
def _delete_cdk_artifacts(project_dir: Path) -> None:
"""Delete files generated by cdk init that we don't need.
Args:
project_dir: The project root directory.
"""
# Files to delete
for name in ("requirements.txt", "requirements-dev.txt", "source.bat", "README.md"):
path = project_dir / name
if path.exists():
path.unlink()
# CDK generates a stack module directory named after the project dir.
# e.g. gds-idea-app-foo → gds_idea_app_foo/gds_idea_app_foo_stack.py
# We replace it with our own app.py, so delete the whole thing.
dir_name = project_dir.name.replace("-", "_")
stack_module = project_dir / dir_name
if stack_module.is_dir():
shutil.rmtree(stack_module)
# CDK's generated app.py imports the stack module above -- delete it too.
cdk_app = project_dir / "app.py"
if cdk_app.exists():
cdk_app.unlink()
# CDK's generated tests/ directory
tests_dir = project_dir / "tests"
if tests_dir.is_dir():
shutil.rmtree(tests_dir)
def _write_webapp_config(project_dir: Path, app_name: str, framework: str) -> None:
"""Write [tool.webapp] section to pyproject.toml for AppConfig.from_pyproject().
Args:
project_dir: The project root directory.
app_name: The application name.
framework: The web framework.
"""
pyproject_path = project_dir / "pyproject.toml"
with open(pyproject_path) as f:
config = tomlkit.load(f)
if "tool" not in config:
config["tool"] = {}
webapp = tomlkit.table()
webapp.add("app_name", app_name)
webapp.add("framework", framework)
config["tool"]["webapp"] = webapp
with open(pyproject_path, "w") as f:
tomlkit.dump(config, f)
def run_init(framework: str, app_name: str, python_version: str) -> None:
"""Scaffold a new project.
Creates a fully configured CDK + web app project with the given framework.
The project directory will be named gds-idea-app-{app_name}.
Args:
framework: The web framework (streamlit, dash, fastapi).
app_name: Name for the application.
python_version: Python version for the project.
"""
# -- Validate inputs --
app_name = _sanitize_app_name(app_name)
repo_name = f"{REPO_PREFIX}-{app_name}"
project_dir = Path.cwd() / repo_name
if project_dir.exists():
click.echo(f"Error: Directory already exists: {project_dir}", err=True)
sys.exit(1)
# -- Check prerequisites before creating anything --
check_prerequisites()
click.echo(f"Scaffolding {framework} app: {app_name}")
click.echo(f" Directory: {repo_name}/")
click.echo(f" Python: {python_version}")
click.echo()
# -- Create directory and run cdk init (must be first, needs empty dir) --
project_dir.mkdir()
click.echo("Running cdk init...")
_run_command(
["cdk", "init", "app", "--language", "python", "--generate-only"],
cwd=project_dir,
project_dir=project_dir,
)
# -- Run uv init on top of cdk output --
click.echo("Running uv init...")
_run_command(["uv", "init", "--no-workspace"], cwd=project_dir, project_dir=project_dir)
# -- Clean up CDK artifacts we don't need --
click.echo("Cleaning up CDK artifacts...")
_delete_cdk_artifacts(project_dir)
# -- Prepare template variables --
python_version_nodot = python_version.replace(".", "")
template_vars = {
"app_name": app_name,
"python_version": python_version,
"python_version_nodot": python_version_nodot,
}
templates = _get_templates_dir()
# -- Copy app.py (CDK entry point) --
click.echo("Copying template files...")
_copy_template(templates / "common" / "app.py", project_dir / "app.py")
# -- Copy framework files into app_src/ --
app_src = project_dir / "app_src"
app_src.mkdir(exist_ok=True)
# Framework app file (e.g. streamlit_app.py)
framework_app = f"{framework}_app.py"
_copy_template(templates / framework / framework_app, app_src / framework_app)
# Dockerfile (has template vars for python version)
_copy_template(
templates / framework / "Dockerfile",
app_src / "Dockerfile",
variables=template_vars,
)
# App pyproject.toml (from .toml.template with substitution)
_copy_template(
templates / framework / "pyproject.toml.template",
app_src / "pyproject.toml",
variables=template_vars,
)
# -- Copy CI/CD workflow --
_copy_template(
templates / "common" / "ci_cd_cdk_app.yml",
project_dir / ".github" / "workflows" / "ci_cd_cdk_app.yml",
)
# -- Copy .devcontainer/ files --
_copy_template(
templates / "common" / "devcontainer.json",
project_dir / ".devcontainer" / "devcontainer.json",
)
_copy_template(
templates / "common" / "docker-compose.yml",
project_dir / ".devcontainer" / "docker-compose.yml",
)
# -- Copy dev_mocks/ --
dev_mocks_src = templates / "dev_mocks"
for mock_file in dev_mocks_src.iterdir():
if mock_file.is_file():
_copy_template(mock_file, project_dir / "dev_mocks" / mock_file.name)
# -- Append to .gitignore --
gitignore = project_dir / ".gitignore"
extra = (templates / "common" / "gitignore-extra").read_text()
with open(gitignore, "a") as f:
f.write("\n")
f.write(extra)
# -- Install CDK dependencies --
click.echo("Installing CDK dependencies...")
_run_command(
[
"uv",
"add",
"aws-cdk-lib",
"constructs",
"gds-idea-cdk-constructs @ git+ssh://git@github.com/co-cddo/gds-idea-cdk-constructs.git",
],
cwd=project_dir,
project_dir=project_dir,
)
# -- Write [tool.webapp] config for AppConfig.from_pyproject() --
click.echo("Writing project configuration...")
_write_webapp_config(project_dir, app_name, framework)
# -- Build and write manifest --
manifest = build_manifest(
framework=framework,
app_name=app_name,
tool_version=__version__,
project_dir=project_dir,
)
write_manifest(project_dir, manifest)
# -- Sync dependencies --
click.echo("Syncing dependencies...")
_run_command(["uv", "sync"], cwd=project_dir, project_dir=project_dir)
# -- Initial git commit --
click.echo("Creating initial commit...")
_run_command(["git", "add", "."], cwd=project_dir, project_dir=project_dir)
_run_command(
["git", "commit", "-m", f"Initial scaffold ({framework}, Python {python_version})"],
cwd=project_dir,
project_dir=project_dir,
)
# -- Print next steps --
click.echo()
click.echo(f"Project created: {repo_name}/")
click.echo()
click.echo("Next steps:")
click.echo(f" cd {repo_name}")
click.echo()
click.echo(" # Create the GitHub repo (requires gh CLI):")
click.echo(f" gh repo create {GITHUB_ORG}/{repo_name} --private --source . --push")
click.echo()
click.echo(" # Or add a remote manually:")
click.echo(f" git remote add origin git@github.com:{GITHUB_ORG}/{repo_name}.git")
click.echo(" git push -u origin main")