doit-toolkit-cli 0.1.9__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.
Files changed (134) hide show
  1. doit_cli/__init__.py +1356 -0
  2. doit_cli/cli/__init__.py +26 -0
  3. doit_cli/cli/analytics_command.py +616 -0
  4. doit_cli/cli/context_command.py +213 -0
  5. doit_cli/cli/diagram_command.py +304 -0
  6. doit_cli/cli/fixit_command.py +641 -0
  7. doit_cli/cli/hooks_command.py +211 -0
  8. doit_cli/cli/init_command.py +613 -0
  9. doit_cli/cli/memory_command.py +293 -0
  10. doit_cli/cli/status_command.py +117 -0
  11. doit_cli/cli/sync_prompts_command.py +248 -0
  12. doit_cli/cli/validate_command.py +196 -0
  13. doit_cli/cli/verify_command.py +204 -0
  14. doit_cli/cli/workflow_mixin.py +224 -0
  15. doit_cli/cli/xref_command.py +555 -0
  16. doit_cli/formatters/__init__.py +8 -0
  17. doit_cli/formatters/base.py +38 -0
  18. doit_cli/formatters/json_formatter.py +126 -0
  19. doit_cli/formatters/markdown_formatter.py +97 -0
  20. doit_cli/formatters/rich_formatter.py +257 -0
  21. doit_cli/main.py +49 -0
  22. doit_cli/models/__init__.py +139 -0
  23. doit_cli/models/agent.py +74 -0
  24. doit_cli/models/analytics_models.py +384 -0
  25. doit_cli/models/context_config.py +464 -0
  26. doit_cli/models/crossref_models.py +182 -0
  27. doit_cli/models/diagram_models.py +363 -0
  28. doit_cli/models/fixit_models.py +355 -0
  29. doit_cli/models/hook_config.py +125 -0
  30. doit_cli/models/project.py +91 -0
  31. doit_cli/models/results.py +121 -0
  32. doit_cli/models/search_models.py +228 -0
  33. doit_cli/models/status_models.py +195 -0
  34. doit_cli/models/sync_models.py +146 -0
  35. doit_cli/models/template.py +77 -0
  36. doit_cli/models/validation_models.py +175 -0
  37. doit_cli/models/workflow_models.py +319 -0
  38. doit_cli/prompts/__init__.py +5 -0
  39. doit_cli/prompts/fixit_prompts.py +344 -0
  40. doit_cli/prompts/interactive.py +390 -0
  41. doit_cli/rules/__init__.py +5 -0
  42. doit_cli/rules/builtin_rules.py +160 -0
  43. doit_cli/services/__init__.py +79 -0
  44. doit_cli/services/agent_detector.py +168 -0
  45. doit_cli/services/analytics_service.py +218 -0
  46. doit_cli/services/architecture_generator.py +290 -0
  47. doit_cli/services/backup_service.py +204 -0
  48. doit_cli/services/config_loader.py +113 -0
  49. doit_cli/services/context_loader.py +1121 -0
  50. doit_cli/services/coverage_calculator.py +142 -0
  51. doit_cli/services/crossref_service.py +237 -0
  52. doit_cli/services/cycle_time_calculator.py +134 -0
  53. doit_cli/services/date_inferrer.py +349 -0
  54. doit_cli/services/diagram_service.py +337 -0
  55. doit_cli/services/drift_detector.py +109 -0
  56. doit_cli/services/entity_parser.py +301 -0
  57. doit_cli/services/er_diagram_generator.py +197 -0
  58. doit_cli/services/fixit_service.py +699 -0
  59. doit_cli/services/github_service.py +192 -0
  60. doit_cli/services/hook_manager.py +258 -0
  61. doit_cli/services/hook_validator.py +528 -0
  62. doit_cli/services/input_validator.py +322 -0
  63. doit_cli/services/memory_search.py +527 -0
  64. doit_cli/services/mermaid_validator.py +334 -0
  65. doit_cli/services/prompt_transformer.py +91 -0
  66. doit_cli/services/prompt_writer.py +133 -0
  67. doit_cli/services/query_interpreter.py +428 -0
  68. doit_cli/services/report_exporter.py +219 -0
  69. doit_cli/services/report_generator.py +256 -0
  70. doit_cli/services/requirement_parser.py +112 -0
  71. doit_cli/services/roadmap_summarizer.py +209 -0
  72. doit_cli/services/rule_engine.py +443 -0
  73. doit_cli/services/scaffolder.py +215 -0
  74. doit_cli/services/score_calculator.py +172 -0
  75. doit_cli/services/section_parser.py +204 -0
  76. doit_cli/services/spec_scanner.py +327 -0
  77. doit_cli/services/state_manager.py +355 -0
  78. doit_cli/services/status_reporter.py +143 -0
  79. doit_cli/services/task_parser.py +347 -0
  80. doit_cli/services/template_manager.py +710 -0
  81. doit_cli/services/template_reader.py +158 -0
  82. doit_cli/services/user_journey_generator.py +214 -0
  83. doit_cli/services/user_story_parser.py +232 -0
  84. doit_cli/services/validation_service.py +188 -0
  85. doit_cli/services/validator.py +232 -0
  86. doit_cli/services/velocity_tracker.py +173 -0
  87. doit_cli/services/workflow_engine.py +405 -0
  88. doit_cli/templates/agent-file-template.md +28 -0
  89. doit_cli/templates/checklist-template.md +39 -0
  90. doit_cli/templates/commands/doit.checkin.md +363 -0
  91. doit_cli/templates/commands/doit.constitution.md +187 -0
  92. doit_cli/templates/commands/doit.documentit.md +485 -0
  93. doit_cli/templates/commands/doit.fixit.md +181 -0
  94. doit_cli/templates/commands/doit.implementit.md +265 -0
  95. doit_cli/templates/commands/doit.planit.md +262 -0
  96. doit_cli/templates/commands/doit.reviewit.md +355 -0
  97. doit_cli/templates/commands/doit.roadmapit.md +368 -0
  98. doit_cli/templates/commands/doit.scaffoldit.md +458 -0
  99. doit_cli/templates/commands/doit.specit.md +521 -0
  100. doit_cli/templates/commands/doit.taskit.md +304 -0
  101. doit_cli/templates/commands/doit.testit.md +277 -0
  102. doit_cli/templates/config/context.yaml +134 -0
  103. doit_cli/templates/config/hooks.yaml +93 -0
  104. doit_cli/templates/config/validation-rules.yaml +64 -0
  105. doit_cli/templates/github-issue-templates/epic.yml +78 -0
  106. doit_cli/templates/github-issue-templates/feature.yml +116 -0
  107. doit_cli/templates/github-issue-templates/task.yml +129 -0
  108. doit_cli/templates/hooks/.gitkeep +0 -0
  109. doit_cli/templates/hooks/post-commit.sh +25 -0
  110. doit_cli/templates/hooks/post-merge.sh +75 -0
  111. doit_cli/templates/hooks/pre-commit.sh +17 -0
  112. doit_cli/templates/hooks/pre-push.sh +18 -0
  113. doit_cli/templates/memory/completed_roadmap.md +50 -0
  114. doit_cli/templates/memory/constitution.md +125 -0
  115. doit_cli/templates/memory/roadmap.md +61 -0
  116. doit_cli/templates/plan-template.md +146 -0
  117. doit_cli/templates/scripts/bash/check-prerequisites.sh +166 -0
  118. doit_cli/templates/scripts/bash/common.sh +156 -0
  119. doit_cli/templates/scripts/bash/create-new-feature.sh +297 -0
  120. doit_cli/templates/scripts/bash/setup-plan.sh +61 -0
  121. doit_cli/templates/scripts/bash/update-agent-context.sh +675 -0
  122. doit_cli/templates/scripts/powershell/check-prerequisites.ps1 +148 -0
  123. doit_cli/templates/scripts/powershell/common.ps1 +137 -0
  124. doit_cli/templates/scripts/powershell/create-new-feature.ps1 +283 -0
  125. doit_cli/templates/scripts/powershell/setup-plan.ps1 +61 -0
  126. doit_cli/templates/scripts/powershell/update-agent-context.ps1 +406 -0
  127. doit_cli/templates/spec-template.md +159 -0
  128. doit_cli/templates/tasks-template.md +313 -0
  129. doit_cli/templates/vscode-settings.json +14 -0
  130. doit_toolkit_cli-0.1.9.dist-info/METADATA +324 -0
  131. doit_toolkit_cli-0.1.9.dist-info/RECORD +134 -0
  132. doit_toolkit_cli-0.1.9.dist-info/WHEEL +4 -0
  133. doit_toolkit_cli-0.1.9.dist-info/entry_points.txt +2 -0
  134. doit_toolkit_cli-0.1.9.dist-info/licenses/LICENSE +21 -0
doit_cli/__init__.py ADDED
@@ -0,0 +1,1356 @@
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "typer",
6
+ # "rich",
7
+ # "platformdirs",
8
+ # "readchar",
9
+ # "httpx",
10
+ # ]
11
+ # ///
12
+ """
13
+ Doit CLI - Setup tool for Doit projects
14
+
15
+ Usage:
16
+ uvx doit-cli.py init <project-name>
17
+ uvx doit-cli.py init .
18
+ uvx doit-cli.py init --here
19
+
20
+ Or install globally:
21
+ uv tool install --from doit-cli.py doit-cli
22
+ doit init <project-name>
23
+ doit init .
24
+ doit init --here
25
+ """
26
+
27
+ import os
28
+ import subprocess
29
+ import sys
30
+ import zipfile
31
+ import tempfile
32
+ import shutil
33
+ import shlex
34
+ import json
35
+ from pathlib import Path
36
+ from typing import Optional, Tuple
37
+
38
+ import typer
39
+ import httpx
40
+ from rich.console import Console
41
+ from rich.panel import Panel
42
+ from rich.progress import Progress, SpinnerColumn, TextColumn
43
+ from rich.text import Text
44
+ from rich.live import Live
45
+ from rich.align import Align
46
+ from rich.table import Table
47
+ from rich.tree import Tree
48
+ from typer.core import TyperGroup
49
+
50
+ # For cross-platform keyboard input
51
+ import readchar
52
+ import ssl
53
+ import truststore
54
+ from datetime import datetime, timezone
55
+
56
+ ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
57
+ client = httpx.Client(verify=ssl_context)
58
+
59
+ def _github_token(cli_token: str | None = None) -> str | None:
60
+ """Return sanitized GitHub token (cli arg takes precedence) or None."""
61
+ return ((cli_token or os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN") or "").strip()) or None
62
+
63
+ def _github_auth_headers(cli_token: str | None = None) -> dict:
64
+ """Return Authorization header dict only when a non-empty token exists."""
65
+ token = _github_token(cli_token)
66
+ return {"Authorization": f"Bearer {token}"} if token else {}
67
+
68
+ def _parse_rate_limit_headers(headers: httpx.Headers) -> dict:
69
+ """Extract and parse GitHub rate-limit headers."""
70
+ info = {}
71
+
72
+ # Standard GitHub rate-limit headers
73
+ if "X-RateLimit-Limit" in headers:
74
+ info["limit"] = headers.get("X-RateLimit-Limit")
75
+ if "X-RateLimit-Remaining" in headers:
76
+ info["remaining"] = headers.get("X-RateLimit-Remaining")
77
+ if "X-RateLimit-Reset" in headers:
78
+ reset_epoch = int(headers.get("X-RateLimit-Reset", "0"))
79
+ if reset_epoch:
80
+ reset_time = datetime.fromtimestamp(reset_epoch, tz=timezone.utc)
81
+ info["reset_epoch"] = reset_epoch
82
+ info["reset_time"] = reset_time
83
+ info["reset_local"] = reset_time.astimezone()
84
+
85
+ # Retry-After header (seconds or HTTP-date)
86
+ if "Retry-After" in headers:
87
+ retry_after = headers.get("Retry-After")
88
+ try:
89
+ info["retry_after_seconds"] = int(retry_after)
90
+ except ValueError:
91
+ # HTTP-date format - not implemented, just store as string
92
+ info["retry_after"] = retry_after
93
+
94
+ return info
95
+
96
+ def _format_rate_limit_error(status_code: int, headers: httpx.Headers, url: str) -> str:
97
+ """Format a user-friendly error message with rate-limit information."""
98
+ rate_info = _parse_rate_limit_headers(headers)
99
+
100
+ lines = [f"GitHub API returned status {status_code} for {url}"]
101
+ lines.append("")
102
+
103
+ if rate_info:
104
+ lines.append("[bold]Rate Limit Information:[/bold]")
105
+ if "limit" in rate_info:
106
+ lines.append(f" • Rate Limit: {rate_info['limit']} requests/hour")
107
+ if "remaining" in rate_info:
108
+ lines.append(f" • Remaining: {rate_info['remaining']}")
109
+ if "reset_local" in rate_info:
110
+ reset_str = rate_info["reset_local"].strftime("%Y-%m-%d %H:%M:%S %Z")
111
+ lines.append(f" • Resets at: {reset_str}")
112
+ if "retry_after_seconds" in rate_info:
113
+ lines.append(f" • Retry after: {rate_info['retry_after_seconds']} seconds")
114
+ lines.append("")
115
+
116
+ # Add troubleshooting guidance
117
+ lines.append("[bold]Troubleshooting Tips:[/bold]")
118
+ lines.append(" • If you're on a shared CI or corporate environment, you may be rate-limited.")
119
+ lines.append(" • Consider using a GitHub token via --github-token or the GH_TOKEN/GITHUB_TOKEN")
120
+ lines.append(" environment variable to increase rate limits.")
121
+ lines.append(" • Authenticated requests have a limit of 5,000/hour vs 60/hour for unauthenticated.")
122
+
123
+ return "\n".join(lines)
124
+
125
+ # Agent configuration with name, folder, install URL, and CLI tool requirement
126
+ AGENT_CONFIG = {
127
+ "copilot": {
128
+ "name": "GitHub Copilot",
129
+ "folder": ".github/",
130
+ "install_url": None, # IDE-based, no CLI check needed
131
+ "requires_cli": False,
132
+ },
133
+ "claude": {
134
+ "name": "Claude Code",
135
+ "folder": ".claude/",
136
+ "install_url": "https://docs.anthropic.com/en/docs/claude-code/setup",
137
+ "requires_cli": True,
138
+ },
139
+ "gemini": {
140
+ "name": "Gemini CLI",
141
+ "folder": ".gemini/",
142
+ "install_url": "https://github.com/google-gemini/gemini-cli",
143
+ "requires_cli": True,
144
+ },
145
+ "cursor-agent": {
146
+ "name": "Cursor",
147
+ "folder": ".cursor/",
148
+ "install_url": None, # IDE-based
149
+ "requires_cli": False,
150
+ },
151
+ "qwen": {
152
+ "name": "Qwen Code",
153
+ "folder": ".qwen/",
154
+ "install_url": "https://github.com/QwenLM/qwen-code",
155
+ "requires_cli": True,
156
+ },
157
+ "opencode": {
158
+ "name": "opencode",
159
+ "folder": ".opencode/",
160
+ "install_url": "https://opencode.ai",
161
+ "requires_cli": True,
162
+ },
163
+ "codex": {
164
+ "name": "Codex CLI",
165
+ "folder": ".codex/",
166
+ "install_url": "https://github.com/openai/codex",
167
+ "requires_cli": True,
168
+ },
169
+ "windsurf": {
170
+ "name": "Windsurf",
171
+ "folder": ".windsurf/",
172
+ "install_url": None, # IDE-based
173
+ "requires_cli": False,
174
+ },
175
+ "kilocode": {
176
+ "name": "Kilo Code",
177
+ "folder": ".kilocode/",
178
+ "install_url": None, # IDE-based
179
+ "requires_cli": False,
180
+ },
181
+ "auggie": {
182
+ "name": "Auggie CLI",
183
+ "folder": ".augment/",
184
+ "install_url": "https://docs.augmentcode.com/cli/setup-auggie/install-auggie-cli",
185
+ "requires_cli": True,
186
+ },
187
+ "codebuddy": {
188
+ "name": "CodeBuddy",
189
+ "folder": ".codebuddy/",
190
+ "install_url": "https://www.codebuddy.ai/cli",
191
+ "requires_cli": True,
192
+ },
193
+ "qoder": {
194
+ "name": "Qoder CLI",
195
+ "folder": ".qoder/",
196
+ "install_url": "https://qoder.com/cli",
197
+ "requires_cli": True,
198
+ },
199
+ "roo": {
200
+ "name": "Roo Code",
201
+ "folder": ".roo/",
202
+ "install_url": None, # IDE-based
203
+ "requires_cli": False,
204
+ },
205
+ "q": {
206
+ "name": "Amazon Q Developer CLI",
207
+ "folder": ".amazonq/",
208
+ "install_url": "https://aws.amazon.com/developer/learning/q-developer-cli/",
209
+ "requires_cli": True,
210
+ },
211
+ "amp": {
212
+ "name": "Amp",
213
+ "folder": ".agents/",
214
+ "install_url": "https://ampcode.com/manual#install",
215
+ "requires_cli": True,
216
+ },
217
+ "shai": {
218
+ "name": "SHAI",
219
+ "folder": ".shai/",
220
+ "install_url": "https://github.com/ovh/shai",
221
+ "requires_cli": True,
222
+ },
223
+ "bob": {
224
+ "name": "IBM Bob",
225
+ "folder": ".bob/",
226
+ "install_url": None, # IDE-based
227
+ "requires_cli": False,
228
+ },
229
+ }
230
+
231
+ SCRIPT_TYPE_CHOICES = {"sh": "POSIX Shell (bash/zsh)", "ps": "PowerShell"}
232
+
233
+ CLAUDE_LOCAL_PATH = Path.home() / ".claude" / "local" / "claude"
234
+
235
+ BANNER = """
236
+ ██████╗ ██████╗ ██╗████████╗
237
+ ██╔══██╗██╔═══██╗██║╚══██╔══╝
238
+ ██║ ██║██║ ██║██║ ██║
239
+ ██║ ██║██║ ██║██║ ██║
240
+ ██████╔╝╚██████╔╝██║ ██║
241
+ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝
242
+ """
243
+
244
+ TAGLINE = "DoIt - Spec-Driven Development Toolkit"
245
+ class StepTracker:
246
+ """Track and render hierarchical steps without emojis, similar to Claude Code tree output.
247
+ Supports live auto-refresh via an attached refresh callback.
248
+ """
249
+ def __init__(self, title: str):
250
+ self.title = title
251
+ self.steps = [] # list of dicts: {key, label, status, detail}
252
+ self.status_order = {"pending": 0, "running": 1, "done": 2, "error": 3, "skipped": 4}
253
+ self._refresh_cb = None # callable to trigger UI refresh
254
+
255
+ def attach_refresh(self, cb):
256
+ self._refresh_cb = cb
257
+
258
+ def add(self, key: str, label: str):
259
+ if key not in [s["key"] for s in self.steps]:
260
+ self.steps.append({"key": key, "label": label, "status": "pending", "detail": ""})
261
+ self._maybe_refresh()
262
+
263
+ def start(self, key: str, detail: str = ""):
264
+ self._update(key, status="running", detail=detail)
265
+
266
+ def complete(self, key: str, detail: str = ""):
267
+ self._update(key, status="done", detail=detail)
268
+
269
+ def error(self, key: str, detail: str = ""):
270
+ self._update(key, status="error", detail=detail)
271
+
272
+ def skip(self, key: str, detail: str = ""):
273
+ self._update(key, status="skipped", detail=detail)
274
+
275
+ def _update(self, key: str, status: str, detail: str):
276
+ for s in self.steps:
277
+ if s["key"] == key:
278
+ s["status"] = status
279
+ if detail:
280
+ s["detail"] = detail
281
+ self._maybe_refresh()
282
+ return
283
+
284
+ self.steps.append({"key": key, "label": key, "status": status, "detail": detail})
285
+ self._maybe_refresh()
286
+
287
+ def _maybe_refresh(self):
288
+ if self._refresh_cb:
289
+ try:
290
+ self._refresh_cb()
291
+ except Exception:
292
+ pass
293
+
294
+ def render(self):
295
+ tree = Tree(f"[cyan]{self.title}[/cyan]", guide_style="grey50")
296
+ for step in self.steps:
297
+ label = step["label"]
298
+ detail_text = step["detail"].strip() if step["detail"] else ""
299
+
300
+ status = step["status"]
301
+ if status == "done":
302
+ symbol = "[green]●[/green]"
303
+ elif status == "pending":
304
+ symbol = "[green dim]○[/green dim]"
305
+ elif status == "running":
306
+ symbol = "[cyan]○[/cyan]"
307
+ elif status == "error":
308
+ symbol = "[red]●[/red]"
309
+ elif status == "skipped":
310
+ symbol = "[yellow]○[/yellow]"
311
+ else:
312
+ symbol = " "
313
+
314
+ if status == "pending":
315
+ # Entire line light gray (pending)
316
+ if detail_text:
317
+ line = f"{symbol} [bright_black]{label} ({detail_text})[/bright_black]"
318
+ else:
319
+ line = f"{symbol} [bright_black]{label}[/bright_black]"
320
+ else:
321
+ # Label white, detail (if any) light gray in parentheses
322
+ if detail_text:
323
+ line = f"{symbol} [white]{label}[/white] [bright_black]({detail_text})[/bright_black]"
324
+ else:
325
+ line = f"{symbol} [white]{label}[/white]"
326
+
327
+ tree.add(line)
328
+ return tree
329
+
330
+ def get_key():
331
+ """Get a single keypress in a cross-platform way using readchar."""
332
+ key = readchar.readkey()
333
+
334
+ if key == readchar.key.UP or key == readchar.key.CTRL_P:
335
+ return 'up'
336
+ if key == readchar.key.DOWN or key == readchar.key.CTRL_N:
337
+ return 'down'
338
+
339
+ if key == readchar.key.ENTER:
340
+ return 'enter'
341
+
342
+ if key == readchar.key.ESC:
343
+ return 'escape'
344
+
345
+ if key == readchar.key.CTRL_C:
346
+ raise KeyboardInterrupt
347
+
348
+ return key
349
+
350
+ def select_with_arrows(options: dict, prompt_text: str = "Select an option", default_key: str = None) -> str:
351
+ """
352
+ Interactive selection using arrow keys with Rich Live display.
353
+
354
+ Args:
355
+ options: Dict with keys as option keys and values as descriptions
356
+ prompt_text: Text to show above the options
357
+ default_key: Default option key to start with
358
+
359
+ Returns:
360
+ Selected option key
361
+ """
362
+ option_keys = list(options.keys())
363
+ if default_key and default_key in option_keys:
364
+ selected_index = option_keys.index(default_key)
365
+ else:
366
+ selected_index = 0
367
+
368
+ selected_key = None
369
+
370
+ def create_selection_panel():
371
+ """Create the selection panel with current selection highlighted."""
372
+ table = Table.grid(padding=(0, 2))
373
+ table.add_column(style="cyan", justify="left", width=3)
374
+ table.add_column(style="white", justify="left")
375
+
376
+ for i, key in enumerate(option_keys):
377
+ if i == selected_index:
378
+ table.add_row("▶", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]")
379
+ else:
380
+ table.add_row(" ", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]")
381
+
382
+ table.add_row("", "")
383
+ table.add_row("", "[dim]Use ↑/↓ to navigate, Enter to select, Esc to cancel[/dim]")
384
+
385
+ return Panel(
386
+ table,
387
+ title=f"[bold]{prompt_text}[/bold]",
388
+ border_style="cyan",
389
+ padding=(1, 2)
390
+ )
391
+
392
+ console.print()
393
+
394
+ def run_selection_loop():
395
+ nonlocal selected_key, selected_index
396
+ with Live(create_selection_panel(), console=console, transient=True, auto_refresh=False) as live:
397
+ while True:
398
+ try:
399
+ key = get_key()
400
+ if key == 'up':
401
+ selected_index = (selected_index - 1) % len(option_keys)
402
+ elif key == 'down':
403
+ selected_index = (selected_index + 1) % len(option_keys)
404
+ elif key == 'enter':
405
+ selected_key = option_keys[selected_index]
406
+ break
407
+ elif key == 'escape':
408
+ console.print("\n[yellow]Selection cancelled[/yellow]")
409
+ raise typer.Exit(1)
410
+
411
+ live.update(create_selection_panel(), refresh=True)
412
+
413
+ except KeyboardInterrupt:
414
+ console.print("\n[yellow]Selection cancelled[/yellow]")
415
+ raise typer.Exit(1)
416
+
417
+ run_selection_loop()
418
+
419
+ if selected_key is None:
420
+ console.print("\n[red]Selection failed.[/red]")
421
+ raise typer.Exit(1)
422
+
423
+ return selected_key
424
+
425
+ console = Console()
426
+
427
+ class BannerGroup(TyperGroup):
428
+ """Custom group that shows banner before help."""
429
+
430
+ def format_help(self, ctx, formatter):
431
+ # Show banner before help
432
+ show_banner()
433
+ super().format_help(ctx, formatter)
434
+
435
+
436
+ app = typer.Typer(
437
+ name="doit",
438
+ help="Setup tool for Doit spec-driven development projects",
439
+ add_completion=False,
440
+ invoke_without_command=True,
441
+ cls=BannerGroup,
442
+ )
443
+
444
+ def show_banner():
445
+ """Display the ASCII art banner."""
446
+ banner_lines = BANNER.strip().split('\n')
447
+ colors = ["bright_blue", "blue", "cyan", "bright_cyan", "white", "bright_white"]
448
+
449
+ styled_banner = Text()
450
+ for i, line in enumerate(banner_lines):
451
+ color = colors[i % len(colors)]
452
+ styled_banner.append(line + "\n", style=color)
453
+
454
+ console.print(Align.center(styled_banner))
455
+ console.print(Align.center(Text(TAGLINE, style="italic bright_yellow")))
456
+ console.print()
457
+
458
+ @app.callback()
459
+ def callback(ctx: typer.Context):
460
+ """Show banner when no subcommand is provided."""
461
+ if ctx.invoked_subcommand is None and "--help" not in sys.argv and "-h" not in sys.argv:
462
+ show_banner()
463
+ console.print(Align.center("[dim]Run 'doit --help' for usage information[/dim]"))
464
+ console.print()
465
+
466
+ def run_command(cmd: list[str], check_return: bool = True, capture: bool = False, shell: bool = False) -> Optional[str]:
467
+ """Run a shell command and optionally capture output."""
468
+ try:
469
+ if capture:
470
+ result = subprocess.run(cmd, check=check_return, capture_output=True, text=True, shell=shell)
471
+ return result.stdout.strip()
472
+ else:
473
+ subprocess.run(cmd, check=check_return, shell=shell)
474
+ return None
475
+ except subprocess.CalledProcessError as e:
476
+ if check_return:
477
+ console.print(f"[red]Error running command:[/red] {' '.join(cmd)}")
478
+ console.print(f"[red]Exit code:[/red] {e.returncode}")
479
+ if hasattr(e, 'stderr') and e.stderr:
480
+ console.print(f"[red]Error output:[/red] {e.stderr}")
481
+ raise
482
+ return None
483
+
484
+ def check_tool(tool: str, tracker: StepTracker = None) -> bool:
485
+ """Check if a tool is installed. Optionally update tracker.
486
+
487
+ Args:
488
+ tool: Name of the tool to check
489
+ tracker: Optional StepTracker to update with results
490
+
491
+ Returns:
492
+ True if tool is found, False otherwise
493
+ """
494
+ if tool == "claude":
495
+ if CLAUDE_LOCAL_PATH.exists() and CLAUDE_LOCAL_PATH.is_file():
496
+ if tracker:
497
+ tracker.complete(tool, "available")
498
+ return True
499
+
500
+ found = shutil.which(tool) is not None
501
+
502
+ if tracker:
503
+ if found:
504
+ tracker.complete(tool, "available")
505
+ else:
506
+ tracker.error(tool, "not found")
507
+
508
+ return found
509
+
510
+ def is_git_repo(path: Path = None) -> bool:
511
+ """Check if the specified path is inside a git repository."""
512
+ if path is None:
513
+ path = Path.cwd()
514
+
515
+ if not path.is_dir():
516
+ return False
517
+
518
+ try:
519
+ # Use git command to check if inside a work tree
520
+ subprocess.run(
521
+ ["git", "rev-parse", "--is-inside-work-tree"],
522
+ check=True,
523
+ capture_output=True,
524
+ cwd=path,
525
+ )
526
+ return True
527
+ except (subprocess.CalledProcessError, FileNotFoundError):
528
+ return False
529
+
530
+ def init_git_repo(project_path: Path, quiet: bool = False) -> Tuple[bool, Optional[str]]:
531
+ """Initialize a git repository in the specified path.
532
+
533
+ Args:
534
+ project_path: Path to initialize git repository in
535
+ quiet: if True suppress console output (tracker handles status)
536
+
537
+ Returns:
538
+ Tuple of (success: bool, error_message: Optional[str])
539
+ """
540
+ try:
541
+ original_cwd = Path.cwd()
542
+ os.chdir(project_path)
543
+ if not quiet:
544
+ console.print("[cyan]Initializing git repository...[/cyan]")
545
+ subprocess.run(["git", "init"], check=True, capture_output=True, text=True)
546
+ subprocess.run(["git", "add", "."], check=True, capture_output=True, text=True)
547
+ subprocess.run(["git", "commit", "-m", "Initial commit from Doit template"], check=True, capture_output=True, text=True)
548
+ if not quiet:
549
+ console.print("[green]✓[/green] Git repository initialized")
550
+ return True, None
551
+
552
+ except subprocess.CalledProcessError as e:
553
+ error_msg = f"Command: {' '.join(e.cmd)}\nExit code: {e.returncode}"
554
+ if e.stderr:
555
+ error_msg += f"\nError: {e.stderr.strip()}"
556
+ elif e.stdout:
557
+ error_msg += f"\nOutput: {e.stdout.strip()}"
558
+
559
+ if not quiet:
560
+ console.print(f"[red]Error initializing git repository:[/red] {e}")
561
+ return False, error_msg
562
+ finally:
563
+ os.chdir(original_cwd)
564
+
565
+ def handle_vscode_settings(sub_item, dest_file, rel_path, verbose=False, tracker=None) -> None:
566
+ """Handle merging or copying of .vscode/settings.json files."""
567
+ def log(message, color="green"):
568
+ if verbose and not tracker:
569
+ console.print(f"[{color}]{message}[/] {rel_path}")
570
+
571
+ try:
572
+ with open(sub_item, 'r', encoding='utf-8') as f:
573
+ new_settings = json.load(f)
574
+
575
+ if dest_file.exists():
576
+ merged = merge_json_files(dest_file, new_settings, verbose=verbose and not tracker)
577
+ with open(dest_file, 'w', encoding='utf-8') as f:
578
+ json.dump(merged, f, indent=4)
579
+ f.write('\n')
580
+ log("Merged:", "green")
581
+ else:
582
+ shutil.copy2(sub_item, dest_file)
583
+ log("Copied (no existing settings.json):", "blue")
584
+
585
+ except Exception as e:
586
+ log(f"Warning: Could not merge, copying instead: {e}", "yellow")
587
+ shutil.copy2(sub_item, dest_file)
588
+
589
+ def merge_json_files(existing_path: Path, new_content: dict, verbose: bool = False) -> dict:
590
+ """Merge new JSON content into existing JSON file.
591
+
592
+ Performs a deep merge where:
593
+ - New keys are added
594
+ - Existing keys are preserved unless overwritten by new content
595
+ - Nested dictionaries are merged recursively
596
+ - Lists and other values are replaced (not merged)
597
+
598
+ Args:
599
+ existing_path: Path to existing JSON file
600
+ new_content: New JSON content to merge in
601
+ verbose: Whether to print merge details
602
+
603
+ Returns:
604
+ Merged JSON content as dict
605
+ """
606
+ try:
607
+ with open(existing_path, 'r', encoding='utf-8') as f:
608
+ existing_content = json.load(f)
609
+ except (FileNotFoundError, json.JSONDecodeError):
610
+ # If file doesn't exist or is invalid, just use new content
611
+ return new_content
612
+
613
+ def deep_merge(base: dict, update: dict) -> dict:
614
+ """Recursively merge update dict into base dict."""
615
+ result = base.copy()
616
+ for key, value in update.items():
617
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
618
+ # Recursively merge nested dictionaries
619
+ result[key] = deep_merge(result[key], value)
620
+ else:
621
+ # Add new key or replace existing value
622
+ result[key] = value
623
+ return result
624
+
625
+ merged = deep_merge(existing_content, new_content)
626
+
627
+ if verbose:
628
+ console.print(f"[cyan]Merged JSON file:[/cyan] {existing_path.name}")
629
+
630
+ return merged
631
+
632
+ def download_template_from_github(ai_assistant: str, download_dir: Path, *, script_type: str = "sh", verbose: bool = True, show_progress: bool = True, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Tuple[Path, dict]:
633
+ repo_owner = "seanbarlow"
634
+ repo_name = "doit"
635
+ if client is None:
636
+ client = httpx.Client(verify=ssl_context)
637
+
638
+ if verbose:
639
+ console.print("[cyan]Fetching latest release information...[/cyan]")
640
+ api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
641
+
642
+ try:
643
+ response = client.get(
644
+ api_url,
645
+ timeout=30,
646
+ follow_redirects=True,
647
+ headers=_github_auth_headers(github_token),
648
+ )
649
+ status = response.status_code
650
+ if status != 200:
651
+ # Format detailed error message with rate-limit info
652
+ error_msg = _format_rate_limit_error(status, response.headers, api_url)
653
+ if debug:
654
+ error_msg += f"\n\n[dim]Response body (truncated 500):[/dim]\n{response.text[:500]}"
655
+ raise RuntimeError(error_msg)
656
+ try:
657
+ release_data = response.json()
658
+ except ValueError as je:
659
+ raise RuntimeError(f"Failed to parse release JSON: {je}\nRaw (truncated 400): {response.text[:400]}")
660
+ except Exception as e:
661
+ console.print(f"[red]Error fetching release information[/red]")
662
+ console.print(Panel(str(e), title="Fetch Error", border_style="red"))
663
+ raise typer.Exit(1)
664
+
665
+ assets = release_data.get("assets", [])
666
+ pattern = f"doit-template-{ai_assistant}-{script_type}"
667
+ matching_assets = [
668
+ asset for asset in assets
669
+ if pattern in asset["name"] and asset["name"].endswith(".zip")
670
+ ]
671
+
672
+ asset = matching_assets[0] if matching_assets else None
673
+
674
+ if asset is None:
675
+ console.print(f"[red]No matching release asset found[/red] for [bold]{ai_assistant}[/bold] (expected pattern: [bold]{pattern}[/bold])")
676
+ asset_names = [a.get('name', '?') for a in assets]
677
+ console.print(Panel("\n".join(asset_names) or "(no assets)", title="Available Assets", border_style="yellow"))
678
+ raise typer.Exit(1)
679
+
680
+ download_url = asset["browser_download_url"]
681
+ filename = asset["name"]
682
+ file_size = asset["size"]
683
+
684
+ if verbose:
685
+ console.print(f"[cyan]Found template:[/cyan] {filename}")
686
+ console.print(f"[cyan]Size:[/cyan] {file_size:,} bytes")
687
+ console.print(f"[cyan]Release:[/cyan] {release_data['tag_name']}")
688
+
689
+ zip_path = download_dir / filename
690
+ if verbose:
691
+ console.print(f"[cyan]Downloading template...[/cyan]")
692
+
693
+ try:
694
+ with client.stream(
695
+ "GET",
696
+ download_url,
697
+ timeout=60,
698
+ follow_redirects=True,
699
+ headers=_github_auth_headers(github_token),
700
+ ) as response:
701
+ if response.status_code != 200:
702
+ # Handle rate-limiting on download as well
703
+ error_msg = _format_rate_limit_error(response.status_code, response.headers, download_url)
704
+ if debug:
705
+ error_msg += f"\n\n[dim]Response body (truncated 400):[/dim]\n{response.text[:400]}"
706
+ raise RuntimeError(error_msg)
707
+ total_size = int(response.headers.get('content-length', 0))
708
+ with open(zip_path, 'wb') as f:
709
+ if total_size == 0:
710
+ for chunk in response.iter_bytes(chunk_size=8192):
711
+ f.write(chunk)
712
+ else:
713
+ if show_progress:
714
+ with Progress(
715
+ SpinnerColumn(),
716
+ TextColumn("[progress.description]{task.description}"),
717
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
718
+ console=console,
719
+ ) as progress:
720
+ task = progress.add_task("Downloading...", total=total_size)
721
+ downloaded = 0
722
+ for chunk in response.iter_bytes(chunk_size=8192):
723
+ f.write(chunk)
724
+ downloaded += len(chunk)
725
+ progress.update(task, completed=downloaded)
726
+ else:
727
+ for chunk in response.iter_bytes(chunk_size=8192):
728
+ f.write(chunk)
729
+ except Exception as e:
730
+ console.print(f"[red]Error downloading template[/red]")
731
+ detail = str(e)
732
+ if zip_path.exists():
733
+ zip_path.unlink()
734
+ console.print(Panel(detail, title="Download Error", border_style="red"))
735
+ raise typer.Exit(1)
736
+ if verbose:
737
+ console.print(f"Downloaded: {filename}")
738
+ metadata = {
739
+ "filename": filename,
740
+ "size": file_size,
741
+ "release": release_data["tag_name"],
742
+ "asset_url": download_url
743
+ }
744
+ return zip_path, metadata
745
+
746
+ def download_and_extract_template(project_path: Path, ai_assistant: str, script_type: str, is_current_dir: bool = False, *, verbose: bool = True, tracker: StepTracker | None = None, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Path:
747
+ """Download the latest release and extract it to create a new project.
748
+ Returns project_path. Uses tracker if provided (with keys: fetch, download, extract, cleanup)
749
+ """
750
+ current_dir = Path.cwd()
751
+
752
+ if tracker:
753
+ tracker.start("fetch", "contacting GitHub API")
754
+ try:
755
+ zip_path, meta = download_template_from_github(
756
+ ai_assistant,
757
+ current_dir,
758
+ script_type=script_type,
759
+ verbose=verbose and tracker is None,
760
+ show_progress=(tracker is None),
761
+ client=client,
762
+ debug=debug,
763
+ github_token=github_token
764
+ )
765
+ if tracker:
766
+ tracker.complete("fetch", f"release {meta['release']} ({meta['size']:,} bytes)")
767
+ tracker.add("download", "Download template")
768
+ tracker.complete("download", meta['filename'])
769
+ except Exception as e:
770
+ if tracker:
771
+ tracker.error("fetch", str(e))
772
+ else:
773
+ if verbose:
774
+ console.print(f"[red]Error downloading template:[/red] {e}")
775
+ raise
776
+
777
+ if tracker:
778
+ tracker.add("extract", "Extract template")
779
+ tracker.start("extract")
780
+ elif verbose:
781
+ console.print("Extracting template...")
782
+
783
+ try:
784
+ if not is_current_dir:
785
+ project_path.mkdir(parents=True)
786
+
787
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
788
+ zip_contents = zip_ref.namelist()
789
+ if tracker:
790
+ tracker.start("zip-list")
791
+ tracker.complete("zip-list", f"{len(zip_contents)} entries")
792
+ elif verbose:
793
+ console.print(f"[cyan]ZIP contains {len(zip_contents)} items[/cyan]")
794
+
795
+ if is_current_dir:
796
+ with tempfile.TemporaryDirectory() as temp_dir:
797
+ temp_path = Path(temp_dir)
798
+ zip_ref.extractall(temp_path)
799
+
800
+ extracted_items = list(temp_path.iterdir())
801
+ if tracker:
802
+ tracker.start("extracted-summary")
803
+ tracker.complete("extracted-summary", f"temp {len(extracted_items)} items")
804
+ elif verbose:
805
+ console.print(f"[cyan]Extracted {len(extracted_items)} items to temp location[/cyan]")
806
+
807
+ source_dir = temp_path
808
+ if len(extracted_items) == 1 and extracted_items[0].is_dir():
809
+ source_dir = extracted_items[0]
810
+ if tracker:
811
+ tracker.add("flatten", "Flatten nested directory")
812
+ tracker.complete("flatten")
813
+ elif verbose:
814
+ console.print(f"[cyan]Found nested directory structure[/cyan]")
815
+
816
+ for item in source_dir.iterdir():
817
+ dest_path = project_path / item.name
818
+ if item.is_dir():
819
+ if dest_path.exists():
820
+ if verbose and not tracker:
821
+ console.print(f"[yellow]Merging directory:[/yellow] {item.name}")
822
+ for sub_item in item.rglob('*'):
823
+ if sub_item.is_file():
824
+ rel_path = sub_item.relative_to(item)
825
+ dest_file = dest_path / rel_path
826
+ dest_file.parent.mkdir(parents=True, exist_ok=True)
827
+ # Special handling for .vscode/settings.json - merge instead of overwrite
828
+ if dest_file.name == "settings.json" and dest_file.parent.name == ".vscode":
829
+ handle_vscode_settings(sub_item, dest_file, rel_path, verbose, tracker)
830
+ else:
831
+ shutil.copy2(sub_item, dest_file)
832
+ else:
833
+ shutil.copytree(item, dest_path)
834
+ else:
835
+ if dest_path.exists() and verbose and not tracker:
836
+ console.print(f"[yellow]Overwriting file:[/yellow] {item.name}")
837
+ shutil.copy2(item, dest_path)
838
+ if verbose and not tracker:
839
+ console.print(f"[cyan]Template files merged into current directory[/cyan]")
840
+ else:
841
+ zip_ref.extractall(project_path)
842
+
843
+ extracted_items = list(project_path.iterdir())
844
+ if tracker:
845
+ tracker.start("extracted-summary")
846
+ tracker.complete("extracted-summary", f"{len(extracted_items)} top-level items")
847
+ elif verbose:
848
+ console.print(f"[cyan]Extracted {len(extracted_items)} items to {project_path}:[/cyan]")
849
+ for item in extracted_items:
850
+ console.print(f" - {item.name} ({'dir' if item.is_dir() else 'file'})")
851
+
852
+ if len(extracted_items) == 1 and extracted_items[0].is_dir():
853
+ nested_dir = extracted_items[0]
854
+ temp_move_dir = project_path.parent / f"{project_path.name}_temp"
855
+
856
+ shutil.move(str(nested_dir), str(temp_move_dir))
857
+
858
+ project_path.rmdir()
859
+
860
+ shutil.move(str(temp_move_dir), str(project_path))
861
+ if tracker:
862
+ tracker.add("flatten", "Flatten nested directory")
863
+ tracker.complete("flatten")
864
+ elif verbose:
865
+ console.print(f"[cyan]Flattened nested directory structure[/cyan]")
866
+
867
+ except Exception as e:
868
+ if tracker:
869
+ tracker.error("extract", str(e))
870
+ else:
871
+ if verbose:
872
+ console.print(f"[red]Error extracting template:[/red] {e}")
873
+ if debug:
874
+ console.print(Panel(str(e), title="Extraction Error", border_style="red"))
875
+
876
+ if not is_current_dir and project_path.exists():
877
+ shutil.rmtree(project_path)
878
+ raise typer.Exit(1)
879
+ else:
880
+ if tracker:
881
+ tracker.complete("extract")
882
+ finally:
883
+ if tracker:
884
+ tracker.add("cleanup", "Remove temporary archive")
885
+
886
+ if zip_path.exists():
887
+ zip_path.unlink()
888
+ if tracker:
889
+ tracker.complete("cleanup")
890
+ elif verbose:
891
+ console.print(f"Cleaned up: {zip_path.name}")
892
+
893
+ return project_path
894
+
895
+
896
+ def ensure_executable_scripts(project_path: Path, tracker: StepTracker | None = None) -> None:
897
+ """Ensure POSIX .sh scripts under .doit/scripts (recursively) have execute bits (no-op on Windows)."""
898
+ if os.name == "nt":
899
+ return # Windows: skip silently
900
+ scripts_root = project_path / ".doit" / "scripts"
901
+ if not scripts_root.is_dir():
902
+ return
903
+ failures: list[str] = []
904
+ updated = 0
905
+ for script in scripts_root.rglob("*.sh"):
906
+ try:
907
+ if script.is_symlink() or not script.is_file():
908
+ continue
909
+ try:
910
+ with script.open("rb") as f:
911
+ if f.read(2) != b"#!":
912
+ continue
913
+ except Exception:
914
+ continue
915
+ st = script.stat(); mode = st.st_mode
916
+ if mode & 0o111:
917
+ continue
918
+ new_mode = mode
919
+ if mode & 0o400: new_mode |= 0o100
920
+ if mode & 0o040: new_mode |= 0o010
921
+ if mode & 0o004: new_mode |= 0o001
922
+ if not (new_mode & 0o100):
923
+ new_mode |= 0o100
924
+ os.chmod(script, new_mode)
925
+ updated += 1
926
+ except Exception as e:
927
+ failures.append(f"{script.relative_to(scripts_root)}: {e}")
928
+ if tracker:
929
+ detail = f"{updated} updated" + (f", {len(failures)} failed" if failures else "")
930
+ tracker.add("chmod", "Set script permissions recursively")
931
+ (tracker.error if failures else tracker.complete)("chmod", detail)
932
+ else:
933
+ if updated:
934
+ console.print(f"[cyan]Updated execute permissions on {updated} script(s) recursively[/cyan]")
935
+ if failures:
936
+ console.print("[yellow]Some scripts could not be updated:[/yellow]")
937
+ for f in failures:
938
+ console.print(f" - {f}")
939
+
940
+ @app.command()
941
+ def init(
942
+ project_name: str = typer.Argument(None, help="Name for your new project directory (optional if using --here, or use '.' for current directory)"),
943
+ ai_assistant: str = typer.Option(None, "--ai", help="AI assistant to use: claude, gemini, copilot, cursor-agent, qwen, opencode, codex, windsurf, kilocode, auggie, codebuddy, amp, shai, q, bob, or qoder "),
944
+ script_type: str = typer.Option(None, "--script", help="Script type to use: sh or ps"),
945
+ ignore_agent_tools: bool = typer.Option(False, "--ignore-agent-tools", help="Skip checks for AI agent tools like Claude Code"),
946
+ no_git: bool = typer.Option(False, "--no-git", help="Skip git repository initialization"),
947
+ here: bool = typer.Option(False, "--here", help="Initialize project in the current directory instead of creating a new one"),
948
+ force: bool = typer.Option(False, "--force", help="Force merge/overwrite when using --here (skip confirmation)"),
949
+ skip_tls: bool = typer.Option(False, "--skip-tls", help="Skip SSL/TLS verification (not recommended)"),
950
+ debug: bool = typer.Option(False, "--debug", help="Show verbose diagnostic output for network and extraction failures"),
951
+ github_token: str = typer.Option(None, "--github-token", help="GitHub token to use for API requests (or set GH_TOKEN or GITHUB_TOKEN environment variable)"),
952
+ ):
953
+ """
954
+ Initialize a new Doit project from the latest template.
955
+
956
+ This command will:
957
+ 1. Check that required tools are installed (git is optional)
958
+ 2. Let you choose your AI assistant
959
+ 3. Download the appropriate template from GitHub
960
+ 4. Extract the template to a new project directory or current directory
961
+ 5. Initialize a fresh git repository (if not --no-git and no existing repo)
962
+ 6. Optionally set up AI assistant commands
963
+
964
+ Examples:
965
+ doit init my-project
966
+ doit init my-project --ai claude
967
+ doit init my-project --ai copilot --no-git
968
+ doit init --ignore-agent-tools my-project
969
+ doit init . --ai claude # Initialize in current directory
970
+ doit init . # Initialize in current directory (interactive AI selection)
971
+ doit init --here --ai claude # Alternative syntax for current directory
972
+ doit init --here --ai codex
973
+ doit init --here --ai codebuddy
974
+ doit init --here
975
+ doit init --here --force # Skip confirmation when current directory not empty
976
+ """
977
+
978
+ show_banner()
979
+
980
+ if project_name == ".":
981
+ here = True
982
+ project_name = None # Clear project_name to use existing validation logic
983
+
984
+ if here and project_name:
985
+ console.print("[red]Error:[/red] Cannot specify both project name and --here flag")
986
+ raise typer.Exit(1)
987
+
988
+ if not here and not project_name:
989
+ console.print("[red]Error:[/red] Must specify either a project name, use '.' for current directory, or use --here flag")
990
+ raise typer.Exit(1)
991
+
992
+ if here:
993
+ project_name = Path.cwd().name
994
+ project_path = Path.cwd()
995
+
996
+ existing_items = list(project_path.iterdir())
997
+ if existing_items:
998
+ console.print(f"[yellow]Warning:[/yellow] Current directory is not empty ({len(existing_items)} items)")
999
+ console.print("[yellow]Template files will be merged with existing content and may overwrite existing files[/yellow]")
1000
+ if force:
1001
+ console.print("[cyan]--force supplied: skipping confirmation and proceeding with merge[/cyan]")
1002
+ else:
1003
+ response = typer.confirm("Do you want to continue?")
1004
+ if not response:
1005
+ console.print("[yellow]Operation cancelled[/yellow]")
1006
+ raise typer.Exit(0)
1007
+ else:
1008
+ project_path = Path(project_name).resolve()
1009
+ if project_path.exists():
1010
+ error_panel = Panel(
1011
+ f"Directory '[cyan]{project_name}[/cyan]' already exists\n"
1012
+ "Please choose a different project name or remove the existing directory.",
1013
+ title="[red]Directory Conflict[/red]",
1014
+ border_style="red",
1015
+ padding=(1, 2)
1016
+ )
1017
+ console.print()
1018
+ console.print(error_panel)
1019
+ raise typer.Exit(1)
1020
+
1021
+ current_dir = Path.cwd()
1022
+
1023
+ setup_lines = [
1024
+ "[cyan]Doit Project Setup[/cyan]",
1025
+ "",
1026
+ f"{'Project':<15} [green]{project_path.name}[/green]",
1027
+ f"{'Working Path':<15} [dim]{current_dir}[/dim]",
1028
+ ]
1029
+
1030
+ if not here:
1031
+ setup_lines.append(f"{'Target Path':<15} [dim]{project_path}[/dim]")
1032
+
1033
+ console.print(Panel("\n".join(setup_lines), border_style="cyan", padding=(1, 2)))
1034
+
1035
+ should_init_git = False
1036
+ if not no_git:
1037
+ should_init_git = check_tool("git")
1038
+ if not should_init_git:
1039
+ console.print("[yellow]Git not found - will skip repository initialization[/yellow]")
1040
+
1041
+ if ai_assistant:
1042
+ if ai_assistant not in AGENT_CONFIG:
1043
+ console.print(f"[red]Error:[/red] Invalid AI assistant '{ai_assistant}'. Choose from: {', '.join(AGENT_CONFIG.keys())}")
1044
+ raise typer.Exit(1)
1045
+ selected_ai = ai_assistant
1046
+ else:
1047
+ # Create options dict for selection (agent_key: display_name)
1048
+ ai_choices = {key: config["name"] for key, config in AGENT_CONFIG.items()}
1049
+ selected_ai = select_with_arrows(
1050
+ ai_choices,
1051
+ "Choose your AI assistant:",
1052
+ "copilot"
1053
+ )
1054
+
1055
+ if not ignore_agent_tools:
1056
+ agent_config = AGENT_CONFIG.get(selected_ai)
1057
+ if agent_config and agent_config["requires_cli"]:
1058
+ install_url = agent_config["install_url"]
1059
+ if not check_tool(selected_ai):
1060
+ error_panel = Panel(
1061
+ f"[cyan]{selected_ai}[/cyan] not found\n"
1062
+ f"Install from: [cyan]{install_url}[/cyan]\n"
1063
+ f"{agent_config['name']} is required to continue with this project type.\n\n"
1064
+ "Tip: Use [cyan]--ignore-agent-tools[/cyan] to skip this check",
1065
+ title="[red]Agent Detection Error[/red]",
1066
+ border_style="red",
1067
+ padding=(1, 2)
1068
+ )
1069
+ console.print()
1070
+ console.print(error_panel)
1071
+ raise typer.Exit(1)
1072
+
1073
+ if script_type:
1074
+ if script_type not in SCRIPT_TYPE_CHOICES:
1075
+ console.print(f"[red]Error:[/red] Invalid script type '{script_type}'. Choose from: {', '.join(SCRIPT_TYPE_CHOICES.keys())}")
1076
+ raise typer.Exit(1)
1077
+ selected_script = script_type
1078
+ else:
1079
+ default_script = "ps" if os.name == "nt" else "sh"
1080
+
1081
+ if sys.stdin.isatty():
1082
+ selected_script = select_with_arrows(SCRIPT_TYPE_CHOICES, "Choose script type (or press Enter)", default_script)
1083
+ else:
1084
+ selected_script = default_script
1085
+
1086
+ console.print(f"[cyan]Selected AI assistant:[/cyan] {selected_ai}")
1087
+ console.print(f"[cyan]Selected script type:[/cyan] {selected_script}")
1088
+
1089
+ tracker = StepTracker("Initialize Doit Project")
1090
+
1091
+ sys._doit_tracker_active = True
1092
+
1093
+ tracker.add("precheck", "Check required tools")
1094
+ tracker.complete("precheck", "ok")
1095
+ tracker.add("ai-select", "Select AI assistant")
1096
+ tracker.complete("ai-select", f"{selected_ai}")
1097
+ tracker.add("script-select", "Select script type")
1098
+ tracker.complete("script-select", selected_script)
1099
+ for key, label in [
1100
+ ("fetch", "Fetch latest release"),
1101
+ ("download", "Download template"),
1102
+ ("extract", "Extract template"),
1103
+ ("zip-list", "Archive contents"),
1104
+ ("extracted-summary", "Extraction summary"),
1105
+ ("chmod", "Ensure scripts executable"),
1106
+ ("cleanup", "Cleanup"),
1107
+ ("git", "Initialize git repository"),
1108
+ ("final", "Finalize")
1109
+ ]:
1110
+ tracker.add(key, label)
1111
+
1112
+ # Track git error message outside Live context so it persists
1113
+ git_error_message = None
1114
+
1115
+ with Live(tracker.render(), console=console, refresh_per_second=8, transient=True) as live:
1116
+ tracker.attach_refresh(lambda: live.update(tracker.render()))
1117
+ try:
1118
+ verify = not skip_tls
1119
+ local_ssl_context = ssl_context if verify else False
1120
+ local_client = httpx.Client(verify=local_ssl_context)
1121
+
1122
+ download_and_extract_template(project_path, selected_ai, selected_script, here, verbose=False, tracker=tracker, client=local_client, debug=debug, github_token=github_token)
1123
+
1124
+ ensure_executable_scripts(project_path, tracker=tracker)
1125
+
1126
+ if not no_git:
1127
+ tracker.start("git")
1128
+ if is_git_repo(project_path):
1129
+ tracker.complete("git", "existing repo detected")
1130
+ elif should_init_git:
1131
+ success, error_msg = init_git_repo(project_path, quiet=True)
1132
+ if success:
1133
+ tracker.complete("git", "initialized")
1134
+ else:
1135
+ tracker.error("git", "init failed")
1136
+ git_error_message = error_msg
1137
+ else:
1138
+ tracker.skip("git", "git not available")
1139
+ else:
1140
+ tracker.skip("git", "--no-git flag")
1141
+
1142
+ tracker.complete("final", "project ready")
1143
+ except Exception as e:
1144
+ tracker.error("final", str(e))
1145
+ console.print(Panel(f"Initialization failed: {e}", title="Failure", border_style="red"))
1146
+ if debug:
1147
+ _env_pairs = [
1148
+ ("Python", sys.version.split()[0]),
1149
+ ("Platform", sys.platform),
1150
+ ("CWD", str(Path.cwd())),
1151
+ ]
1152
+ _label_width = max(len(k) for k, _ in _env_pairs)
1153
+ env_lines = [f"{k.ljust(_label_width)} → [bright_black]{v}[/bright_black]" for k, v in _env_pairs]
1154
+ console.print(Panel("\n".join(env_lines), title="Debug Environment", border_style="magenta"))
1155
+ if not here and project_path.exists():
1156
+ shutil.rmtree(project_path)
1157
+ raise typer.Exit(1)
1158
+ finally:
1159
+ pass
1160
+
1161
+ console.print(tracker.render())
1162
+ console.print("\n[bold green]Project ready.[/bold green]")
1163
+
1164
+ # Show git error details if initialization failed
1165
+ if git_error_message:
1166
+ console.print()
1167
+ git_error_panel = Panel(
1168
+ f"[yellow]Warning:[/yellow] Git repository initialization failed\n\n"
1169
+ f"{git_error_message}\n\n"
1170
+ f"[dim]You can initialize git manually later with:[/dim]\n"
1171
+ f"[cyan]cd {project_path if not here else '.'}[/cyan]\n"
1172
+ f"[cyan]git init[/cyan]\n"
1173
+ f"[cyan]git add .[/cyan]\n"
1174
+ f"[cyan]git commit -m \"Initial commit\"[/cyan]",
1175
+ title="[red]Git Initialization Failed[/red]",
1176
+ border_style="red",
1177
+ padding=(1, 2)
1178
+ )
1179
+ console.print(git_error_panel)
1180
+
1181
+ # Agent folder security notice
1182
+ agent_config = AGENT_CONFIG.get(selected_ai)
1183
+ if agent_config:
1184
+ agent_folder = agent_config["folder"]
1185
+ security_notice = Panel(
1186
+ f"Some agents may store credentials, auth tokens, or other identifying and private artifacts in the agent folder within your project.\n"
1187
+ f"Consider adding [cyan]{agent_folder}[/cyan] (or parts of it) to [cyan].gitignore[/cyan] to prevent accidental credential leakage.",
1188
+ title="[yellow]Agent Folder Security[/yellow]",
1189
+ border_style="yellow",
1190
+ padding=(1, 2)
1191
+ )
1192
+ console.print()
1193
+ console.print(security_notice)
1194
+
1195
+ steps_lines = []
1196
+ if not here:
1197
+ steps_lines.append(f"1. Go to the project folder: [cyan]cd {project_name}[/cyan]")
1198
+ step_num = 2
1199
+ else:
1200
+ steps_lines.append("1. You're already in the project directory!")
1201
+ step_num = 2
1202
+
1203
+ # Add Codex-specific setup step if needed
1204
+ if selected_ai == "codex":
1205
+ codex_path = project_path / ".codex"
1206
+ quoted_path = shlex.quote(str(codex_path))
1207
+ if os.name == "nt": # Windows
1208
+ cmd = f"setx CODEX_HOME {quoted_path}"
1209
+ else: # Unix-like systems
1210
+ cmd = f"export CODEX_HOME={quoted_path}"
1211
+
1212
+ steps_lines.append(f"{step_num}. Set [cyan]CODEX_HOME[/cyan] environment variable before running Codex: [cyan]{cmd}[/cyan]")
1213
+ step_num += 1
1214
+
1215
+ steps_lines.append(f"{step_num}. Start using slash commands with your AI agent:")
1216
+
1217
+ steps_lines.append(" 2.1 [cyan]/doit.constitution[/] - Establish project principles")
1218
+ steps_lines.append(" 2.2 [cyan]/doit.specit[/] - Create feature specification")
1219
+ steps_lines.append(" 2.3 [cyan]/doit.planit[/] - Create implementation plan")
1220
+ steps_lines.append(" 2.4 [cyan]/doit.taskit[/] - Generate actionable tasks")
1221
+ steps_lines.append(" 2.5 [cyan]/doit.implementit[/] - Execute implementation")
1222
+ steps_lines.append(" 2.6 [cyan]/doit.testit[/] - Run tests")
1223
+ steps_lines.append(" 2.7 [cyan]/doit.reviewit[/] - Review code")
1224
+ steps_lines.append(" 2.8 [cyan]/doit.checkin[/] - Finalize and create PR")
1225
+
1226
+ steps_panel = Panel("\n".join(steps_lines), title="Next Steps", border_style="cyan", padding=(1,2))
1227
+ console.print()
1228
+ console.print(steps_panel)
1229
+
1230
+ @app.command()
1231
+ def check():
1232
+ """Check that all required tools are installed."""
1233
+ show_banner()
1234
+ console.print("[bold]Checking for installed tools...[/bold]\n")
1235
+
1236
+ tracker = StepTracker("Check Available Tools")
1237
+
1238
+ tracker.add("git", "Git version control")
1239
+ git_ok = check_tool("git", tracker=tracker)
1240
+
1241
+ agent_results = {}
1242
+ for agent_key, agent_config in AGENT_CONFIG.items():
1243
+ agent_name = agent_config["name"]
1244
+ requires_cli = agent_config["requires_cli"]
1245
+
1246
+ tracker.add(agent_key, agent_name)
1247
+
1248
+ if requires_cli:
1249
+ agent_results[agent_key] = check_tool(agent_key, tracker=tracker)
1250
+ else:
1251
+ # IDE-based agent - skip CLI check and mark as optional
1252
+ tracker.skip(agent_key, "IDE-based, no CLI check")
1253
+ agent_results[agent_key] = False # Don't count IDE agents as "found"
1254
+
1255
+ # Check VS Code variants (not in agent config)
1256
+ tracker.add("code", "Visual Studio Code")
1257
+ code_ok = check_tool("code", tracker=tracker)
1258
+
1259
+ tracker.add("code-insiders", "Visual Studio Code Insiders")
1260
+ code_insiders_ok = check_tool("code-insiders", tracker=tracker)
1261
+
1262
+ console.print(tracker.render())
1263
+
1264
+ console.print("\n[bold green]Doit CLI is ready to use![/bold green]")
1265
+
1266
+ if not git_ok:
1267
+ console.print("[dim]Tip: Install git for repository management[/dim]")
1268
+
1269
+ if not any(agent_results.values()):
1270
+ console.print("[dim]Tip: Install an AI assistant for the best experience[/dim]")
1271
+
1272
+ @app.command()
1273
+ def version():
1274
+ """Display version and system information."""
1275
+ import platform
1276
+ import importlib.metadata
1277
+
1278
+ show_banner()
1279
+
1280
+ # Get CLI version from package metadata
1281
+ cli_version = "unknown"
1282
+ try:
1283
+ cli_version = importlib.metadata.version("doit-cli")
1284
+ except Exception:
1285
+ # Fallback: try reading from pyproject.toml if running from source
1286
+ try:
1287
+ import tomllib
1288
+ pyproject_path = Path(__file__).parent.parent.parent / "pyproject.toml"
1289
+ if pyproject_path.exists():
1290
+ with open(pyproject_path, "rb") as f:
1291
+ data = tomllib.load(f)
1292
+ cli_version = data.get("project", {}).get("version", "unknown")
1293
+ except Exception:
1294
+ pass
1295
+
1296
+ # Fetch latest template release version
1297
+ repo_owner = "seanbarlow"
1298
+ repo_name = "doit"
1299
+ api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
1300
+
1301
+ template_version = "unknown"
1302
+ release_date = "unknown"
1303
+
1304
+ try:
1305
+ response = client.get(
1306
+ api_url,
1307
+ timeout=10,
1308
+ follow_redirects=True,
1309
+ headers=_github_auth_headers(),
1310
+ )
1311
+ if response.status_code == 200:
1312
+ release_data = response.json()
1313
+ template_version = release_data.get("tag_name", "unknown")
1314
+ # Remove 'v' prefix if present
1315
+ if template_version.startswith("v"):
1316
+ template_version = template_version[1:]
1317
+ release_date = release_data.get("published_at", "unknown")
1318
+ if release_date != "unknown":
1319
+ # Format the date nicely
1320
+ try:
1321
+ dt = datetime.fromisoformat(release_date.replace('Z', '+00:00'))
1322
+ release_date = dt.strftime("%Y-%m-%d")
1323
+ except Exception:
1324
+ pass
1325
+ except Exception:
1326
+ pass
1327
+
1328
+ info_table = Table(show_header=False, box=None, padding=(0, 2))
1329
+ info_table.add_column("Key", style="cyan", justify="right")
1330
+ info_table.add_column("Value", style="white")
1331
+
1332
+ info_table.add_row("CLI Version", cli_version)
1333
+ info_table.add_row("Template Version", template_version)
1334
+ info_table.add_row("Released", release_date)
1335
+ info_table.add_row("", "")
1336
+ info_table.add_row("Python", platform.python_version())
1337
+ info_table.add_row("Platform", platform.system())
1338
+ info_table.add_row("Architecture", platform.machine())
1339
+ info_table.add_row("OS Version", platform.version())
1340
+
1341
+ panel = Panel(
1342
+ info_table,
1343
+ title="[bold cyan]Doit CLI Information[/bold cyan]",
1344
+ border_style="cyan",
1345
+ padding=(1, 2)
1346
+ )
1347
+
1348
+ console.print(panel)
1349
+ console.print()
1350
+
1351
+ def main():
1352
+ app()
1353
+
1354
+ if __name__ == "__main__":
1355
+ main()
1356
+