diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 4f68379998..dab81c93cb 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -355,12 +355,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` | 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 TypeScript file no project contains changed beside one that selects a project; a window whose only changes are TypeScript files outside every project indexes none. 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. | +| 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), one process per project of their reference closures, each project once; a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a TypeScript file no project contains changed beside one that selects a project; a window whose only changes are TypeScript files outside every project indexes none. 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 45cdc8a45a..2eafd7114d 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -104,6 +104,20 @@ PYEOF fi fi +# indexed_no_file : whether run is confirmed empty, as +# scip-typescript 0.4.0 reports a process whose projects matched no input file: +# exit 1, no output, that report on stdout and nothing on stderr. A process that +# throws while indexing prints the same report, then its stack on stderr. A +# project whose tsconfig fails to load (an unknown option, an unresolvable +# extends) prints its diagnostics on stdout before the same report, so stdout +# must hold nothing else: that project has files the index would lose. +indexed_no_file() { + local part="$WORK/index.part.$1" + [[ "$2" == 1 && ! -e "$part.scip" && ! -s "$part.err" ]] \ + && grep -q '^[[:space:]]*error: no files got indexed\.' "$part.log" \ + && ! grep -qvE '^[[:space:]]*(error: no files got indexed\..*)?$' "$part.log" +} + # paths_rewrite [tsconfig...]: scip_ts_paths.py over the given configs, or # over every workspace package's tsconfig.json when none is given; the same # files are restored on exit. @@ -161,11 +175,6 @@ JSONEOF fi local ws=() [[ -n "$WORKSPACES" ]] && ws=("$WORKSPACES") - # 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 @@ -180,24 +189,54 @@ JSONEOF 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 + # One indexer process per project: scip-typescript shares its source-file + # cache across every target of a process, so one process over the umbrella + # keeps the heap growth of the root pass. It also indexes each referenced + # project inside the process of every member that reaches it; the plan runs + # each project of the closures once instead, a project with references + # through a generated config without them, and gives the merge each run once + # per member whose process would have indexed it, in that order. A project + # whose documents the merge would drop for every such member does not run. + local plan kind run own arg runs=() owns=() parts=() merge_args=() known_args=() t rc for t in "${ALL_PROJECTS[@]}"; do - merge_args+=(--known-project "$t") + known_args+=(--known-project "$t") + done + plan=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" plan "$CHECKOUT" "${known_args[@]}" -- "${targets[@]}") + while IFS=$'\t' read -r kind run arg own; do + case "$kind" in + config) on_exit "rm -f $(printf %q "$run")" ;; + index) + runs[run]=$arg + owns[run]=$own + ;; + merge) + merge_args+=(--project "$arg") + parts+=("$WORK/index.part.$run.scip") + ;; + esac + done <<<"$plan" + for run in "${!runs[@]}"; do + rc=0 + NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ + "$SCIP_TYPESCRIPT" index "${ws[@]}" "${runs[run]}" --output "$WORK/index.part.$run.scip" \ + >"$WORK/index.part.$run.log" 2>"$WORK/index.part.$run.err" || rc=$? + cat "$WORK/index.part.$run.log" "$WORK/index.part.$run.err" >&2 + # A referenced project that matches no file was harmless inside a member's + # process; alone it is an empty part, which the merge reads as empty. Any + # other failure, a killed process included, fails the pass with its status. + if [[ $rc -ne 0 ]]; then + if [[ "${owns[run]}" == 0 ]] && indexed_no_file "$run" "$rc"; then + echo ">> ${runs[run]} indexed no file — read as empty" >&2 + else + echo ">> scip-typescript failed on ${runs[run]} (exit $rc)" >&2 + exit "$rc" + fi + fi done + # Always merge so a member's run that followed project references also + # drops documents it does not own. "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ - "${merge_args[@]}" "${parts[@]}" + "${merge_args[@]}" "${known_args[@]}" "${parts[@]}" } cd "$CHECKOUT" diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index bd3f7cf12e..ecbc127270 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -49,6 +49,7 @@ def _load_harness_module(name: str) -> Any: _ts_projects = _load_harness_module("scip_ts_projects") project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope +scope_specificity = _ts_projects.scope_specificity _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index _top_level_records = _converter._top_level_records @@ -57,21 +58,12 @@ def _load_harness_module(name: str) -> Any: _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 -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] + 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. diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 8c44ab47f0..92b2875d83 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -11,16 +11,29 @@ member owns when the window also selects a member or changes a manifest or lockfile. A window whose only changes are such paths selects none: the merge keeps a document only from a member that owns it. + +`plan` turns the selected members into indexer runs. scip-typescript indexes +every project a target references, recursively, in the same process, so one +process per member indexes a shared reference once for each member that +reaches it. The plan runs each project of the members' reference closures +once, a project with references through a generated config that extends it +without them, and lists for the merge which members' walks reached each run. +A referenced project whose documents the merge would drop for every member +that reaches it does not run. """ from __future__ import annotations import argparse +import contextlib import json import os import re import sys +import tempfile +from collections.abc import Iterator from pathlib import Path +from typing import Any, NamedTuple TS_SUFFIXES = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") LOCKFILE_NAMES = { @@ -42,6 +55,13 @@ _TRAILING_COMMA = re.compile(r",(\s*[}\]])") +# A generated config beside the one it extends, under a fresh name: `include` +# and `${configDir}` resolve from the same directory, and the leading dot keeps +# it out of `*` globs. +NO_REFERENCES_PREFIX = ".scip-norefs." +_CONFIG_DIR = "${configdir}" +_GLOB_CHARS = re.compile(r"[*?]") + def strip_jsonc(text: str) -> str: """Remove // and /* */ comments without treating text inside strings as comments.""" @@ -188,6 +208,221 @@ def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Pat return out +class ProjectRun(NamedTuple): + """One scip-typescript process over the project of `config`, named by + `target`. With `drop_references` the process gets instead a generated config + that extends `config` without its references, which `write_plan` creates.""" + + target: str + config: Path + drop_references: bool = False + own: bool = False + + +def _indexer_config(checkout: Path, root: str) -> Path: + """The tsconfig scip-typescript reads for a project argument, as its + `indexSingleProject` resolves it: a directory's tsconfig.json, else the path.""" + path = Path(os.path.normpath(os.path.join(checkout, root))) + return path / "tsconfig.json" if path.is_dir() else path + + +def _declares_no_files(data: dict[str, Any]) -> bool: + files = data.get("files") + include = data.get("include") + return (files == [] and include in (None, [])) or (files is None and include == []) + + +def _walk_references(checkout: Path, root: str, seen: set[str]) -> Iterator[tuple[str, bool]]: + """Yield (project, has references) in the order scip-typescript 0.4.0 + indexes them for one target: references first, depth first, each argument + string once per process. A reference is the absolute path it names.""" + if root in seen: + return + seen.add(root) + config = _indexer_config(checkout, root) + if not config.is_file(): + return + try: + data: dict[str, Any] | None = load_tsconfig(config) + except (OSError, ValueError): + data = None # the indexer fails on it, as it does inside a member's process + references = [] + for entry in (data or {}).get("references") or []: + rel = _reference_path(entry) + if rel: + references.append(os.path.normpath(os.path.join(config.parent, rel))) + for reference in references: + yield from _walk_references(checkout, reference, seen) + if data is None or not _declares_no_files(data): + yield root, bool(references) + + +def _extended_config(config: Path, spec: str) -> Path | None: + """The file an `extends` entry names, found as TypeScript finds a relative + path or a config under node_modules by its path; None otherwise.""" + if spec.startswith(".") or os.path.isabs(spec): + path = Path(os.path.normpath(os.path.join(config.parent, spec))) + candidates = [path, path.with_name(path.name + ".json")] + else: + candidates = [] + for parent in (config.parent, *config.parent.parents): + base = parent / "node_modules" / spec + candidates += [base, base.with_name(base.name + ".json"), base / "tsconfig.json"] + return next((path for path in candidates if path.is_file()), None) + + +def _files_stay_in(config: Path, directory: Path, seen: set[Path] | None = None) -> bool: + """Whether every `files` and `include` entry of `config` and the configs it + extends lies in `directory`, so every document the project emits does. + False when an extended config cannot be found or read.""" + seen = set() if seen is None else seen + if config in seen: + return True + seen.add(config) + try: + data = load_tsconfig(config) + except (OSError, ValueError): + return False + for entry in [*(data.get("files") or []), *(data.get("include") or [])]: + if not isinstance(entry, str): + return False + if entry.lower().startswith(_CONFIG_DIR): + entry = str(directory) + entry[len(_CONFIG_DIR) :] + fixed = _GLOB_CHARS.split(entry, maxsplit=1)[0] + path = os.path.normpath(os.path.join(config.parent, fixed)) + if path != str(directory) and not path.startswith(str(directory) + os.sep): + return False + extends = data.get("extends") or [] + for spec in [extends] if isinstance(extends, str) else extends: + base = _extended_config(config, spec) if isinstance(spec, str) else None + if base is None or not _files_stay_in(base, directory, seen): + return False + return True + + +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) + return 0 if scope in (".", "") else len(scope) + + +def _merge_can_keep(checkout: Path, config: Path, member: str, known: list[str]) -> bool: + """Whether the merge can keep, for `member`, a document `config`'s project + emits. When all of them lie in the project's directory, it cannot if that + directory is outside the member's scope, or inside a known member more + specific than `member`: that member owns every one of them.""" + if not config.is_relative_to(checkout) or not _files_stay_in(config, config.parent): + return True + directory = posix_path(str(config.parent.relative_to(checkout))) or "." + scope = project_scope(member) + if not project_owns(member, directory) and not project_owns(directory, scope): + return False + return not any( + project_owns(other, directory) and scope_specificity(other) > scope_specificity(member) + for other in known + ) + + +def plan_project_runs( + checkout: Path, targets: list[str], known: list[str] | None = None +) -> tuple[list[ProjectRun], list[tuple[int, str]]]: + """Runs for each project in the targets' reference closures, and the merge + order: (run index, member) for every project each member's own process + would have indexed, in that order, so the merge keeps the same documents. + A pair whose documents the merge would drop is left out, and a project + left with no pair does not run. `known` is the full member set the merge + assigns ownership over (default: the targets). + + `references` is the one tsconfig field `extends` does not inherit, so the + generated config indexes the same files with the same options. A project + outside the checkout, or a jsconfig.json (scip-typescript adds compiler + options by that file name), runs as it is and still follows its references. + """ + checkout = Path(os.path.abspath(checkout)) + known = targets if known is None else known + member_of = {_indexer_config(checkout, target): target for target in targets} + runs: list[ProjectRun] = [] + run_of: dict[Path, int] = {} + merge: list[tuple[int, str]] = [] + for target in targets: + for root, has_references in _walk_references(checkout, target, set()): + config = _indexer_config(checkout, root) + if not _merge_can_keep(checkout, config, target, known): + continue + if config not in run_of: + run_of[config] = len(runs) + target_of_run = member_of.get(config, root) + run = _project_run(checkout, target_of_run, config, has_references) + # Only a member without references ran alone before: an empty one failed then too. + runs.append(run._replace(own=config in member_of and not run.drop_references)) + merge.append((run_of[config], target)) + return runs, merge + + +def _project_run(checkout: Path, target: str, config: Path, has_references: bool) -> ProjectRun: + drop = has_references and config.name != "jsconfig.json" and config.is_relative_to(checkout) + return ProjectRun(target, config, drop) + + +def _write_without_references(config: Path) -> Path: + """Create a config that extends `config`, beside it under a fresh name: a + file already in the tree is never overwritten, and the harness removes only + the file created here.""" + fd, name = tempfile.mkstemp( + prefix=NO_REFERENCES_PREFIX, suffix=f".{config.name}", dir=config.parent + ) + try: + handle = os.fdopen(fd, "w", encoding="utf-8") + except BaseException: # a created file must not outlive the attempt + # fdopen that fails leaves the descriptor unowned; once it returns, the file + # object closes it. + with contextlib.suppress(OSError): + os.close(fd) + with contextlib.suppress(OSError): + Path(name).unlink(missing_ok=True) + raise + try: + with handle: + handle.write(json.dumps({"extends": f"./{config.name}"}) + "\n") + except BaseException: # a created file must not outlive the attempt + # The caller removes only the paths this helper returned, so a partial file + # goes here. + with contextlib.suppress(OSError): + Path(name).unlink(missing_ok=True) + raise + return Path(name) + + +def write_plan(checkout: Path, targets: list[str], known: list[str] | None = None) -> list[str]: + """Write the generated configs and return the plan as tab-separated lines: + `config ` for each file written, `index ` for each run + (own is 1 for a member that ran alone before, whose empty run still fails the + pass) and `merge ` in merge order.""" + checkout = Path(os.path.abspath(checkout)) + runs, merge = plan_project_runs(checkout, targets, known) + lines: list[str] = [] + index: list[str] = [] + written: list[Path] = [] + try: + for i, run in enumerate(runs): + target = run.target + if run.drop_references: + generated = _write_without_references(run.config) + written.append(generated) + lines.append(f"config\t{generated}") + target = str(generated.relative_to(checkout)) + index.append(f"index\t{i}\t{target}\t{int(run.own)}") + except BaseException: + # The caller learns of a config only from the returned plan: remove those written so far. + for path in written: + path.unlink(missing_ok=True) + raise + lines.extend(index) + lines.extend(f"merge\t{i}\t{member}" for i, member in merge) + return lines + + def posix_path(path: str) -> str: """Normalize slashes and a `./` prefix; keep a leading hidden-directory dot.""" path = path.replace("\\", "/") @@ -313,6 +548,19 @@ def main(argv: list[str] | None = None) -> int: shared.add_argument("--changed-file-list", type=Path) shared.add_argument("--deleted-file-list", type=Path) + plan = sub.add_parser( + "plan", + help="write the generated configs and print the indexer runs for member targets", + ) + plan.add_argument("checkout", type=Path) + plan.add_argument( + "--known-project", + action="append", + default=[], + help="full member set the merge assigns ownership over (default: the targets)", + ) + plan.add_argument("targets", nargs="*") + config = sub.add_parser( "has-config", help="exit 0 if the window contains a package manifest, lockfile, or tsconfig", @@ -323,6 +571,8 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if args.cmd == "discover": projects = discover_umbrella_projects(args.checkout) + elif args.cmd == "plan": + projects = write_plan(args.checkout, list(args.targets), args.known_project or None) 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 diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index a680ebc60d..0eb37a48db 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -5,10 +5,13 @@ import json import os +import re import subprocess from pathlib import Path from typing import Any +import pytest + _SCRIPT = ( Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_typescript_delta.sh" ) @@ -43,7 +46,73 @@ for a in "$@"; do printf '\\t%s' "$a"; done printf '\\n' } >>"$CALLS" -while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done +while [[ $# -gt 0 ]]; do + [[ "$1" == "--dry-run" ]] && echo '{}' >"$2" + [[ "$1" == "--index" && -n "${MERGED-}" ]] && cp "$2" "$MERGED" + shift +done +""" + +# Indexes like scip-typescript 0.4.0: each target, after the projects it +# references (depth first, each argument once per process), writes one +# document per project and logs the tsconfig of every project it indexes. +_FAKE_SCIP_INDEXING = """#!/usr/bin/env bash +{ + printf 'run' + for a in "$@"; do printf '\\t%s' "$a"; done + printf '\\n' +} >>"$CALLS" +if [[ -n "${KILL_PROJECT-}" && "$2" == *"$KILL_PROJECT"* ]]; then + echo "error: no files got indexed. To fix this problem, make sure that the TypeScript projects" + exit 137 +fi +if [[ -n "${BROKEN_PROJECT-}" && "$2" == *"$BROKEN_PROJECT"* ]]; then + # A tsconfig that fails to load: the diagnostics go to stdout, then the same report. + echo "error TS5023: Unknown compiler option 'bogusOption'." + echo + echo "error: no files got indexed. To fix this problem, make sure that the TypeScript projects" + exit 1 +fi +exec "$REAL_PYTHON" "$SCIP_WRITER" "$@" +""" + +_SCIP_WRITER = """ +import json, os, sys +sys.path.insert(0, os.environ["SCIP_VENDOR"]) +import scip_pb2 + +args = sys.argv[2:] +out = args[args.index("--output") + 1] +targets = [a for a in args[: args.index("--output")] if not a.startswith("-")] +index = scip_pb2.Index() +seen = set() + +def walk(root): + if root in seen: + return + seen.add(root) + path = os.path.abspath(root) + config = os.path.join(path, "tsconfig.json") if os.path.isdir(path) else path + data = json.load(open(config)) + for ref in data.get("references", []): + walk(os.path.normpath(os.path.join(os.path.dirname(config), ref["path"]))) + if data.get("files") == [] or any("nothing" in i for i in data.get("include", [])): + return + with open(os.environ["INDEXED"], "a") as log: + log.write(os.path.relpath(config) + "\\n") + doc = index.documents.add() + doc.relative_path = os.path.relpath(os.path.dirname(config)) + "/indexed.ts" + +for target in targets: + walk(target) +if not index.documents: + # 0.4.0: a process that indexed no document exits 1 and deletes its output. + print( + "error: no files got indexed. To fix this problem, make sure that the TypeScript" + f" projects {json.dumps(targets)} contain input files or reference other projects." + ) + sys.exit(1) +open(out, "wb").write(index.SerializeToString()) """ @@ -74,13 +143,20 @@ def _repo(tmp_path: Path) -> Path: return repo -def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: +def _run( + tmp_path: Path, + repo: Path, + base: str, + head: str, + scip: str = _FAKE_SCIP, + extra_env: dict[str, str] | None = None, +) -> str: bin_dir = tmp_path / "bin" bin_dir.mkdir(exist_ok=True) calls = tmp_path / "calls" calls.unlink(missing_ok=True) Path(f"{calls}.tsconfig").unlink(missing_ok=True) - for name, body in (("scip-typescript", _FAKE_SCIP), ("python", _FAKE_PYTHON)): + for name, body in (("scip-typescript", scip), ("python", _FAKE_PYTHON)): dest = bin_dir / name dest.write_text(body) dest.chmod(0o755) @@ -94,6 +170,7 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: "PYTHON": str(bin_dir / "python"), "REAL_PYTHON": shutil.which("python3") or "python3", "SCIP_TYPESCRIPT": str(bin_dir / "scip-typescript"), + **(extra_env or {}), } # Don't leak a parent SCIP_TS_PROJECTS into the test. env.pop("SCIP_TS_PROJECTS", None) @@ -727,3 +804,198 @@ def test_delta_with_a_non_utf8_file_name_in_the_window(tmp_path: Path) -> None: assert b"packages/lib/caf\xe9.md" in window.split(b"\n") log = _run(tmp_path, repo, base, head) assert _targets(_runs(log)) == ["packages/app"] + + +def _closure_repo(tmp_path: Path) -> Path: + """`app` references `lib`, a member, and `app/tools`, which no member names.""" + 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"], "references": [{"path": "../lib"}, {"path": "./tools"}]} + ), + "packages/app/src/a.ts": "export const a = 1;\n", + "packages/app/tools/tsconfig.json": json.dumps({"include": ["*.ts"]}), + "packages/app/tools/t.ts": "export const t = 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_indexing( + tmp_path: Path, + repo: Path, + base: str, + head: str, + kill_project: str = "", + broken_project: str = "", +) -> tuple[list[str], set[str]]: + """Run the harness with an indexer that follows references; return the + tsconfig of every project indexed, in order, and the merged documents. + The indexer exits 137 after its report line for a target containing `kill_project`; + for one containing `broken_project` it prints a TypeScript error, then the report, and exits 1.""" + import sys + + vendor = _SCRIPT.parent / "vendor" + writer = tmp_path / "scip_writer.py" + writer.write_text(_SCIP_WRITER) + indexed = tmp_path / "indexed" + indexed.unlink(missing_ok=True) + merged = tmp_path / "merged.scip" + merged.unlink(missing_ok=True) + _run( + tmp_path, + repo, + base, + head, + scip=_FAKE_SCIP_INDEXING, + extra_env={ + "BROKEN_PROJECT": broken_project, + "INDEXED": str(indexed), + "KILL_PROJECT": kill_project, + "MERGED": str(merged), + "SCIP_VENDOR": str(vendor), + "SCIP_WRITER": str(writer), + }, + ) + sys.path.insert(0, str(vendor)) + import scip_pb2 + + index = scip_pb2.Index() + index.ParseFromString(merged.read_bytes()) + # A generated config has a fresh name on every pass. + indexed_configs = [ + re.sub(r"\.scip-norefs\.\w{8}\.", ".scip-norefs.*.", line) + for line in indexed.read_text().splitlines() + ] + return indexed_configs, {doc.relative_path for doc in index.documents} + + +def test_full_pass_indexes_each_project_of_a_shared_closure_once(tmp_path: Path) -> None: + """One process per member indexed `lib` twice, once inside `app`'s process. + Each project is indexed once and the merge keeps the same documents.""" + repo = _closure_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + indexed, documents = _run_indexing(tmp_path, repo, "--full", head) + assert sorted(indexed) == [ + "packages/app/.scip-norefs.*.tsconfig.json", + "packages/app/tools/tsconfig.json", + "packages/lib/tsconfig.json", + ] + assert documents == { + "packages/app/indexed.ts", + "packages/app/tools/indexed.ts", + "packages/lib/indexed.ts", + } + assert _git(repo, "status", "--porcelain", "--ignored") == "" + + +def test_delta_indexes_the_closure_of_the_selected_member_only(tmp_path: Path) -> None: + """An edit in `app` runs `app` and `tools`. `lib` does not run: its files + lie in packages/lib, so the merge drops them for `app`, as it dropped the + copies `app`'s own process made.""" + repo = _closure_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") + indexed, documents = _run_indexing(tmp_path, repo, base, head) + assert sorted(indexed) == [ + "packages/app/.scip-norefs.*.tsconfig.json", + "packages/app/tools/tsconfig.json", + ] + assert documents == {"packages/app/indexed.ts", "packages/app/tools/indexed.ts"} + + base = head + (repo / "packages/lib/src/b.ts").write_text("export const b = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch lib") + head = _git(repo, "rev-parse", "HEAD") + indexed, documents = _run_indexing(tmp_path, repo, base, head) + assert indexed == ["packages/lib/tsconfig.json"] + assert documents == {"packages/lib/indexed.ts"} + + +def test_a_referenced_project_that_matches_no_file_does_not_fail_the_pass( + tmp_path: Path, +) -> None: + """Inside `app`'s process the empty `shared` was harmless: `app`'s own + documents kept the count above zero. Run alone, scip-typescript 0.4.0 + exits 1 and deletes its output; the pass reads that run as empty.""" + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps({"files": [], "references": [{"path": "packages/app"}]}), + "packages/app/tsconfig.json": json.dumps( + {"include": ["src"], "references": [{"path": "../shared"}]} + ), + "packages/app/src/a.ts": "export const a = 1;\n", + "packages/shared/tsconfig.json": json.dumps({"include": ["../nothing/*.ts"]}), + } + 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") + indexed, documents = _run_indexing(tmp_path, repo, "--full", head) + assert indexed == ["packages/app/.scip-norefs.*.tsconfig.json"] + assert documents == {"packages/app/indexed.ts"} + assert _git(repo, "status", "--porcelain", "--ignored") == "" + + +def test_a_referenced_indexer_killed_before_its_output_fails_the_pass(tmp_path: Path) -> None: + """`tools` owns no member and is killed before it writes: the pass fails with + the indexer's exit status instead of converting an index without `tools`.""" + repo = _closure_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + with pytest.raises(subprocess.CalledProcessError) as failed: + _run_indexing(tmp_path, repo, "--full", head, kill_project="tools") + assert failed.value.returncode == 137 + assert "convert" not in (tmp_path / "calls").read_text() + + +def test_a_referenced_project_whose_tsconfig_fails_to_load_fails_the_pass( + tmp_path: Path, +) -> None: + """scip-typescript prints a config's diagnostics on stdout and skips the project, then + ends like an empty run: exit 1, the report on stdout, nothing on stderr. Only a stdout + holding nothing but the report is an empty project, so this pass fails with the exit + status instead of dropping the project's files.""" + repo = _closure_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + with pytest.raises(subprocess.CalledProcessError) as failed: + _run_indexing(tmp_path, repo, "--full", head, broken_project="tools") + assert failed.value.returncode == 1 + assert "convert" not in (tmp_path / "calls").read_text() + + +def test_a_tracked_file_with_the_generated_config_name_is_left_as_it_is( + tmp_path: Path, +) -> None: + repo = _closure_repo(tmp_path) + tracked = repo / "packages/app/.scip-norefs.tsconfig.json" + tracked.write_text('{"compilerOptions": {"strict": true}}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "tracked") + head = _git(repo, "rev-parse", "HEAD") + _, documents = _run_indexing(tmp_path, repo, "--full", head) + assert tracked.read_bytes() == b'{"compilerOptions": {"strict": true}}\n' + assert _git(repo, "status", "--porcelain", "--ignored") == "" + assert documents == { + "packages/app/indexed.ts", + "packages/app/tools/indexed.ts", + "packages/lib/indexed.ts", + } diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index 9948d60528..134c4a4662 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -9,6 +9,8 @@ import sys from pathlib import Path +import pytest + _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) @@ -16,6 +18,8 @@ discover_umbrella_projects = _MOD.discover_umbrella_projects is_umbrella_tsconfig = _MOD.is_umbrella_tsconfig load_tsconfig = _MOD.load_tsconfig +plan_project_runs = _MOD.plan_project_runs +write_plan = _MOD.write_plan select_projects_for_delta = _MOD.select_projects_for_delta @@ -252,3 +256,233 @@ def test_filter_reads_and_prints_names_that_are_not_utf8(tmp_path: Path) -> None argv = [sys.executable, os.fsencode(_SCRIPT), cmd, b"--changed-file-list"] rc = subprocess.run([*argv, os.fsencode(changed)], env=env, capture_output=True) assert rc.returncode == 0, rc.stderr + + +def _closure_tree(root: Path) -> list[str]: + """Two packages as typescript-eslint lays them out: build and spec configs + named by the umbrella, each build config referencing its dependencies'.""" + _write( + root, + "packages/a/tsconfig.build.json", + json.dumps({"include": ["src"], "references": [{"path": "../b/tsconfig.build.json"}]}), + ) + _write( + root, + "packages/a/tsconfig.spec.json", + json.dumps({"include": ["tests"], "references": [{"path": "./tsconfig.build.json"}]}), + ) + _write(root, "packages/b/tsconfig.build.json", json.dumps({"include": ["src"]})) + return [ + "packages/a/tsconfig.build.json", + "packages/a/tsconfig.spec.json", + "packages/b/tsconfig.build.json", + ] + + +def test_plan_runs_each_project_once_for_the_members_that_keep_its_documents( + tmp_path: Path, +) -> None: + """One process per member indexed b three times and a's build config twice. + The plan runs each once, in the per-member order; b's files lie in + packages/b, which a's members do not own, so b runs for itself only.""" + targets = _closure_tree(tmp_path) + runs, merge = plan_project_runs(tmp_path, targets) + assert [(run.target, run.drop_references) for run in runs] == [ + ("packages/a/tsconfig.build.json", True), + ("packages/a/tsconfig.spec.json", True), + ("packages/b/tsconfig.build.json", False), + ] + a_build, a_spec, b_build = targets + assert merge == [(0, a_build), (0, a_spec), (1, a_spec), (2, b_build)] + + +def test_plan_skips_package_references_of_a_root_level_member(tmp_path: Path) -> None: + """A delta selects a root-level member with a package beside it. The package + member owns everything under packages/a, so the root member's reference + to it does not run, while a root-level config it references does.""" + targets = _closure_tree(tmp_path) + _write( + tmp_path, + "tsconfig.repo.json", + json.dumps( + { + "include": ["*.ts"], + "references": [ + {"path": "./packages/a/tsconfig.build.json"}, + {"path": "./tsconfig.spec.json"}, + ], + } + ), + ) + _write(tmp_path, "tsconfig.spec.json", json.dumps({"include": ["vitest.config.mts"]})) + known = [*targets, "tsconfig.repo.json"] + runs, merge = plan_project_runs(tmp_path, ["tsconfig.repo.json"], known) + assert [(run.target, run.drop_references) for run in runs] == [ + (str(tmp_path / "tsconfig.spec.json"), False), + ("tsconfig.repo.json", True), + ] + assert merge == [(0, "tsconfig.repo.json"), (1, "tsconfig.repo.json")] + + +def test_plan_keeps_a_reference_whose_files_may_leave_its_directory(tmp_path: Path) -> None: + """An `include` outside the project, or an `extends` the helper cannot + find, may put documents under the member: that reference still runs.""" + _write( + tmp_path, + "packages/app/tsconfig.json", + json.dumps({"include": ["src"], "references": [{"path": "../lib"}, {"path": "../util"}]}), + ) + _write( + tmp_path, + "packages/lib/tsconfig.json", + json.dumps({"include": ["src", "../app/shared"]}), + ) + _write( + tmp_path, + "packages/util/tsconfig.json", + json.dumps({"extends": "@missing/tsconfig", "include": ["src"]}), + ) + known = ["packages/app", "packages/lib", "packages/util"] + runs, merge = plan_project_runs(tmp_path, ["packages/app"], known) + assert [(run.target, run.drop_references) for run in runs] == [ + (str(tmp_path / "packages/lib"), False), + (str(tmp_path / "packages/util"), False), + ("packages/app", True), + ] + assert merge == [(0, "packages/app"), (1, "packages/app"), (2, "packages/app")] + + +def test_plan_without_references_runs_the_members_as_they_are(tmp_path: Path) -> None: + for name in ("app", "lib"): + _write(tmp_path, f"packages/{name}/tsconfig.json", json.dumps({"include": ["src"]})) + targets = ["packages/app", "packages/lib"] + assert write_plan(tmp_path, targets) == [ + "index\t0\tpackages/app\t1", + "index\t1\tpackages/lib\t1", + "merge\t0\tpackages/app", + "merge\t1\tpackages/lib", + ] + assert sorted(p.name for p in (tmp_path / "packages/app").iterdir()) == ["tsconfig.json"] + + +def test_plan_writes_a_config_that_extends_the_project_without_its_references( + tmp_path: Path, +) -> None: + targets = _closure_tree(tmp_path) + lines = write_plan(tmp_path, targets) + generated = sorted(tmp_path.glob("packages/*/.scip-norefs.*")) + assert sorted(line for line in lines if line.startswith("config")) == sorted( + f"config\t{path}" for path in generated + ) + build = next(path for path in generated if path.name.endswith(".tsconfig.build.json")) + assert build.parent == tmp_path / "packages/a" + assert json.loads(build.read_text()) == {"extends": "./tsconfig.build.json"} + assert f"index\t0\t{build.relative_to(tmp_path)}\t0" in lines + assert len(generated) == 2 # a's build and spec configs; b has no references + + +def test_a_plan_that_fails_midway_removes_the_configs_it_wrote( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + targets = _closure_tree(tmp_path) + real = _MOD._write_without_references + calls: list[Path] = [] + + def fail_on_the_second(config: Path) -> Path: + if calls: + raise OSError("read-only directory") + calls.append(real(config)) + return calls[0] + + monkeypatch.setattr(_MOD, "_write_without_references", fail_on_the_second) + with pytest.raises(OSError, match="read-only"): + write_plan(tmp_path, targets) + assert len(calls) == 1 + assert list(tmp_path.glob("packages/*/.scip-norefs.*")) == [] + + +def test_a_generated_config_is_removed_when_writing_it_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + targets = _closure_tree(tmp_path) + real_fdopen = os.fdopen + + class FailingWrite: + def __init__(self, fd: int) -> None: + self._file = real_fdopen(fd, "w", encoding="utf-8") + + def __enter__(self) -> FailingWrite: + return self + + def __exit__(self, *exc: object) -> None: + self._file.close() + + def write(self, text: str) -> int: + raise OSError("no space left on device") + + monkeypatch.setattr(_MOD.os, "fdopen", lambda fd, *args, **kwargs: FailingWrite(fd)) + with pytest.raises(OSError, match="no space left"): + write_plan(tmp_path, targets) + assert list(tmp_path.glob("packages/*/.scip-norefs.*")) == [] + + +def test_a_generated_config_is_removed_when_it_cannot_be_opened( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + targets = _closure_tree(tmp_path) + opened: list[int] = [] + closed: list[int] = [] + real_close = os.close + + def failing_fdopen(fd: int, *args: object, **kwargs: object) -> None: + opened.append(fd) + raise OSError("too many open files") + + def recording_close(fd: int) -> None: + closed.append(fd) + real_close(fd) + + monkeypatch.setattr(_MOD.os, "fdopen", failing_fdopen) + monkeypatch.setattr(_MOD.os, "close", recording_close) + with pytest.raises(OSError, match="too many open files"): + write_plan(tmp_path, targets) + assert list(tmp_path.glob("packages/*/.scip-norefs.*")) == [] + # mkstemp's descriptor outlives a failed fdopen unless the helper closes it. + assert opened, "fdopen was never reached" + assert opened[0] in closed + + +def test_plan_walks_a_solution_config_without_running_it(tmp_path: Path) -> None: + """A config with no files of its own is never indexed, but its references are.""" + _write( + tmp_path, + "packages/app/tsconfig.json", + json.dumps({"include": ["src"], "references": [{"path": "./tools"}]}), + ) + _write( + tmp_path, + "packages/app/tools/tsconfig.json", + json.dumps({"files": [], "references": [{"path": "./tsconfig.build.json"}]}), + ) + _write(tmp_path, "packages/app/tools/tsconfig.build.json", json.dumps({"include": ["*.ts"]})) + runs, merge = plan_project_runs(tmp_path, ["packages/app"]) + assert [(run.target, run.drop_references) for run in runs] == [ + (str(tmp_path / "packages/app/tools/tsconfig.build.json"), False), + ("packages/app", True), + ] + assert merge == [(0, "packages/app"), (1, "packages/app")] + + +def test_plan_runs_a_jsconfig_as_it_is(tmp_path: Path) -> None: + """scip-typescript adds compiler options by the file name jsconfig.json.""" + _write( + tmp_path, + "web/jsconfig.json", + json.dumps({"include": ["src"], "references": [{"path": "../lib"}]}), + ) + _write(tmp_path, "lib/tsconfig.json", json.dumps({"include": ["src"]})) + runs, _ = plan_project_runs(tmp_path, ["web/jsconfig.json", "lib"]) + assert [(run.target, run.drop_references) for run in runs] == [ + ("web/jsconfig.json", False), + ("lib", False), + ]