Skip to content
Merged
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
24 changes: 18 additions & 6 deletions src/specify_cli/presets/_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
from ._registry import PresetRegistry


def _is_frontmatter_fence(line: str) -> bool:
"""Return whether ``line`` is a frontmatter delimiter (``---`` on its own line).

Trailing whitespace is tolerated, as in ``CommandRegistrar.parse_frontmatter``.
Leading whitespace is not: an indented ``---`` can be scalar content.
"""
return line.rstrip() == "---"


class PresetResolver:
"""Resolves template names to file paths using a priority stack.

Expand Down Expand Up @@ -604,10 +613,12 @@ def _find_in_subdirs(base_dir: Path) -> Optional[Path]:
try:
cmd_content = candidate.read_text(encoding="utf-8")
lines = cmd_content.splitlines(keepends=True)
if lines and lines[0].removeprefix("\ufeff").rstrip("\r\n") == "---":
if lines and _is_frontmatter_fence(
lines[0].removeprefix("\ufeff")
):
fence_end = -1
for fi, fline in enumerate(lines[1:], start=1):
if fline.rstrip("\r\n") == "---":
if _is_frontmatter_fence(fline):
fence_end = fi
break
if fence_end > 0:
Expand Down Expand Up @@ -880,17 +891,18 @@ def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]:
def _split_frontmatter(text: str) -> tuple:
"""Return (frontmatter_block_with_fences, body) or (None, text).

Uses line-based fence detection (fence must be ``---`` on its
own line) to avoid false matches on ``---`` inside YAML values.
Uses line-based fence detection (fence is ``---`` on its own line,
trailing whitespace allowed) to avoid false matches on ``---``
inside YAML values.
"""
frontmatter_text = text.removeprefix("\ufeff")
lines = frontmatter_text.splitlines(keepends=True)
if not lines or lines[0].rstrip("\r\n") != "---":
if not lines or not _is_frontmatter_fence(lines[0]):
return None, text

fence_end = -1
for i, line in enumerate(lines[1:], start=1):
if line.rstrip("\r\n") == "---":
if _is_frontmatter_fence(line):
fence_end = i
break

Expand Down
135 changes: 135 additions & 0 deletions tests/specify_cli/presets/test_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -1773,6 +1773,141 @@ def test_resolve_content_keeps_bom_without_complete_frontmatter(
# No complete frontmatter means content stays unchanged, matching #5562.
assert content == core_content + "\n\n" + preset_content

@pytest.mark.parametrize("newline", ["\n", "\r\n"], ids=["lf", "crlf"])
@pytest.mark.parametrize(
("opening", "closing"),
[
("---", "--- "),
("---", "---\t"),
("--- ", "---"),
("---\t", "---"),
],
ids=["end-space", "end-tab", "start-space", "start-tab"],
)
def test_resolve_content_strips_frontmatter_with_trailing_whitespace_on_fences(
self, project_dir, temp_dir, valid_pack_data, opening, closing, newline
):
"""A space or tab after a frontmatter delimiter must not leak the block."""
commands_dir = project_dir / ".specify" / "templates" / "commands"
commands_dir.mkdir(parents=True, exist_ok=True)
(commands_dir / "fence-ws-compose.md").write_text(
"---\ndescription: Core command\n---\nCore body content\n",
encoding="utf-8",
)
preset_content = (
f"{opening}\ndescription: Fence whitespace preset\nstrategy: append\n{closing}\n"
"Appended body content\n"
).replace("\n", newline)
pack_dir = _create_pack(
temp_dir,
valid_pack_data,
"fence-ws-compose-pack",
preset_content,
strategy="append",
template_type="command",
template_name="speckit.fence-ws-compose",
)
PresetManager(project_dir).install_from_directory(pack_dir, "0.1.5")

content = PresetResolver(project_dir).resolve_content(
"speckit.fence-ws-compose", "command"
)

assert content is not None
assert "strategy: append" not in content
assert "Appended body content" in content
assert "Core body content" in content
frontmatter = yaml.safe_load(content.split("---", 2)[1])
assert frontmatter == {"description": "Fence whitespace preset"}
assert content.count("---") == 2

@pytest.mark.parametrize(
("opening", "closing"),
[
("---", "--- "),
("---", "---\t"),
("--- ", "---"),
("---\t", "---"),
],
ids=["end-space", "end-tab", "start-space", "start-tab"],
)
def test_resolve_content_legacy_frontmatter_strategy_with_trailing_whitespace_on_fences(
self, project_dir, temp_dir, valid_pack_data, opening, closing
):
"""A frontmatter strategy is still honoured when a delimiter has trailing whitespace."""
commands_dir = project_dir / ".specify" / "templates" / "commands"
commands_dir.mkdir(parents=True, exist_ok=True)
(commands_dir / "fence-ws-legacy.md").write_text(
"Core body content\n", encoding="utf-8"
)
pack_dir = _create_pack(
temp_dir,
valid_pack_data,
"fence-ws-legacy-pack",
f"{opening}\ndescription: Fence whitespace preset\nstrategy: append\n{closing}\n"
"Appended body content\n",
template_type="command",
template_name="speckit.fence-ws-legacy",
)
PresetManager(project_dir).install_from_directory(pack_dir, "0.1.5")

resolver = PresetResolver(project_dir)
layers = resolver.collect_all_layers("speckit.fence-ws-legacy", "command")
content = resolver.resolve_content("speckit.fence-ws-legacy", "command")

assert layers[0]["strategy"] == "append"
assert content is not None
assert "Core body content" in content
assert "Appended body content" in content
assert "strategy: append" not in content

@pytest.mark.parametrize(
("opening", "closing"),
[
("---- ", "---"),
(" ---", "---"),
("---", "---- "),
("---", "--- text"),
("---", " ---"),
],
ids=[
"start-four-dashes",
"start-indented",
"end-four-dashes",
"end-text-after-dashes",
"end-indented",
],
)
def test_resolve_content_keeps_layer_without_exact_frontmatter_fences(
self, project_dir, temp_dir, valid_pack_data, opening, closing
):
"""Only ``---`` delimits frontmatter: longer, labelled or indented lines do not."""
commands_dir = project_dir / ".specify" / "templates" / "commands"
commands_dir.mkdir(parents=True, exist_ok=True)
core_content = "Core body content\n"
(commands_dir / "fence-exact.md").write_text(core_content, encoding="utf-8")
preset_content = (
f"{opening}\ndescription: Not a fence\nstrategy: append\n{closing}\n"
"Appended body content\n"
)
pack_dir = _create_pack(
temp_dir,
valid_pack_data,
"fence-exact-pack",
preset_content,
strategy="append",
template_type="command",
template_name="speckit.fence-exact",
)
PresetManager(project_dir).install_from_directory(pack_dir, "0.1.5")

content = PresetResolver(project_dir).resolve_content(
"speckit.fence-exact", "command"
)

# No complete frontmatter means the layer is appended unchanged.
assert content == core_content + "\n\n" + preset_content

@pytest.mark.parametrize("prefix", ["", "\ufeff"], ids=["plain", "bom"])
def test_legacy_frontmatter_replace_section_requires_manifest_declaration(
self, project_dir, valid_pack_data, prefix
Expand Down
Loading