From 6583acc1d92d14ecdcc7b62c38a7b96ed53f9e0b Mon Sep 17 00:00:00 2001 From: pengzh1 <24854675+pengzh1@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:12:32 +0800 Subject: [PATCH] fix(presets): tolerate trailing whitespace on command frontmatter fences PresetResolver recognised a command file's frontmatter only when the delimiter lines were exactly ``---``. A stray space or tab after the closing line meant _split_frontmatter never saw the end of the block, so a preset's YAML (description, strategy) was appended to the composed command body, and the legacy frontmatter strategy lookup kept the default "replace". The opening line had the same exact-match rule and the same failure. Both delimiters are now matched with one predicate: ``---`` on its own line, trailing whitespace ignored. That is the rule CommandRegistrar.parse_frontmatter already applies to the closing line. Leading whitespace is still rejected because an indented ``---`` can be scalar content. The rstrip("\r\n") on the reattached block only trims its line terminator and is unchanged. Assisted-by: ZCode (model: GLM-5.4, autonomous) --- src/specify_cli/presets/_resolver.py | 24 +++- tests/specify_cli/presets/test_resolver.py | 135 +++++++++++++++++++++ 2 files changed, 153 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/presets/_resolver.py b/src/specify_cli/presets/_resolver.py index f6c94700e6..bd3f839cf2 100644 --- a/src/specify_cli/presets/_resolver.py +++ b/src/specify_cli/presets/_resolver.py @@ -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. @@ -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: @@ -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 diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index 56463a38b3..dad0f3e33d 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -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