diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index 1214cc376f..424c112dde 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -547,7 +547,7 @@ def init( from ._file_policy import ( ProjectPolicyError, prepare_init_root, read_project_options, ) - from .file_helper import FileHelperError + from .file_helper import FileHelper, FileHelperError try: # Existing targets are checked before any integration or scaffold mutation. @@ -1041,7 +1041,26 @@ def init( ensure_constitution_from_template(project_path, tracker=tracker) tracker.complete("final", "project ready") - except (typer.Exit, SystemExit): + except (typer.Exit, SystemExit) as exc: + # A failing step that already reported its own error exits + # here (e.g. a shared-infrastructure OSError becomes + # typer.Exit(1)); remove a directory this run created, as the + # generic failure path below does. + exit_code = getattr(exc, "exit_code", getattr(exc, "code", 1)) + if ( + exit_code not in (0, None) + and not here and not dir_existed_before + and initial_directory_state(project_path) is None + and not lifecycle_owns_rollback() + ): + # Deny-mode, handle-based removal beneath the trusted + # parent; best effort, so the step's own error stands + # (an already-missing target raises FileNotFoundError). + try: + with FileHelper(project_path.parent) as files: + files.delete(project_path.name, recursive=True) + except (OSError, FileHelperError): + pass raise except Exception as e: tracker.error("final", str(e)) diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index af61010c42..7ca6e205dc 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -30,6 +30,7 @@ _init_directory: ContextVar[tuple[Path, bool, list[Path]] | None] = ContextVar( "external_integration_init_directory", default=None ) +_init_root: ContextVar[Path | None] = ContextVar("external_integration_init_root", default=None) _success_messages: ContextVar[list[str] | None] = ContextVar( "external_integration_success_messages", default=None ) @@ -52,9 +53,14 @@ def lifecycle_success(message: str) -> None: def initial_directory_state(path: Path) -> tuple[bool, list[Path]] | None: - """Init validation sees the directory before the lifecycle lock created it.""" + """Init validation sees the directory before the lifecycle lock created it. + + The lifecycle records the target as spelled (``parent/../proj``) while + init later works with the resolved path, so also match the root the + lifecycle resolved through ``preflight_init_root``. + """ state = _init_directory.get() - if state is not None and state[0] == path: + if state is not None and path in (state[0], _init_root.get()): return state[1], state[2] return None @@ -652,6 +658,8 @@ def invoke(*args, **kwargs): (creation_root, root.exists(), list(root.iterdir()) if root.is_dir() else []) ) stack.callback(_init_directory.reset, token) + root_token = _init_root.set(root) + stack.callback(_init_root.reset, root_token) transaction = ( _transaction(root, key, state, records, creation_root=creation_root) if operation == "init" diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 7dd683e4e7..b0f7260287 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -257,6 +257,118 @@ def test_invalid_integration_value_is_rendered_literally(tmp_path: Path): assert "nope[/red]" in _strip(result.stdout) +def _fail_shared_infra(monkeypatch, unowned: str | None = None, probe=None): + """Make the shared-infrastructure step fail part-way, as a full disk would. + + ``_install_shared_infra_or_exit`` turns the ``OSError`` into + ``typer.Exit(1)``, which is how init sees a real shared-infra failure. + ``unowned`` names a project-root file written outside any journalled + scope, standing in for a concurrent write the rollback must preserve. + ``probe`` is called with the project path init passed to the installer. + """ + import specify_cli + + def partial_install(project_path, *args, **kwargs): + if probe is not None: + probe(Path(project_path)) + scripts = Path(project_path) / ".specify" / "scripts" + scripts.mkdir(parents=True, exist_ok=True) + (scripts / "partial.sh").write_text("#!/usr/bin/env bash\n", encoding="utf-8") + if unowned: + (Path(project_path) / unowned).write_text("unowned\n", encoding="utf-8") + raise OSError(28, "No space left on device") + + monkeypatch.setattr(specify_cli, "_install_shared_infra", partial_install) + + +def test_shared_infra_failure_removes_new_project_dir(tmp_path: Path, monkeypatch): + """A failed init into a new directory removes it, so a retry can succeed. + + The shared-infrastructure failure arrives as ``typer.Exit(1)``. It used to + be re-raised before the cleanup ran, leaving a half-initialized project + that made the retry fail with "Directory already exists". + """ + # Scope only the failing installer, so the retry keeps the home and + # environment isolation fixtures. + with monkeypatch.context() as failing: + _fail_shared_infra(failing) + result = _init(tmp_path, "proj") + + assert result.exit_code == 1, _strip(result.stdout) + assert "Failed to install shared infrastructure" in _strip(result.stdout) + assert not (tmp_path / "proj").exists() + + retry = _init(tmp_path, "proj") + assert retry.exit_code == 0, _strip(retry.stdout) + assert (tmp_path / "proj" / ".specify").is_dir() + + +def test_shared_infra_failure_leaves_noncanonical_target_to_lifecycle( + tmp_path: Path, monkeypatch +): + """Lifecycle rollback, not init's cleanup, owns a noncanonical new target. + + The lifecycle records ``anchor/../proj`` as spelled while init works with + the resolved path. The lookup must still match, so init leaves the + directory to journal rollback, which preserves files it does not own + instead of deleting the whole target. + """ + from specify_cli.integrations import installer + from specify_cli.integrations._lifecycle import initial_directory_state + + (tmp_path / "anchor").mkdir() + monkeypatch.setattr(installer, "read_records", lambda root: {"generic": {}}) + monkeypatch.setattr(installer, "load_installed_integrations", lambda root: None) + lookups: dict[str, object] = {} + + def probe(project_path: Path) -> None: + # The deletion guard also checks lifecycle_owns_rollback(), so assert + # the lookup itself: it must match the resolved target init uses and + # still reject an unrelated directory. + lookups["target"] = project_path + lookups["resolved"] = initial_directory_state(project_path) + lookups["unrelated"] = initial_directory_state(tmp_path / "anchor") + + _fail_shared_infra(monkeypatch, unowned="concurrent.txt", probe=probe) + + result = _init(tmp_path, str(Path("anchor") / ".." / "proj")) + + assert result.exit_code == 1, _strip(result.stdout) + project = tmp_path / "proj" + assert lookups["target"] == project.resolve() + assert lookups["resolved"] == (False, []) + assert lookups["unrelated"] is None + assert (project / "concurrent.txt").read_text(encoding="utf-8") == "unowned\n" + + +def test_shared_infra_failure_keeps_existing_project_dir(tmp_path: Path, monkeypatch): + """A failed init never deletes a directory that existed before it ran.""" + existing = tmp_path / "proj" + existing.mkdir() + keep = existing / "notes.txt" + keep.write_text("user data\n", encoding="utf-8") + _fail_shared_infra(monkeypatch) + + previous = os.getcwd() + os.chdir(tmp_path) + try: + result = CliRunner().invoke( + app, + [ + "init", "proj", "--force", + "--integration", "generic", + "--integration-options", "--commands-dir .agent/commands", + "--ignore-agent-tools", "--offline", + ], + catch_exceptions=True, + ) + finally: + os.chdir(previous) + + assert result.exit_code == 1, _strip(result.stdout) + assert keep.read_text(encoding="utf-8") == "user data\n" + + def _cd_argument(stdout: str) -> str: """Return the argument of the printed `cd` command, verbatim.