Skip to content

Commit bebc977

Browse files
feat: install a JavaScript workspace's dependencies before the analysis
A call from one package of a JavaScript monorepo into another resolves only once the packages are installed, so a fresh checkout showed no calls between them. Core now installs them itself when CODEBOARDING_INSTALL_DEPENDENCIES is set (no install scripts, frozen lockfile, hard timeout), for the head checkout and the merge-base worktree alike. The action provides the rest: - `install_dependencies` (default true) turns it on. - prepare-dependencies.sh detects a workspace and its package manager (the `packageManager` pin, else the lockfile's), skips Yarn Plug'n'Play, and points every package manager's cache at one store under RUNNER_TEMP. - Bun comes from oven-sh/setup-bun at the pinned version; pnpm and Yarn from corepack. - The store is restored per lockfile, falling back to the previous one, and saved only by sync: a cache saved inside a pull request is visible to no other, so it would only use up the repository's quota. The install needs the Core release that adds it; with the current pin the variable is ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 381a0c4 commit bebc977

4 files changed

Lines changed: 279 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,16 @@ A pull request whose changed files are all outside what the engine analyses (doc
104104

105105
Every review comment ends with a machine-readable HTML comment, `<!-- codeboarding: platform_url=… changed=… analysed_files_changed=… head=… -->`, for readers that should not parse the prose or the diagram. The progress comment carries the platform link from the start, so a pull request can be opened there while the run is still going.
106106

107+
### JavaScript workspaces
108+
109+
In a JavaScript or TypeScript monorepo (npm, pnpm, Yarn or Bun workspaces), a call from one package into another only resolves once the packages are installed, so a fresh checkout shows no calls between them. With `install_dependencies: true` (the default), the action installs the analyzed repository's dependencies before the analysis:
110+
111+
- **Without install scripts and with the lockfile frozen.** No dependency code runs, and the lockfile is never changed.
112+
- **With the pinned package manager:** the version `packageManager` names, else the one the lockfile belongs to. Bun is set up with `oven-sh/setup-bun`; pnpm and Yarn come from corepack.
113+
- **From a cached store.** The package store is cached once per lockfile, about 1 GB for a large monorepo, and counts against the repository's 10 GB of free Actions cache. Only sync saves it, so pull request runs read it without adding to the repository's cache use.
114+
115+
A repository that is not a workspace, has no lockfile, or uses Yarn Plug'n'Play (which keeps no `node_modules`) is analyzed without an install. If an install fails, the analysis runs as it would without one. For a private registry, set the token your `.npmrc` reads in the job's `env` (for example `NPM_TOKEN: ${{ secrets.NPM_TOKEN }}`); the install inherits it. Set `install_dependencies: false` to skip installing entirely.
116+
107117
## Authentication and providers
108118

109119
The `llm` input is required and says where analysis credentials come from. There are

‎action.yml‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,10 @@ inputs:
152152
in_place: committed as .codeboarding/ on the synced branch itself.
153153
required: false
154154
default: 'codeboarding_branch'
155+
install_dependencies:
156+
description: "Install the analyzed repository's JavaScript workspace dependencies before the analysis (no install scripts, frozen lockfile), so calls between its packages resolve. The package store is cached per lockfile. Set to false to skip."
157+
required: false
158+
default: 'true'
155159
warmstart_retention_days:
156160
description: 'Days to keep the reusable analysis. Only the next run reads it.'
157161
required: false
@@ -392,6 +396,40 @@ runs:
392396
distribution: temurin
393397
java-version: '21'
394398

399+
# Core installs the dependencies itself, for the head checkout and the merge-base worktree
400+
# alike; these steps only provide the package manager and one cached store for both.
401+
- name: Prepare dependency install
402+
id: deps
403+
if: steps.guard.outputs.skip != 'true'
404+
shell: bash
405+
env:
406+
CHECKOUT_DIR: ${{ github.workspace }}/.codeboarding-target
407+
STORE_DIR: ${{ runner.temp }}/cb-deps
408+
INSTALL_DEPENDENCIES: ${{ inputs.install_dependencies }}
409+
run: "$GITHUB_ACTION_PATH/scripts/action/prepare-dependencies.sh"
410+
411+
- name: Setup Bun for dependency install
412+
if: steps.guard.outputs.skip != 'true' && steps.deps.outputs.manager == 'bun'
413+
uses: oven-sh/setup-bun@v2
414+
with:
415+
bun-version: ${{ steps.deps.outputs.version || 'latest' }}
416+
417+
- name: Enable corepack for dependency install
418+
if: steps.guard.outputs.skip != 'true' && (steps.deps.outputs.manager == 'pnpm' || steps.deps.outputs.manager == 'yarn')
419+
shell: bash
420+
run: corepack enable
421+
422+
# Only sync saves the store, on the branch it runs on, which PR runs can read; a cache saved
423+
# inside one pull request is visible to no other, so it would only use up the repository's quota.
424+
- name: Restore dependency cache
425+
id: deps_cache
426+
if: steps.guard.outputs.skip != 'true' && steps.deps.outputs.manager != ''
427+
uses: actions/cache/restore@v4
428+
with:
429+
path: ${{ runner.temp }}/cb-deps
430+
key: cb-deps-${{ runner.os }}-${{ steps.deps.outputs.manager }}-${{ hashFiles(steps.deps.outputs.lockfile) }}
431+
restore-keys: cb-deps-${{ runner.os }}-${{ steps.deps.outputs.manager }}-
432+
395433
- name: Install CodeBoarding
396434
if: steps.guard.outputs.skip != 'true'
397435
shell: bash
@@ -539,6 +577,14 @@ runs:
539577
retention-days: 30
540578
if-no-files-found: ignore
541579

580+
- name: Save dependency cache
581+
if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.deps.outputs.manager != '' && steps.deps_cache.outputs.cache-hit != 'true' && steps.sync_analyze.outcome == 'success'
582+
continue-on-error: true
583+
uses: actions/cache/save@v4
584+
with:
585+
path: ${{ runner.temp }}/cb-deps
586+
key: ${{ steps.deps_cache.outputs.cache-primary-key }}
587+
542588
- name: Write sync summary
543589
if: always() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync'
544590
shell: bash
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env bash
2+
# Decides whether Core installs the analyzed repository's JavaScript workspace dependencies,
3+
# and prepares the runner for it: which package manager, at which version, cached where.
4+
#
5+
# Why: tsserver resolves a call into another workspace package through node_modules, which a
6+
# fresh checkout lacks; without it a monorepo's packages show no calls between them. Core runs
7+
# the install itself (no install scripts, frozen lockfile), for the head checkout and for the
8+
# merge-base worktree alike, so this step only provides the package manager and one store both
9+
# installs and the dependency cache share.
10+
#
11+
# Outputs: manager, version, lockfile (relative to the workspace, for hashFiles). manager is
12+
# empty when nothing will be installed, and every later dependency step is skipped.
13+
# Exports for the analysis steps: CODEBOARDING_INSTALL_DEPENDENCIES and each package manager's
14+
# cache location, all pointing at STORE_DIR.
15+
set -euo pipefail
16+
17+
out() { echo "$1=$2" >> "$GITHUB_OUTPUT"; }
18+
skip() {
19+
echo "Dependencies: not installed ($1)."
20+
out manager ""
21+
exit 0
22+
}
23+
24+
[ "${INSTALL_DEPENDENCIES:-true}" = true ] || skip "install_dependencies is false"
25+
[ -f "$CHECKOUT_DIR/package.json" ] || skip "no package.json"
26+
27+
# Same rules as Core's static_analyzer/workspace_dependencies.py: a workspace, a pinned or
28+
# lockfile-named package manager, and never Yarn Plug'n'Play, which has no node_modules.
29+
read -r manager version lockfile reason < <(python3 - "$CHECKOUT_DIR" <<'PY'
30+
import json, re, sys
31+
from pathlib import Path
32+
33+
repo = Path(sys.argv[1])
34+
try:
35+
manifest = json.loads((repo / "package.json").read_text(encoding="utf-8"))
36+
except (OSError, ValueError):
37+
manifest = {}
38+
workspaces = manifest.get("workspaces") if isinstance(manifest, dict) else None
39+
if isinstance(workspaces, dict):
40+
workspaces = workspaces.get("packages")
41+
if not workspaces and not (repo / "pnpm-workspace.yaml").is_file():
42+
print("- - - not-a-workspace")
43+
sys.exit()
44+
lockfiles = [("bun.lock", "bun"), ("bun.lockb", "bun"), ("pnpm-lock.yaml", "pnpm"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]
45+
present = [(name, manager) for name, manager in lockfiles if (repo / name).is_file()]
46+
manager, version = None, "-"
47+
declared = manifest.get("packageManager") if isinstance(manifest, dict) else None
48+
match = re.match(r"^(bun|pnpm|yarn|npm)@([0-9][^+\s]*)", declared) if isinstance(declared, str) else None
49+
if match:
50+
manager, version = match.group(1), match.group(2)
51+
elif present:
52+
manager = present[0][1]
53+
lockfile = next((name for name, owner in present if owner == manager), None)
54+
if manager is None or lockfile is None:
55+
print("- - - no-lockfile")
56+
sys.exit()
57+
if manager == "yarn":
58+
yarnrc = repo / ".yarnrc.yml"
59+
berry = version != "-" and not version.startswith("1.")
60+
linker = re.search(r"^\s*nodeLinker:\s*['\"]?([\w-]+)", yarnrc.read_text(errors="ignore"), re.M) if yarnrc.is_file() else None
61+
if (linker and linker.group(1) == "pnp") or (not linker and (yarnrc.is_file() or berry)):
62+
print("- - - plug-n-play")
63+
sys.exit()
64+
print(manager, version, lockfile, "ok")
65+
PY
66+
)
67+
68+
case "$reason" in
69+
not-a-workspace) skip "not a JavaScript workspace" ;;
70+
no-lockfile) skip "no lockfile" ;;
71+
plug-n-play) skip "Yarn Plug'n'Play keeps no node_modules" ;;
72+
esac
73+
[ "$version" != "-" ] || version=""
74+
75+
mkdir -p "$STORE_DIR"
76+
{
77+
echo "CODEBOARDING_INSTALL_DEPENDENCIES=1"
78+
echo "COREPACK_ENABLE_DOWNLOAD_PROMPT=0"
79+
echo "BUN_INSTALL_CACHE_DIR=$STORE_DIR/bun"
80+
echo "npm_config_store_dir=$STORE_DIR/pnpm"
81+
echo "YARN_CACHE_FOLDER=$STORE_DIR/yarn"
82+
echo "npm_config_cache=$STORE_DIR/npm"
83+
} >> "$GITHUB_ENV"
84+
out manager "$manager"
85+
out version "$version"
86+
out lockfile ".codeboarding-target/$lockfile"
87+
echo "Dependencies: $manager${version:+ $version} from $lockfile; Core installs them without install scripts."

‎tests/test_prepare_dependencies.py‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
"""The dependency step prepares an install only for a JavaScript workspace that can have node_modules."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
import os
7+
import re
8+
import subprocess
9+
import tempfile
10+
import unittest
11+
from pathlib import Path
12+
13+
ROOT = Path(__file__).resolve().parent.parent
14+
SCRIPT = ROOT / "scripts" / "action" / "prepare-dependencies.sh"
15+
16+
17+
def prepare(files: dict[str, str], install: str = "true") -> tuple[subprocess.CompletedProcess, dict, dict]:
18+
"""Runs the step on a checkout holding *files*; returns the result, its outputs and its exported env."""
19+
with tempfile.TemporaryDirectory() as tmp:
20+
checkout, store = Path(tmp) / "checkout", Path(tmp) / "store"
21+
for name, text in files.items():
22+
(checkout / name).parent.mkdir(parents=True, exist_ok=True)
23+
(checkout / name).write_text(text, encoding="utf-8")
24+
checkout.mkdir(exist_ok=True)
25+
output, env_file = Path(tmp) / "output", Path(tmp) / "env"
26+
output.write_text("", encoding="utf-8")
27+
env_file.write_text("", encoding="utf-8")
28+
result = subprocess.run(
29+
[str(SCRIPT)],
30+
env={
31+
"PATH": os.environ["PATH"],
32+
"GITHUB_OUTPUT": str(output),
33+
"GITHUB_ENV": str(env_file),
34+
"CHECKOUT_DIR": str(checkout),
35+
"STORE_DIR": str(store),
36+
"INSTALL_DEPENDENCIES": install,
37+
},
38+
capture_output=True,
39+
text=True,
40+
check=False,
41+
)
42+
outputs = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines())
43+
exported = dict(line.split("=", 1) for line in env_file.read_text(encoding="utf-8").splitlines())
44+
return result, outputs, exported
45+
46+
47+
def workspace(**manifest: object) -> str:
48+
return json.dumps({"name": "root", "workspaces": ["packages/*"], **manifest})
49+
50+
51+
class PrepareDependenciesTests(unittest.TestCase):
52+
def test_a_bun_workspace_is_prepared_with_its_pinned_version(self) -> None:
53+
result, outputs, env = prepare({"package.json": workspace(packageManager="bun@1.3.13"), "bun.lock": ""})
54+
self.assertEqual(result.returncode, 0, result.stderr)
55+
self.assertEqual(outputs, {"manager": "bun", "version": "1.3.13", "lockfile": ".codeboarding-target/bun.lock"})
56+
self.assertEqual(env["CODEBOARDING_INSTALL_DEPENDENCIES"], "1")
57+
for variable in ("BUN_INSTALL_CACHE_DIR", "npm_config_store_dir", "YARN_CACHE_FOLDER", "npm_config_cache"):
58+
self.assertTrue(env[variable].startswith(env["BUN_INSTALL_CACHE_DIR"].rsplit("/", 1)[0]), variable)
59+
60+
def test_the_lockfile_names_the_manager_when_nothing_is_pinned(self) -> None:
61+
_, outputs, _ = prepare({"package.json": workspace(), "pnpm-lock.yaml": ""})
62+
self.assertEqual((outputs["manager"], outputs["version"]), ("pnpm", ""))
63+
64+
def test_a_pnpm_workspace_file_counts_as_a_workspace(self) -> None:
65+
_, outputs, _ = prepare(
66+
{"package.json": json.dumps({"name": "root"}), "pnpm-workspace.yaml": "", "pnpm-lock.yaml": ""}
67+
)
68+
self.assertEqual(outputs["manager"], "pnpm")
69+
70+
def test_a_single_package_is_not_installed(self) -> None:
71+
result, outputs, env = prepare({"package.json": json.dumps({"name": "app"}), "package-lock.json": ""})
72+
self.assertEqual(outputs, {"manager": ""})
73+
self.assertEqual(env, {})
74+
self.assertIn("not a JavaScript workspace", result.stdout)
75+
76+
def test_a_pinned_manager_without_its_lockfile_is_not_installed(self) -> None:
77+
result, outputs, _ = prepare(
78+
{"package.json": workspace(packageManager="pnpm@10.29.3"), "package-lock.json": ""}
79+
)
80+
self.assertEqual(outputs, {"manager": ""})
81+
self.assertIn("no lockfile", result.stdout)
82+
83+
def test_yarn_plug_n_play_is_not_installed(self) -> None:
84+
result, outputs, _ = prepare({"package.json": workspace(packageManager="yarn@4.5.0"), "yarn.lock": ""})
85+
self.assertEqual(outputs, {"manager": ""})
86+
self.assertIn("Plug'n'Play", result.stdout)
87+
88+
def test_yarn_berry_with_node_modules_is_installed(self) -> None:
89+
_, outputs, _ = prepare(
90+
{
91+
"package.json": workspace(packageManager="yarn@4.5.0"),
92+
"yarn.lock": "",
93+
".yarnrc.yml": "nodeLinker: node-modules\n",
94+
}
95+
)
96+
self.assertEqual((outputs["manager"], outputs["version"]), ("yarn", "4.5.0"))
97+
98+
def test_turning_it_off_skips_everything(self) -> None:
99+
result, outputs, env = prepare({"package.json": workspace(), "bun.lock": ""}, install="false")
100+
self.assertEqual(outputs, {"manager": ""})
101+
self.assertEqual(env, {})
102+
self.assertIn("install_dependencies is false", result.stdout)
103+
104+
def test_a_repository_without_package_json_is_skipped(self) -> None:
105+
_, outputs, _ = prepare({"main.py": ""})
106+
self.assertEqual(outputs, {"manager": ""})
107+
108+
109+
class ActionWiringTests(unittest.TestCase):
110+
"""The steps around the script: the store is restored for every run and saved only by sync."""
111+
112+
def setUp(self) -> None:
113+
self.action = (ROOT / "action.yml").read_text(encoding="utf-8")
114+
115+
def test_the_input_defaults_to_installing(self) -> None:
116+
block = re.search(r"^ install_dependencies:\n((?: .*\n)+)", self.action, re.MULTILINE)
117+
self.assertIsNotNone(block)
118+
assert block is not None
119+
self.assertIn("default: 'true'", block.group(1))
120+
121+
def test_only_sync_saves_the_store(self) -> None:
122+
save = self.action.split("- name: Save dependency cache", 1)[1].split("- name:", 1)[0]
123+
self.assertIn("steps.guard.outputs.mode == 'sync'", save)
124+
self.assertIn("actions/cache/save@", save)
125+
126+
def test_the_store_is_prepared_before_the_engine_runs(self) -> None:
127+
self.assertLess(
128+
self.action.index("- name: Restore dependency cache"), self.action.index("- name: Generate sync baseline")
129+
)
130+
self.assertLess(
131+
self.action.index("- name: Restore dependency cache"), self.action.index("- name: Generate review baseline")
132+
)
133+
134+
135+
if __name__ == "__main__":
136+
unittest.main()

0 commit comments

Comments
 (0)