From ff38bd95ff872f80dc46f3406c5604785d9ab956 Mon Sep 17 00:00:00 2001 From: IlayWolfson <210835034+IlayWolfson@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:00:24 +0200 Subject: [PATCH] fix: substitute [DATE] in create-new-feature and setup-plan scripts Replaces literal [DATE] with today's local YYYY-MM-DD date when create-new-feature and setup-plan write spec.md and plan.md, across bash, PowerShell 5.1, and Python. Plain string replace, so other placeholders are untouched; --dry-run, --json and no-overwrite of an existing spec.md/plan.md behave as before. Part of #4335. Assisted-by: Antigravity (model: claude-opus-5-5-high, autonomous) Assisted-by: Antigravity (model: gemini-4-neon-high, autonomous) --- scripts/bash/create-new-feature.sh | 5 + scripts/bash/setup-plan.sh | 9 +- scripts/powershell/create-new-feature.ps1 | 4 + scripts/powershell/setup-plan.ps1 | 4 + scripts/python/create_new_feature.py | 4 + scripts/python/setup_plan.py | 5 + tests/test_setup_plan_no_overwrite.py | 9 +- tests/test_template_date_substitution.py | 355 ++++++++++++++++++++++ 8 files changed, 393 insertions(+), 2 deletions(-) create mode 100644 tests/test_template_date_substitution.py diff --git a/scripts/bash/create-new-feature.sh b/scripts/bash/create-new-feature.sh index 6c2f04b8bd..fa5dcb7f55 100644 --- a/scripts/bash/create-new-feature.sh +++ b/scripts/bash/create-new-feature.sh @@ -454,6 +454,11 @@ if [ "$DRY_RUN" != true ]; then if [ "$NEEDS_SPEC" = true ]; then if [ "$SPEC_TEMPLATE_FOUND" = true ]; then + # Fill the literal [DATE] placeholder with today's local date (#4335). + # Parameter expansion keeps the template text literal; the escaped + # brackets match only the exact token. + SPEC_TODAY=$(date +%Y-%m-%d) + SPEC_TEMPLATE_CONTENT=${SPEC_TEMPLATE_CONTENT//\[DATE\]/$SPEC_TODAY} printf '%s' "$SPEC_TEMPLATE_CONTENT" > "$SPEC_FILE" else echo "Warning: Spec template not found; created empty spec file" >&2 diff --git a/scripts/bash/setup-plan.sh b/scripts/bash/setup-plan.sh index 9c8d163409..d6aa4aef9c 100644 --- a/scripts/bash/setup-plan.sh +++ b/scripts/bash/setup-plan.sh @@ -51,7 +51,14 @@ else echo "Restore a valid plan template and rerun plan setup." >&2 exit 1 fi - cat "$template_file" > "$IMPL_PLAN" + # Fill the literal [DATE] placeholder with today's local date (#4335). + # The sentinel keeps trailing newlines; parameter expansion keeps the + # template text literal and the escaped brackets match only the token. + plan_content=$(cat "$template_file"; printf x) + plan_content=${plan_content%x} + plan_today=$(date +%Y-%m-%d) + plan_content=${plan_content//\[DATE\]/$plan_today} + printf '%s' "$plan_content" > "$IMPL_PLAN" if $JSON_MODE; then echo "Copied plan template to $IMPL_PLAN" >&2 else diff --git a/scripts/powershell/create-new-feature.ps1 b/scripts/powershell/create-new-feature.ps1 index edb75b3222..82094c0e57 100644 --- a/scripts/powershell/create-new-feature.ps1 +++ b/scripts/powershell/create-new-feature.ps1 @@ -307,6 +307,10 @@ if (-not $DryRun) { if ($needsSpec) { if ($null -ne $content) { + # Fill the literal [DATE] placeholder with today's local date (#4335). + # String.Replace is ordinal and literal (no regex, no expansion). + $today = (Get-Date).ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture) + $content = $content.Replace('[DATE]', $today) $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($specFile, $content, $utf8NoBom) } else { diff --git a/scripts/powershell/setup-plan.ps1 b/scripts/powershell/setup-plan.ps1 index d7949ec88b..8f61afeac5 100644 --- a/scripts/powershell/setup-plan.ps1 +++ b/scripts/powershell/setup-plan.ps1 @@ -55,6 +55,10 @@ if (Test-Path -LiteralPath $paths.IMPL_PLAN -PathType Leaf) { [Console]::Error.WriteLine("Restore a valid plan template and rerun plan setup.") exit 1 } + # Fill the literal [DATE] placeholder with today's local date (#4335). + # String.Replace is ordinal and literal (no regex, no expansion). + $today = (Get-Date).ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture) + $content = $content.Replace('[DATE]', $today) $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($paths.IMPL_PLAN, $content, $utf8NoBom) # Emit the copy status like the bash twin (setup-plan.sh); route to stderr diff --git a/scripts/python/create_new_feature.py b/scripts/python/create_new_feature.py index 2099a73708..8dcdf160a8 100644 --- a/scripts/python/create_new_feature.py +++ b/scripts/python/create_new_feature.py @@ -419,6 +419,10 @@ def main(argv: list[str] | None = None) -> int: if needs_spec: if template_content is not None: + # Fill the literal [DATE] placeholder with today's local date (#4335). + template_content = template_content.replace( + "[DATE]", datetime.date.today().isoformat() + ) spec_file.write_bytes(template_content.encode("utf-8")) else: print( diff --git a/scripts/python/setup_plan.py b/scripts/python/setup_plan.py index 200b6d52aa..57f247c906 100644 --- a/scripts/python/setup_plan.py +++ b/scripts/python/setup_plan.py @@ -3,6 +3,7 @@ from __future__ import annotations +import datetime import json import sys from pathlib import Path @@ -81,6 +82,10 @@ def main(argv: list[str] | None = None) -> int: file=sys.stderr, ) return 1 + # Fill the literal [DATE] placeholder with today's local date (#4335). + template_content = template_content.replace( + "[DATE]", datetime.date.today().isoformat() + ) paths.impl_plan.write_bytes(template_content.encode("utf-8")) print(f"Copied plan template to {paths.impl_plan}", file=status_stream) else: diff --git a/tests/test_setup_plan_no_overwrite.py b/tests/test_setup_plan_no_overwrite.py index 2f4734ca0d..cabed97d3e 100644 --- a/tests/test_setup_plan_no_overwrite.py +++ b/tests/test_setup_plan_no_overwrite.py @@ -1,5 +1,6 @@ """Tests for setup-plan preserving existing plan.md (#2653).""" +import datetime import json import os import shutil @@ -240,6 +241,7 @@ def test_ps_setup_plan_does_not_match_another_features_plan(plan_repo: Path) -> script = plan_repo / ".specify" / "scripts" / "powershell" / "setup-plan.ps1" exe = "pwsh" if HAS_PWSH else _WINDOWS_POWERSHELL + before = datetime.date.today().isoformat() result = subprocess.run( [exe, "-NoProfile", "-File", str(script), "-Json"], cwd=plan_repo, @@ -248,11 +250,16 @@ def test_ps_setup_plan_does_not_match_another_features_plan(plan_repo: Path) -> check=False, env=_clean_env(), ) + after = datetime.date.today().isoformat() assert result.returncode == 0, result.stderr data = json.loads(result.stdout) plan_path = plan_repo / "specs" / feature_name / "plan.md" assert Path(data["IMPL_PLAN"]) == plan_path - assert plan_path.read_text(encoding="utf-8") == PLAN_TEMPLATE.read_text(encoding="utf-8") + # setup-plan fills the template's [DATE] placeholder with today's date (#4335). + template = PLAN_TEMPLATE.read_text(encoding="utf-8") + assert plan_path.read_text(encoding="utf-8") in { + template.replace("[DATE]", day) for day in (before, after) + } assert (neighbor / "plan.md").read_text(encoding="utf-8") == existing_content assert "Copied plan template" in result.stderr diff --git a/tests/test_template_date_substitution.py b/tests/test_template_date_substitution.py new file mode 100644 index 0000000000..967fb10834 --- /dev/null +++ b/tests/test_template_date_substitution.py @@ -0,0 +1,355 @@ +"""Regression tests for mechanical [DATE] substitution (#4335).""" + +from __future__ import annotations + +import datetime +from pathlib import Path + +import pytest + +from tests.conftest import requires_bash +from tests.parity_helpers import ( + HAS_POWERSHELL, + PROJECT_ROOT, + bash_cmd, + install_scripts, + json_stdout, + make_repo, + ps_cmd, + py_cmd, + run, + write_feature_json, +) + +SPEC_TEMPLATE = PROJECT_ROOT / "templates" / "spec-template.md" +PLAN_TEMPLATE = PROJECT_ROOT / "templates" / "plan-template.md" + +PORTS = [ + pytest.param("bash", marks=requires_bash), + pytest.param( + "powershell", + marks=pytest.mark.skipif(not HAS_POWERSHELL, reason="no PowerShell available"), + ), + pytest.param("python"), +] + +SPECIAL_CHARS_TEMPLATE = ( + "-n first line with [DATE] and second [DATE] on same line\n" + "Case sensitive: [date] [Date] [dAtE]\n" + "Other date tokens: [DATE_CREATED] [RATIFICATION_DATE] [LAST_AMENDED_DATE]\n" + "Nested brackets: [[DATE]]\n" + "Other placeholders: $ARGUMENTS [FEATURE NAME] [###-feature-name]\n" + "Regex and shell chars: & \\& \\1 \\n \\t $env:USERNAME $(whoami) `id` %s %100%\n" + "Quotes and backslashes: 'single' \"double\" C:\\Users\\test\\file\n" + "Unicode: שלום עולם 添加用户 🎯 réservation\n" + "Final date: [DATE]\n" +) + + +def _create_feature_cmd( + repo: Path, + port: str, + *extra_args: str, + json_mode: bool = False, + dry_run: bool = False, + allow_existing: bool = False, + short_name: str | None = None, +) -> list[str]: + if port == "powershell": + args: list[str] = [] + if json_mode: + args.append("-Json") + if dry_run: + args.append("-DryRun") + if allow_existing: + args.append("-AllowExistingBranch") + if short_name is not None: + args.extend(["-ShortName", short_name]) + args.extend(extra_args) + return ps_cmd(repo, "create-new-feature", *args) + + args = [] + if json_mode: + args.append("--json") + if dry_run: + args.append("--dry-run") + if allow_existing: + args.append("--allow-existing-branch") + if short_name is not None: + args.extend(["--short-name", short_name]) + args.extend(extra_args) + command = bash_cmd if port == "bash" else py_cmd + return command(repo, "create-new-feature", *args) + + +def _setup_plan_cmd(repo: Path, port: str, *, json_mode: bool = False) -> list[str]: + if port == "powershell": + return ps_cmd(repo, "setup-plan", *(("-Json",) if json_mode else ())) + command = bash_cmd if port == "bash" else py_cmd + return command(repo, "setup-plan", *(("--json",) if json_mode else ())) + + +def _setup_create_repo(tmp_path: Path, template_bytes: bytes | None) -> Path: + repo = make_repo(tmp_path) + install_scripts(repo, "create-new-feature") + templates = repo / ".specify" / "templates" + templates.mkdir(parents=True, exist_ok=True) + if template_bytes is not None: + (templates / "spec-template.md").write_bytes(template_bytes) + return repo + + +def _setup_plan_repo(tmp_path: Path, template_bytes: bytes | None) -> tuple[Path, Path]: + repo = make_repo(tmp_path) + install_scripts(repo, "setup-plan") + write_feature_json(repo, "specs/001-my-feature") + feature_dir = repo / "specs" / "001-my-feature" + feature_dir.mkdir(parents=True) + templates = repo / ".specify" / "templates" + templates.mkdir(parents=True, exist_ok=True) + if template_bytes is not None: + (templates / "plan-template.md").write_bytes(template_bytes) + return repo, feature_dir + + +def _assert_substituted_bytes( + actual_bytes: bytes, template_text: str, before: str, after: str +) -> None: + assert not actual_bytes.startswith(b"\xef\xbb\xbf"), "Output must not have a UTF-8 BOM" + expected_candidates = { + template_text.replace("[DATE]", day).encode("utf-8") + for day in (before, after) + } + assert actual_bytes in expected_candidates + + +# ── create-new-feature [DATE] substitution ─────────────────────────────────── + + +@pytest.mark.parametrize("port", PORTS) +def test_create_new_feature_substitutes_stock_spec_template_date( + tmp_path: Path, port: str +) -> None: + template_bytes = SPEC_TEMPLATE.read_bytes() + template_text = template_bytes.decode("utf-8") + assert "**Created**: [DATE]" in template_text + + repo = _setup_create_repo(tmp_path, template_bytes) + before = datetime.date.today().isoformat() + result = run( + _create_feature_cmd(repo, port, "Add auth", json_mode=True, short_name="auth"), + repo, + ) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + payload = json_stdout(result) + spec_file = repo / "specs" / payload["BRANCH_NAME"] / "spec.md" + raw = spec_file.read_bytes() + + _assert_substituted_bytes(raw, template_text, before, after) + rendered = raw.decode("utf-8") + assert "[DATE]" not in rendered + assert any(f"**Created**: {day}" in rendered for day in (before, after)) + assert "**Status**: Draft" in rendered + assert '**Input**: User description: "$ARGUMENTS"' in rendered + assert "[FEATURE NAME]" in rendered + assert "`[###-feature-name]`" in rendered + + +@pytest.mark.parametrize("port", PORTS) +def test_create_new_feature_preserves_special_chars_and_other_tokens( + tmp_path: Path, port: str +) -> None: + repo = _setup_create_repo(tmp_path, SPECIAL_CHARS_TEMPLATE.encode("utf-8")) + before = datetime.date.today().isoformat() + result = run( + _create_feature_cmd(repo, port, "Test chars", json_mode=True, short_name="chars"), + repo, + ) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + spec_file = repo / "specs" / "001-chars" / "spec.md" + _assert_substituted_bytes( + spec_file.read_bytes(), SPECIAL_CHARS_TEMPLATE, before, after + ) + + +@pytest.mark.parametrize("port", PORTS) +@pytest.mark.parametrize( + "template_text", + [ + "# No date placeholder here\nBody only.\n", + "# No trailing newline\nDate: [DATE]", + "# Multiple trailing newlines\n[DATE] and [DATE]\n\n\n", + ], + ids=["zero_occurrences", "no_trailing_newline", "multiple_trailing_newlines"], +) +def test_create_new_feature_handles_occurrence_counts_and_trailing_newlines( + tmp_path: Path, port: str, template_text: str +) -> None: + repo = _setup_create_repo(tmp_path, template_text.encode("utf-8")) + before = datetime.date.today().isoformat() + result = run( + _create_feature_cmd(repo, port, "Test eol", json_mode=True, short_name="eol"), + repo, + ) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + spec_file = repo / "specs" / "001-eol" / "spec.md" + _assert_substituted_bytes(spec_file.read_bytes(), template_text, before, after) + + +@pytest.mark.parametrize("port", PORTS) +def test_create_new_feature_preserves_dry_run_missing_template_and_existing_spec( + tmp_path: Path, port: str +) -> None: + # 1. --dry-run does not create directory or spec.md + dry_repo = _setup_create_repo(tmp_path / "dry", b"Date: [DATE]\n") + dry_result = run( + _create_feature_cmd( + dry_repo, port, "Dry run", json_mode=True, dry_run=True, short_name="dry" + ), + dry_repo, + ) + assert dry_result.returncode == 0, dry_result.stderr + assert json_stdout(dry_result)["DRY_RUN"] is True + assert not (dry_repo / "specs" / "001-dry").exists() + + # 2. Missing spec template warns and creates empty spec.md + missing_repo = _setup_create_repo(tmp_path / "missing", None) + missing_result = run( + _create_feature_cmd( + missing_repo, port, "Missing", json_mode=True, short_name="missing" + ), + missing_repo, + ) + assert missing_result.returncode == 0, missing_result.stderr + assert "Spec template not found" in missing_result.stderr + assert (missing_repo / "specs" / "001-missing" / "spec.md").read_bytes() == b"" + + # 3. Existing spec.md with --allow-existing-branch is not overwritten or modified + existing_repo = _setup_create_repo(tmp_path / "existing", b"New [DATE]\n") + existing_dir = existing_repo / "specs" / "001-existing" + existing_dir.mkdir(parents=True) + existing_bytes = b"Existing literal [DATE] must stay untouched\n" + (existing_dir / "spec.md").write_bytes(existing_bytes) + # Pin the feature number so the run targets the seeded 001-existing directory. + number_args = ("-Number", "1") if port == "powershell" else ("--number", "1") + existing_result = run( + _create_feature_cmd( + existing_repo, + port, + "Existing", + *number_args, + json_mode=True, + allow_existing=True, + short_name="existing", + ), + existing_repo, + ) + assert existing_result.returncode == 0, existing_result.stderr + assert json_stdout(existing_result)["BRANCH_NAME"] == "001-existing" + assert (existing_dir / "spec.md").read_bytes() == existing_bytes + + +# ── setup-plan [DATE] substitution ─────────────────────────────────────────── + + +@pytest.mark.parametrize("port", PORTS) +def test_setup_plan_substitutes_stock_plan_template_date( + tmp_path: Path, port: str +) -> None: + template_bytes = PLAN_TEMPLATE.read_bytes() + template_text = template_bytes.decode("utf-8") + assert "**Date**: [DATE]" in template_text + + repo, feature_dir = _setup_plan_repo(tmp_path, template_bytes) + before = datetime.date.today().isoformat() + result = run(_setup_plan_cmd(repo, port, json_mode=True), repo) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + payload = json_stdout(result) + assert "IMPL_PLAN" in payload + raw = (feature_dir / "plan.md").read_bytes() + + _assert_substituted_bytes(raw, template_text, before, after) + rendered = raw.decode("utf-8") + assert "[DATE]" not in rendered + assert any(f"**Date**: {day}" in rendered for day in (before, after)) + assert "**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`" in rendered + + +@pytest.mark.parametrize("port", PORTS) +def test_setup_plan_preserves_special_chars_and_other_tokens( + tmp_path: Path, port: str +) -> None: + repo, feature_dir = _setup_plan_repo( + tmp_path, SPECIAL_CHARS_TEMPLATE.encode("utf-8") + ) + before = datetime.date.today().isoformat() + result = run(_setup_plan_cmd(repo, port, json_mode=True), repo) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + _assert_substituted_bytes( + (feature_dir / "plan.md").read_bytes(), SPECIAL_CHARS_TEMPLATE, before, after + ) + + +@pytest.mark.parametrize("port", PORTS) +@pytest.mark.parametrize( + "template_text", + [ + "# No date placeholder here\nBody only.\n", + "# No trailing newline\nDate: [DATE]", + "# Multiple trailing newlines\n[DATE] and [DATE]\n\n\n", + ], + ids=["zero_occurrences", "no_trailing_newline", "multiple_trailing_newlines"], +) +def test_setup_plan_handles_occurrence_counts_and_trailing_newlines( + tmp_path: Path, port: str, template_text: str +) -> None: + repo, feature_dir = _setup_plan_repo(tmp_path, template_text.encode("utf-8")) + before = datetime.date.today().isoformat() + result = run(_setup_plan_cmd(repo, port, json_mode=False), repo) + after = datetime.date.today().isoformat() + + assert result.returncode == 0, result.stderr + _assert_substituted_bytes( + (feature_dir / "plan.md").read_bytes(), template_text, before, after + ) + + +@pytest.mark.parametrize("port", PORTS) +def test_setup_plan_preserves_existing_plan_and_error_paths( + tmp_path: Path, port: str +) -> None: + # 1. Existing plan.md with literal [DATE] is not overwritten or modified + existing_repo, existing_feature = _setup_plan_repo( + tmp_path / "existing", b"Template [DATE]\n" + ) + existing_bytes = b"Existing plan [DATE] must remain untouched\n" + (existing_feature / "plan.md").write_bytes(existing_bytes) + existing_result = run(_setup_plan_cmd(existing_repo, port, json_mode=True), existing_repo) + assert existing_result.returncode == 0, existing_result.stderr + assert (existing_feature / "plan.md").read_bytes() == existing_bytes + + # 2. Missing plan template exits 1 without creating plan.md + missing_repo, missing_feature = _setup_plan_repo(tmp_path / "missing", None) + missing_result = run(_setup_plan_cmd(missing_repo, port, json_mode=True), missing_repo) + assert missing_result.returncode == 1 + assert missing_result.stdout == "" + assert "Plan template not found" in missing_result.stderr + assert not (missing_feature / "plan.md").exists() + + # 3. Empty plan template exits 1 without creating plan.md + empty_repo, empty_feature = _setup_plan_repo(tmp_path / "empty", b"") + empty_result = run(_setup_plan_cmd(empty_repo, port, json_mode=True), empty_repo) + assert empty_result.returncode == 1 + assert empty_result.stdout == "" + assert "Plan template is empty" in empty_result.stderr + assert not (empty_feature / "plan.md").exists()