feat(cli): single 'sca' entry point + 'sca init' shell integration

- simplecad-cache/simplecad-export entry points are gone (hard cut):
  the same commands live under the unified dispatcher
  (simplecadapi.cli) as 'sca cache ...' and 'sca export ...', each
  group registered at parser level so per-group --help works
- sca init now wires the shell by default (--no-shell skips): a
  ~/.sca/bin/sca shim (Windows sca.cmd) execs the installing venv's
  console script — the venv bin itself never goes on PATH — and the
  shim dir lands on PATH via a marked, removable block in ~/.zshenv
  (read by non-interactive shells, so agents see the command),
  ~/.bashrc, fish conf.d, or the Windows user PATH registry value
  with a change broadcast; rc files are created only for the login
  shell or when they already exist; re-running init refreshes the
  shim (target discovery is symlink-safe, no resolve() out of venv)
- addon/cache/export cli modules expose configure(subparsers) +
  _execute(args); module run() keeps the CLI-shaped argv
- docs: sca namespace across evergreen docs, shell-integration
  section, 'never writes shell profiles' contract line retired
- tests: +17 (dispatcher groups, shell integration, entry-point
  absence); cache/export suites moved to group-token argv
This commit is contained in:
NiJingzhe
2026-09-13 04:19:17 +08:00
parent 3224233a62
commit b939f44043
17 changed files with 674 additions and 130 deletions
+6 -6
View File
@@ -323,9 +323,9 @@ print(cold.cache_report.hit, warm.cache_report.hit)
Inspect or maintain the cache with stable JSON output:
```bash
simplecad-cache status
simplecad-cache verify
simplecad-cache prune
sca cache status
sca cache verify
sca cache prune
```
See the [persistent cache and product build workflow](docs/skill/references/docs/guides/cache-build-workflow.md)
@@ -354,7 +354,7 @@ Export the standard delivery set (AP242 STEP, binary STL, and OBJ) from a
validated product package with no wrapper script:
```bash
uv run simplecad-export out/mounting_plate.scadpkg --output-dir out/exports
uv run sca export out/mounting_plate.scadpkg --output-dir out/exports
```
Request additional targets explicitly. FCStd requires `FreeCADCmd` (or an
@@ -362,9 +362,9 @@ explicit `--freecad-cmd` path); `--check` validates the package, output paths,
and selected target prerequisites without writing files.
```bash
uv run simplecad-export out/mounting_plate.scadpkg \
uv run sca export out/mounting_plate.scadpkg \
--format fcstd --format mjcf --output-dir out/exports --check
uv run simplecad-export out/mounting_plate.scadpkg \
uv run sca export out/mounting_plate.scadpkg \
--format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports
```
STL and OBJ share one direct OpenCASCADE tessellation of the evaluated BREP.
+3 -3
View File
@@ -267,9 +267,9 @@ print(cold.cache_report.hit, warm.cache_report.hit)
缓存检查和维护命令输出稳定 JSON:
```bash
simplecad-cache status
simplecad-cache verify
simplecad-cache prune
sca cache status
sca cache verify
sca cache prune
```
cache mode、配置优先级、PRT 复用、增量失效、损坏修复和破坏性命令确认见
@@ -94,18 +94,18 @@ Environment overrides are `SIMPLECAD_CACHE_MODE`, `SIMPLECAD_CACHE_DIR`,
## Diagnostics and maintenance
`simplecad-cache` prints one stable JSON object. `status`, `verify`, and the
`sca cache` prints one stable JSON object. `status`, `verify`, and the
default `prune` mode are read-only. Explicit mutation is required for repair,
pruning, and clearing.
```bash
simplecad-cache status
simplecad-cache status --namespace part
simplecad-cache verify
simplecad-cache verify --repair
simplecad-cache prune
simplecad-cache prune --apply
simplecad-cache clear --namespace part --yes
sca cache status
sca cache status --namespace part
sca cache verify
sca cache verify --repair
sca cache prune
sca cache prune --apply
sca cache clear --namespace part --yes
```
`verify` always checks record schema/path, object presence, byte length, and
@@ -189,8 +189,7 @@ sca addon list # registry contents + on-disk drift
- Locations resolve as flag > environment variable (`SCA_ADDON_HOME`,
`SCA_SKILLS_DIR`) > `~/.sca/config.toml` > defaults
(`~/.sca/addons`, `~/.agents/skills`). The CLI never writes shell
profiles; env vars are user-side overrides.
(`~/.sca/addons`, `~/.agents/skills`).
- Skills install as `sca-<name>` inside the skills directory — copied,
never symlinked. A non-registry directory of that name is never
overwritten.
@@ -198,6 +197,26 @@ sca addon list # registry contents + on-disk drift
files); `--method clone` is the escape hatch for private
repositories.
### Shell integration (`sca init`)
`sca` is the single CLI for the whole SDK (`sca addon …`, `sca cache …`,
`sca export …`), and `sca init` makes it resolve in any new shell —
interactive or scripted, on any of the supported platforms:
- a shim `~/.sca/bin/sca` (Windows: `sca.cmd`) execs the real console
script of the install that ran `sca init`; the venv's own `bin` is
never put on PATH;
- that directory lands on PATH via a marked, removable
`# >>> sca shell integration >>>` block: `~/.zshenv` for zsh (read by
non-interactive shells too, so agents see the command), `~/.bashrc`
for bash, `~/.config/fish/conf.d/sca-path.fish` for fish; on Windows
the user-scope `PATH` registry value is updated and refreshed.
- rc files are only created for the login shell or when they already
exist — no dotfiles are planted for shells that are not in use;
`--no-shell` skips the step; re-running `sca init` refreshes the shim
after the install moves. Removing the block(s) and `~/.sca/bin`
uninstalls the wiring.
### Hard failures vs warnings
| Outcome | Behavior |
@@ -80,7 +80,7 @@ persistent cache, writing a durable build, or running cache maintenance.
- Product build: `part`, `assemble`, `file_input`, `resolve_cache_policy`,
`PartBuildResult`, `AssemblyBuildResult`, `AssemblySolveReport`, `CacheReport`.
- Cache: `CachePolicy`, `CacheMode`, `ContentAddressedStore`,
`simplecad-cache` CLI (status/verify/prune/clear).
`sca cache` CLI (status/verify/prune/clear).
- Packages: `capture`, `CaptureResult`, `ProductPackage`,
`build_product_package`, `read_product_package`, `load_product_package`,
`validate_product_package`.
@@ -11,7 +11,7 @@ output names, prints one JSON report, and lets independent targets finish even
when an optional target is unavailable:
```bash
uv run simplecad-export out/product.scadpkg --output-dir out/exports
uv run sca export out/product.scadpkg --output-dir out/exports
```
Without `--format`, this writes AP242 STEP, binary STL, and OBJ. Add unusual
@@ -19,9 +19,9 @@ or backend-dependent outputs deliberately; `--check` performs all package,
output-path, and selected-target prerequisite checks without writing files:
```bash
uv run simplecad-export out/product.scadpkg \
uv run sca export out/product.scadpkg \
--format fcstd --format mjcf --output-dir out/exports --check
uv run simplecad-export out/product.scadpkg \
uv run sca export out/product.scadpkg \
--format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports
```
@@ -47,7 +47,7 @@ optional_domains:
- step-inspection # roundtrip validation of exports
artifacts:
- refreshed package (capture re-run if sources changed)
- simplecad-export JSON report (or API reports for programmatic export)
- sca export JSON report (or API reports for programmatic export)
validation_gates:
- package is current (sources unchanged since capture)
- each export report read and printed
@@ -70,7 +70,7 @@ repair_routes:
`.FCStd`; neutral exchange → AP242 `.step`; DCC/surface inspection →
`.obj`; additive manufacturing → `.stl`; MuJoCo simulation → MJCF.
3. **Preflight and export from the package path**. Start with
`uv run simplecad-export <package>.scadpkg --output-dir <dir> --check`.
`uv run sca export <package>.scadpkg --output-dir <dir> --check`.
It checks the package and default STEP/STL/OBJ targets. Add each non-default
target with `--format`; FCStd requires FreeCADCmd (or `--freecad-cmd`) and
MJCF requires an assembly-rooted package. Re-run without `--check` to write
@@ -103,12 +103,12 @@ and `validate_step_roundtrip_rdescriptor` when roundtrip validation applies.
- MJCF: every intended joint present; loop-closing constraints emitted as
equality/connect; public connectors only expose sites/endpoints.
- `.FCStd`: translation consumed the intended package revision.
- `simplecad-export --check` passes before delivery export; the final JSON
- `sca export --check` passes before delivery export; the final JSON
report records every requested target as successful.
## Failure routes
- FreeCAD/FreeCADCmd missing → `simplecad-export --check --format fcstd`
- FreeCAD/FreeCADCmd missing → `sca export --check --format fcstd`
reports the missing backend before writing. Export default STEP/STL/OBJ if
requested, offer STEP as the neutral fallback, and say so explicitly.
- STL/OBJ too coarse or too large → adjust deflection parameters, re-export;
+1 -3
View File
@@ -143,6 +143,4 @@ exclude = [
testpaths = ["test", "tests"]
[project.scripts]
simplecad-cache = "simplecadapi.cache.cli:main"
simplecad-export = "simplecadapi.exporter.cli:main"
sca = "simplecadapi.addon.cli:main"
sca = "simplecadapi.cli:main"
+76 -42
View File
@@ -1,9 +1,12 @@
"""The ``sca`` console script: SimpleCADAPI addon manager.
"""The ``init`` and ``addon`` groups of the top-level ``sca`` console script
(see :mod:`simplecadapi.cli` for the dispatcher and the cache/export groups).
Commands (human-readable output; machine-checkable reports come back
from :func:`run` for tests and tooling):
Groups (human-readable output; machine-checkable reports come back from
:func:`run` for tests and tooling):
* ``sca init`` — create the addon home and write config
* ``sca init`` — create the addon home, write config, and
wire the ``sca`` shim + PATH block so the command resolves in any new
shell (``--no-shell`` skips the wiring)
* ``sca addon add <source>`` — install an addon (GitHub or local path)
* ``sca addon update [name]`` — re-fetch one addon or all of them
* ``sca addon remove <name>`` — delete exactly what was installed
@@ -23,6 +26,7 @@ from typing import Any, Mapping, Sequence
from . import AddonError
from .home import ResolvedPaths, init_home, resolve_paths
from .install import install_addon, list_addons, parse_source, remove_addon, update_addon
from .shell import integrate_shell
from .use import use_addon
@@ -35,20 +39,56 @@ def _add_location_flags(parser: argparse.ArgumentParser) -> None:
)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="sca",
description="SimpleCADAPI addon manager: install third-party analysis, "
"simulation, and downstream tooling packaged with agent skills.",
)
groups = parser.add_subparsers(dest="group", required=True)
def _run_init(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
resolved = resolve_paths(home=args.home, skills_dir=args.skills_dir)
report: dict[str, Any] = dict(init_home(resolved))
report["shell"] = {"skipped": True} if args.no_shell else integrate_shell()
return report, 0
init = groups.add_parser(
def _run_addon(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
resolved = resolve_paths(home=args.home, skills_dir=args.skills_dir)
if args.command == "add":
source = parse_source(args.source)
return install_addon(resolved, source, method=args.method), 0
if args.command == "update":
return (_update_all(resolved) if args.name is None else update_addon(resolved, args.name)), 0
if args.command == "remove":
return remove_addon(resolved, args.name), 0
if args.command == "list":
return list_addons(resolved), 0
if args.command == "use":
report = use_addon(resolved, args.name, args.cmd, capture_output=args.capture)
return report, report.get("exit_code", 0)
raise AssertionError(f"unsupported command: {args.command}")
def _update_all(resolved: ResolvedPaths) -> dict[str, Any]:
from .registry import load_registry
registry = load_registry(resolved.home) if resolved.home.is_dir() else {"addons": {}}
names = sorted(registry.get("addons", {}))
if not names:
raise AddonError("no addons installed; nothing to update")
return {
"action": "update-all",
"updated": [update_addon(resolved, name) for name in names],
}
def configure(subparsers: argparse._SubParsersAction) -> None:
"""Register the ``init`` and ``addon`` groups on a parent subparsers."""
init = subparsers.add_parser(
"init", help="create the addon home, registry, and config (idempotent)"
)
_add_location_flags(init)
init.add_argument(
"--no-shell", action="store_true",
help="skip the shell integration (sca shim + PATH block)",
)
init.set_defaults(handler=_run_init, printer=_print)
addon = groups.add_parser("addon", help="manage SimpleCADAPI addons")
addon = subparsers.add_parser("addon", help="manage SimpleCADAPI addons")
commands = addon.add_subparsers(dest="command", required=True)
add = commands.add_parser(
@@ -93,40 +133,23 @@ def _parser() -> argparse.ArgumentParser:
"--capture", action="store_true",
help="capture the command's output into the report instead of streaming it",
)
addon.set_defaults(handler=_run_addon, printer=_print)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="sca",
description="SimpleCADAPI command line: setup, addons, package export, "
"cache diagnostics.",
)
subparsers = parser.add_subparsers(dest="group", required=True)
configure(subparsers)
return parser
def _update_all(resolved: ResolvedPaths) -> dict[str, Any]:
from .registry import load_registry
registry = load_registry(resolved.home) if resolved.home.is_dir() else {"addons": {}}
names = sorted(registry.get("addons", {}))
if not names:
raise AddonError("no addons installed; nothing to update")
return {
"action": "update-all",
"updated": [update_addon(resolved, name) for name in names],
}
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
resolved = resolve_paths(home=args.home, skills_dir=args.skills_dir)
if args.group == "init":
return init_home(resolved), 0
if args.command == "add":
source = parse_source(args.source)
return install_addon(resolved, source, method=args.method), 0
if args.command == "update":
return (_update_all(resolved) if args.name is None else update_addon(resolved, args.name)), 0
if args.command == "remove":
return remove_addon(resolved, args.name), 0
if args.command == "list":
return list_addons(resolved), 0
if args.command == "use":
report = use_addon(resolved, args.name, args.cmd, capture_output=args.capture)
return report, report.get("exit_code", 0)
raise AssertionError(f"unsupported command: {args.command}")
return args.handler(args)
def _print_check(check: Mapping[str, Any] | None) -> None:
@@ -152,6 +175,17 @@ def _print(report: Mapping[str, Any]) -> None:
print(f" registry: {report.get('registry')}")
if report.get("created") == "yes":
print(" hint: export SCA_ADDON_HOME / SCA_SKILLS_DIR to override these")
shell = report.get("shell") or {}
if shell.get("skipped"):
print(" shell: integration skipped (--no-shell)")
elif shell.get("shim"):
print(f" shell: shim {shell['shim']}")
for rc_path, state in shell.get("shell_blocks", {}).items():
print(f" PATH block: {rc_path} ({state})")
if "windows_path" in shell:
print(f" windows PATH: {shell['windows_path']}")
for note in shell.get("notes", []):
print(f" note: {note}")
return
action = report.get("action")
if action == "update-all":
+1 -1
View File
@@ -4,7 +4,7 @@ Resolution chain for both locations, most specific first:
1. the ``--home`` / ``--skills-dir`` CLI flag;
2. the ``SCA_ADDON_HOME`` / ``SCA_SKILLS_DIR`` environment variables
(user-side overrides — the CLI never writes shell profiles);
(user-side overrides);
3. ``~/.sca/config.toml`` (written by ``sca init``; its presence
is the "initialized" marker);
4. platform defaults: ``~/.sca/addons`` and ``~/.agents/skills``.
+194
View File
@@ -0,0 +1,194 @@
"""``sca init`` shell integration: make ``sca`` resolve in any new shell.
One ``sca init`` wires the command everywhere without the user touching
PATH by hand:
1. a shim directory ``~/.sca/bin`` holding a wrapper that execs the real
console script living next to the interpreter that ran ``sca init``;
the venv's own ``bin`` is never put on PATH (it would shadow ``python``
and friends globally — the shim is surgical);
2. that directory on PATH: a marked, removable block in ``~/.zshenv``
(zsh reads it in non-interactive shells too, so agents and scripts see
the command; ``~/.zshrc`` would only serve interactive terminals),
``~/.bashrc`` (bash), ``~/.config/fish/conf.d/sca-path.fish`` (fish);
on Windows, the user-scope ``PATH`` registry value (HKCU\\Environment)
plus a broadcast so newly opened shells pick it up.
Only the marked block, the shim directory, and (Windows) the single PATH
entry are ever written. An rc file is created only for the user's login
shell or when it already exists — ``sca init`` never plants dotfiles for
shells that are not in use. ``--no-shell`` skips the step; re-running
``sca init`` after the install environment moves refreshes the shim.
Removal is manual by construction: delete the marked block(s) and
``~/.sca/bin`` (Windows: drop the ``.sca\\bin`` PATH entry).
"""
from __future__ import annotations
import os
import shlex
import sys
from pathlib import Path
from typing import Any
BLOCK_BEGIN = "# >>> sca shell integration >>>"
BLOCK_END = "# <<< sca shell integration <<<"
_SHIM_DIR_PARTS = (".sca", "bin")
def shim_dir(home: Path | None = None) -> Path:
"""Directory holding the ``sca`` wrapper (default ``~/.sca/bin``)."""
base = home if home is not None else Path.home()
return base.joinpath(*_SHIM_DIR_PARTS)
def console_script_target(executable: Path | None = None) -> Path:
"""The real ``sca`` console script next to the running interpreter.
Deliberately no symlink resolution: venv interpreters are usually
symlinks into a toolchain directory, and following them would leave
the venv whose ``bin/`` holds the console script.
"""
interpreter = Path(executable or sys.executable)
if not interpreter.is_absolute():
interpreter = Path.cwd() / interpreter
return interpreter.parent / ("sca.exe" if sys.platform == "win32" else "sca")
def render_posix_shim(target: Path) -> str:
quoted = shlex.quote(str(target))
return (
"#!/bin/sh\n"
"# Written by `sca init`; re-run `sca init` after the install moves.\n"
f"SCA_TARGET={quoted}\n"
'if [ ! -x "$SCA_TARGET" ]; then\n'
' echo "sca: console script $SCA_TARGET is missing;" '
'"re-run \'sca init\' from the environment that provides simplecadapi" >&2\n'
" exit 127\n"
"fi\n"
'exec "$SCA_TARGET" "$@"\n'
)
def render_cmd_shim(target: Path) -> str:
return (
"@echo off\r\n"
"rem Written by `sca init`; re-run `sca init` after the install moves.\r\n"
f'if not exist "{target}" (\r\n'
" echo sca: console script is missing; "
"re-run sca init from the environment that provides simplecadapi 1>&2\r\n"
" exit /b 127\r\n"
")\r\n"
f'@"{target}" %*\r\n'
)
def _path_block() -> str:
return f"{BLOCK_BEGIN}\n" 'export PATH="$HOME/.sca/bin:$PATH"\n' f"{BLOCK_END}\n"
def _fish_block() -> str:
return f"{BLOCK_BEGIN}\n" 'set -gx PATH "$HOME/.sca/bin" $PATH\n' f"{BLOCK_END}\n"
def _upsert_block(path: Path, block: str) -> str:
"""Append the marked block once; return "written" or "present"."""
text = path.read_text(encoding="utf-8") if path.is_file() else ""
if BLOCK_BEGIN in text:
return "present"
if text and not text.endswith("\n"):
text += "\n"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text + block, encoding="utf-8")
return "written"
def _login_shell() -> str:
return Path(os.environ.get("SHELL", "")).name.lower()
def _posix_rc_targets(home: Path) -> dict[Path, str]:
"""rc file -> block kind, for shells actually in use on this machine."""
targets: dict[Path, str] = {}
shell = _login_shell()
zshenv = home / ".zshenv"
bashrc = home / ".bashrc"
fish_file = home / ".config" / "fish" / "conf.d" / "sca-path.fish"
if zshenv.is_file() or shell == "zsh":
targets[zshenv] = "posix"
if bashrc.is_file() or shell == "bash":
targets[bashrc] = "posix"
if (home / ".config" / "fish").is_dir() or shell == "fish":
targets[fish_file] = "fish"
return targets
def _ensure_path_entry(entries: list[str], entry: str) -> tuple[list[str], bool]:
"""Insert ``entry`` at the front of a PATH entry list if absent."""
wanted = entry.rstrip("\\/").lower()
if any(item.rstrip("\\/").lower() == wanted for item in entries):
return entries, False
return [entry, *entries], True
def _windows_user_path(shim: Path) -> dict[str, Any]:
"""Prepend the shim dir to the user-scope PATH (HKCU\\Environment); no admin."""
import winreg
entry = str(shim)
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key: # ty: ignore[unresolved-attribute]
try:
value, value_type = winreg.QueryValueEx(key, "Path") # ty: ignore[unresolved-attribute]
except FileNotFoundError:
value, value_type = "", winreg.REG_EXPAND_SZ # ty: ignore[unresolved-attribute]
entries, changed = _ensure_path_entry(str(value).split(";"), entry)
report: dict[str, Any] = {"windows_path": "present" if not changed else "appended"}
if changed:
with winreg.OpenKey( # ty: ignore[unresolved-attribute]
winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE # ty: ignore[unresolved-attribute]
) as key:
winreg.SetValueEx(key, "Path", 0, value_type, ";".join(entries)) # ty: ignore[unresolved-attribute]
_broadcast_environment_change()
report["notes"] = ["PATH updated; already-open terminals must be reopened"]
return report
def _broadcast_environment_change() -> None:
import ctypes
HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG = 0xFFFF, 0x001A, 0x0002
result = ctypes.c_ulong()
ctypes.windll.user32.SendMessageTimeoutW( # ty: ignore[unresolved-attribute]
HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",
SMTO_ABORTIFHUNG, 5000, ctypes.byref(result),
)
def integrate_shell(home: Path | None = None) -> dict[str, Any]:
"""Write the shim and PATH wiring; return a report for the init output."""
base = home if home is not None else Path.home()
target = console_script_target()
report: dict[str, Any] = {"shim": None, "shell_blocks": {}, "notes": []}
if not target.is_file():
report["notes"].append(
f"no console script next to {sys.executable!r}; shell integration "
"skipped — run `sca init` from the environment that provides simplecadapi"
)
return report
directory = shim_dir(base)
directory.mkdir(parents=True, exist_ok=True)
if sys.platform == "win32":
shim = directory / "sca.cmd"
shim.write_text(render_cmd_shim(target), encoding="utf-8")
report.update(_windows_user_path(directory))
else:
shim = directory / "sca"
shim.write_text(render_posix_shim(target), encoding="utf-8")
shim.chmod(0o755)
for rc_path, kind in _posix_rc_targets(base).items():
block = _fish_block() if kind == "fish" else _path_block()
report["shell_blocks"][str(rc_path)] = _upsert_block(rc_path, block)
report["shim"] = str(shim)
return report
+29 -22
View File
@@ -1,4 +1,7 @@
"""Command-line diagnostics for the SimpleCAD content-addressed cache."""
"""Command-line diagnostics for the SimpleCAD content-addressed cache.
This module owns the ``sca cache`` group (see :mod:`simplecadapi.cli`).
"""
from __future__ import annotations
@@ -11,8 +14,11 @@ from .policy import CacheMode, CachePolicy, resolve_cache_policy
from .store import ContentAddressedStore
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="simplecad-cache")
def configure(subparsers: argparse._SubParsersAction) -> None:
"""Register the ``cache`` group on a parent subparsers action."""
parser = subparsers.add_parser(
"cache", help="content-addressed cache diagnostics (status/verify/prune/clear)"
)
parser.add_argument(
"--project-root",
type=Path,
@@ -20,24 +26,35 @@ def _parser() -> argparse.ArgumentParser:
help="project root used to resolve pyproject.toml and relative cache paths",
)
parser.add_argument("--cache-dir", type=Path, help="override the resolved cache root")
subparsers = parser.add_subparsers(dest="command", required=True)
commands = parser.add_subparsers(dest="command", required=True)
status = subparsers.add_parser("status", help="report cache counts")
status = commands.add_parser("status", help="report cache counts")
status.add_argument("--namespace")
verify = subparsers.add_parser("verify", help="verify records and objects")
verify = commands.add_parser("verify", help="verify records and objects")
verify.add_argument("--namespace")
verify.add_argument("--repair", action="store_true")
prune = subparsers.add_parser("prune", help="report or quarantine orphan objects")
prune = commands.add_parser("prune", help="report or quarantine orphan objects")
prune.add_argument("--apply", action="store_true")
clear = subparsers.add_parser("clear", help="clear one namespace or the complete cache")
clear = commands.add_parser("clear", help="clear one namespace or the complete cache")
clear.add_argument("--namespace")
clear.add_argument("--yes", action="store_true", help="confirm destructive removal")
parser.set_defaults(handler=_execute, printer=_print_report)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="sca", description=__doc__)
configure(parser.add_subparsers(dest="group", required=True))
return parser
def _print_report(report: dict[str, Any]) -> None:
print(json.dumps(report, sort_keys=True))
def _policy(args: argparse.Namespace, *, writable: bool) -> CachePolicy:
explicit: dict[str, Any] = {}
if args.cache_dir is not None:
@@ -48,8 +65,7 @@ def _policy(args: argparse.Namespace, *, writable: bool) -> CachePolicy:
return resolve_cache_policy(explicit or None, project_root=args.project_root)
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
if args.command == "clear" and not args.yes:
raise ValueError("clear requires --yes confirmation")
writable = bool(
@@ -73,15 +89,6 @@ def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
raise AssertionError(f"unsupported command: {args.command}")
def main(argv: Sequence[str] | None = None) -> int:
try:
report, exit_code = run(argv)
except (OSError, PermissionError, ValueError) as exc:
print(json.dumps({"error": type(exc).__name__, "message": str(exc)}, sort_keys=True))
return 2
print(json.dumps(report, sort_keys=True))
return exit_code
if __name__ == "__main__":
raise SystemExit(main())
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
return _execute(args)
+66
View File
@@ -0,0 +1,66 @@
"""The single ``sca`` console script: the whole SimpleCADAPI command line.
Groups, each owned by its module and registered here at parser level so
``sca <group> --help`` works::
sca init # machine setup: addon home + shell wiring
sca addon add|update|remove|list|use
sca cache status|verify|prune|clear
sca export <package.scadpkg> [--format ...]
Shared contract: group handlers return ``(report, exit_code)`` and are
followed by the group's own printer (human-readable for init/addon, JSON
for cache/export); errors print one ``sca: ...`` line to stderr and exit 2.
The historical ``simplecad-cache``/``simplecad-export`` entry points are
gone — the same commands live here.
"""
from __future__ import annotations
import argparse
import sys
from typing import Any, Sequence
from .addon import AddonError
from .addon.install import sca_version
def build_parser() -> argparse.ArgumentParser:
from .addon import cli as addon_cli
from .cache import cli as cache_cli
from .exporter import cli as exporter_cli
parser = argparse.ArgumentParser(
prog="sca",
description="SimpleCADAPI command line: setup, addons, package export, "
"cache diagnostics.",
)
parser.add_argument(
"--version", action="version", version=f"sca {sca_version()}"
)
subparsers = parser.add_subparsers(dest="group", required=True)
addon_cli.configure(subparsers)
cache_cli.configure(subparsers)
exporter_cli.configure(subparsers)
return parser
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int, Any]:
"""Parse and dispatch; return ``(report, exit_code, printer)``."""
args = build_parser().parse_args(argv)
report, exit_code = args.handler(args)
return report, exit_code, args.printer
def main(argv: Sequence[str] | None = None) -> int:
try:
report, exit_code, printer = run(argv)
except (AddonError, OSError, ValueError) as exc:
print(f"sca: {type(exc).__name__}: {exc}", file=sys.stderr)
return 2
printer(report)
return exit_code
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())
+23 -18
View File
@@ -1,4 +1,7 @@
"""Command-line export of validated ``.scadpkg`` product packages."""
"""Command-line export of validated ``.scadpkg`` product packages.
This module owns the ``sca export`` group (see :mod:`simplecadapi.cli`).
"""
from __future__ import annotations
@@ -36,9 +39,11 @@ _SUFFIXES = {
}
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="simplecad-export",
def configure(subparsers: argparse._SubParsersAction) -> None:
"""Register the ``export`` group on a parent subparsers action."""
parser = subparsers.add_parser(
"export",
help="export a validated .scadpkg product package (step/stl/obj by default)",
description="Export a validated .scadpkg product package.",
)
parser.add_argument("input", type=Path, help="input .scadpkg package")
@@ -64,9 +69,19 @@ def _parser() -> argparse.ArgumentParser:
parser.add_argument("--relative", action="store_true", help="use relative mesh deflection")
parser.add_argument("--freecad-cmd", help="path to FreeCADCmd/FreeCAD for FCStd output")
parser.add_argument("--document-name", default="SimpleCADProduct")
parser.set_defaults(handler=_execute, printer=_print_report)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="sca")
configure(parser.add_subparsers(dest="group", required=True))
return parser
def _print_report(report: dict[str, Any]) -> None:
print(json.dumps(report, default=str, sort_keys=True))
def _parse_outputs(items: Sequence[str]) -> dict[str, Path]:
outputs: dict[str, Path] = {}
for item in items:
@@ -110,8 +125,7 @@ def _report_value(value: Any) -> Any:
return value
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
input_path = args.input.expanduser().resolve()
if input_path.suffix.lower() != ".scadpkg":
raise ValueError("input must end in .scadpkg")
@@ -182,15 +196,6 @@ def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
return report, 0 if not failures else 1
def main(argv: Sequence[str] | None = None) -> int:
try:
report, exit_code = run(argv)
except (OSError, PermissionError, ValueError) as exc:
print(json.dumps({"error": type(exc).__name__, "message": str(exc)}, sort_keys=True))
return 2
print(json.dumps(report, default=str, sort_keys=True))
return exit_code
if __name__ == "__main__":
raise SystemExit(main())
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
return _execute(args)
+12 -12
View File
@@ -21,24 +21,24 @@ def test_status_verify_and_prune_report_stable_counts(tmp_path):
orphan.parent.mkdir(parents=True, exist_ok=True)
orphan.write_bytes(b"orphan")
status, exit_code = run(["--cache-dir", str(root), "status", "--namespace", "part"])
status, exit_code = run(["cache", "--cache-dir", str(root), "status", "--namespace", "part"])
assert exit_code == 0
assert status["records"] == 1
assert status["objects"] == 2
assert status["orphan_objects"] == 1
verified, exit_code = run(["--cache-dir", str(root), "verify"])
verified, exit_code = run(["cache", "--cache-dir", str(root), "verify"])
assert exit_code == 1
assert verified["records_checked"] == 2
assert verified["invalid_records"] == 0
assert verified["orphan_objects"] == 1
preview, exit_code = run(["--cache-dir", str(root), "prune"])
preview, exit_code = run(["cache", "--cache-dir", str(root), "prune"])
assert exit_code == 0
assert preview == {"orphan_objects": 1, "reclaimed_bytes": 6, "dry_run": True}
assert orphan.exists()
applied, exit_code = run(["--cache-dir", str(root), "prune", "--apply"])
applied, exit_code = run(["cache", "--cache-dir", str(root), "prune", "--apply"])
assert exit_code == 0
assert applied["orphan_objects"] == 1
assert applied["dry_run"] is False
@@ -51,17 +51,17 @@ def test_verify_detects_and_repairs_corrupt_object(tmp_path):
record = store.put("part", sha256_bytes(b"part-key"), b"valid")
store.object_path(record.object_hash).write_bytes(b"broken")
report, exit_code = run(["--cache-dir", str(root), "verify"])
report, exit_code = run(["cache", "--cache-dir", str(root), "verify"])
assert exit_code == 1
assert report["invalid_records"] == 1
assert report["invalid_objects"] == 1
repaired, exit_code = run(["--cache-dir", str(root), "verify", "--repair"])
repaired, exit_code = run(["cache", "--cache-dir", str(root), "verify", "--repair"])
assert exit_code == 1
assert repaired["repaired"] is True
assert store.stats().quarantined == 2
clean, exit_code = run(["--cache-dir", str(root), "verify"])
clean, exit_code = run(["cache", "--cache-dir", str(root), "verify"])
assert exit_code == 0
assert clean["ok"] is True
@@ -76,7 +76,7 @@ def test_verify_hashes_objects_when_runtime_read_verification_is_disabled(tmp_pa
store.object_path(record.object_hash).write_bytes(b"xxxxx")
assert store.get("part", key) is not None
report, exit_code = run(["--cache-dir", str(root), "verify"])
report, exit_code = run(["cache", "--cache-dir", str(root), "verify"])
assert exit_code == 1
assert report["invalid_objects"] == 1
@@ -84,13 +84,13 @@ def test_verify_hashes_objects_when_runtime_read_verification_is_disabled(tmp_pa
def test_read_only_commands_and_unconfirmed_clear_do_not_create_cache(tmp_path):
root = tmp_path / "absent-cache"
status, exit_code = run(["--cache-dir", str(root), "status"])
status, exit_code = run(["cache", "--cache-dir", str(root), "status"])
assert exit_code == 0
assert status["records"] == 0
assert not root.exists()
try:
run(["--cache-dir", str(root), "clear"])
run(["cache", "--cache-dir", str(root), "clear"])
except ValueError as exc:
assert "--yes" in str(exc)
else:
@@ -108,14 +108,14 @@ def test_clear_requires_confirmation_and_preserves_shared_objects(tmp_path):
store.put("assembly", assembly_key, payload)
try:
run(["--cache-dir", str(root), "clear", "--namespace", "part"])
run(["cache", "--cache-dir", str(root), "clear", "--namespace", "part"])
except ValueError as exc:
assert "confirm" in str(exc)
else:
raise AssertionError("clear without --yes must fail")
report, exit_code = run(
["--cache-dir", str(root), "clear", "--namespace", "part", "--yes"]
["cache", "--cache-dir", str(root), "clear", "--namespace", "part", "--yes"]
)
assert exit_code == 0
assert report["cleared"] is True
+5 -5
View File
@@ -12,7 +12,7 @@ def test_check_defaults_to_step_stl_and_obj(monkeypatch, tmp_path: Path):
input_path = tmp_path / "bracket.scadpkg"
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
report, exit_code = cli.run([str(input_path), "--check", "--output-dir", str(tmp_path / "out")])
report, exit_code = cli.run(["export", str(input_path), "--check", "--output-dir", str(tmp_path / "out")])
assert exit_code == 0
assert report["check_only"] is True
@@ -26,7 +26,7 @@ def test_check_fcstd_reports_missing_freecad(monkeypatch, tmp_path: Path):
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
monkeypatch.setattr(cli, "discover_freecad_executable", lambda: None)
report, exit_code = cli.run([str(tmp_path / "part.scadpkg"), "--format", "fcstd", "--check"])
report, exit_code = cli.run(["export", str(tmp_path / "part.scadpkg"), "--format", "fcstd", "--check"])
assert exit_code == 1
assert report["formats"]["fcstd"]["ok"] is False
@@ -36,7 +36,7 @@ def test_check_fcstd_reports_missing_freecad(monkeypatch, tmp_path: Path):
def test_check_mjcf_requires_assembly(monkeypatch, tmp_path: Path):
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
report, exit_code = cli.run([str(tmp_path / "part.scadpkg"), "--format", "mjcf", "--check"])
report, exit_code = cli.run(["export", str(tmp_path / "part.scadpkg"), "--format", "mjcf", "--check"])
assert exit_code == 1
assert report["formats"]["mjcf"]["ok"] is False
@@ -44,7 +44,7 @@ def test_check_mjcf_requires_assembly(monkeypatch, tmp_path: Path):
def test_check_rejects_unknown_package_extension(tmp_path: Path):
try:
cli.run([str(tmp_path / "part.json"), "--check"])
cli.run(["export", str(tmp_path / "part.json"), "--check"])
except ValueError as exc:
assert ".scadpkg" in str(exc)
else:
@@ -53,7 +53,7 @@ def test_check_rejects_unknown_package_extension(tmp_path: Path):
def test_output_override_requires_selected_optional_format(tmp_path: Path):
try:
cli.run([str(tmp_path / "part.scadpkg"), "--check", "--output", "fcstd=part.FCStd"])
cli.run(["export", str(tmp_path / "part.scadpkg"), "--check", "--output", "fcstd=part.FCStd"])
except ValueError as exc:
assert "--format" in str(exc)
else:
+81
View File
@@ -0,0 +1,81 @@
"""Tests for the unified ``sca`` entry point (:mod:`simplecadapi.cli`)."""
from importlib.metadata import entry_points
from pathlib import Path
import pytest
from simplecadapi.cli import run
@pytest.fixture(autouse=True)
def fake_user_home(tmp_path, monkeypatch):
monkeypatch.setattr(Path, "home", lambda: tmp_path)
monkeypatch.delenv("SCA_ADDON_HOME", raising=False)
monkeypatch.delenv("SCA_SKILLS_DIR", raising=False)
return tmp_path
def test_init_group_runs_with_shell_integration(tmp_path):
report, code, printer = run(["init"])
assert code == 0
assert Path(report["home"]) == tmp_path / ".sca" / "addons"
assert report["shell"]["shim"]
assert (tmp_path / ".zshenv").is_file()
assert callable(printer)
def test_init_no_shell_writes_no_shim(tmp_path):
report, code, _ = run(["init", "--no-shell"])
assert code == 0
assert report["shell"] == {"skipped": True}
assert not (tmp_path / ".sca" / "bin").exists()
def test_addon_group_dispatches(tmp_path):
run(["init"])
report, code, _ = run(["addon", "list"])
assert code == 0
assert report["addons"] == []
def test_cache_group_dispatches(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
report, code, printer = run(
["cache", "--cache-dir", str(tmp_path / "cache"), "status"]
)
assert code == 0
assert isinstance(report, dict)
assert callable(printer)
def test_export_group_dispatches(tmp_path, monkeypatch):
from simplecadapi.exporter import cli as export_cli
package = type("P", (), {"root_kind": "part", "root_id": "part-bracket"})
monkeypatch.setattr(export_cli, "read_product_package", lambda value: package)
pkg = tmp_path / "bracket.scadpkg"
pkg.write_bytes(b"stub")
report, code, _ = run(
["export", str(pkg), "--check", "--output-dir", str(tmp_path / "out")]
)
assert code == 0
assert report["ok"] is True
assert set(report["formats"]) == {"step", "stl", "obj"}
def test_version_reports_the_sdk_version(capsys):
from simplecadapi.addon.install import sca_version
with pytest.raises(SystemExit) as excinfo:
run(["--version"])
assert excinfo.value.code == 0
assert sca_version() in capsys.readouterr().out
def test_legacy_entry_points_are_gone():
scripts = {ep.name for ep in entry_points(group="console_scripts")}
assert "sca" in scripts
assert "simplecad-cache" not in scripts
assert "simplecad-export" not in scripts
+140
View File
@@ -0,0 +1,140 @@
"""Unit tests for the ``sca init`` shell integration (shim + PATH wiring)."""
import stat
import sys
from pathlib import Path
import pytest
from simplecadapi.addon.shell import (
BLOCK_BEGIN,
_ensure_path_entry,
console_script_target,
integrate_shell,
render_cmd_shim,
render_posix_shim,
)
@pytest.fixture(autouse=True)
def sandbox(tmp_path, monkeypatch):
monkeypatch.setattr(Path, "home", lambda: tmp_path)
return tmp_path
def _fake_install(root: Path, name: str = "venv") -> Path:
"""A fake venv whose bin/ holds the sca console script; returns python."""
venv_bin = root / name / "bin"
venv_bin.mkdir(parents=True)
script = venv_bin / "sca"
script.write_text("#!/bin/sh\n", encoding="utf-8")
script.chmod(0o755)
return venv_bin / "python3"
def _patch_interpreter(monkeypatch, python: Path) -> None:
monkeypatch.setattr(sys, "executable", str(python))
def test_integrate_writes_shim_and_zshenv_for_zsh(tmp_path, monkeypatch):
_patch_interpreter(monkeypatch, _fake_install(tmp_path))
monkeypatch.setenv("SHELL", "/bin/zsh")
report = integrate_shell()
shim = Path(report["shim"])
assert shim == tmp_path / ".sca" / "bin" / "sca"
assert shim.stat().st_mode & stat.S_IXUSR
assert shim.read_text(encoding="utf-8").startswith("#!/bin/sh")
assert str(tmp_path / "venv" / "bin" / "sca") in shim.read_text(encoding="utf-8")
zshenv = (tmp_path / ".zshenv").read_text(encoding="utf-8")
assert BLOCK_BEGIN in zshenv
assert 'export PATH="$HOME/.sca/bin:$PATH"' in zshenv
assert report["shell_blocks"][str(tmp_path / ".zshenv")] == "written"
def test_integrate_is_idempotent_and_refreshes_stale_shim(tmp_path, monkeypatch):
_patch_interpreter(monkeypatch, _fake_install(tmp_path, "venv-a"))
monkeypatch.setenv("SHELL", "/bin/zsh")
first = integrate_shell()
second = integrate_shell()
assert second["shell_blocks"][str(tmp_path / ".zshenv")] == "present"
zshenv = (tmp_path / ".zshenv").read_text(encoding="utf-8")
assert zshenv.count(BLOCK_BEGIN) == 1
_patch_interpreter(monkeypatch, _fake_install(tmp_path, "venv-b"))
integrate_shell()
shim = Path(first["shim"]).read_text(encoding="utf-8")
assert "venv-b/bin/sca" in shim and "venv-a" not in shim
def test_bash_users_get_bashrc_and_no_zshenv(tmp_path, monkeypatch):
_patch_interpreter(monkeypatch, _fake_install(tmp_path))
monkeypatch.setenv("SHELL", "/bin/bash")
(tmp_path / ".bashrc").write_text("# my rc\n", encoding="utf-8")
report = integrate_shell()
bashrc = (tmp_path / ".bashrc").read_text(encoding="utf-8")
assert 'export PATH="$HOME/.sca/bin:$PATH"' in bashrc
assert bashrc.startswith("# my rc\n")
assert not (tmp_path / ".zshenv").exists()
assert set(report["shell_blocks"]) == {str(tmp_path / ".bashrc")}
def test_fish_conf_d_file_when_fish_is_in_use(tmp_path, monkeypatch):
_patch_interpreter(monkeypatch, _fake_install(tmp_path))
monkeypatch.setenv("SHELL", "/usr/bin/fish")
integrate_shell()
fish_file = tmp_path / ".config" / "fish" / "conf.d" / "sca-path.fish"
assert 'set -gx PATH "$HOME/.sca/bin" $PATH' in fish_file.read_text(encoding="utf-8")
def test_unknown_shell_writes_no_rc_files(tmp_path, monkeypatch):
_patch_interpreter(monkeypatch, _fake_install(tmp_path))
monkeypatch.setenv("SHELL", "")
report = integrate_shell()
assert report["shim"] is not None
assert report["shell_blocks"] == {}
def test_missing_console_script_skips_with_a_note(tmp_path, monkeypatch):
interpreter = tmp_path / "bare" / "python3"
interpreter.parent.mkdir(parents=True)
interpreter.write_text("", encoding="utf-8")
_patch_interpreter(monkeypatch, interpreter)
monkeypatch.setenv("SHELL", "/bin/zsh")
report = integrate_shell()
assert report["shim"] is None
assert report["notes"] and "shell integration" in report["notes"][0]
assert not (tmp_path / ".zshenv").exists()
def test_posix_shim_fails_loudly_when_target_is_gone(tmp_path):
shim_text = render_posix_shim(tmp_path / "gone" / "sca")
assert "exit 127" in shim_text
def test_cmd_shim_references_target_and_passes_args(tmp_path):
text = render_cmd_shim(tmp_path / "venv" / "Scripts" / "sca.exe")
assert str(tmp_path / "venv" / "Scripts" / "sca.exe") in text
assert "%*" in text
def test_ensure_path_entry_is_idempotent_and_case_insensitive():
entries, changed = _ensure_path_entry(["C:\\Tools"], "C:\\Users\\x\\.sca\\bin")
assert changed and entries == ["C:\\Users\\x\\.sca\\bin", "C:\\Tools"]
entries, changed = _ensure_path_entry(["c:\\users\\x\\.sca\\bin"], "C:\\Users\\X\\.sca\\bin")
assert not changed
def test_console_script_target_stays_inside_the_venv(tmp_path, monkeypatch):
# venv interpreters are symlinks into a toolchain; the target must
# stay next to the invoked path, not the resolved one
venv_bin = tmp_path / "venv" / "bin"
venv_bin.mkdir(parents=True)
target = console_script_target(venv_bin / "python3")
assert target == venv_bin / "sca"