diff --git a/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md b/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md new file mode 100644 index 00000000..e449ccfa --- /dev/null +++ b/changelog.d/3601-specfuse-run-no-longer-cuts-a-missing-fe.md @@ -0,0 +1,5 @@ +--- +class: fixed +trace: #3601 +--- +specfuse run no longer cuts a missing feature branch from a base that lacks the feature folder and then crashes; it refuses before switching branches and says how to proceed. diff --git a/specfuse/loop/loop.py b/specfuse/loop/loop.py index 54a9128d..8cedae4f 100644 --- a/specfuse/loop/loop.py +++ b/specfuse/loop/loop.py @@ -3570,6 +3570,34 @@ def _checked_checkout(checkout_args: list[str], action: str) -> str: return proc.stdout.strip() +def _feature_plan_missing_on_base(feature_dir: "Path | None", base: str) -> "str | None": + """Repo-relative PLAN.md path when it is committed at HEAD but absent from + *base*, else None (#3601). None too when it cannot be resolved: this guard + only ever adds a refusal, never a new way to fail.""" + if feature_dir is None: + return None + try: + top = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + capture_output=True, text=True, check=True, + ).stdout.strip() + rel = (Path(feature_dir) / "PLAN.md").resolve().relative_to( + Path(top).resolve() + ).as_posix() + except (subprocess.CalledProcessError, ValueError): + return None + + def _present(rev: str) -> bool: + return subprocess.run( + ["git", "cat-file", "-e", f"{rev}:{rel}"], + capture_output=True, check=False, + ).returncode == 0 + + if _present("HEAD") and not _present(base): + return rel + return None + + def ensure_feature_branch(feat_fm: dict, feature_dir: "Path | None" = None) -> None: """Ensure HEAD is on the feature's declared branch, creating it if needed. @@ -3728,6 +3756,22 @@ def ensure_feature_branch(feat_fm: dict, feature_dir: "Path | None" = None) -> N ) print(f"Switched to feature branch '{branch}' (was on '{current}').") else: + # A feature folder committed on the current branch but absent from the + # base would not exist on a branch cut from that base: the next read of + # PLAN.md would crash with the operator already moved off their branch + # (#3601). Refuse before switching. An untracked folder is unaffected + # -- `checkout -B` carries it along, which is what --prepare relies on. + plan_rel = _feature_plan_missing_on_base(feature_dir, base) + if plan_rel: + raise FeatureBranchError( + f"feature branch '{branch}' does not exist, and its base " + f"'{base}' does not contain '{plan_rel}': a branch cut from " + f"'{base}' would not hold this feature. The feature is " + f"committed on '{current}'. Either create the branch from here " + f"(`git branch {branch}`) or merge the feature into '{base}' " + f"first, then re-run. Nothing was switched; you are still on " + f"'{current}'." + ) # Create-from-base carries the working tree onto the new branch. Only # the expected /pick-feature flips may ride along; anything else stops. dirty = _tracked_dirty_paths() @@ -11901,7 +11945,12 @@ def run( require_session_env_writable() require_feature_folder_committed(feature_dir, feat_fm, feature_id) require_feature_folder_unmodified(feature_dir, feat_fm, feature_id) - ensure_feature_branch(feat_fm, feature_dir) + try: + ensure_feature_branch(feat_fm, feature_dir) + except FeatureBranchError as exc: + print(f"specfuse run cannot enter the feature branch:\n{exc}", + file=sys.stderr) + return 1 try: diff --git a/tests/test_feature_branch_missing_on_base.py b/tests/test_feature_branch_missing_on_base.py new file mode 100644 index 00000000..a9fcdf66 --- /dev/null +++ b/tests/test_feature_branch_missing_on_base.py @@ -0,0 +1,127 @@ +# +# Copyright 2026 Specfuse contributors +# Licensed under the Apache License, Version 2.0. See LICENSE. +# +"""ensure_feature_branch must not cut a branch that lacks the feature (#3601). + +A feature folder committed on a working branch, whose PLAN.md names a branch +that does not exist yet and a `base` that does not contain the folder, used to +be cut from that base: the new branch had no PLAN.md, the next read raised a +bare FileNotFoundError, and the operator was left on the new branch. The driver +now refuses before switching, and leaves the operator where they were. + +Real git in a tmpdir; no mocking. +""" + +from __future__ import annotations + +import os +import subprocess +import unittest +from contextlib import contextmanager +from pathlib import Path +from tempfile import TemporaryDirectory + +from tests._loop_loader import load_loop + +loop = load_loop() + +FEATURE = ".specfuse/features/FEAT-X-0001-demo" +FM = {"branch": "feat/FEAT-X-0001-demo", "base": "main"} + + +def _git(root: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(root), *args], + capture_output=True, text=True, check=True, + ).stdout.strip() + + +@contextmanager +def _chdir(path: Path): + prev = Path.cwd() + os.chdir(path) + try: + yield + finally: + os.chdir(prev) + + +@contextmanager +def _repo(): + """A temp git repo on `main` with one commit, no origin configured.""" + with TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + subprocess.run(["git", "init", "-q", "-b", "main", str(root)], check=True) + _git(root, "config", "user.email", "test@example.com") + _git(root, "config", "user.name", "Test") + _git(root, "config", "commit.gpgSign", "false") + (root / "README.md").write_text("# fixture\n") + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "init") + yield root + + +def _write_feature(root: Path) -> Path: + fd = root / FEATURE + fd.mkdir(parents=True) + (fd / "PLAN.md").write_text( + "---\nfeature_id: FEAT-X-0001\nbranch: feat/FEAT-X-0001-demo\nbase: main\n---\n" + ) + return fd + + +def _branch_exists(root: Path, name: str) -> bool: + return subprocess.run( + ["git", "-C", str(root), "rev-parse", "--verify", "-q", name], + capture_output=True, check=False, + ).returncode == 0 + + +class TestFeatureMissingOnBase(unittest.TestCase): + def test_refuses_before_switching_when_base_lacks_the_committed_feature(self): + with _repo() as root: + _git(root, "checkout", "-q", "-b", "work") + fd = _write_feature(root) + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "draft feature on work") + + with _chdir(root): + with self.assertRaises(loop.FeatureBranchError) as ctx: + loop.ensure_feature_branch(dict(FM), fd) + + msg = str(ctx.exception) + self.assertIn(f"{FEATURE}/PLAN.md", msg) + self.assertIn("'main'", msg) + self.assertIn("'work'", msg) + self.assertEqual(_git(root, "branch", "--show-current"), "work") + self.assertFalse(_branch_exists(root, FM["branch"])) + self.assertTrue((fd / "PLAN.md").is_file()) + + def test_base_that_holds_the_feature_still_creates_the_branch(self): + with _repo() as root: + fd = _write_feature(root) + _git(root, "add", ".") + _git(root, "commit", "-q", "-m", "feature on main") + + with _chdir(root): + loop.ensure_feature_branch(dict(FM), fd) + + self.assertEqual(_git(root, "branch", "--show-current"), FM["branch"]) + self.assertTrue((fd / "PLAN.md").is_file()) + + def test_untracked_feature_folder_still_rides_onto_the_new_branch(self): + # The draft-feature / --prepare path: the folder is not committed + # anywhere yet, so `checkout -B` carries it along untouched. + with _repo() as root: + fd = _write_feature(root) + + with _chdir(root): + loop.ensure_feature_branch(dict(FM), fd) + + self.assertEqual(_git(root, "branch", "--show-current"), FM["branch"]) + self.assertTrue((fd / "PLAN.md").is_file()) + + +if __name__ == "__main__": + unittest.main()