|
| 1 | +"""Init step — bootstrap a Spec Kit project from within a workflow. |
| 2 | +
|
| 3 | +Runs the same scaffolding as ``specify init`` so a workflow can create |
| 4 | +(or merge into) a project before driving the rest of the spec-driven |
| 5 | +process. The step invokes the ``init`` command in-process and captures |
| 6 | +its exit code and output. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import os |
| 12 | +from typing import Any |
| 13 | + |
| 14 | +from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus |
| 15 | +from specify_cli.workflows.expressions import evaluate_expression |
| 16 | + |
| 17 | + |
| 18 | +class InitStep(StepBase): |
| 19 | + """Bootstrap a project, equivalent to running ``specify init``. |
| 20 | +
|
| 21 | + The step runs the bundled ``specify init`` command non-interactively, |
| 22 | + scaffolding templates, scripts, shared infrastructure, and the |
| 23 | + selected coding agent integration into the target directory. |
| 24 | +
|
| 25 | + Because workflows run unattended, the step defaults to |
| 26 | + ``--ignore-agent-tools`` (skip checks for an installed agent CLI) and |
| 27 | + resolves the integration from the step config, falling back to the |
| 28 | + workflow-level default integration. |
| 29 | +
|
| 30 | + Example YAML:: |
| 31 | +
|
| 32 | + - id: bootstrap |
| 33 | + type: init |
| 34 | + here: true |
| 35 | + integration: copilot |
| 36 | + script: sh |
| 37 | +
|
| 38 | + Supported config fields (all optional): |
| 39 | +
|
| 40 | + ``project`` |
| 41 | + Project name or path to create. Use ``"."`` for the current |
| 42 | + directory. Ignored when ``here`` is truthy. |
| 43 | + ``here`` |
| 44 | + Initialize in the target directory instead of creating a new one. |
| 45 | + ``integration`` |
| 46 | + Integration key (e.g. ``copilot``). Defaults to the workflow's |
| 47 | + default integration. |
| 48 | + ``script`` |
| 49 | + Script type, ``sh`` or ``ps``. |
| 50 | + ``force`` |
| 51 | + Merge/overwrite without confirmation when the directory is not |
| 52 | + empty. |
| 53 | + ``no_git`` |
| 54 | + Skip git repository initialization. |
| 55 | + ``ignore_agent_tools`` |
| 56 | + Skip checks for the coding agent CLI (defaults to ``true``). |
| 57 | + ``preset`` |
| 58 | + Preset ID to install during initialization. |
| 59 | + ``branch_numbering`` |
| 60 | + Branch numbering strategy (``sequential`` or ``timestamp``). |
| 61 | + """ |
| 62 | + |
| 63 | + type_key = "init" |
| 64 | + |
| 65 | + def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: |
| 66 | + project = self._resolve(config.get("project"), context) |
| 67 | + here = self._resolve_bool(config.get("here"), context) |
| 68 | + |
| 69 | + integration = config.get("integration") or context.default_integration |
| 70 | + integration = self._resolve(integration, context) |
| 71 | + |
| 72 | + script = self._resolve(config.get("script"), context) |
| 73 | + preset = self._resolve(config.get("preset"), context) |
| 74 | + branch_numbering = self._resolve(config.get("branch_numbering"), context) |
| 75 | + |
| 76 | + force = self._resolve_bool(config.get("force"), context) |
| 77 | + no_git = self._resolve_bool(config.get("no_git"), context) |
| 78 | + # Workflows run unattended; skip the agent CLI presence check by default. |
| 79 | + ignore_agent_tools = self._resolve_bool( |
| 80 | + config.get("ignore_agent_tools", True), context |
| 81 | + ) |
| 82 | + |
| 83 | + argv: list[str] = ["init"] |
| 84 | + if here: |
| 85 | + argv.append("--here") |
| 86 | + elif project: |
| 87 | + argv.append(str(project)) |
| 88 | + else: |
| 89 | + # No explicit target → initialize the current directory. |
| 90 | + argv.append(".") |
| 91 | + |
| 92 | + if integration: |
| 93 | + argv.extend(["--integration", str(integration)]) |
| 94 | + if script: |
| 95 | + argv.extend(["--script", str(script)]) |
| 96 | + if branch_numbering: |
| 97 | + argv.extend(["--branch-numbering", str(branch_numbering)]) |
| 98 | + if preset: |
| 99 | + argv.extend(["--preset", str(preset)]) |
| 100 | + if force: |
| 101 | + argv.append("--force") |
| 102 | + if no_git: |
| 103 | + argv.append("--no-git") |
| 104 | + if ignore_agent_tools: |
| 105 | + argv.append("--ignore-agent-tools") |
| 106 | + |
| 107 | + exit_code, stdout, stderr = self._run_init(argv, context) |
| 108 | + |
| 109 | + output: dict[str, Any] = { |
| 110 | + "argv": argv, |
| 111 | + "project": project, |
| 112 | + "here": here, |
| 113 | + "integration": integration, |
| 114 | + "script": script, |
| 115 | + "exit_code": exit_code, |
| 116 | + "stdout": stdout, |
| 117 | + "stderr": stderr, |
| 118 | + } |
| 119 | + |
| 120 | + if exit_code != 0: |
| 121 | + return StepResult( |
| 122 | + status=StepStatus.FAILED, |
| 123 | + output=output, |
| 124 | + error=( |
| 125 | + stderr.strip() |
| 126 | + or f"specify init exited with code {exit_code}." |
| 127 | + ), |
| 128 | + ) |
| 129 | + return StepResult(status=StepStatus.COMPLETED, output=output) |
| 130 | + |
| 131 | + @staticmethod |
| 132 | + def _resolve(value: Any, context: StepContext) -> Any: |
| 133 | + """Resolve ``{{ ... }}`` expressions in string config values.""" |
| 134 | + if isinstance(value, str) and "{{" in value: |
| 135 | + return evaluate_expression(value, context) |
| 136 | + return value |
| 137 | + |
| 138 | + @classmethod |
| 139 | + def _resolve_bool(cls, value: Any, context: StepContext) -> bool: |
| 140 | + """Coerce a config value (possibly an expression) to a boolean.""" |
| 141 | + resolved = cls._resolve(value, context) |
| 142 | + if isinstance(resolved, str): |
| 143 | + return resolved.strip().lower() in ("true", "1", "yes") |
| 144 | + return bool(resolved) |
| 145 | + |
| 146 | + @staticmethod |
| 147 | + def _run_init( |
| 148 | + argv: list[str], context: StepContext |
| 149 | + ) -> tuple[int, str, str]: |
| 150 | + """Invoke ``specify init`` in-process and capture exit code/output. |
| 151 | +
|
| 152 | + Runs with the working directory set to ``context.project_root`` so |
| 153 | + that ``--here`` and relative project paths target the right place. |
| 154 | + """ |
| 155 | + from typer.testing import CliRunner |
| 156 | + |
| 157 | + from specify_cli import app |
| 158 | + |
| 159 | + runner = CliRunner() |
| 160 | + |
| 161 | + prev_cwd = os.getcwd() |
| 162 | + if context.project_root: |
| 163 | + try: |
| 164 | + os.chdir(context.project_root) |
| 165 | + except OSError as exc: |
| 166 | + return (1, "", f"Cannot enter project root: {exc}") |
| 167 | + try: |
| 168 | + result = runner.invoke(app, argv, catch_exceptions=True) |
| 169 | + finally: |
| 170 | + os.chdir(prev_cwd) |
| 171 | + |
| 172 | + stdout = result.output or "" |
| 173 | + # click >= 8.2 captures stderr separately; older versions mix it in. |
| 174 | + try: |
| 175 | + stderr = result.stderr if result.stderr_bytes is not None else "" |
| 176 | + except (ValueError, AttributeError): |
| 177 | + stderr = "" |
| 178 | + |
| 179 | + if result.exit_code != 0 and result.exception is not None: |
| 180 | + detail = f"{type(result.exception).__name__}: {result.exception}" |
| 181 | + stderr = f"{stderr}\n{detail}".strip() if stderr else detail |
| 182 | + |
| 183 | + return (result.exit_code, stdout, stderr) |
| 184 | + |
| 185 | + def validate(self, config: dict[str, Any]) -> list[str]: |
| 186 | + errors = super().validate(config) |
| 187 | + script = config.get("script") |
| 188 | + if isinstance(script, str) and "{{" not in script and script not in ("sh", "ps"): |
| 189 | + errors.append( |
| 190 | + f"Init step {config.get('id', '?')!r}: 'script' must be 'sh' or 'ps'." |
| 191 | + ) |
| 192 | + return errors |
0 commit comments