-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_project.py
More file actions
703 lines (614 loc) · 26.1 KB
/
setup_project.py
File metadata and controls
703 lines (614 loc) · 26.1 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#!/usr/bin/env python3
"""Post-clone setup script for the Claude Code Python Template.
Replaces placeholders in all template files with user-provided values.
Supports both interactive mode (for humans) and CLI mode (for Claude agents).
Usage:
Interactive: python setup_project.py
CLI: python setup_project.py --name my-project --namespace my_project
Monorepo: python setup_project.py --name my-project --namespace my_project --type mono --packages "api,core,client"
Single: python setup_project.py --name my-project --namespace my_project --type single
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
TEMPLATE_DIR = Path(__file__).parent
PLACEHOLDERS = {
"{{project_name}}": "",
"{{namespace}}": "",
"{{description}}": "",
"{{author_name}}": "",
"{{author_email}}": "",
"{{python_version}}": "",
"{{base_branch}}": "",
"{{year}}": "",
}
# Files to process for placeholder substitution
TEXT_EXTENSIONS = {
".py",
".toml",
".yml",
".yaml",
".md",
".json",
".cfg",
".ini",
".txt",
".sh",
".dockerfile",
".dockerignore",
".gitignore",
"",
}
# Files/dirs to skip
SKIP_PATHS = {".git", "__pycache__", ".venv", "venv", "node_modules", "uv.lock"}
def is_text_file(path: Path) -> bool:
"""Check if a file should be processed for placeholder substitution."""
return path.suffix.lower() in TEXT_EXTENSIONS or path.name in {
"Dockerfile",
"Makefile",
"LICENSE",
".gitignore",
".dockerignore",
}
def replace_in_file(filepath: Path, replacements: dict[str, str]) -> bool:
"""Replace placeholders in a single file. Returns True if changes were made."""
try:
content = filepath.read_text(encoding="utf-8")
except (UnicodeDecodeError, PermissionError):
return False
original = content
for placeholder, value in replacements.items():
content = content.replace(placeholder, value)
if content != original:
filepath.write_text(content, encoding="utf-8")
return True
return False
def rename_namespace_dirs(root: Path, namespace: str) -> list[str]:
"""Rename {{namespace}} directories to the actual namespace value."""
renamed = []
# Walk bottom-up so child renames happen before parent
for dirpath, dirnames, _filenames in os.walk(root, topdown=False):
for dirname in dirnames:
if dirname == "{{namespace}}":
old_path = Path(dirpath) / dirname
new_path = Path(dirpath) / namespace
if old_path.exists():
shutil.move(str(old_path), str(new_path))
renamed.append(f" {old_path} -> {new_path}")
return renamed
def flatten_to_single_package(root: Path, namespace: str) -> list[str]:
"""Convert monorepo layout to single-package layout.
Moves libs/core/ content to src/{{namespace}}/ and removes apps/libs structure.
"""
actions = []
src_dir = root / "src" / namespace
src_dir.mkdir(parents=True, exist_ok=True)
# Move core library code to src/
core_pkg = root / "libs" / "core" / namespace / "core"
if core_pkg.exists():
for item in core_pkg.iterdir():
dest = src_dir / item.name
shutil.move(str(item), str(dest))
actions.append(f" Moved {item} -> {dest}")
# Copy core init to src namespace init
core_init = root / "libs" / "core" / namespace
if core_init.exists():
init_file = core_init / "__init__.py"
if init_file.exists():
shutil.copy2(str(init_file), str(src_dir / "__init__.py"))
# Remove monorepo dirs
for d in ["apps", "libs"]:
target = root / d
if target.exists():
shutil.rmtree(str(target))
actions.append(f" Removed {d}/")
# Update root pyproject.toml - remove workspace config
pyproject = root / "pyproject.toml"
if pyproject.exists():
content = pyproject.read_text(encoding="utf-8")
# Remove workspace section
content = re.sub(
r"\[tool\.uv\.workspace\]\nmembers = \[.*?\]\n*",
"",
content,
flags=re.DOTALL,
)
# Update hatch build to point to src/
if "[tool.hatch.build.targets.wheel]" not in content:
content += '\n[tool.hatch.build.targets.wheel]\npackages = ["src/' + namespace + '"]\n'
pyproject.write_text(content, encoding="utf-8")
actions.append(" Updated pyproject.toml (removed workspace, added src build)")
# Update CI workflow - remove per-package test jobs
tests_yml = root / ".github" / "workflows" / "tests.yml"
if tests_yml.exists():
content = tests_yml.read_text(encoding="utf-8")
# Simplify to single test job
content = re.sub(
r" test-core:.*?(?= typecheck:)",
" test:\n"
" runs-on: ubuntu-latest\n"
" needs: lint\n"
" steps:\n"
" - uses: actions/checkout@v4\n"
" - uses: astral-sh/setup-uv@v5\n"
" with:\n"
' version: ">=0.5.0"\n'
" - uses: actions/setup-python@v5\n"
" with:\n"
' python-version: "3.11"\n'
" - name: Install dependencies\n"
" run: uv sync --all-packages --group dev\n"
" - name: Run tests\n"
" run: uv run pytest -v --tb=short\n\n",
content,
flags=re.DOTALL,
)
# Remove server test job
content = re.sub(r" test-server:.*?(?= typecheck:)", "", content, flags=re.DOTALL)
tests_yml.write_text(content, encoding="utf-8")
actions.append(" Simplified tests.yml for single-package layout")
# Remove Dockerfile (monorepo-specific)
dockerfile = root / "apps" / "server" / "Dockerfile"
if dockerfile.exists():
dockerfile.unlink()
actions.append(" Single-package layout complete: src/" + namespace + "/")
return actions
def _update_package_contents(pkg_path: Path, namespace: str, old_name: str, new_name: str) -> None:
"""Update pyproject.toml and __init__.py contents after a package directory rename.
Uses the ``-{name}`` pattern for pyproject.toml replacements to avoid false matches
(e.g. ``-core`` -> ``-engine`` is safe; bare ``core`` could match unrelated strings).
:param pkg_path: path to the renamed package directory (e.g. ``root/libs/engine``)
:param namespace: python namespace (e.g. ``vizier``)
:param old_name: original package name (e.g. ``core``)
:param new_name: new package name (e.g. ``engine``)
"""
toml_path = pkg_path / "pyproject.toml"
if toml_path.exists():
content = toml_path.read_text(encoding="utf-8")
content = content.replace(f"-{old_name}", f"-{new_name}")
content = content.replace(old_name.title(), new_name.title())
toml_path.write_text(content, encoding="utf-8")
init_path = pkg_path / namespace / new_name / "__init__.py"
if init_path.exists():
content = init_path.read_text(encoding="utf-8")
content = content.replace(old_name, new_name)
init_path.write_text(content, encoding="utf-8")
def rename_packages(root: Path, namespace: str, packages: list[str]) -> list[str]:
"""Rename example packages (core, server) to user-specified names.
After directory renames, updates pyproject.toml names/descriptions and __init__.py
docstrings. Also updates cross-references (e.g. app dependencies on renamed libs).
:param root: project root directory
:param namespace: python namespace (e.g. ``vizier``)
:param packages: list of package names, optionally prefixed with ``lib:`` or ``app:``
:return: list of action descriptions
"""
actions = []
# Map default packages to user packages
default_libs = ["core"]
default_apps = ["server"]
user_libs: list[str] = []
user_apps: list[str] = []
for pkg in packages:
pkg = pkg.strip()
if pkg.startswith("lib:"):
user_libs.append(pkg[4:])
elif pkg.startswith("app:"):
user_apps.append(pkg[4:])
else:
if not user_libs:
user_libs.append(pkg)
else:
user_apps.append(pkg)
# Track lib renames for cross-reference updates
lib_renames: list[tuple[str, str]] = []
# Rename lib packages
for old, new in zip(default_libs, user_libs, strict=False):
old_path = root / "libs" / old
new_path = root / "libs" / new
if old_path.exists() and old != new:
shutil.move(str(old_path), str(new_path))
old_inner = new_path / namespace / old
new_inner = new_path / namespace / new
if old_inner.exists():
shutil.move(str(old_inner), str(new_inner))
_update_package_contents(new_path, namespace, old, new)
lib_renames.append((old, new))
actions.append(f" libs/{old} -> libs/{new}")
# Rename app packages
for old, new in zip(default_apps, user_apps, strict=False):
old_path = root / "apps" / old
new_path = root / "apps" / new
if old_path.exists() and old != new:
shutil.move(str(old_path), str(new_path))
old_inner = new_path / namespace / old
new_inner = new_path / namespace / new
if old_inner.exists():
shutil.move(str(old_inner), str(new_inner))
_update_package_contents(new_path, namespace, old, new)
actions.append(f" apps/{old} -> apps/{new}")
# Update cross-references: app pyproject.toml files referencing renamed libs
if lib_renames:
apps_dir = root / "apps"
if apps_dir.exists():
for app_dir in apps_dir.iterdir():
if not app_dir.is_dir():
continue
toml_path = app_dir / "pyproject.toml"
if toml_path.exists():
content = toml_path.read_text(encoding="utf-8")
for old_lib, new_lib in lib_renames:
content = content.replace(f"-{old_lib}", f"-{new_lib}")
toml_path.write_text(content, encoding="utf-8")
# Create additional lib packages beyond the defaults
for lib in user_libs[len(default_libs) :]:
lib_path = root / "libs" / lib
pkg_path = lib_path / namespace / lib
pkg_path.mkdir(parents=True, exist_ok=True)
(pkg_path / "__init__.py").write_text(f'"""{lib} library."""\n\n__version__ = "0.1.0"\n')
core_toml = root / "libs" / (user_libs[0] if user_libs else "core") / "pyproject.toml"
if core_toml.exists():
content = core_toml.read_text(encoding="utf-8")
content = content.replace(f"-{user_libs[0]}", f"-{lib}")
content = content.replace(user_libs[0].title(), lib.title())
(lib_path / "pyproject.toml").write_text(content, encoding="utf-8")
tests_dir = lib_path / "tests"
tests_dir.mkdir(exist_ok=True)
(tests_dir / "__init__.py").write_text("")
actions.append(f" Created libs/{lib}/")
# Create additional app packages beyond the defaults
for app in user_apps[len(default_apps) :]:
app_path = root / "apps" / app
pkg_path = app_path / namespace / app
pkg_path.mkdir(parents=True, exist_ok=True)
(pkg_path / "__init__.py").write_text(f'"""{app} application."""\n\n__version__ = "0.1.0"\n')
first_app = user_apps[0] if user_apps else "server"
server_toml = root / "apps" / first_app / "pyproject.toml"
if server_toml.exists():
content = server_toml.read_text(encoding="utf-8")
content = content.replace(f"-{first_app}", f"-{app}")
content = content.replace(first_app.title(), app.title())
(app_path / "pyproject.toml").write_text(content, encoding="utf-8")
tests_dir = app_path / "tests"
tests_dir.mkdir(exist_ok=True)
(tests_dir / "__init__.py").write_text("")
actions.append(f" Created apps/{app}/")
return actions
# --- Docker Compose templates for devcontainer services ---
_COMPOSE_APP_BLOCK = """\
services:
app:
build:
context: .
dockerfile: Dockerfile
args:
TZ: ${TZ:-America/Los_Angeles}
CLAUDE_CODE_VERSION: latest
volumes:
- ..:/workspace:cached
command: sleep infinity
cap_add:
- NET_ADMIN
- NET_RAW
"""
COMPOSE_TEMPLATES: dict[str, str] = {
"postgres": _COMPOSE_APP_BLOCK
+ """\
environment:
- DATABASE_URL=postgres://{{namespace}}:{{namespace}}@db:5432/{{namespace}}
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-bookworm
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
POSTGRES_USER: {{namespace}}
POSTGRES_PASSWORD: {{namespace}}
POSTGRES_DB: {{namespace}}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U {{namespace}}"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres-data:
""",
"postgres-redis": _COMPOSE_APP_BLOCK
+ """\
environment:
- DATABASE_URL=postgres://{{namespace}}:{{namespace}}@db:5432/{{namespace}}
- REDIS_URL=redis://redis:6379/0
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
db:
image: postgres:16-bookworm
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
POSTGRES_USER: {{namespace}}
POSTGRES_PASSWORD: {{namespace}}
POSTGRES_DB: {{namespace}}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U {{namespace}}"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7-bookworm
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres-data:
""",
"custom": _COMPOSE_APP_BLOCK
+ """\
# Add environment variables, depends_on, and services below
""",
}
def configure_devcontainer_services(root: Path, services: str, replacements: dict[str, str]) -> list[str]:
"""Generate docker-compose.yml and update devcontainer.json for the chosen service profile.
:param root: project root directory
:param services: service profile name (postgres, postgres-redis, custom)
:param replacements: placeholder replacement map
:return: list of action descriptions
"""
actions = []
devcontainer_dir = root / ".devcontainer"
# Write docker-compose.yml from template
template = COMPOSE_TEMPLATES[services]
for placeholder, value in replacements.items():
template = template.replace(placeholder, value)
compose_path = devcontainer_dir / "docker-compose.yml"
compose_path.write_text(template, encoding="utf-8")
actions.append(f" Created .devcontainer/docker-compose.yml ({services} profile)")
# Rewrite devcontainer.json: switch from simple build to docker-compose mode
devcontainer_json = devcontainer_dir / "devcontainer.json"
if devcontainer_json.exists():
raw = devcontainer_json.read_text(encoding="utf-8")
try:
config = json.loads(raw)
except json.JSONDecodeError as exc:
print(f" Warning: Failed to parse devcontainer.json ({exc})")
print(" Hint: Remove JSON comments before running with --services")
return actions
# Remove simple-build keys
config.pop("build", None)
config.pop("runArgs", None)
config.pop("workspaceMount", None)
# Add compose keys (insert at position 1, after "name")
items = list(config.items())
new_items = [items[0]] # "name"
new_items.append(("dockerComposeFile", "docker-compose.yml"))
new_items.append(("service", "app"))
new_items.extend(items[1:])
config = dict(new_items)
devcontainer_json.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
actions.append(" Updated devcontainer.json for docker-compose mode")
return actions
def get_input(prompt: str, default: str = "") -> str:
"""Get user input with optional default."""
if default:
result = input(f"{prompt} [{default}]: ").strip()
return result if result else default
return input(f"{prompt}: ").strip()
def interactive_setup() -> dict[str, str]:
"""Collect configuration interactively."""
print("\n=== Claude Code Python Template Setup ===\n")
config = {}
config["project_name"] = get_input("Project name (e.g., my-project)")
config["namespace"] = get_input(
"Python namespace (e.g., my_project)",
config["project_name"].replace("-", "_"),
)
config["description"] = get_input("Short description", "A Python project")
config["author_name"] = get_input("Author name")
config["author_email"] = get_input("Author email")
config["python_version"] = get_input("Python version", "3.11")
config["base_branch"] = get_input("Base branch name", "master")
print("\nProject type:")
print(" 1. Monorepo (apps/ + libs/ with uv workspaces)")
print(" 2. Single package (src/ layout)")
choice = get_input("Choose [1/2]", "1")
config["type"] = "single" if choice == "2" else "mono"
if config["type"] == "mono":
packages = get_input(
"Package names (comma-separated, prefix with lib: or app:)",
"core,server",
)
config["packages"] = packages
print("\nDocker Compose services (for devcontainer):")
print(" 1. None (simple build, no extra services)")
print(" 2. PostgreSQL")
print(" 3. PostgreSQL + Redis")
print(" 4. Custom (skeleton -- add your own services)")
svc_choice = get_input("Choose [1/2/3/4]", "1")
svc_map = {"1": "none", "2": "postgres", "3": "postgres-redis", "4": "custom"}
config["services"] = svc_map.get(svc_choice, "none")
return config
def main() -> None:
"""Run the setup script."""
parser = argparse.ArgumentParser(description="Setup Claude Code Python Template")
parser.add_argument("--name", help="Project name (e.g., my-project)")
parser.add_argument("--namespace", help="Python namespace (e.g., my_project)")
parser.add_argument("--description", default="A Python project", help="Short description")
parser.add_argument("--author", default="", help="Author name")
parser.add_argument("--email", default="", help="Author email")
parser.add_argument("--python-version", default="3.11", help="Python version (default: 3.11)")
parser.add_argument("--base-branch", default="master", help="Base branch (default: master)")
parser.add_argument("--type", choices=["mono", "single"], default="mono", help="Project type")
parser.add_argument("--packages", default="core,server", help="Package names (comma-separated)")
parser.add_argument(
"--services",
choices=["none", "postgres", "postgres-redis", "custom"],
default="none",
help="Docker Compose services profile for devcontainer (default: none)",
)
parser.add_argument("--git-init", action="store_true", help="Initialize git and make initial commit")
parser.add_argument("--keep-setup", action="store_true", help="Don't delete this setup script after running")
args = parser.parse_args()
# Interactive mode if no name provided
if not args.name:
config = interactive_setup()
else:
config = {
"project_name": args.name,
"namespace": args.namespace or args.name.replace("-", "_"),
"description": args.description,
"author_name": args.author,
"author_email": args.email,
"python_version": args.python_version,
"base_branch": args.base_branch,
"type": args.type,
"packages": args.packages,
"services": args.services,
}
# Validate required fields
if not config.get("project_name"):
print("Error: Project name is required.")
sys.exit(1)
# Build replacements
replacements = {
"{{project_name}}": config["project_name"],
"{{namespace}}": config.get("namespace", config["project_name"].replace("-", "_")),
"{{description}}": config.get("description", "A Python project"),
"{{author_name}}": config.get("author_name", ""),
"{{author_email}}": config.get("author_email", ""),
"{{python_version}}": config.get("python_version", "3.11"),
"{{base_branch}}": config.get("base_branch", "master"),
"{{year}}": str(datetime.now().year),
}
namespace = replacements["{{namespace}}"]
print(f"\nSetting up project: {config['project_name']}")
print(f" Namespace: {namespace}")
print(f" Type: {config.get('type', 'mono')}")
print(f" Base branch: {config.get('base_branch', 'master')}")
print(f" Devcontainer services: {config.get('services', 'none')}")
# Step 1: Rename {{namespace}} directories
print("\nRenaming namespace directories...")
renamed = rename_namespace_dirs(TEMPLATE_DIR, namespace)
for r in renamed:
print(r)
# Step 2: Replace placeholders in all text files
print("\nReplacing placeholders...")
changed_count = 0
for dirpath, dirnames, filenames in os.walk(TEMPLATE_DIR):
# Skip hidden/build dirs
dirnames[:] = [d for d in dirnames if d not in SKIP_PATHS]
for filename in filenames:
filepath = Path(dirpath) / filename
if is_text_file(filepath) and replace_in_file(filepath, replacements):
changed_count += 1
print(f" Updated {changed_count} files")
# Step 2b: Make hook scripts executable
hooks_dir = TEMPLATE_DIR / ".claude" / "hooks"
if hooks_dir.exists():
hook_count = 0
for hook_file in hooks_dir.glob("*.sh"):
hook_file.chmod(hook_file.stat().st_mode | 0o755)
hook_count += 1
if hook_count:
print(f" Made {hook_count} hook scripts executable")
# Step 3: Handle project type
if config.get("type") == "single":
print("\nConverting to single-package layout...")
actions = flatten_to_single_package(TEMPLATE_DIR, namespace)
for a in actions:
print(a)
elif config.get("packages") and config["packages"] != "core,server":
print("\nRenaming packages...")
packages = [p.strip() for p in config["packages"].split(",")]
actions = rename_packages(TEMPLATE_DIR, namespace, packages)
for a in actions:
print(a)
# Step 4: Update CLAUDE.md package table
claude_md = TEMPLATE_DIR / "CLAUDE.md"
if claude_md.exists() and config.get("type") == "mono":
content = claude_md.read_text(encoding="utf-8")
packages = [p.strip() for p in config.get("packages", "core,server").split(",")]
table_lines = []
for pkg in packages:
pkg_clean = pkg.replace("lib:", "").replace("app:", "")
if pkg.startswith("lib:") or pkg == packages[0]:
table_lines.append(f"| **{pkg_clean}** | `libs/{pkg_clean}/` | {pkg_clean.title()} library |")
else:
table_lines.append(f"| **{pkg_clean}** | `apps/{pkg_clean}/` | {pkg_clean.title()} application |")
table_str = "\n".join(table_lines)
content = re.sub(
r"\| \*\*core\*\*.*?\| \*\*server\*\*.*?\|",
table_str,
content,
flags=re.DOTALL,
)
claude_md.write_text(content, encoding="utf-8")
# Step 5: Configure devcontainer services
services = config.get("services", "none")
if services != "none":
print(f"\nConfiguring devcontainer services ({services})...")
actions = configure_devcontainer_services(TEMPLATE_DIR, services, replacements)
for a in actions:
print(a)
# Step 6: Git init if requested
if getattr(args, "git_init", False):
print("\nInitializing git repository...")
try:
subprocess.run(["git", "init"], check=True, timeout=30)
subprocess.run(["git", "add", "-A"], check=True, timeout=30)
subprocess.run(
["git", "commit", "-m", "Initial project setup from Claude Code Python Template"],
check=True,
timeout=30,
)
print(" Git repository initialized with initial commit")
except subprocess.CalledProcessError as e:
print(f" Warning: Git operation failed: {' '.join(e.cmd)} (exit code {e.returncode})")
except subprocess.TimeoutExpired as e:
print(f" Warning: Git operation timed out after 30s: {' '.join(e.cmd)}")
# Step 7: Install Claude Code plugins
print("\nInstalling Claude Code plugins...")
if shutil.which("claude"):
try:
result = subprocess.run(
["claude", "plugin", "install", "security-guidance", "--scope", "project"],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
print(" Installed security-guidance plugin")
else:
print(" Warning: Failed to install security-guidance plugin")
print(" Run manually: claude plugin install security-guidance --scope project")
except subprocess.TimeoutExpired:
print(" Warning: Plugin installation timed out")
print(" Run manually: claude plugin install security-guidance --scope project")
else:
print(" Claude CLI not found -- install plugins after installing Claude Code:")
print(" claude plugin install security-guidance --scope project")
# Step 8: Self-delete unless --keep-setup
if not getattr(args, "keep_setup", False):
print(f"\nRemoving setup script ({Path(__file__).name})...")
print(" Run: rm setup_project.py")
print("\n=== Setup complete! ===")
print("\nNext steps:")
print(f" 1. cd {TEMPLATE_DIR}")
print(" 2. uv sync --all-packages --group dev")
print(" 3. uv run pytest")
print(" 4. Start coding!")
if __name__ == "__main__":
main()