Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions scripts/bash/common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,13 @@ get_feature_paths() {
feature_dir="$_fd"
# Normalize relative paths to absolute under repo root
[[ "$feature_dir" != /* ]] && feature_dir="$repo_root/$feature_dir"
# A persisted pointer whose target is gone (renumbered or deleted specs
# dir) is no feature context: fail like a missing pointer instead of
# handing out paths under a directory that does not exist (#5566).
if [[ ! -d "$feature_dir" ]]; then
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or run the specify command to create .specify/feature.json." >&2
return 1
fi
else
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory." >&2
return 1
Expand Down
8 changes: 8 additions & 0 deletions scripts/powershell/common.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ function Get-FeaturePathsEnv {
if (-not [System.IO.Path]::IsPathRooted($featureDir)) {
$featureDir = Join-Path $repoRoot $featureDir
}
# A persisted pointer whose target is gone (renumbered or deleted specs
# dir) is no feature context: fail like a missing pointer instead of
# handing out paths under a directory that does not exist (#5566).
if (-not (Test-Path -LiteralPath $featureDir -PathType Container)) {
[Console]::Error.WriteLine("ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or run the specify command to create .specify/feature.json.")
if ($ReturnNullOnError) { return $null }
exit 1
}
} else {
[Console]::Error.WriteLine("ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory.")
if ($ReturnNullOnError) { return $null }
Expand Down
10 changes: 10 additions & 0 deletions scripts/python/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,16 @@ def get_feature_paths(
feature_dir = Path(stored)
if not feature_dir.is_absolute():
feature_dir = repo_root / feature_dir
# A persisted pointer whose target is gone (renumbered or deleted specs
# dir) is no feature context: fail like a missing pointer instead of
# handing out paths under a directory that does not exist (#5566).
if not feature_dir.is_dir():
print(
"ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY "
"or run the specify command to create .specify/feature.json.",
file=sys.stderr,
)
raise SystemExit(1)
else:
print(
"ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY "
Expand Down
148 changes: 148 additions & 0 deletions tests/test_feature_json_stale_pointer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""A ``.specify/feature.json`` pointer to a missing directory is no feature context.

``check-prerequisites --json --paths-only`` used to exit 0 and print paths under a
directory that is gone; with no ``feature.json`` at all the same command exits 1.
"""

from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path

import pytest

from tests.conftest import requires_bash
from tests.parity_helpers import clean_env, run

SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"

HAS_PWSH = shutil.which("pwsh") is not None
# Windows PowerShell 5.1 specifically, never pwsh: a behavioural change to
# PowerShell functionality needs evidence from it (CONTRIBUTING.md).
_WINDOWS_POWERSHELL = (
shutil.which("powershell.exe") or shutil.which("powershell")
) if os.name == "nt" else None
requires_pwsh = pytest.mark.skipif(not HAS_PWSH, reason="pwsh not available")
requires_windows_powershell = pytest.mark.skipif(
_WINDOWS_POWERSHELL is None, reason="Windows PowerShell 5.1 not available"
)
# Each host runs the full set of cases.
PORTS = [
pytest.param("bash", marks=requires_bash),
pytest.param("pwsh", marks=requires_pwsh),
pytest.param("windows-powershell", marks=requires_windows_powershell),
pytest.param("python"),
]

# Printed by every port when there is no feature context at all (#5566).
MISSING_POINTER_ERROR = (
"ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY "
"or run the specify command to create .specify/feature.json."
)


@pytest.fixture
def project(tmp_path: Path) -> Path:
"""A git repository with the three check-prerequisites variants installed."""
repo = tmp_path / "proj"
(repo / ".specify").mkdir(parents=True)
ident = ["-c", "user.name=Test User", "-c", "user.email=test@example.com"]
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", *ident, "commit", "--allow-empty", "-qm", "init"], cwd=repo, check=True)
for folder, names in (
("bash", "common.sh check-prerequisites.sh"),
("powershell", "common.ps1 check-prerequisites.ps1"),
("python", "common.py check_prerequisites.py"),
):
target = repo / ".specify" / "scripts" / folder
target.mkdir(parents=True)
for name in names.split():
shutil.copy(SCRIPTS / folder / name, target / name)
return repo


def _point_at(repo: Path, feature_directory: str) -> None:
body = json.dumps({"feature_directory": feature_directory}, separators=(",", ":"))
(repo / ".specify" / "feature.json").write_text(body + "\n", encoding="utf-8")


def _path(value: str) -> Path:
# Git for Windows Bash prints drives as /c/..., which Path() does not equate with C:\...
if os.name == "nt" and re.match(r"^/[A-Za-z]/", value):
value = f"{value[1].upper()}:{value[2:]}"
return Path(value)


def _paths_only(repo: Path, port: str, env: dict[str, str] | None = None):
scripts = repo / ".specify" / "scripts"
exe = {"pwsh": "pwsh", "windows-powershell": _WINDOWS_POWERSHELL}.get(port)
if port == "bash":
cmd = ["bash", str(scripts / "bash" / "check-prerequisites.sh"), "--json", "--paths-only"]
elif exe:
cmd = [exe, "-NoProfile", "-File", str(scripts / "powershell" / "check-prerequisites.ps1"), "-Json", "-PathsOnly"]
else:
cmd = [sys.executable, str(scripts / "python" / "check_prerequisites.py"), "--json", "--paths-only"]
return run(cmd, repo, env or clean_env())


@pytest.mark.parametrize("port", PORTS)
@pytest.mark.parametrize("kind", ["missing_dir", "regular_file", "dangling_symlink"])
def test_stale_pointer_fails_like_no_pointer(project: Path, port: str, kind: str) -> None:
target = project / "specs" / "001-gone"
target.parent.mkdir(parents=True)
if kind == "regular_file":
target.write_text("not a directory\n", encoding="utf-8")
elif kind == "dangling_symlink":
try:
target.symlink_to(target.with_name("001-never-created"), target_is_directory=True)
except (OSError, NotImplementedError):
pytest.skip("this platform cannot create a symlink here")
_point_at(project, "specs/001-gone")

result = _paths_only(project, port)

assert result.returncode == 1, result.stderr + result.stdout
assert MISSING_POINTER_ERROR in result.stderr, result.stderr
# The symptom: a FEATURE_DIR printed under the missing path.
assert "FEATURE_DIR" not in result.stdout, result.stdout


@pytest.mark.parametrize("port", PORTS)
def test_valid_pointer_still_resolves(project: Path, port: str) -> None:
feature = project / "specs" / "001-present"
feature.mkdir(parents=True)
(feature / "plan.md").write_text("# plan\n", encoding="utf-8")
_point_at(project, "specs/001-present")

result = _paths_only(project, port)

assert result.returncode == 0, result.stderr
payload = json.loads(result.stdout)
assert _path(payload["FEATURE_DIR"]) == feature
assert _path(payload["IMPL_PLAN"]) == feature / "plan.md"


@pytest.mark.parametrize("port", PORTS)
def test_missing_feature_json_still_fails(project: Path, port: str) -> None:
result = _paths_only(project, port)

assert result.returncode == 1, result.stderr + result.stdout
assert MISSING_POINTER_ERROR in result.stderr, result.stderr


@pytest.mark.parametrize("port", PORTS)
def test_env_var_pointing_at_missing_dir_is_kept(project: Path, port: str) -> None:
"""The explicit override may name a directory that is created later."""
env = clean_env()
env["SPECIFY_FEATURE_DIRECTORY"] = "specs/999-not-created-yet"

result = _paths_only(project, port, env)

assert result.returncode == 0, result.stderr
payload = json.loads(result.stdout)
assert _path(payload["FEATURE_DIR"]) == project / "specs" / "999-not-created-yet"
1 change: 1 addition & 0 deletions tests/test_init_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def test_composes_with_target_feature_json(tmp_path: Path) -> None:
(web / ".specify" / "feature.json").write_text(
'{"feature_directory": "specs/004-fj"}'
)
(web / "specs" / "004-fj").mkdir(parents=True)
env = {**_clean_env(), "SPECIFY_INIT_DIR": str(web)}
result = _bash("get_feature_paths", cwd=tmp_path, env=env)
assert result.returncode == 0, result.stderr
Expand Down
9 changes: 6 additions & 3 deletions tests/test_setup_plan_no_overwrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ def plan_repo(tmp_path: Path) -> Path:
_install_bash_scripts(repo)
_install_ps_scripts(repo)
_write_feature_json(repo)
# A persisted pointer must name an existing directory (#5566).
(repo / "specs" / "001-my-feature").mkdir(parents=True)
return repo


Expand Down Expand Up @@ -116,7 +118,7 @@ def test_setup_plan_creates_plan_when_missing(plan_repo: Path) -> None:
def test_setup_plan_preserves_existing_plan(plan_repo: Path) -> None:
"""Rerun must not overwrite an existing plan.md."""
feat = plan_repo / "specs" / "001-my-feature"
feat.mkdir(parents=True)
feat.mkdir(parents=True, exist_ok=True)
existing_content = "# My carefully authored plan\n\nDo not overwrite me.\n"
(feat / "plan.md").write_text(existing_content, encoding="utf-8")

Expand All @@ -138,7 +140,7 @@ def test_setup_plan_preserves_existing_plan(plan_repo: Path) -> None:
def test_setup_plan_skip_message_on_stderr_in_json_mode(plan_repo: Path) -> None:
"""In --json mode, status messages must go to stderr, not stdout."""
feat = plan_repo / "specs" / "001-my-feature"
feat.mkdir(parents=True)
feat.mkdir(parents=True, exist_ok=True)
(feat / "plan.md").write_text("# existing\n", encoding="utf-8")

script = plan_repo / ".specify" / "scripts" / "bash" / "setup-plan.sh"
Expand Down Expand Up @@ -206,7 +208,7 @@ def test_ps_setup_plan_preserves_existing_plan(plan_repo: Path, feature_name: st
"""Rerun must not overwrite an existing plan.md."""
_write_feature_json(plan_repo, f"specs/{feature_name}")
feat = plan_repo / "specs" / feature_name
feat.mkdir(parents=True)
feat.mkdir(parents=True, exist_ok=True)
existing_content = "# My carefully authored plan\n\nDo not overwrite me.\n"
(feat / "plan.md").write_text(existing_content, encoding="utf-8")

Expand Down Expand Up @@ -234,6 +236,7 @@ def test_ps_setup_plan_does_not_match_another_features_plan(plan_repo: Path) ->
"""A wildcard-shaped feature path must not match a neighboring plan."""
feature_name = "001-my-feature [v2]"
_write_feature_json(plan_repo, f"specs/{feature_name}")
(plan_repo / "specs" / feature_name).mkdir(parents=True)
neighbor = plan_repo / "specs" / "001-my-feature v"
neighbor.mkdir(parents=True)
existing_content = "# Another feature's plan\n"
Expand Down