diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 50add441736..75c583a0f23 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -348,12 +348,12 @@ applies it. Per touched file the apply upserts what the delta emits and tombston file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a delta gives the same live set. -| Producer | Language | Watermark | Workers | How it runs | -| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | -| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | -| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Whole-workspace index per pass, bounded to the window's files by the converter. | -| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | -| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | +| Producer | Language | Watermark | Workers | How it runs | +| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | +| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. The converter still bounds the output to the TypeScript window. | +| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | +| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | `code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label and workers per producer; status handlers and the dashboard read it. A delta worker diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index e735120d1ce..2353888518d 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -10,11 +10,13 @@ # DELTA_OUT DELTA_OUT=/path/delta.json run_typescript_delta.sh # the in-server worker's mode: index, convert, write the JSON # delta; no upload, no watermark read. Exits 0 with no file -# when no TypeScript file changed in the window. +# when no TypeScript file changed and no shared config or +# lockfile selected members to reindex. # -# scip-typescript has no per-file mode — it indexes the workspace (langfuse: -# 4,603 files in ~4 min, a 384 MB index) — so both modes run the full index and -# let the converter's --changed-files bound the DELTA to the window's files. +# scip-typescript has no per-file mode, so a named or discovered project is +# indexed as a whole. A delta still bounds the converted output with +# --changed-files, and only the projects that contain those files are indexed +# unless a shared config or lockfile changed. # # Env: LOOM_API_KEY (writer; upload mode), SCIP_TYPESCRIPT (bin; `npm i -g # @sourcegraph/scip-typescript@0.4.0`, node 22 or 24), PYTHON (venv python), @@ -44,7 +46,16 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then read -r -a PROJECTS <<<"$SCIP_TS_PROJECTS" WORKSPACES="" # every target below has a tsconfig; inference would write one into the tree SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects +elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then + # umbrella root tsconfig: index member projects instead of loading the root. + # One path per line (a member directory may contain a space). + mapfile -t PROJECTS <<<"$discovered" + WORKSPACES="" + SCIP_TS_PATHS=0 fi +# Ownership uses the full discovered set even when a delta indexes a subset, +# so a root-level tsconfig cannot keep documents a more specific member owns. +ALL_PROJECTS=("${PROJECTS[@]}") if [[ -z "${WORKSPACES+x}" ]]; then if [[ -f "$CHECKOUT/pnpm-workspace.yaml" ]]; then @@ -104,6 +115,11 @@ index_workspace() { fi for proj in "${PROJECTS[@]}"; do proj=${proj%/} + # An umbrella reference may name a tsconfig file (e.g. tsconfig.build.json). + if [[ -f "$proj" ]]; then + targets+=("$proj") + continue + fi [[ -d "$proj" ]] || { echo ">> project $proj is not in the tree — skipped" >&2 continue @@ -127,27 +143,99 @@ JSONEOF done local ws=() [[ -n "$WORKSPACES" ]] && ws=("$WORKSPACES") - NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ - "$SCIP_TYPESCRIPT" index "${ws[@]}" "${targets[@]}" --output "$WORK/index.scip" >&2 + # One indexer process per member: scip-typescript walks every target in a + # single process and shares its source-file cache across them, so passing + # the whole umbrella as arguments keeps the same heap growth the root + # pass already hits. Isolated runs drop that cache between members. + local parts=() target part i=0 + if [[ ${#targets[@]} -eq 0 ]]; then + # No member list: a regular root tsconfig (or a pnpm/yarn workspace) + # is indexed by invoking scip-typescript on the checkout with only the + # workspace flags. An umbrella whose members were all skipped still + # writes an empty index. + if [[ ${#PROJECTS[@]} -eq 0 ]]; then + NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ + "$SCIP_TYPESCRIPT" index "${ws[@]}" --output "$WORK/index.scip" >&2 + else + : >"$WORK/index.scip" + fi + return + fi + for target in "${targets[@]}"; do + part="$WORK/index.part.$i.scip" + NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ + "$SCIP_TYPESCRIPT" index "${ws[@]}" "$target" --output "$part" >&2 + parts+=("$part") + i=$((i + 1)) + done + # Always merge so a single member that followed project references + # also drops documents it does not own. + local merge_args=() t + for t in "${targets[@]}"; do + merge_args+=(--project "$t") + done + for t in "${ALL_PROJECTS[@]}"; do + merge_args+=(--known-project "$t") + done + "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ + "${merge_args[@]}" "${parts[@]}" } cd "$CHECKOUT" CONVERT_ARGS=(--index "$WORK/index.scip" --commit "$HEAD_SHA") +CONFIG_ONLY_REBUILD=0 if [[ "$BASE" != "--full" ]]; then require_base "$BASE" window_files "$WORK" "$BASE" "$HEAD_SHA" "${TS_GLOBS[@]}" - if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then + if [[ ${#PROJECTS[@]} -gt 0 ]]; then + # The convert window is TypeScript-only; the project filter also needs + # shared configs and lockfiles so a mixed window falls back to every member. + mkdir -p "$WORK/project-window" + window_files "$WORK/project-window" "$BASE" "$HEAD_SHA" + filter_args=() + [[ -s "$WORK/project-window/changed.txt" ]] && filter_args+=(--changed-file-list "$WORK/project-window/changed.txt") + [[ -s "$WORK/project-window/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/project-window/deleted.txt") + filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") + if [[ -n "$filtered" ]]; then + mapfile -t PROJECTS <<<"$filtered" + else + # An empty filter is a real empty selection (e.g. an unowned + # package.json). Do not keep the full member set. + PROJECTS=() + fi + # A package manifest, lockfile, or tsconfig in a selected member (or a + # shared root config) can change resolution. Convert the full selected + # indexes; keep TypeScript deletions so removed files still drop out + # of the compiler rows. An unowned config does not rebuild anyone. + if [[ ${#PROJECTS[@]} -gt 0 ]] \ + && "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then + CONFIG_ONLY_REBUILD=1 + fi + fi + if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" && "$CONFIG_ONLY_REBUILD" != "1" ]]; then echo ">> no TypeScript changes in $BASE..$HEAD_SHA" if [[ -n "${DELTA_OUT:-}" ]]; then exit 0; fi # the worker advances the watermark itself echo ">> advancing watermark via empty delta" fi - CONVERT_ARGS+=(--base "$BASE" --changed-files "$WORK/changed.txt" --deleted-files "$WORK/deleted.txt") + if [[ "$CONFIG_ONLY_REBUILD" == "1" ]]; then + if [[ -s "$WORK/changed.txt" || -s "$WORK/deleted.txt" ]]; then + echo ">> mixed window with a config change — converting full member indexes" + else + echo ">> config-only window — reindexing selected members" + fi + CONVERT_ARGS+=(--base "$BASE") + if [[ -s "$WORK/deleted.txt" ]]; then + CONVERT_ARGS+=(--deleted-files "$WORK/deleted.txt") + fi + else + CONVERT_ARGS+=(--base "$BASE" --changed-files "$WORK/changed.txt" --deleted-files "$WORK/deleted.txt") + fi else echo ">> no scip_commit_ts watermark — full TypeScript backfill" CONVERT_ARGS+=(--full) fi -if [[ "$BASE" != "--full" && ! -s "$WORK/changed.txt" ]]; then +if [[ "$BASE" != "--full" && ! -s "$WORK/changed.txt" && "$CONFIG_ONLY_REBUILD" != "1" ]]; then # nothing to read from an index: a zero-byte file is an empty Index, and # the delta carries only the window's deletions : >"$WORK/index.scip" diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py new file mode 100644 index 00000000000..c4a32d9fb21 --- /dev/null +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Merge SCIP Index files into one index. + +Each input is a complete Index (scip-typescript --output). Documents are +keyed by relative_path so a file emitted by more than one isolated run +appears once. When --project is given for each input, a document is taken +from the member that uniquely owns it (the longest matching project +scope); that drops copies a dependent emitted by following TypeScript +project references. Sibling tsconfigs in the same directory share a +scope, so each keeps the documents it emitted and a path present in more +than one of those indexes keeps the last copy. Metadata is taken from +the first non-empty input. External +symbols are concatenated. An all-empty input list, or only empty files, +writes a zero-byte output so the converter treats it as an empty index. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import sys +from pathlib import Path +from typing import Any + +_HARNESS = Path(__file__).resolve().parent +_VENDOR = _HARNESS / "vendor" + + +def _load_ts_projects() -> Any: + spec = importlib.util.spec_from_file_location( + "scip_ts_projects", _HARNESS / "scip_ts_projects.py" + ) + if spec is None or spec.loader is None: + raise SystemExit(f"cannot load {_HARNESS / 'scip_ts_projects.py'}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +_ts_projects = _load_ts_projects() +project_owns = _ts_projects.project_owns +project_scope = _ts_projects.project_scope + + +def _ensure_scip_pb2() -> Any: + if str(_VENDOR) not in sys.path: + sys.path.insert(0, str(_VENDOR)) + try: + import scip_pb2 + except Exception as e: # ImportError, or protobuf VersionError + raise SystemExit( + f"cannot load vendor/scip_pb2.py ({e}): merging indexes needs protobuf>=7.35.1" + ) from e + return scip_pb2 + + +def _scope_specificity(project: str) -> int: + """Longer directory scopes win. The root scope '.' has length 1, which + would otherwise tie a one-character member directory such as 'a'.""" + scope = project_scope(project) + if scope in (".", ""): + return 0 + return len(scope) + + +def _preferred_owner(projects: list[str], relpath: str) -> str | None: + owners = [project for project in projects if project_owns(project, relpath)] + if not owners: + return None + best_scope = max(_scope_specificity(project) for project in owners) + tied = [project for project in owners if _scope_specificity(project) == best_scope] + # Sibling explicit tsconfigs share a directory scope. Returning one of + # them still lets each sibling keep its documents (scopes match) while + # a shorter ancestor, such as a root tsconfig, is dropped. + return tied[0] + + +def merge_indexes( + paths: list[Path], + output: Path, + projects: list[str] | None = None, + known_projects: list[str] | None = None, +) -> None: + if projects is not None and len(projects) != len(paths): + raise SystemExit("--project count must match the number of indexes") + scip_pb2 = _ensure_scip_pb2() + merged = scip_pb2.Index() + documents: dict[str, object] = {} + has_payload = False + for i, path in enumerate(paths): + data = path.read_bytes() if path.is_file() else b"" + if not data: + continue + idx = scip_pb2.Index() + idx.ParseFromString(data) + if not has_payload and idx.HasField("metadata"): + merged.metadata.CopyFrom(idx.metadata) + project = projects[i] if projects is not None else None + for doc in idx.documents: + rel = doc.relative_path + if projects is not None and project is not None: + # Keep documents this member owns. Documents followed through + # TypeScript project references into another package are + # dropped even when that package is not in this merge, so a + # subset rebuild cannot overwrite the other package's rows. + # known_projects is the full discovered set: a root-level + # tsconfig owns every path, so ownership still prefers a + # longer member that was not indexed in this run. + if not project_owns(project, rel): + continue + owners = known_projects if known_projects is not None else projects + owner = _preferred_owner(owners, rel) + # Compare scopes, not raw project strings: a generated + # member target is dir/tsconfig.scip.json, while + # --known-project still names dir. + if owner is not None and project_scope(owner) != project_scope(project): + continue + copied = scip_pb2.Document() + copied.CopyFrom(doc) + documents[rel] = copied + merged.external_symbols.extend(idx.external_symbols) + has_payload = True + if not has_payload: + output.write_bytes(b"") + return + for doc in documents.values(): + merged.documents.append(doc) + output.write_bytes(merged.SerializeToString()) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument( + "--project", + action="append", + default=[], + help="member path for the corresponding index (same order); " + "documents are kept from the owning member", + ) + parser.add_argument( + "--known-project", + action="append", + default=[], + help="full discovered member set used for ownership; a document is " + "dropped when a more specific member owns it, even if that member " + "was not indexed in this run", + ) + parser.add_argument("indexes", nargs="+", type=Path) + args = parser.parse_args(argv) + projects = args.project or None + known = args.known_project or None + merge_indexes(args.indexes, args.output, projects, known) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py new file mode 100755 index 00000000000..48a1d08e210 --- /dev/null +++ b/scripts/scip_harness/scip_ts_projects.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +"""Discover and narrow TypeScript projects for scip-typescript. + +An umbrella (solution-style) root tsconfig — one that only references other +projects, typically with `"files": []` — cannot be indexed as a single +workspace: scip-typescript loads every referenced project at once and can +exhaust the heap. This helper expands that root to its member project +directories or explicit tsconfig files, and on a delta pass keeps only the +members that contain a changed path. A change to a shared config or lockfile, +or a TypeScript path that no member owns, falls back to the full member set. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path + +TS_SUFFIXES = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") +LOCKFILE_NAMES = { + "package-lock.json", + "yarn.lock", + "pnpm-lock.yaml", + "bun.lock", + "bun.lockb", + "npm-shrinkwrap.json", +} +ROOT_SHARED_NAMES = { + "package.json", + "pnpm-workspace.yaml", + "lerna.json", + "nx.json", + "turbo.json", + "rush.json", +} + +_TRAILING_COMMA = re.compile(r",(\s*[}\]])") + + +def strip_jsonc(text: str) -> str: + """Remove // and /* */ comments without treating text inside strings as comments.""" + out: list[str] = [] + i = 0 + n = len(text) + in_str = False + escape = False + while i < n: + ch = text[i] + if in_str: + out.append(ch) + if escape: + escape = False + elif ch == "\\": + escape = True + elif ch == '"': + in_str = False + i += 1 + continue + if ch == '"': + in_str = True + out.append(ch) + i += 1 + continue + if ch == "/" and i + 1 < n and text[i + 1] == "/": + i += 2 + while i < n and text[i] not in "\n\r": + i += 1 + continue + if ch == "/" and i + 1 < n and text[i + 1] == "*": + i += 2 + while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"): + i += 1 + i = min(i + 2, n) + out.append(" ") + continue + out.append(ch) + i += 1 + return "".join(out) + + +def load_tsconfig(path: Path) -> dict: + text = path.read_text(encoding="utf-8") + try: + data = json.loads(text) + except json.JSONDecodeError: + stripped = _TRAILING_COMMA.sub(r"\1", strip_jsonc(text)) + data = json.loads(stripped) + if not isinstance(data, dict): + raise ValueError(f"{path} is not a JSON object") + return data + + +def is_umbrella_tsconfig(data: dict) -> bool: + references = data.get("references") + if not isinstance(references, list) or not references: + return False + files = data.get("files") + include = data.get("include") + if files == [] and include in (None, []): + return True + if files is None and include == []: + return True + return False + + +def _reference_path(entry: object) -> str | None: + if isinstance(entry, str): + return entry + if isinstance(entry, dict) and isinstance(entry.get("path"), str): + return entry["path"] + return None + + +def _project_dir_for_reference(base: Path, rel: str) -> Path | None: + target = (base / rel).resolve() + if target.is_file(): + return target.parent + if target.is_dir(): + return target + # a missing directory still names a project the harness can skip + if rel: + return (base / rel).resolve() + return None + + +def discover_umbrella_projects(checkout: Path, tsconfig: Path | None = None) -> list[str]: + """Member project directories or explicit tsconfig paths of an umbrella + root, or an empty list if the root tsconfig is a regular project.""" + checkout = checkout.resolve() + root = tsconfig or (checkout / "tsconfig.json") + if not root.is_file(): + return [] + try: + data = load_tsconfig(root) + except (OSError, ValueError, json.JSONDecodeError): + return [] + if not is_umbrella_tsconfig(data): + return [] + return _expand_references(checkout, root, data, seen=set()) + + +def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Path]) -> list[str]: + checkout = checkout.resolve() + tsconfig = tsconfig.resolve() + if tsconfig in seen: + return [] + seen.add(tsconfig) + base = tsconfig.parent + out: list[str] = [] + for entry in data.get("references") or []: + rel = _reference_path(entry) + if not rel: + continue + explicit = (base / rel).resolve() if rel.endswith(".json") else None + if explicit is not None and explicit.is_file(): + member_tsconfig = explicit + project_dir = explicit.parent + else: + project_dir = _project_dir_for_reference(base, rel) + if project_dir is None: + continue + member_tsconfig = project_dir / "tsconfig.json" + if member_tsconfig.is_file(): + try: + member = load_tsconfig(member_tsconfig) + except (OSError, ValueError, json.JSONDecodeError): + member = {} + if is_umbrella_tsconfig(member): + out.extend(_expand_references(checkout, member_tsconfig, member, seen)) + continue + try: + if explicit is not None and explicit.is_file(): + rel_proj = str(explicit.relative_to(checkout)) + else: + rel_proj = str(project_dir.relative_to(checkout)) + except ValueError: + continue + if rel_proj in (".", ""): + continue + if rel_proj not in out: + out.append(rel_proj) + return out + + +def posix_path(path: str) -> str: + """Normalize slashes and a `./` prefix; keep a leading hidden-directory dot.""" + path = path.replace("\\", "/") + while path.startswith("./"): + path = path[2:] + return path + + +def project_scope(project: str) -> str: + """Directory a discovered target owns: the file's parent for an explicit tsconfig. + + A root-level file such as tsconfig.app.json owns the checkout root ('.'). + An empty scope would make project_owns reject every document, and merge + would drop the index for the common Vite/Angular solution-style layout. + """ + path = posix_path(project).rstrip("/") + if path.endswith(".json"): + parent = str(Path(path).parent) + if parent in (".", ""): + return "." + return posix_path(parent) + return path + + +def project_owns(project: str, relpath: str) -> bool: + proj = project_scope(project) + path = posix_path(relpath) + if not proj: + return False + if proj == ".": + return True + return path == proj or path.startswith(proj + "/") + + +def is_typescript_path(relpath: str) -> bool: + name = posix_path(relpath) + return name.endswith(TS_SUFFIXES) + + +def is_shared_change(relpath: str) -> bool: + path = posix_path(relpath) + name = Path(path).name + if name in LOCKFILE_NAMES: + return True + if "/" in path: + return False + if name in ROOT_SHARED_NAMES: + return True + return name.startswith("tsconfig") and name.endswith(".json") + + +def is_project_config_change(relpath: str) -> bool: + """A package manifest, lockfile, or tsconfig that can change resolution.""" + name = Path(posix_path(relpath)).name + if name in LOCKFILE_NAMES or name in ROOT_SHARED_NAMES: + return True + return name.startswith("tsconfig") and name.endswith(".json") + + +def is_index_trigger(relpath: str) -> bool: + """A path that should select its owning member for (re)indexing.""" + return is_typescript_path(relpath) or is_project_config_change(relpath) + + +def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> list[str]: + """Projects to index for this window. Shared config/lockfile changes, or + any TypeScript path that no named project owns, keep the full set. + + A non-TypeScript, non-config change inside a member (a README, for + example) does not select that member. + """ + if not projects: + return [] + if any(is_shared_change(path) for path in changed_paths): + return list(projects) + selected = [ + project + for project in projects + if any(project_owns(project, path) and is_index_trigger(path) for path in changed_paths) + ] + unowned_ts = [ + path + for path in changed_paths + if is_typescript_path(path) and not any(project_owns(project, path) for project in projects) + ] + if unowned_ts: + return list(projects) + return selected + + +def _read_lines(path: Path | None) -> list[str]: + if path is None or not path.is_file(): + return [] + return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="cmd", required=True) + + discover = sub.add_parser("discover", help="print umbrella member directories") + discover.add_argument("checkout", type=Path) + + filt = sub.add_parser("filter", help="narrow projects to the delta's changed paths") + filt.add_argument("--changed-file-list", type=Path) + filt.add_argument("--deleted-file-list", type=Path) + filt.add_argument("projects", nargs="*") + + shared = sub.add_parser( + "has-shared", + help="exit 0 if the window contains a shared config or lockfile", + ) + shared.add_argument("--changed-file-list", type=Path) + shared.add_argument("--deleted-file-list", type=Path) + + config = sub.add_parser( + "has-config", + help="exit 0 if the window contains a package manifest, lockfile, or tsconfig", + ) + config.add_argument("--changed-file-list", type=Path) + config.add_argument("--deleted-file-list", type=Path) + + args = parser.parse_args(argv) + if args.cmd == "discover": + projects = discover_umbrella_projects(args.checkout) + elif args.cmd == "has-shared": + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + return 0 if any(is_shared_change(path) for path in changed) else 1 + elif args.cmd == "has-config": + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + return 0 if any(is_project_config_change(path) for path in changed) else 1 + else: + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + projects = select_projects_for_delta(list(args.projects), changed) + # One path per line so a member whose path contains a space is not split + # by the shell when it loads the list. + for project in projects: + sys.stdout.write(f"{project}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/unit/test_run_typescript_delta_projects.py b/tests/unit/test_run_typescript_delta_projects.py index 6cec2be801a..3d5f5a7bd97 100644 --- a/tests/unit/test_run_typescript_delta_projects.py +++ b/tests/unit/test_run_typescript_delta_projects.py @@ -14,7 +14,11 @@ ) _FAKE_SCIP = """#!/usr/bin/env bash -echo "args $*" >>"$CALLS" +{ + printf 'run' + for a in "$@"; do printf '\t%s' "$a"; done + printf '\n' +} >>"$CALLS" for f in plug/tsconfig.scip.json plug/package.json lib/tsconfig.scip.json lib/package.json; do [[ -f "$f" ]] && echo "present $f $(head -c 40 "$f")" >>"$CALLS" done @@ -22,6 +26,9 @@ """ _FAKE_PYTHON = """#!/usr/bin/env bash +case "${1-}" in + *scip_merge_indexes.py|*scip_ts_projects.py) exec "$REAL_PYTHON" "$@" ;; +esac while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done """ @@ -55,11 +62,14 @@ def test_named_projects_are_indexed_through_their_own_or_a_generated_tsconfig( (bin_dir / name).write_text(body) (bin_dir / name).chmod(0o755) calls = tmp_path / "calls" + import shutil + env = { **os.environ, "CALLS": str(calls), "DELTA_OUT": str(tmp_path / "delta.json"), "PYTHON": str(bin_dir / "python"), + "REAL_PYTHON": shutil.which("python3") or "python3", "SCIP_TYPESCRIPT": str(bin_dir / "scip-typescript"), "SCIP_TS_PROJECTS": "app plug lib missing", } @@ -71,9 +81,14 @@ def test_named_projects_are_indexed_through_their_own_or_a_generated_tsconfig( text=True, ) log = calls.read_text().splitlines() - args = next(line for line in log if line.startswith("args ")).split() - assert args[1:5] == ["index", "app", "plug/tsconfig.scip.json", "lib/tsconfig.scip.json"] - assert "--infer-tsconfig" not in args, "inference writes a tsconfig.json into the tree" + runs = [line.split("\t")[1:] for line in log if line.startswith("run")] + targets = [] + for run in runs: + assert run[0] == "index" + assert run[2] == "--output" + targets.append(run[1]) + assert "--infer-tsconfig" not in run, "inference writes a tsconfig.json into the tree" + assert targets == ["app", "plug/tsconfig.scip.json", "lib/tsconfig.scip.json"] present = {line.split()[1]: line for line in log if line.startswith("present ")} assert set(present) == { "plug/tsconfig.scip.json", diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py new file mode 100644 index 00000000000..1890760170b --- /dev/null +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -0,0 +1,457 @@ +"""run_typescript_delta.sh expands an umbrella root and indexes only the +projects touched by a delta. scip-typescript and the converter are stubs.""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path + +_SCRIPT = ( + Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_typescript_delta.sh" +) + +_FAKE_SCIP = """#!/usr/bin/env bash +{ + printf 'run' + for a in "$@"; do printf '\\t%s' "$a"; done + printf '\\n' +} >>"$CALLS" +while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done +""" + +_FAKE_PYTHON = """#!/usr/bin/env bash +# Forward discover/filter/merge to the real helpers; stub only the converter. +case "${1-}" in + *scip_ts_projects.py|*scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; +esac +{ + printf 'convert' + for a in "$@"; do printf '\\t%s' "$a"; done + printf '\\n' +} >>"$CALLS" +while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done +""" + + +def _git(cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True + ).stdout.strip() + + +def _repo(tmp_path: Path) -> Path: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + calls = tmp_path / "calls" + calls.unlink(missing_ok=True) + for name, body in (("scip-typescript", _FAKE_SCIP), ("python", _FAKE_PYTHON)): + dest = bin_dir / name + dest.write_text(body) + dest.chmod(0o755) + import shutil + + # The wrapper must call the real helper; record its path. + env = { + **os.environ, + "CALLS": str(calls), + "DELTA_OUT": str(tmp_path / "delta.json"), + "PYTHON": str(bin_dir / "python"), + "REAL_PYTHON": shutil.which("python3") or "python3", + "SCIP_TYPESCRIPT": str(bin_dir / "scip-typescript"), + } + # Don't leak a parent SCIP_TS_PROJECTS into the test. + env.pop("SCIP_TS_PROJECTS", None) + subprocess.run( + ["bash", str(_SCRIPT), str(repo), base, head], + env=env, + check=True, + capture_output=True, + text=True, + ) + return calls.read_text() if calls.exists() else "" + + +def _runs(log: str) -> list[list[str]]: + """Indexer invocations, each a list of argv (tabs, so a path may contain a space).""" + runs = [] + for line in log.splitlines(): + if line.startswith("run"): + runs.append(line.split("\t")[1:]) + return runs + + +def _targets(runs: list[list[str]]) -> list[str]: + out = [] + for run in runs: + assert run[0] == "index" + output_at = run.index("--output") + # One process per member: a single target between `index` and `--output`. + assert output_at == 2, run + out.append(run[1]) + return out + + +def test_umbrella_root_is_indexed_as_member_projects(tmp_path: Path) -> None: + repo = _repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + runs = _runs(log) + assert _targets(runs) == ["packages/app", "packages/lib"] + assert all("--pnpm-workspaces" not in run and "--infer-tsconfig" not in run for run in runs) + + +def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch app") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] + + +def test_delta_with_shared_config_indexes_every_member(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "app and package") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + + +def test_inline_jsonc_umbrella_is_expanded(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "tsconfig.json").write_text( + """{ + "files": [], // solution-style + "compilerOptions": { "paths": { "@/*": ["./src/*"] } }, + "references": [ + { "path": "packages/app" }, + { "path": "packages/lib" }, + ], +} +""" + ) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "jsonc root") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + + +def test_explicit_tsconfig_file_is_passed_to_the_indexer(tmp_path: Path) -> None: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app/tsconfig.build.json"}]} + ), + "packages/app/tsconfig.build.json": json.dumps( + {"include": ["src/index.ts"], "compilerOptions": {"strict": True}} + ), + "packages/app/src/index.ts": "export const a = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/app/tsconfig.build.json"] + assert not (repo / "packages/app/tsconfig.scip.json").exists() + + +def test_delta_with_owned_and_unowned_typescript_indexes_every_member(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "outside.ts").write_text("export const o = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "outside") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "outside.ts").write_text("export const o = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "mixed") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + + +def test_member_path_with_a_space_survives_full_and_delta_passes(tmp_path: Path) -> None: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + { + "files": [], + "references": [{"path": "packages/my app"}, {"path": "packages/lib"}], + } + ), + "packages/my app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/my app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/my app", "packages/lib"] + + base = head + (repo / "packages/my app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch spaced") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/my app"] + + +def test_full_pass_starts_one_indexer_process_per_member(tmp_path: Path) -> None: + """A full pass must not hand every member to one scip-typescript process. + + The pinned indexer shares its source-file cache across targets in one + process; isolating runs is what drops that heap between members. + """ + repo = tmp_path / "repo" + references = [] + files: dict[str, str] = {} + names = [f"packages/pkg{i:02d}" for i in range(24)] + for name in names: + references.append({"path": name}) + files[f"{name}/tsconfig.json"] = json.dumps({"include": ["src"]}) + files[f"{name}/src/index.ts"] = "export const n = 1;\n" + files["tsconfig.json"] = json.dumps({"files": [], "references": references}) + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + runs = _runs(log) + assert len(runs) == 24 + assert _targets(runs) == names + + +def _root_repo(tmp_path: Path) -> Path: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps({"compilerOptions": {"strict": True}, "include": ["src"]}), + "src/a.ts": "export const a = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _project_args(run: list[str]) -> list[str]: + output_at = run.index("--output") + return [a for a in run[1:output_at] if not a.startswith("-")] + + +def test_regular_root_tsconfig_is_indexed_as_the_workspace_on_a_full_pass(tmp_path: Path) -> None: + repo = _root_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + runs = _runs(log) + assert len(runs) == 1 + assert runs[0][0] == "index" + assert _project_args(runs[0]) == [] + + +def test_regular_root_tsconfig_is_indexed_as_the_workspace_on_a_delta(tmp_path: Path) -> None: + repo = _root_repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit a") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + runs = _runs(log) + assert len(runs) == 1 + assert runs[0][0] == "index" + assert _project_args(runs[0]) == [] + + +def test_delta_config_only_reindexes_every_member(tmp_path: Path) -> None: + """A root package.json change must still index members and write a delta.""" + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package") + base = _git(repo, "rev-parse", "HEAD") + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "bump version") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + assert (tmp_path / "delta.json").is_file() + convert_lines = [line for line in log.splitlines() if line.startswith("convert")] + assert convert_lines, log + convert_args = convert_lines[-1].split("\t")[1:] + assert "--changed-files" not in convert_args + assert "--deleted-files" not in convert_args + assert "--base" in convert_args + + +def test_delta_with_only_an_unrelated_non_ts_change_skips_the_indexer( + tmp_path: Path, +) -> None: + repo = _repo(tmp_path) + (repo / "README.md").write_text("hello\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "readme") + base = _git(repo, "rev-parse", "HEAD") + (repo / "README.md").write_text("hello world\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit readme") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() + + +def _convert_args(log: str) -> list[str]: + convert_lines = [line for line in log.splitlines() if line.startswith("convert")] + assert convert_lines, log + return convert_lines[-1].split("\t")[1:] + + +def test_mixed_window_converts_full_member_indexes_and_keeps_deletions( + tmp_path: Path, +) -> None: + """A root package.json plus a TypeScript edit must not pass --changed-files. + + Both members are indexed because resolution may have changed. The converter + still receives TypeScript deletions so those rows drop out. + """ + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + (repo / "packages/app/src/gone.ts").write_text("export const gone = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package and gone") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "packages/app/src/gone.ts").unlink() + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "mixed window") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args + assert "--deleted-files" in convert_args + + +def test_member_readme_change_skips_the_indexer(tmp_path: Path) -> None: + repo = _repo(tmp_path) + readme = repo / "packages/app/README.md" + readme.write_text("hello\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add member readme") + base = _git(repo, "rev-parse", "HEAD") + readme.write_text("hello world\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit member readme") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() + + +def test_delta_member_tsconfig_only_reindexes_that_member(tmp_path: Path) -> None: + """A nested tsconfig change must not take the empty-delta early exit.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/tsconfig.json").write_text(json.dumps({"include": ["src", "extra"]})) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "member tsconfig") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] + assert (tmp_path / "delta.json").is_file() + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args + + +def test_mixed_member_tsconfig_and_typescript_converts_full_member_index( + tmp_path: Path, +) -> None: + """A member tsconfig plus a TypeScript edit must not pass --changed-files.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/tsconfig.json").write_text(json.dumps({"include": ["src", "extra"]})) + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "member config and ts") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args + + +def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: + """A config path no member owns must not reindex the full member set.""" + repo = _repo(tmp_path) + other = repo / "tools/cli/package.json" + other.parent.mkdir(parents=True, exist_ok=True) + other.write_text('{"name": "cli"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add unowned package") + base = _git(repo, "rev-parse", "HEAD") + other.write_text('{"name": "cli", "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit unowned package") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py new file mode 100644 index 00000000000..45c2990217f --- /dev/null +++ b/tests/unit/test_scip_merge_indexes.py @@ -0,0 +1,319 @@ +"""Merge isolated scip-typescript Index files into one index.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" +_SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) +_MOD = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MOD) + + +def _index_with_docs(relative_paths: list[str], texts: list[str] | None = None) -> bytes: + scip_pb2 = _MOD._ensure_scip_pb2() + idx = scip_pb2.Index() + idx.metadata.project_root = "file:///repo" + for i, path in enumerate(relative_paths): + doc = idx.documents.add() + doc.relative_path = path + if texts is not None: + doc.text = texts[i] + return idx.SerializeToString() + + +def test_merge_concatenates_documents_and_skips_empty_parts(tmp_path: Path) -> None: + a = tmp_path / "a.scip" + b = tmp_path / "b.scip" + empty = tmp_path / "empty.scip" + a.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + b.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + empty.write_bytes(b"") + out = tmp_path / "merged.scip" + _MOD.merge_indexes([a, empty, b], out) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert merged.metadata.project_root == "file:///repo" + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + + +def test_merge_of_only_empty_files_is_zero_bytes(tmp_path: Path) -> None: + empty = tmp_path / "empty.scip" + empty.write_bytes(b"") + out = tmp_path / "merged.scip" + _MOD.merge_indexes([empty], out) + assert out.read_bytes() == b"" + + +def test_merge_drops_referenced_documents_in_favor_of_the_owner(tmp_path: Path) -> None: + dependent = tmp_path / "app.scip" + owner = tmp_path / "lib.scip" + # An isolated run on app still follows the reference into lib. + dependent.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/lib/src/b.ts"], + ["from-app", "from-app-ref"], + ) + ) + owner.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [dependent, owner], + out, + projects=["packages/app", "packages/lib"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/lib/src/b.ts": "from-lib", + } + + +def test_merge_without_projects_keeps_the_last_copy_of_a_path(tmp_path: Path) -> None: + first = tmp_path / "first.scip" + second = tmp_path / "second.scip" + first.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["first"])) + second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["second"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([first, second], out) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/lib/src/b.ts"] + assert merged.documents[0].text == "second" + + +def test_merge_prefers_the_longest_project_scope(tmp_path: Path) -> None: + app = tmp_path / "app.scip" + widget = tmp_path / "widget.scip" + app.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/app/widget/src/w.ts"], + ["app", "from-app"], + ) + ) + widget.write_bytes(_index_with_docs(["packages/app/widget/src/w.ts"], ["from-widget"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, widget], + out, + projects=["packages/app", "packages/app/widget"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "app", + "packages/app/widget/src/w.ts": "from-widget", + } + + +def test_merge_keeps_documents_from_sibling_tsconfigs(tmp_path: Path) -> None: + """Explicit tsconfigs in one directory share project_scope; unique docs must stay.""" + app = tmp_path / "app.scip" + test = tmp_path / "test.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + test.write_bytes(_index_with_docs(["packages/app/src/a.spec.ts"], ["from-test"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, test], + out, + projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/app/src/a.spec.ts": "from-test", + } + + +def test_merge_sibling_tsconfigs_keep_the_last_copy_of_an_overlapping_path( + tmp_path: Path, +) -> None: + first = tmp_path / "app.scip" + second = tmp_path / "test.scip" + first.write_bytes(_index_with_docs(["packages/app/src/shared.ts"], ["from-app"])) + second.write_bytes(_index_with_docs(["packages/app/src/shared.ts"], ["from-test"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [first, second], + out, + projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/shared.ts"] + assert merged.documents[0].text == "from-test" + + +def test_merge_drops_unowned_references_when_the_owner_is_absent(tmp_path: Path) -> None: + """A subset rebuild must not keep documents from a package that was not indexed.""" + dependent = tmp_path / "app.scip" + dependent.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/lib/src/b.ts"], + ["from-app", "from-app-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([dependent], out, projects=["packages/app"]) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app"} + + +def test_merge_keeps_documents_from_a_root_level_tsconfig(tmp_path: Path) -> None: + """A root tsconfig.app.json must not have its documents dropped as unowned.""" + app = tmp_path / "app.scip" + app.write_bytes(_index_with_docs(["src/main.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([app], out, projects=["tsconfig.app.json"]) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-app"} + + +def test_merge_prefers_a_nested_member_over_a_root_tsconfig(tmp_path: Path) -> None: + root = tmp_path / "root.scip" + app = tmp_path / "app.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root, app], + out, + projects=["tsconfig.app.json", "packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root", "packages/app/src/a.ts": "from-app"} + + +def test_merge_drops_followed_docs_from_a_root_tsconfig_when_the_member_is_absent( + tmp_path: Path, +) -> None: + """A subset rebuild of tsconfig.app.json must not keep packages/app rows.""" + root = tmp_path / "root.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root], + out, + projects=["tsconfig.app.json"], + known_projects=["tsconfig.app.json", "packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root"} + + +def test_merge_keeps_docs_when_project_is_a_generated_tsconfig_scip_json( + tmp_path: Path, +) -> None: + """A member named dir/tsconfig.scip.json must match known-project dir.""" + app = tmp_path / "app.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app], + out, + projects=["packages/app/tsconfig.scip.json"], + known_projects=["packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app"} + + +def test_merge_drops_root_docs_when_sibling_app_configs_share_the_owner_scope( + tmp_path: Path, +) -> None: + """A root index merged last must not replace docs from a more specific dir.""" + app = tmp_path / "app.scip" + test = tmp_path / "test.scip" + root = tmp_path / "root.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + test.write_bytes(_index_with_docs(["packages/app/src/a.spec.ts"], ["from-test"])) + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, test, root], + out, + projects=[ + "packages/app/tsconfig.app.json", + "packages/app/tsconfig.test.json", + "tsconfig.app.json", + ], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/app/src/a.spec.ts": "from-test", + "src/main.ts": "from-root", + } + + +def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Path) -> None: + """A root scope '.' must not tie a one-character member directory.""" + root = tmp_path / "root.scip" + member = tmp_path / "a.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "a/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + member.write_bytes(_index_with_docs(["a/src/a.ts"], ["from-a"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root, member], + out, + projects=["tsconfig.app.json", "a"], + known_projects=["tsconfig.app.json", "a"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root", "a/src/a.ts": "from-a"} diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py new file mode 100644 index 00000000000..98cf5f5bab7 --- /dev/null +++ b/tests/unit/test_scip_ts_projects.py @@ -0,0 +1,208 @@ +"""Umbrella-root discovery and delta project selection for the TypeScript tier.""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_ts_projects.py" +_SPEC = importlib.util.spec_from_file_location("scip_ts_projects", _SCRIPT) +_MOD = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MOD) +discover_umbrella_projects = _MOD.discover_umbrella_projects +is_umbrella_tsconfig = _MOD.is_umbrella_tsconfig +load_tsconfig = _MOD.load_tsconfig +select_projects_for_delta = _MOD.select_projects_for_delta + + +def _write(root: Path, rel: str, text: str) -> None: + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +def test_solution_style_root_is_an_umbrella() -> None: + assert is_umbrella_tsconfig({"files": [], "references": [{"path": "packages/app"}]}) + assert is_umbrella_tsconfig({"files": [], "include": [], "references": [{"path": "a"}]}) + assert not is_umbrella_tsconfig( + {"files": [], "include": ["src"], "references": [{"path": "a"}]} + ) + assert not is_umbrella_tsconfig({"compilerOptions": {}, "include": ["src"]}) + assert not is_umbrella_tsconfig({"references": [{"path": "packages/app"}]}) + + +def test_load_tsconfig_tolerates_comments_and_trailing_commas(tmp_path: Path) -> None: + path = tmp_path / "tsconfig.json" + path.write_text( + """{ + // solution-style root + "files": [], + "references": [ + { "path": "packages/app" }, + ], +} +""" + ) + data = load_tsconfig(path) + assert data["files"] == [] + assert data["references"][0]["path"] == "packages/app" + + +def test_discover_expands_umbrella_and_nested_umbrellas(tmp_path: Path) -> None: + _write( + tmp_path, + "tsconfig.json", + json.dumps({"files": [], "references": [{"path": "packages/app"}, {"path": "libs"}]}), + ) + _write(tmp_path, "packages/app/tsconfig.json", json.dumps({"include": ["src"]})) + _write( + tmp_path, + "libs/tsconfig.json", + json.dumps({"files": [], "references": [{"path": "core"}, {"path": "util"}]}), + ) + _write(tmp_path, "libs/core/tsconfig.json", json.dumps({"include": ["src"]})) + _write(tmp_path, "libs/util/tsconfig.json", json.dumps({"include": ["src"]})) + assert discover_umbrella_projects(tmp_path) == [ + "packages/app", + "libs/core", + "libs/util", + ] + + +def test_plain_root_tsconfig_is_not_expanded(tmp_path: Path) -> None: + _write(tmp_path, "tsconfig.json", json.dumps({"include": ["src"], "compilerOptions": {}})) + _write(tmp_path, "src/index.ts", "export {}\n") + assert discover_umbrella_projects(tmp_path) == [] + + +def test_delta_keeps_only_projects_that_own_the_changed_files() -> None: + projects = ["packages/app", "packages/lib", "packages/cli"] + assert select_projects_for_delta(projects, ["packages/lib/src/a.ts"]) == ["packages/lib"] + assert select_projects_for_delta( + projects, ["packages/app/src/a.ts", "packages/cli/bin.ts"] + ) == [ + "packages/app", + "packages/cli", + ] + # a sibling with a shared prefix must not pull in packages/app + assert select_projects_for_delta( + ["packages/app", "packages/app-extra"], + ["packages/app-extra/src/a.ts"], + ) == ["packages/app-extra"] + + +def test_shared_config_or_lockfile_keeps_the_full_set() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["package.json"]) == projects + assert select_projects_for_delta(projects, ["tsconfig.base.json"]) == projects + assert select_projects_for_delta(projects, ["packages/app/pnpm-lock.yaml"]) == projects + assert select_projects_for_delta(projects, ["packages/app/package.json"]) == ["packages/app"] + + +def test_non_typescript_changes_do_not_force_a_full_set() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["README.md"]) == [] + + +def test_load_tsconfig_accepts_inline_comments_and_paths_globs(tmp_path: Path) -> None: + path = tmp_path / "tsconfig.json" + path.write_text( + """{ + "files": [], // umbrella root + "compilerOptions": { + "paths": { "@/*": ["./src/*"] } + }, + "references": [ + { "path": "packages/app" }, /* app */ + ], +} +""" + ) + data = load_tsconfig(path) + assert data["files"] == [] + assert data["compilerOptions"]["paths"]["@/*"] == ["./src/*"] + assert data["references"][0]["path"] == "packages/app" + + +def test_discover_preserves_explicit_tsconfig_file_references(tmp_path: Path) -> None: + _write( + tmp_path, + "tsconfig.json", + json.dumps({"files": [], "references": [{"path": "packages/app/tsconfig.build.json"}]}), + ) + _write( + tmp_path, + "packages/app/tsconfig.build.json", + json.dumps({"include": ["src/index.ts"], "compilerOptions": {"strict": True}}), + ) + assert discover_umbrella_projects(tmp_path) == ["packages/app/tsconfig.build.json"] + + +def test_delta_falls_back_when_any_typescript_path_is_unowned() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/src/a.ts", "outside.ts"]) == projects + assert select_projects_for_delta( + ["packages/app/tsconfig.build.json", "packages/lib"], + ["packages/app/src/a.ts"], + ) == ["packages/app/tsconfig.build.json"] + + +def test_posix_path_keeps_a_hidden_member_directory() -> None: + posix_path = _MOD.posix_path + assert posix_path(".storybook") == ".storybook" + assert posix_path("./.storybook/main.ts") == ".storybook/main.ts" + assert posix_path("./packages/app") == "packages/app" + assert posix_path("packages\\app\\src\\a.ts") == "packages/app/src/a.ts" + + +def test_hidden_member_is_not_confused_with_an_unhidden_sibling() -> None: + project_owns = _MOD.project_owns + assert project_owns(".storybook", ".storybook/main.ts") + assert not project_owns("storybook", ".storybook/main.ts") + assert not project_owns(".storybook", "storybook/main.ts") + assert select_projects_for_delta( + [".storybook", "storybook"], + [".storybook/main.ts"], + ) == [".storybook"] + assert select_projects_for_delta( + [".storybook", "storybook"], + ["storybook/src/a.ts"], + ) == ["storybook"] + + +def test_member_readme_does_not_select_its_project() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/README.md"]) == [] + assert select_projects_for_delta( + projects, ["packages/app/README.md", "packages/lib/src/b.ts"] + ) == ["packages/lib"] + + +def test_member_package_json_still_selects_its_project() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/package.json"]) == ["packages/app"] + assert select_projects_for_delta(projects, ["packages/app/tsconfig.json"]) == ["packages/app"] + + +def test_root_level_tsconfig_owns_documents_at_the_checkout_root() -> None: + """Vite/Angular roots use tsconfig.app.json at the checkout root.""" + assert _MOD.project_scope("tsconfig.app.json") == "." + assert _MOD.project_scope("packages/app/tsconfig.app.json") == "packages/app" + owns = _MOD.project_owns + assert owns("tsconfig.app.json", "src/main.ts") + assert owns("tsconfig.app.json", "main.ts") + # Root scope covers nested paths too; merge prefers a longer member scope. + assert owns("tsconfig.app.json", "packages/app/src/a.ts") + assert owns("packages/app/tsconfig.app.json", "packages/app/src/a.ts") + assert not owns("packages/app/tsconfig.app.json", "src/main.ts") + + +def test_delta_selects_a_root_tsconfig_for_a_root_source_change() -> None: + projects = ["tsconfig.app.json", "packages/lib"] + assert select_projects_for_delta(projects, ["src/main.ts"]) == ["tsconfig.app.json"] + # The root tsconfig also owns packages/lib; merge prefers the longer scope. + assert select_projects_for_delta(projects, ["packages/lib/src/b.ts"]) == [ + "tsconfig.app.json", + "packages/lib", + ]