Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(cli): add repowise grammars fetch to stage COBOL and Apex grammars offline (#4471)

Florian Josef Altendorfer2ba1e5cbf8a3
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 92fb59ebc..ab8d3e549 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -79,8 +79,9 @@ repository graph cannot observe. The one COBOL claim is a paragraph that
nothing names and nothing falls through into, at low confidence and never
deletion-ready.
The COBOL and Apex grammars download on first use; offline, set
-`REPOWISE_GRAMMAR_DIR` to a pre-staged grammar cache. `repowise doctor` reports
-whether it is cached.
+`REPOWISE_GRAMMAR_DIR` to a pre-staged grammar cache. `repowise grammars fetch
+<dir>` stages that cache on a machine with network access; copy `<dir>` to the
+offline machine. `repowise doctor` reports whether each grammar is cached.
COBOL is read in fixed reference format, with `EXEC SQL/CICS/DLI` blocks and
`COPY` statements masked before parsing; a copybook parses as a data or
procedure fragment. `COPY` and `EXEC SQL INCLUDE` members resolve to the
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 7fbf9fc54..10b6a1c8d 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -49,7 +49,7 @@ Grouped by task; `PATH` and flags are in each command's section.
set-default`](#repowise-workspace-set-default-alias), [`workspace diagnostics`](#repowise-workspace-diagnostics),
[`workspace check`](#repowise-workspace-check), [`workspace metrics`](#repowise-workspace-metrics-path), [`workspace
impacted-tests`](#repowise-workspace-impacted-tests-repopath)
-- **Maintenance:** [`doctor`](#repowise-doctor-path), [`whats-new`](#repowise-whats-new),
+- **Maintenance:** [`doctor`](#repowise-doctor-path), [`grammars fetch`](#repowise-grammars-fetch-dir), [`whats-new`](#repowise-whats-new),
[`telemetry`](#repowise-telemetry), [`plugins`](#repowise-plugins), [`config hints`](#repowise-config-hints-onoff),
[`login`](#repowise-login), [`logout`](#repowise-logout), [`whoami`](#repowise-whoami),
[`publish`](#repowise-publish-path), [`delete`](#repowise-delete-repo_id), [`uninstall`](#repowise-uninstall-path),
@@ -2057,6 +2057,15 @@ repowise doctor --workspace --repair
- **Distill:** validates `distill:` (unknown keys, bad permission values, unknown filters, non-positive store sizing);
shows omission store size vs cap and whether the opt-in rewrite hook is installed (absence passes).
+### `repowise grammars fetch DIR`
+
+Download the grammars that otherwise download on first use (COBOL, Apex) into `DIR`, printing each with its cache
+state. Exits 1 if any fails. Copy `DIR` to the offline machine and set `REPOWISE_GRAMMAR_DIR` to it.
+
+```bash
+repowise grammars fetch ./grammars
+```
+
### `repowise whats-new`
Release notes since you last looked, then marks the current version seen. Offline, from the bundled changelog.
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
index 54409d40b..7041d4684 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
@@ -270,8 +270,8 @@ def _runtime_grammar_rows(repo_path: _DoctorPath) -> list[DoctorCheck]:
name,
False,
f"not downloaded; {count:,} files would index without symbols. "
- "Re-run 'repowise init' with network access, or set "
- "REPOWISE_GRAMMAR_DIR to a pre-staged grammar cache first",
+ "Re-run 'repowise init' with network access, or stage a cache with "
+ "'repowise grammars fetch <dir>' and set REPOWISE_GRAMMAR_DIR to it",
)
)
return rows
diff --git a/packages/cli/src/repowise/cli/commands/grammars_cmd.py b/packages/cli/src/repowise/cli/commands/grammars_cmd.py
new file mode 100644
index 000000000..d8a830011
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/grammars_cmd.py
@@ -0,0 +1,40 @@
+"""``repowise grammars``: stage the grammars that download on first use.
+
+COBOL and Apex grammars come from the language pack at runtime rather than in a
+wheel. ``fetch`` fills a directory on a machine with network access, to copy to
+an offline one and point ``REPOWISE_GRAMMAR_DIR`` at.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+
+from repowise.cli.helpers import console
+
+
[email protected]("grammars")
+def grammars_group() -> None:
+ """Manage grammars that download on first use (COBOL, Apex)."""
+
+
+@grammars_group.command("fetch")
[email protected]("directory", type=click.Path(file_okay=False, path_type=Path))
+def fetch_command(directory: Path) -> None:
+ """Download every runtime grammar into DIRECTORY for offline use."""
+ from repowise.core.ingestion.languages.registry import REGISTRY
+ from repowise.core.ingestion.parser.grammars import GRAMMAR_DIR_ENV, fetch_runtime_grammars
+
+ directory = directory.resolve()
+ results = fetch_runtime_grammars(str(directory))
+ for tag, cached, error in results:
+ spec = REGISTRY.get(tag)
+ name = spec.display_name if spec else tag
+ if cached:
+ console.print(f" [green]OK[/green] {name}: cached in {directory}")
+ else:
+ console.print(f" [red]FAIL[/red] {name}: {error or 'not downloaded'}")
+ if not all(cached for _tag, cached, _error in results):
+ raise SystemExit(1)
+ console.print(f"\nOn the offline machine, set {GRAMMAR_DIR_ENV}={directory}")
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index a6dd368f5..d008e0ea8 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -99,6 +99,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("status", "status_cmd:status_command"),
("next", "next_cmd:next_command"),
("doctor", "doctor_cmd:doctor_command"),
+ ("grammars", "grammars_cmd:grammars_group"),
("watch", "watch_cmd:watch_command"),
("serve", "serve_cmd:serve_command"),
("mcp", "mcp_cmd:mcp_command"),
diff --git a/packages/core/src/repowise/core/ingestion/parser/grammars.py b/packages/core/src/repowise/core/ingestion/parser/grammars.py
index c217f55b4..54996d216 100644
--- a/packages/core/src/repowise/core/ingestion/parser/grammars.py
+++ b/packages/core/src/repowise/core/ingestion/parser/grammars.py
@@ -153,6 +153,27 @@ def runtime_grammar_cache(tag: str) -> tuple[bool, str]:
return name in pack.downloaded_languages(), str(pack.cache_dir())
+def fetch_runtime_grammars(cache_dir: str) -> list[tuple[str, bool, str]]:
+ """Download every runtime grammar into *cache_dir*: ``(tag, cached, error)`` for each."""
+ import tree_sitter_language_pack as pack
+
+ # Not $REPOWISE_GRAMMAR_DIR: this stages a cache for another machine.
+ pack.configure(pack.PackConfig(cache_dir=cache_dir))
+ results: list[tuple[str, bool, str]] = []
+ for spec in _LANG_REGISTRY.all_specs():
+ if spec.grammar_package != _RUNTIME_DOWNLOAD_PACKAGE:
+ continue
+ name = spec.grammar_loader_args[0] if spec.grammar_loader_args else spec.tag
+ try:
+ getattr(pack, spec.grammar_loader)(name)
+ except Exception as exc:
+ # A cached file that will not load is still a failed fetch.
+ results.append((spec.tag, False, str(exc) or type(exc).__name__))
+ continue
+ results.append((spec.tag, name in pack.downloaded_languages(), ""))
+ return results
+
+
# Loaded grammars, filled one language at a time by ``_get_language``.
_LANGUAGE_REGISTRY: dict[str, Language] = {}
# Failed tags and why; a failure is not retried per file.
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index f08e0b74e..36f28fb6f 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -37,7 +37,7 @@ _EXPECTED_NAMES = frozenset(
"costs", "coverage",
"dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
"events", "expand",
- "export", "generate", "generate-claude-md", "health", "hook",
+ "export", "generate", "generate-claude-md", "grammars", "health", "hook",
"impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "packages", "plugins",
"publish", "reindex", "report",
"restyle",
diff --git a/tests/unit/ingestion/test_runtime_grammars.py b/tests/unit/ingestion/test_runtime_grammars.py
index 369fd42ce..79c96cbab 100644
--- a/tests/unit/ingestion/test_runtime_grammars.py
+++ b/tests/unit/ingestion/test_runtime_grammars.py
@@ -133,3 +133,61 @@ def test_doctor_counts_untracked_files_ingestion_would_index(
assert [(r.name, r.ok) for r in rows] == [("COBOL grammar", False)]
assert "1 files would index without symbols" in rows[0].detail
+
+
+def test_fetch_requests_every_runtime_grammar_into_the_given_dir(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ import tree_sitter_language_pack as pack
+
+ configured: list[object] = []
+ requested: list[str] = []
+ monkeypatch.setattr(pack, "configure", configured.append)
+ monkeypatch.setattr(pack, "get_language", requested.append)
+ monkeypatch.setattr(pack, "downloaded_languages", lambda: ["cobol"])
+ monkeypatch.setenv(grammars.GRAMMAR_DIR_ENV, "/elsewhere")
+
+ result = grammars.fetch_runtime_grammars(str(tmp_path))
+
+ assert [c.cache_dir for c in configured] == [str(tmp_path)]
+ assert sorted(requested) == ["apex", "cobol"]
+ assert sorted(result) == [("apex", False, ""), ("cobol", True, "")]
+
+
+def test_fetch_reports_a_grammar_that_fails_to_load_even_when_its_file_is_cached(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ import tree_sitter_language_pack as pack
+
+ def get_language(name: str) -> None:
+ if name == "cobol":
+ raise OSError("bad ELF header")
+ raise RuntimeError
+
+ monkeypatch.setattr(pack, "configure", lambda config: None)
+ monkeypatch.setattr(pack, "get_language", get_language)
+ monkeypatch.setattr(pack, "downloaded_languages", lambda: ["apex", "cobol"])
+
+ result = grammars.fetch_runtime_grammars(str(tmp_path))
+
+ assert sorted(result) == [("apex", False, "RuntimeError"), ("cobol", False, "bad ELF header")]
+
+
+def test_the_fetch_command_names_each_grammar_and_fails_when_one_is_missing(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ from click.testing import CliRunner
+
+ from repowise.cli.main import cli
+
+ monkeypatch.setattr(
+ grammars,
+ "fetch_runtime_grammars",
+ lambda cache_dir: [("cobol", True, ""), ("apex", False, "Download error")],
+ )
+
+ result = CliRunner().invoke(cli, ["grammars", "fetch", str(tmp_path)])
+
+ assert result.exit_code == 1
+ assert f"COBOL: cached in {tmp_path}" in result.output
+ assert "Apex: Download error" in result.output