diff --git a/docs/presets/cli.md b/docs/presets/cli.md index da54bbdb18..70e7e47081 100644 --- a/docs/presets/cli.md +++ b/docs/presets/cli.md @@ -188,11 +188,16 @@ Usage errors preserve their usage exit code as with `list --json`. ```bash specify preset resolve spec-template specify preset resolve speckit.specify +specify preset resolve --kind script +specify preset resolve --kind script --output ``` Accepts an extensionless template name or a dot-separated command name. Names use lowercase letters, digits, and hyphens; command segments must be -non-empty. This command does not offer a script-type selector. +non-empty. By default, dotted names resolve as commands and other names as +templates. Use `--kind script` to inspect a script artifact, including a +manifest-declared file such as an `.mjs` module. Use `--kind command` to resolve +a command whose name is not dotted. Shows the highest-priority layer's path and source. If output is composed, it also shows the contributing composition chain, starting at its effective @@ -201,6 +206,13 @@ Invalid composition produces a warning; a missing name is reported as not found. For all artifact kinds and hidden layers, use the separate [artifact reference](../overview/artifacts.md). +For a script that uses a composition strategy, the reported layer path is not +the composed output. Pass `--output ` to write the effective script to +that location. The command creates missing parent directories and overwrites +an existing destination file. Relative module imports in the written output +resolve from the output file's directory; referenced files are not copied. +`--output` is only valid with `--kind script`. + ## Enable or disable a preset ```bash diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index cbb9db3428..987b77e923 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -12,6 +12,7 @@ from copy import deepcopy from pathlib import Path from typing import Any, Dict, Iterable, List, Optional +from urllib.parse import quote import yaml @@ -235,7 +236,12 @@ def _replace(m: re.Match) -> str: @staticmethod def rewrite_extension_paths( - text: str, extension_id: str, extension_dir: Path + text: str, + extension_id: str, + extension_dir: Path, + *, + source_path: Path | None = None, + relative_to: Path | None = None, ) -> str: """Rewrite extension-relative paths to their installed locations. @@ -255,28 +261,89 @@ def rewrite_extension_paths( skip = {"commands", ".git", "specs"} try: - subdirs = [ + subdirs = { entry.name for entry in extension_dir.iterdir() if entry.is_dir() and entry.name not in skip and not entry.name.startswith(".") - ] + } except OSError: - return text + subdirs = set() + # Script dependencies are relative to the script file, not the extension + # root. Only materialization relocates those references; command and + # template bodies keep their existing extension-root rewrite rules. + if source_path is not None and relative_to is not None: + try: + subdirs.update( + entry.name + for entry in source_path.parent.iterdir() + if entry.is_dir() + and entry.name not in skip + and not entry.name.startswith(".") + ) + except OSError: + pass - for subdir in subdirs: + for subdir in sorted(subdirs): # Only rewrite relative references (subdir/... or ./subdir/...); # absolute paths like /subdir/... keep their meaning. Use a # callable replacement: subdir/extension_id come from the # filesystem and could contain backslashes or "\1"-like # sequences, which would corrupt a string replacement template. - replacement = f".specify/extensions/{extension_id}/{subdir}/" - text = re.sub( - r'(^|[\s`"\'(])(?:\./)?' + re.escape(subdir) + "/", - lambda m: m.group(1) + replacement, - text, + pattern = re.compile( + r'(^|[\s`"\'(])(?P\./)?' + re.escape(subdir) + "/" ) + if not pattern.search(text): + continue + + def _replacement(match: re.Match) -> str: + target_dir = (extension_dir / subdir).resolve() + if ( + match.group("dot") + and source_path is not None + and relative_to is not None + and (source_path.parent / subdir).is_dir() + ): + target_dir = (source_path.parent / subdir).resolve() + if relative_to is None: + replacement = f".specify/extensions/{extension_id}/{subdir}/" + else: + require_reference = bool( + re.search( + r"\brequire(?:\.resolve)?\s*\(\s*$", + text[: match.start()], + ) + ) + module_specifier = ( + not require_reference + and ( + source_path is None + or source_path.suffix.lower() + in {".cjs", ".js", ".mjs"} + ) + ) + try: + replacement = os.path.relpath( + target_dir, start=relative_to.resolve() + ).replace(os.sep, "/") + except ValueError: + replacement = ( + target_dir.as_uri() if module_specifier else str(target_dir) + ) + if module_specifier: + if not replacement.startswith(("./", "../", "/", "file:")): + replacement = f"./{replacement}" + elif not os.path.isabs(replacement) and not replacement.startswith( + ("./", "../") + ): + replacement = f"./{replacement}" + if module_specifier and not replacement.startswith("file:"): + replacement = quote(replacement, safe="/-._~") + replacement = f"{replacement}/" + return match.group(1) + replacement + + text = pattern.sub(_replacement, text) return text def render_markdown_command( diff --git a/src/specify_cli/artifacts/catalog.py b/src/specify_cli/artifacts/catalog.py index 2780201cbf..d9ee5d10a6 100644 --- a/src/specify_cli/artifacts/catalog.py +++ b/src/specify_cli/artifacts/catalog.py @@ -73,6 +73,72 @@ def _resolve_script_reference(script_root: Path, token: str) -> Path | None: return candidate if candidate.is_file() else None +def _selected_core_script_paths(project_root: Path) -> dict[str, Path]: + """Return built-in scripts selected by the project's runtime policy.""" + from .._init_options import load_init_options + from ..agents import CommandRegistrar + from ..integrations.base import IntegrationBase + + command_dirs = tuple( + directory + for directory in ( + _project_core_asset_root(project_root, "commands"), + _locate_shared_asset_dir("commands"), + ) + if directory is not None + ) + script_dirs = tuple( + directory + for directory in ( + project_root / ".specify" / "scripts", + _project_core_asset_root(project_root, "scripts"), + _locate_shared_asset_dir("scripts"), + ) + if directory is not None + ) + requested = load_init_options(project_root).get("script") + selected: dict[str, Path] = {} + + for command_dir in command_dirs: + for template_path in sorted(command_dir.glob("*.md"), key=lambda p: p.name): + try: + content = template_path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + continue + frontmatter, _body = CommandRegistrar.parse_frontmatter(content) + scripts = frontmatter.get("scripts", {}) + if not isinstance(scripts, dict): + continue + script_commands = { + key: value + for key, value in scripts.items() + if isinstance(key, str) and isinstance(value, str) and value.strip() + } + if not script_commands: + continue + try: + variant = IntegrationBase.select_script_variant( + requested, script_commands + ) + tokens = shlex.split(script_commands[variant], posix=True) + except (KeyError, ValueError): + continue + if not tokens: + continue + + path = None + for script_dir in script_dirs: + path = _resolve_script_reference(script_dir, tokens[0]) + if path is not None: + break + if path is None: + continue + name = path.stem.replace("_", "-") if variant == "py" else path.stem + selected.setdefault(name, path) + + return selected + + def _locate_shared_asset_dir(subdir: str) -> Path | None: """Locate a core asset directory without changing shared asset behavior.""" if subdir not in {"commands", "scripts", "templates"}: @@ -1031,67 +1097,7 @@ def _iter_core_candidates( def _selected_core_script_paths(self) -> dict[str, Path]: """Return built-in scripts selected by the project's existing runtime policy.""" - from .._init_options import load_init_options - from ..agents import CommandRegistrar - from ..integrations.base import IntegrationBase - - command_dirs = tuple( - directory - for directory in ( - _project_core_asset_root(self.project_root, "commands"), - _locate_shared_asset_dir("commands"), - ) - if directory is not None - ) - script_dirs = tuple( - directory - for directory in ( - _project_core_asset_root(self.project_root, "scripts"), - _locate_shared_asset_dir("scripts"), - ) - if directory is not None - ) - requested = load_init_options(self.project_root).get("script") - selected: dict[str, Path] = {} - - for command_dir in command_dirs: - for template_path in sorted(command_dir.glob("*.md"), key=lambda p: p.name): - try: - content = template_path.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - continue - frontmatter, _body = CommandRegistrar.parse_frontmatter(content) - scripts = frontmatter.get("scripts", {}) - if not isinstance(scripts, dict): - continue - script_commands = { - key: value - for key, value in scripts.items() - if isinstance(key, str) and isinstance(value, str) and value.strip() - } - if not script_commands: - continue - try: - variant = IntegrationBase.select_script_variant( - requested, script_commands - ) - tokens = shlex.split(script_commands[variant], posix=True) - except (KeyError, ValueError): - continue - if not tokens: - continue - - path = None - for script_dir in script_dirs: - path = _resolve_script_reference(script_dir, tokens[0]) - if path is not None: - break - if path is None: - continue - name = path.stem.replace("_", "-") if variant == "py" else path.stem - selected.setdefault(name, path) - - return selected + return _selected_core_script_paths(self.project_root) def _describe_layer( self, diff --git a/src/specify_cli/presets/_resolver.py b/src/specify_cli/presets/_resolver.py index 9da56a2e95..c2ea474ac9 100644 --- a/src/specify_cli/presets/_resolver.py +++ b/src/specify_cli/presets/_resolver.py @@ -346,6 +346,14 @@ def resolve( if core.exists(): return core + # Match artifact inventory and composition resolution: built-in + # command scripts depend on the project's selected runtime. + from ..artifacts.catalog import _selected_core_script_paths + + selected = _selected_core_script_paths(self.project_root) + if template_name in selected: + return selected[template_name] + # Priority 5: Bundled core_pack (wheel install) or repo-root templates # (source-checkout / editable install). This is the canonical home for # speckit's built-in command/template files and must always be checked @@ -728,6 +736,14 @@ def _find_bundled_core( if stem and stem != template_name: names.append(stem) + if template_type == "script": + from ..artifacts.catalog import _selected_core_script_paths + + selected = _selected_core_script_paths(self.project_root) + for name in names: + if name in selected: + return selected[name] + core_pack = _locate_core_pack() if core_pack is not None: for name in names: @@ -760,6 +776,8 @@ def resolve_content( self, template_name: str, template_type: str = "template", + *, + relative_import_base: Path | None = None, ) -> Optional[str]: """Resolve a template name and return composed content. @@ -824,7 +842,15 @@ def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]: from ..agents import CommandRegistrar text = CommandRegistrar.rewrite_extension_paths( - text, extension_id, extension_dir + text, + extension_id, + extension_dir, + source_path=layer["path"], + relative_to=( + relative_import_base + if template_type == "script" + else None + ), ) return text diff --git a/src/specify_cli/presets/command_resolve.py b/src/specify_cli/presets/command_resolve.py index 688b87398d..eda23b1e6f 100644 --- a/src/specify_cli/presets/command_resolve.py +++ b/src/specify_cli/presets/command_resolve.py @@ -2,7 +2,11 @@ from __future__ import annotations +import os import re +import stat +from pathlib import Path +from typing import Literal import typer from rich.markup import escape as _escape_markup @@ -17,14 +21,28 @@ def preset_resolve( template_name: str = typer.Argument( ..., help="Template name to resolve (e.g., spec-template)" ), + kind: Literal["command", "script", "template"] | None = typer.Option( + None, + "--kind", + help="Artifact kind (defaults to command for dotted names, template otherwise)", + ), + output: Path | None = typer.Option( # noqa: B008 + None, + "--output", + help=( + "Write the effective script to this path " + "(required to materialize composition)" + ), + ), ): - """Show which template will be resolved for a given name.""" + """Show which artifact wins, or materialize an effective script.""" from .. import _require_specify_project from . import PresetResolver - is_command = "." in template_name + template_type = kind or ("command" if "." in template_name else "template") + is_command = template_type == "command" valid_name = ( - re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)+", template_name) + re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", template_name) if is_command else re.fullmatch(r"[a-z0-9-]+", template_name) ) @@ -37,9 +55,86 @@ def preset_resolve( ) raise typer.Exit(1) + if output is not None and template_type != "script": + console.print("[red]Error:[/red] --output can only be used with --kind script") + raise typer.Exit(1) + project_root = _require_specify_project() resolver = PresetResolver(project_root) - template_type = "command" if is_command else "template" + + if output is not None: + output_path = output.expanduser() + if not output_path.is_absolute(): + output_path = Path.cwd() / output_path + output_path = output_path.resolve() + layers = resolver.collect_all_layers(template_name, "script") + base_index = next( + ( + index + for index, layer in enumerate(layers) + if layer["strategy"] == "replace" + ), + None, + ) + contributing_layers = ( + layers[: base_index + 1] if base_index is not None else layers + ) + for layer in contributing_layers: + source_path = Path(layer["path"]) + try: + aliases_source = output_path == source_path.resolve() or ( + output_path.exists() and os.path.samefile(output_path, source_path) + ) + except OSError: + aliases_source = output_path == source_path.resolve() + if aliases_source: + console.print( + "[red]Error:[/red] --output must not overwrite a contributing script" + ) + raise typer.Exit(1) + try: + content = resolver.resolve_content( + template_name, + "script", + relative_import_base=output_path.parent, + ) + except Exception as exc: + console.print( + f"[red]Error:[/red] Could not resolve script: " + f"{_escape_markup(str(exc))}" + ) + raise typer.Exit(1) from exc + if content is None: + console.print( + f"[yellow]{_escape_markup(str(template_name))}[/yellow]: " + "not found or cannot be composed" + ) + raise typer.Exit(1) + + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(content, encoding="utf-8") + execute_bits = 0 + for layer in contributing_layers: + source_mode = Path(layer["path"]).stat().st_mode + execute_bits |= stat.S_IMODE(source_mode) & 0o111 + if execute_bits: + output_path.chmod( + stat.S_IMODE(output_path.stat().st_mode) | execute_bits + ) + except OSError as exc: + console.print( + f"[red]Error:[/red] Could not write script to " + f"{_escape_markup(str(output_path))}: {_escape_markup(str(exc))}" + ) + raise typer.Exit(1) from exc + + console.print( + f" [bold]{_escape_markup(str(template_name))}[/bold]: " + f"{_escape_markup(str(output_path))}" + ) + console.print(" [dim](effective script written to --output path)[/dim]") + return try: layers = resolver.collect_all_layers(template_name, template_type) @@ -85,6 +180,12 @@ def preset_resolve( console.print( " [dim]Final output is composed from multiple preset layers; the path above is the highest-priority contributing layer.[/dim]" ) + if template_type == "script": + console.print( + " [dim]Use --output PATH to write the effective composed " + "script. Relative imports in the output resolve from that " + "file's directory.[/dim]" + ) console.print("\n [bold]Composition chain:[/bold]") # Compute the effective base: first replace layer scanning from # highest priority (matching resolve_content top-down logic). diff --git a/tests/specify_cli/presets/test_command_resolve.py b/tests/specify_cli/presets/test_command_resolve.py index b563618726..e9cd956350 100644 --- a/tests/specify_cli/presets/test_command_resolve.py +++ b/tests/specify_cli/presets/test_command_resolve.py @@ -1,9 +1,12 @@ from __future__ import annotations +import re +import stat from pathlib import Path +from urllib.parse import unquote -import yaml import pytest +import yaml from specify_cli.presets import ( PresetManager, @@ -72,6 +75,90 @@ def _install( manager.install_from_directory(src, "9.9.9", priority) return manager + def _install_script( + self, + temp_dir, + project_dir, + content, + *, + strategy="replace", + pack_id="script-pack", + priority=10, + extension=".mjs", + executable=False, + ): + """Install a manifest-declared script artifact.""" + src = temp_dir / f"src-{pack_id}" + (src / "adapters").mkdir(parents=True) + source_script = src / "adapters" / f"page-adapter{extension}" + source_script.write_text(content) + if executable: + source_script.chmod(0o755) + (src / "preset.yml").write_text( + yaml.dump( + { + "schema_version": "1.0", + "preset": { + "id": pack_id, + "name": pack_id, + "version": "1.0.0", + "description": "JavaScript script fixture", + }, + "requires": {"speckit_version": ">=0.0.1"}, + "provides": { + "templates": [ + { + "type": "script", + "name": "designer-page-adapter", + "file": f"adapters/page-adapter{extension}", + "strategy": strategy, + } + ] + }, + } + ) + ) + manager = PresetManager(project_dir) + manager.install_from_directory(src, "9.9.9", priority) + return manager + + @pytest.mark.parametrize("executable", [False, True]) + def test_resolve_materialized_script_preserves_executable_mode( + self, temp_dir, project_dir, executable + ): + manager = self._install_script( + temp_dir, + project_dir, + "#!/bin/sh\necho ready\n", + extension=".sh", + executable=executable, + ) + output_path = project_dir / "generated" / "setup.sh" + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 0, (result.output, result.exception) + assert output_path.read_text(encoding="utf-8") == "#!/bin/sh\necho ready\n" + source_path = ( + manager.presets_dir + / "script-pack" + / "adapters" + / "page-adapter.sh" + ) + expected_execute_bits = stat.S_IMODE(source_path.stat().st_mode) & 0o111 + assert stat.S_IMODE(output_path.stat().st_mode) & 0o111 == expected_execute_bits + def _invoke(self, project_dir, args): from unittest.mock import patch @@ -136,6 +223,368 @@ def test_resolve_accepts_dotted_command_name(self, project_dir): assert result.exit_code == 0, (result.output, result.exception) assert "constitution.md" in "".join(strip_ansi(result.output).split()) + def test_resolve_accepts_undotted_command_name_when_kind_is_explicit( + self, temp_dir, project_dir + ): + src = temp_dir / "undotted-command" + (src / "commands").mkdir(parents=True) + (src / "commands" / "standalone.md").write_text("# Standalone\n") + (src / "preset.yml").write_text( + yaml.safe_dump( + { + "schema_version": "1.0", + "preset": { + "id": "undotted-command", + "name": "Undotted Command", + "version": "1.0.0", + "description": "Fixture", + }, + "requires": {"speckit_version": ">=0.0.1"}, + "provides": { + "templates": [ + { + "type": "command", + "name": "standalone", + "file": "commands/standalone.md", + } + ] + }, + } + ) + ) + PresetManager(project_dir).install_from_directory(src, "9.9.9") + + result = self._invoke( + project_dir, + ["preset", "resolve", "standalone", "--kind", "command"], + ) + + assert result.exit_code == 0, (result.output, result.exception) + assert "standalone.md" in "".join(strip_ansi(result.output).split()) + + def test_resolve_script_kind_finds_manifest_declared_module( + self, temp_dir, project_dir + ): + self._install_script(temp_dir, project_dir, "export default 'adapter';\n") + + default_result = self._invoke( + project_dir, ["preset", "resolve", "designer-page-adapter"] + ) + assert default_result.exit_code == 0 + assert "not found" in strip_ansi(default_result.output) + + result = self._invoke( + project_dir, + ["preset", "resolve", "designer-page-adapter", "--kind", "script"], + ) + + assert result.exit_code == 0, (result.output, result.exception) + output = "".join(strip_ansi(result.output).split()) + expected_path = ( + project_dir / ".specify/presets/script-pack/adapters/page-adapter.mjs" + ) + assert str(expected_path) in output + + def test_resolve_materializes_composed_script_at_requested_path( + self, temp_dir, project_dir + ): + self._install_script( + temp_dir, + project_dir, + "import './helper.mjs';\n$CORE_SCRIPT\n", + strategy="wrap", + pack_id="wrapper-pack", + priority=5, + ) + self._install_script( + temp_dir, + project_dir, + "export default 'base';\n", + pack_id="base-pack", + priority=10, + ) + output_path = project_dir / "generated" / "adapter.mjs" + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 0, (result.output, result.exception) + assert output_path.read_text() == ( + "import './helper.mjs';\nexport default 'base';\n\n" + ) + assert str(output_path.resolve()) in "".join(strip_ansi(result.output).split()) + + @pytest.mark.parametrize("project_suffix", ["#1", "%3"]) + def test_resolve_materialized_extension_imports_from_output_directory( + self, temp_dir, project_dir, project_suffix + ): + project_dir = project_dir.parent / f"{project_dir.name}{project_suffix}" + project_dir.mkdir() + extension_dir = project_dir / ".specify" / "extensions" / "script-ext" + scripts_dir = extension_dir / "scripts" + scripts_dir.mkdir(parents=True) + nested_library_dir = scripts_dir / "lib" + nested_library_dir.mkdir(parents=True) + # A root-level library must not shadow the dependency relative to this script. + (extension_dir / "lib").mkdir() + (extension_dir / "lib" / "helper.mjs").write_text( + "export const helper = 'extension-root';\n" + ) + (scripts_dir / "adapter.mjs").write_text( + "import './lib/helper.mjs';\nexport default 'extension';\n" + ) + (nested_library_dir / "helper.mjs").write_text( + "export const helper = 'script-local';\n" + ) + (extension_dir / "extension.yml").write_text( + "schema_version: '1.0'\n" + "extension:\n id: script-ext\n name: Script Ext\n version: 1.0.0\n" + " description: Fixture\n author: test\n" + " repository: https://example.com\n license: MIT\n" + "requires:\n speckit_version: '>=0.2.0'\n" + "provides:\n scripts:\n" + " - name: designer-page-adapter\n" + " file: scripts/adapter.mjs\n" + " description: Adapter\n runtimes: [bash]\n" + ) + self._install_script( + temp_dir, + project_dir, + "$CORE_SCRIPT\n", + strategy="wrap", + pack_id="script-wrapper", + priority=5, + ) + output_path = project_dir.parent / "materialized" / "adapter.mjs" + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 0, (result.output, result.exception) + content = output_path.read_text(encoding="utf-8") + match = re.search(r"import '([^']+)'", content) + assert match is not None + import_path = match.group(1) + assert "%23" in import_path or "%3F" in import_path or "%25" in import_path + referenced = (output_path.parent / unquote(import_path)).resolve() + assert referenced == (nested_library_dir / "helper.mjs").resolve() + assert referenced.is_file() + + def test_resolve_script_composition_without_output_explains_materialization( + self, temp_dir, project_dir + ): + self._install_script( + temp_dir, + project_dir, + "$CORE_SCRIPT\n", + strategy="wrap", + pack_id="wrapper-pack", + priority=5, + ) + self._install_script( + temp_dir, + project_dir, + "export default 'base';\n", + pack_id="base-pack", + priority=10, + ) + + result = self._invoke( + project_dir, + ["preset", "resolve", "designer-page-adapter", "--kind", "script"], + ) + + assert result.exit_code == 0, (result.output, result.exception) + output = strip_ansi(result.output) + assert "Use--outputPATH" in "".join(output.split()) + compact_output = "".join(output.split()) + assert ( + "Relativeimportsintheoutputresolvefromthatfile'sdirectory" in compact_output + ) + + def test_resolve_output_requires_script_kind(self, project_dir): + result = self._invoke( + project_dir, + ["preset", "resolve", "spec-template", "--output", "out.mjs"], + ) + + assert result.exit_code == 1 + assert "--output can only be used with --kind script" in strip_ansi( + result.output + ) + + def test_resolve_script_replace_over_wrap_does_not_compose( + self, temp_dir, project_dir + ): + # Winning layer (priority 5) uses replace; lower layer (priority 10) uses wrap + self._install_script( + temp_dir, + project_dir, + "export default 'winner-replace';\n", + strategy="replace", + pack_id="winner-pack", + priority=5, + ) + self._install_script( + temp_dir, + project_dir, + "// wrap layer\n$CORE_SCRIPT\n", + strategy="wrap", + pack_id="lower-wrap-pack", + priority=10, + ) + + result = self._invoke( + project_dir, + ["preset", "resolve", "designer-page-adapter", "--kind", "script"], + ) + + assert result.exit_code == 0, (result.output, result.exception) + output = strip_ansi(result.output) + assert "Composition chain" not in output + assert "--output" not in output + assert "winner-pack" in output + + def test_resolve_materialize_missing_script_fails_and_creates_no_file( + self, project_dir + ): + output_path = project_dir / "generated" / "missing.mjs" + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "non-existent-script", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 1 + assert "not found or cannot be composed" in strip_ansi(result.output) + assert not output_path.exists() + + def test_resolve_materialize_wrap_without_base_fails_and_preserves_destination( + self, temp_dir, project_dir + ): + self._install_script( + temp_dir, + project_dir, + "import './wrap.mjs';\n$CORE_SCRIPT\n", + strategy="wrap", + pack_id="orphan-wrapper", + priority=5, + ) + output_path = project_dir / "generated" / "preserved.mjs" + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("initial content", encoding="utf-8") + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 1 + output = strip_ansi(result.output) + assert ( + "not found or cannot be composed" in output + or "Could not resolve script" in output + ) + assert output_path.read_text(encoding="utf-8") == "initial content" + + def test_resolve_materialize_destination_write_failure(self, temp_dir, project_dir): + self._install_script( + temp_dir, + project_dir, + "export default 'test';\n", + pack_id="base-pack", + priority=10, + ) + # Create a file where a directory should be to force an OSError / NotADirectoryError + blocker_file = project_dir / "blocker_file" + blocker_file.write_text("i am a file", encoding="utf-8") + output_path = blocker_file / "uncreatable" / "output.mjs" + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 1 + assert "Could not write script to" in strip_ansi(result.output) + + @pytest.mark.parametrize("alias_kind", ["same-path", "symlink", "hardlink"]) + def test_resolve_refuses_to_overwrite_contributing_script( + self, temp_dir, project_dir, alias_kind + ): + self._install_script(temp_dir, project_dir, "export default 'source';\n") + source_path = ( + project_dir / ".specify/presets/script-pack/adapters/page-adapter.mjs" + ) + original = source_path.read_text(encoding="utf-8") + output_path = source_path + if alias_kind == "symlink": + output_path = project_dir / "generated-link.mjs" + output_path.symlink_to(source_path) + elif alias_kind == "hardlink": + output_path = project_dir / "generated-hardlink.mjs" + output_path.hardlink_to(source_path) + + result = self._invoke( + project_dir, + [ + "preset", + "resolve", + "designer-page-adapter", + "--kind", + "script", + "--output", + str(output_path), + ], + ) + + assert result.exit_code == 1 + assert "must not overwrite" in strip_ansi(result.output) + assert source_path.read_text(encoding="utf-8") == original + def test_resolve_rejects_empty_command_segments(self, project_dir): """Dotted command identifiers cannot contain empty path-like segments.""" result = self._invoke( diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index f052361c76..1a4e04f142 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -6,6 +6,7 @@ import pytest import yaml +from specify_cli.agents import CommandRegistrar from specify_cli.extensions import ExtensionRegistry from specify_cli.presets import ( PresetManager, @@ -125,6 +126,168 @@ def test_hidden_invalid_section_presets_do_not_block_replace(tmp_path, kind, win class TestPresetResolver: """Test PresetResolver priority stack.""" + @pytest.mark.parametrize( + "reference", ["require('./lib/helper.cjs')", "require.resolve('./lib/helper.cjs')"] + ) + def test_extension_script_rewrite_keeps_commonjs_paths_unencoded( + self, tmp_path, reference + ): + project = tmp_path / "project#1" + extension_dir = project / ".specify" / "extensions" / "example" + script_dir = extension_dir / "scripts" + (script_dir / "lib").mkdir(parents=True) + source_path = script_dir / "adapter.cjs" + + result = CommandRegistrar.rewrite_extension_paths( + f"{reference};\n", + "example", + extension_dir, + source_path=source_path, + relative_to=tmp_path / "output", + ) + + assert "%23" not in result + assert "../project#1/.specify/extensions/example/scripts/lib/helper.cjs" in result + + def test_extension_script_rewrite_skips_unreferenced_directories( + self, tmp_path, monkeypatch + ): + extension_dir = tmp_path / "extension" + (extension_dir / "lib").mkdir(parents=True) + monkeypatch.setattr( + "specify_cli.agents.os.path.relpath", + lambda *args, **kwargs: (_ for _ in ()).throw( + AssertionError("no relative path is needed for an unreferenced dir") + ), + ) + + result = CommandRegistrar.rewrite_extension_paths( + "export default true;\n", + "example", + extension_dir, + relative_to=tmp_path / "other-drive-output", + ) + + assert result == "export default true;\n" + + def test_extension_script_rewrite_handles_cross_drive_reference( + self, tmp_path, monkeypatch + ): + extension_dir = tmp_path / "extension" + (extension_dir / "lib").mkdir(parents=True) + monkeypatch.setattr( + "specify_cli.agents.os.path.relpath", + lambda *args, **kwargs: (_ for _ in ()).throw( + ValueError("different drives") + ), + ) + + result = CommandRegistrar.rewrite_extension_paths( + "import 'lib/helper.mjs';\n", + "example", + extension_dir, + relative_to=tmp_path / "output", + ) + + assert f"{(extension_dir / 'lib').as_uri()}/helper.mjs" in result + + def test_extension_script_rewrite_keeps_command_adjacent_references(self, tmp_path): + extension_dir = tmp_path / "extension" + command_lib = extension_dir / "commands" / "lib" + command_lib.mkdir(parents=True) + source_path = extension_dir / "commands" / "demo.md" + + result = CommandRegistrar.rewrite_extension_paths( + "Read ./lib/reference.md\n", + "example", + extension_dir, + source_path=source_path, + ) + + assert result == "Read ./lib/reference.md\n" + + def test_extension_script_rewrite_keeps_shell_paths_unencoded(self, tmp_path): + project = tmp_path / "project#1" + extension_dir = project / ".specify" / "extensions" / "example" + script_dir = extension_dir / "scripts" + (script_dir / "lib").mkdir(parents=True) + source_path = script_dir / "run.sh" + output_dir = tmp_path / "generated" + + result = CommandRegistrar.rewrite_extension_paths( + ". './lib/helper.sh'\n", + "example", + extension_dir, + source_path=source_path, + relative_to=output_dir, + ) + + assert "%23" not in result + assert ( + "../project#1/.specify/extensions/example/scripts/lib/helper.sh" in result + ) + + def test_extension_script_rewrite_prefixes_dot_leading_output_paths(self, tmp_path): + extension_dir = tmp_path / ".specify" / "extensions" / "example" + script_dir = extension_dir / "scripts" + (script_dir / "lib").mkdir(parents=True) + source_path = script_dir / "run.mjs" + + result = CommandRegistrar.rewrite_extension_paths( + "import './lib/helper.mjs';\n", + "example", + extension_dir, + source_path=source_path, + relative_to=tmp_path, + ) + + assert ( + "import './.specify/extensions/example/scripts/lib/helper.mjs';" in result + ) + + def test_script_composition_uses_runtime_selected_core_base( + self, project_dir, tmp_path, valid_pack_data, monkeypatch + ): + base = tmp_path / "selected" / "bash" / "setup-plan.sh" + base.parent.mkdir(parents=True) + base.write_text("echo selected runtime\n", encoding="utf-8") + monkeypatch.setattr( + "specify_cli.artifacts.catalog._selected_core_script_paths", + lambda _project_root: {"setup-plan": base}, + ) + pack_data = {**valid_pack_data} + pack_data["preset"] = { + **valid_pack_data["preset"], + "id": "setup-plan-wrapper", + "name": "Setup Plan Wrapper", + } + pack_data["provides"] = { + "templates": [ + { + "type": "script", + "name": "setup-plan", + "file": "scripts/setup-plan.sh", + "strategy": "wrap", + } + ] + } + pack_dir = tmp_path / "setup-plan-wrapper" + (pack_dir / "scripts").mkdir(parents=True) + (pack_dir / "preset.yml").write_text(yaml.safe_dump(pack_data)) + (pack_dir / "scripts/setup-plan.sh").write_text( + "echo wrapper\n$CORE_SCRIPT\n", encoding="utf-8" + ) + PresetManager(project_dir).install_from_directory(pack_dir, "0.1.0") + + resolver = PresetResolver(project_dir) + layers = resolver.collect_all_layers("setup-plan", "script") + content = resolver.resolve_content("setup-plan", "script") + + assert layers[1]["path"] == base + assert content is not None + assert "echo wrapper" in content + assert "echo selected runtime" in content + def test_resolve_core_template(self, project_dir): """Test resolving a core template.""" resolver = PresetResolver(project_dir) @@ -1191,6 +1354,37 @@ def test_extension_script_resolve_and_resolve_with_source_parity(self, project_d assert with_source["path"] == str(script_dir / "collect.sh") assert with_source["source"] == "extension:collectext2 (unregistered)" + def test_runtime_selected_core_script_resolve_and_source_parity(self, project_dir): + options = project_dir / ".specify" / "init-options.json" + options.parent.mkdir(parents=True, exist_ok=True) + options.write_text('{"script": "py"}', encoding="utf-8") + + resolver = PresetResolver(project_dir) + + resolved = resolver.resolve("setup-plan", "script") + assert resolved is not None + assert resolved.name == "setup_plan.py" + + with_source = resolver.resolve_with_source("setup-plan", "script") + assert with_source is not None + assert with_source["path"] == str(resolved) + assert with_source["source"] == "core" + + def test_installed_core_script_overrides_bundled_runtime_script(self, project_dir): + options = project_dir / ".specify" / "init-options.json" + options.parent.mkdir(parents=True, exist_ok=True) + options.write_text('{"script": "py"}', encoding="utf-8") + installed_scripts = project_dir / ".specify" / "scripts" / "python" + installed_scripts.mkdir(parents=True, exist_ok=True) + custom_script = installed_scripts / "setup_plan.py" + custom_script.write_text('print("custom setup")\n', encoding="utf-8") + + resolved = PresetResolver(project_dir).resolve("setup-plan", "script") + + assert resolved is not None + assert resolved.resolve() == custom_script.resolve() + assert resolved.read_text(encoding="utf-8") == 'print("custom setup")\n' + class TestResolveContent: """Test PresetResolver.resolve_content() composition.""" diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 9f7a4997df..370c87933b 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -4609,6 +4609,70 @@ def test_rewrite_extension_paths_handles_regex_special_replacement_text( # absolute paths are still left untouched assert f"/{weird_subdir}/abs.md" in rewritten + def test_rewrite_extension_paths_keeps_require_paths_unencoded(self, temp_dir): + from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar + + ext_dir = temp_dir / "extension#1" + source_path = ext_dir / "scripts" / "adapter.cjs" + (source_path.parent / "lib").mkdir(parents=True) + (source_path.parent / "lib" / "helper.cjs").write_text("module.exports = 1") + (source_path.parent / "lib" / "helper.mjs").write_text("export default 1") + (source_path.parent / "lib" / "helper.sh").write_text("echo ready") + output_root = temp_dir / "generated" + output_root.mkdir() + text = "require('./lib/helper.cjs');\nimport './lib/helper.mjs';\n" + + rewritten = AgentCommandRegistrar.rewrite_extension_paths( + text, + "extension#1", + ext_dir, + source_path=source_path, + relative_to=output_root, + ) + + require_path, import_path = rewritten.splitlines() + assert "extension#1" in require_path + assert "extension%231" not in require_path + assert "extension%231" in import_path + + shell_source = source_path.parent / "run.sh" + shell = AgentCommandRegistrar.rewrite_extension_paths( + ". './lib/helper.sh'\n", + "extension#1", + ext_dir, + source_path=shell_source, + relative_to=output_root, + ) + assert "extension#1" in shell + assert "extension%231" not in shell + + def test_rewrite_extension_require_uses_native_path_across_drives( + self, temp_dir, monkeypatch + ): + from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar + + ext_dir = temp_dir / "extension#1" + source_path = ext_dir / "scripts" / "adapter.cjs" + (source_path.parent / "lib").mkdir(parents=True) + output_root = temp_dir / "generated" + output_root.mkdir() + + def different_drive(_path, *, start): + raise ValueError("paths are on different drives") + + monkeypatch.setattr("specify_cli.agents.os.path.relpath", different_drive) + rewritten = AgentCommandRegistrar.rewrite_extension_paths( + "require('./lib/helper.cjs');\n", + "extension#1", + ext_dir, + source_path=source_path, + relative_to=output_root, + ) + + assert str((source_path.parent / "lib").resolve()) in rewritten + assert "file:" not in rewritten + assert "%23" not in rewritten + def test_rewrite_extension_paths_missing_dir_returns_text(self, temp_dir): """A missing extension directory leaves the text unchanged.""" from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar