Skip to content
Open
14 changes: 13 additions & 1 deletion docs/presets/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name> --kind script
specify preset resolve <name> --kind script --output <path>
```

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
Expand All @@ -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 <path>` 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
Expand Down
87 changes: 77 additions & 10 deletions src/specify_cli/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand All @@ -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<dot>\./)?' + 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()
):
Comment thread
Copilot marked this conversation as resolved.
Resolved
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, "/")
Comment thread
Copilot marked this conversation as resolved.
Resolved
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="/-._~")
Comment thread
Copilot marked this conversation as resolved.
Resolved
replacement = f"{replacement}/"
return match.group(1) + replacement

text = pattern.sub(_replacement, text)
return text

def render_markdown_command(
Expand Down
128 changes: 67 additions & 61 deletions src/specify_cli/artifacts/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}:
Expand Down Expand Up @@ -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,
Expand Down
28 changes: 27 additions & 1 deletion src/specify_cli/presets/_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
Comment thread
mnriem marked this conversation as resolved.
Resolved

core_pack = _locate_core_pack()
if core_pack is not None:
for name in names:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
),
Comment thread
Copilot marked this conversation as resolved.
Resolved
)
return text

Expand Down
Loading
Loading