blob: 13a0db63276062c34ead863aeae11cde85997742 [file] [edit]
// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {execFile} from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {promisify} from 'node:util';
import {getGnBinary} from '../gn_deps_verifier/gn_ast/gn_ast.ts';
import {unquoteFromGn} from '../gn_deps_verifier/gn_ast/gn_ast_factory.ts';
import type {GnAstNode} from '../gn_deps_verifier/gn_ast/gn_ast_types.ts';
import {applyAssignment, walkStatements} from '../gn_deps_verifier/gn_ast/gn_ast_visitor.ts';
import {isNotFoundError} from '../gn_deps_verifier/utils/error.ts';
import {GnLabel} from '../gn_deps_verifier/utils/gn_label.ts';
const execFileAsync = promisify(execFile);
const MAX_GN_CONCURRENCY = 8;
const GN_MAX_BUFFER_BYTES = 50 * 1024 * 1024;
// Templates whose `.gni` definitions set `testonly = true` internally without requiring it at call sites.
const TESTONLY_BY_DEFAULT_TEMPLATES = new Set([
'devtools_api_test_module',
'node_script_test',
'node_ts_library',
'script_test',
]);
const DEP_ATTRIBUTES = ['deps', 'ts_deps', 'public_deps', 'data_deps'] as const;
export interface GnTarget {
/** Canonical GN target label (for example, `//front_end/core/common:common` or `//:root_tests`). */
label: string;
/** GN template or rule name (for example, `devtools_ui_module` or `group`). */
templateName: string;
/** Normalized repository-relative POSIX path to the owning `BUILD.gn` file. */
buildFile: string;
/** Normalized repository-relative POSIX paths for each entry declared in `sources`. */
resolvedSources: string[];
/** Canonical GN labels resolved across `deps`, `ts_deps`, `public_deps`, and `data_deps`. */
allDeps: string[];
/** Effective `testonly` flag from explicit assignments or template defaults. */
testonly: boolean;
}
export interface ReachableTargetsResult {
/** Existing GN targets discovered during traversal, keyed by canonical label. */
targets: Map<string, GnTarget>;
/** Canonical GN labels referenced during traversal that could not be resolved to a target. */
unresolved: Set<string>;
}
/**
* Normalizes a repository-relative path to POSIX separators without leading or trailing slashes,
* mapping empty, `/`, `.`, and `./` inputs to `.`.
*/
export function normalizeRepoRelPath(relPath: string): string {
const normalized = path.posix.normalize(relPath.replaceAll('\\', '/')).replace(/^\/+|\/+$/g, '');
return normalized || '.';
}
function isGnAstNode(value: unknown): value is GnAstNode {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* Strips a trailing GN toolchain suffix from a label string (for example,
* `//front_end/panels/a:unittests(//build/toolchain:host)` -> `//front_end/panels/a:unittests`).
*
* `GnLabel` does not parse toolchain suffixes, and `GnBuildReader` indexes targets by `BUILD.gn`
* label regardless of toolchain.
*/
function stripToolchainSuffix(label: string): string {
const parenIndex = label.indexOf('(');
if (parenIndex !== -1 && label.endsWith(')')) {
return label.slice(0, parenIndex);
}
return label;
}
/**
* Determines whether BFS traversal continues through `target`'s dependencies.
*
* Always expands `isEntryTarget` (so traversal starts even if the root is a production target),
* `testonly` targets, and `generated_file` targets (such as test-input manifests), while pruning
* at non-testonly production targets (GN forbids non-testonly targets, including `group`, from
* depending on `testonly` targets).
*/
function shouldExpandTarget(target: GnTarget, isEntryTarget: boolean): boolean {
return isEntryTarget || target.testonly || target.templateName === 'generated_file';
}
/**
* Reads `BUILD.gn` target metadata and test-graph reachability directly from disk.
*
* Exists separately from `scripts/gn_deps_verifier/` because manifest checks require `sources`-only
* ownership (excluding `inputs`/`entrypoint`), all four dependency attributes (`deps`, `ts_deps`,
* `public_deps`, `data_deps`), and transitive reachability queries. Walks `if`/`else` blocks
* sequentially (by design: `devtools-frontend` `BUILD.gn` files only use additive `+=` inside
* conditionals on dependencies and never overwrite `sources`, `deps`, or `testonly` across
* branches) and prunes reachability at non-testonly targets.
*/
export class GnBuildReader {
readonly #rootDir: string;
readonly #gnBinary: string;
readonly #buildFileCache = new Map<string, Promise<Map<string, GnTarget>|null>>();
readonly #reachableCache = new Map<string, Promise<ReachableTargetsResult>>();
constructor(rootDir: string) {
this.#rootDir = path.resolve(rootDir);
try {
this.#gnBinary = getGnBinary(this.#rootDir);
} catch {
this.#gnBinary = getGnBinary(import.meta.dirname);
}
}
#getBuildFile(relBuildPath: string): Promise<Map<string, GnTarget>|null> {
const normalizedPath = normalizeRepoRelPath(relBuildPath);
const cached = this.#buildFileCache.get(normalizedPath);
if (cached) {
return cached;
}
const loadPromise = this.#loadBuildFile(normalizedPath);
this.#buildFileCache.set(normalizedPath, loadPromise);
return loadPromise;
}
/**
* Loads and parses a single `BUILD.gn` file via `gn format --dump-tree=json`.
*
* Inspects `FUNCTION` AST nodes shaped as `child[0].child[0]` (`LITERAL` target name) and
* `child[1]` (`BLOCK` body), walks `if`/`else` blocks sequentially into one variable map (by
* design, because `devtools-frontend` `BUILD.gn` files only use additive `+=` inside conditionals
* rather than branch-overwriting `sources`/`deps`/`testonly` assignments), records only `sources`
* (excluding `inputs` and `entrypoint`), resolves dependencies across `DEP_ATTRIBUTES`, and
* computes `testonly` using last-assignment-wins (`=== 'true'`) with template-default fallback.
*/
async #loadBuildFile(relBuildPath: string): Promise<Map<string, GnTarget>|null> {
const absPath = path.resolve(this.#rootDir, relBuildPath);
try {
await fs.promises.access(absPath);
} catch (error) {
if (isNotFoundError(error)) {
return null;
}
throw error;
}
let ast: GnAstNode;
try {
const {stdout} = await execFileAsync(this.#gnBinary, ['format', '--dump-tree=json', absPath], {
encoding: 'utf-8',
maxBuffer: GN_MAX_BUFFER_BYTES,
});
const parsed: unknown = JSON.parse(stdout);
if (!isGnAstNode(parsed)) {
throw new Error('Unexpected GN AST output');
}
ast = parsed;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to parse GN AST for ${relBuildPath}: ${message}`, {cause: error});
}
const dirName = path.posix.dirname(relBuildPath);
const relDir = dirName === '.' ? '' : dirName;
const absDir = path.dirname(absPath);
const variables = new Map<string, string[]>();
const targets = new Map<string, GnTarget>();
const visitNode = (node: GnAstNode): void => {
if (applyAssignment(variables, node)) {
return;
}
if (node.type === 'FUNCTION') {
const targetNameNode = node.child?.[0]?.child?.[0];
const block = node.child?.[1];
if (targetNameNode?.type !== 'LITERAL' || block?.type !== 'BLOCK') {
return;
}
const templateName = node.value ?? '';
const label = `//${relDir}:${unquoteFromGn(targetNameNode.value)}`;
const scopedVariables = new Map(variables);
walkStatements(block.child ?? [], statement => {
applyAssignment(scopedVariables, statement);
});
const rawSources = Array.from(new Set(scopedVariables.get('sources') ?? []));
const resolvedSources = rawSources.map(src => {
const posixSource = src.replaceAll('\\', '/');
if (posixSource.startsWith('//')) {
return normalizeRepoRelPath(posixSource.slice(2));
}
return normalizeRepoRelPath(relDir === '' ? posixSource : `${relDir}/${posixSource}`);
});
const allDeps = Array.from(new Set(
DEP_ATTRIBUTES.flatMap(attr => scopedVariables.get(attr) ?? [])
.filter(Boolean)
.map(dep => GnLabel.resolveDeclaredDep(stripToolchainSuffix(dep), absDir, this.#rootDir)),
));
const lastTestonly = scopedVariables.get('testonly')?.at(-1);
const testonly =
lastTestonly !== undefined ? lastTestonly === 'true' : TESTONLY_BY_DEFAULT_TEMPLATES.has(templateName);
targets.set(label, {
label,
templateName,
buildFile: relBuildPath,
resolvedSources,
allDeps,
testonly,
});
// Do not recurse into FUNCTION bodies so local assignments do not leak to file-level variables.
return;
}
if (node.child) {
for (const child of node.child) {
visitNode(child);
}
}
};
visitNode(ast);
return targets;
}
async getTarget(label: string): Promise<GnTarget|undefined> {
const parsed = GnLabel.parse(stripToolchainSuffix(label));
if (!parsed?.name) {
return undefined;
}
const targets = await this.#getBuildFile(path.posix.join(parsed.dirPath, 'BUILD.gn'));
return targets?.get(parsed.toString());
}
/**
* Collects all existing targets reachable from `rootLabel` via cached level-by-level BFS,
* alongside any referenced labels that could not be resolved to a target.
*
* Returns empty `targets` when `rootLabel` is invalid or missing (recording missing valid labels
* in `unresolved`). Non-testonly production boundary targets reached during traversal are
* recorded in `targets` without expanding their dependencies.
*/
getReachableTargets(rootLabel: string): Promise<ReachableTargetsResult> {
const parsed = GnLabel.parse(stripToolchainSuffix(rootLabel));
if (!parsed?.name) {
return Promise.resolve({targets: new Map(), unresolved: new Set()});
}
const canonicalRoot = parsed.toString();
const cached = this.#reachableCache.get(canonicalRoot);
if (cached) {
return cached;
}
const loadPromise = this.#collectReachableTargets(canonicalRoot);
this.#reachableCache.set(canonicalRoot, loadPromise);
return loadPromise;
}
async #collectReachableTargets(canonicalRoot: string): Promise<ReachableTargetsResult> {
const targets = new Map<string, GnTarget>();
const unresolved = new Set<string>();
const visited = new Set<string>([canonicalRoot]);
let frontier: string[] = [canonicalRoot];
while (frontier.length > 0) {
const nextFrontier: string[] = [];
for (let i = 0; i < frontier.length; i += MAX_GN_CONCURRENCY) {
const batch = frontier.slice(i, i + MAX_GN_CONCURRENCY);
const resolvedBatch = await Promise.all(batch.map(label => this.getTarget(label)));
for (let j = 0; j < batch.length; j++) {
const target = resolvedBatch[j];
if (!target) {
unresolved.add(batch[j]);
continue;
}
targets.set(target.label, target);
if (!shouldExpandTarget(target, target.label === canonicalRoot)) {
continue;
}
for (const dep of target.allDeps) {
if (!visited.has(dep)) {
visited.add(dep);
nextFrontier.push(dep);
}
}
}
}
frontier = nextFrontier;
}
return {targets, unresolved};
}
}