import { getPluginConfiguration } from '@yarnpkg/cli'; import type { LocatorHash } from '@yarnpkg/core'; import { Configuration, Project, structUtils, ThrowReport, } from '@yarnpkg/core'; import { ppath } from '@yarnpkg/fslib'; import { parseSyml } from '@yarnpkg/parsers'; import { execa } from 'execa'; import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; export const ROOT_WORKSPACE = new URL('../..', import.meta.url).pathname; // Files that can change without requiring a full rebuild/test run. const IGNORED_ROOT_FILES = new Set([ '.gitignore', 'AGENTS.md', 'CLAUDE.md', 'README.md', // The lockfile has special logic for determining whether a package // build/test/lint run is required, so it should not trigger a full run on its // own. 'yarn.lock', // The root package.json has special logic: only a version-only change (e.g., // from a release PR) is safe to ignore. Any other change triggers a full run. 'package.json', ]); export type Workspace = { location: string; name: string; }; export type DependencyGraph = { dependants: Record>; dependencies: Record>; }; /** * Get all non-root workspaces in the monorepo. * * @param options - The options object. * @param options.includePrivate - Whether to include private workspaces. * @returns All workspaces. */ export async function getAllWorkspaces({ includePrivate = false, }: { includePrivate?: boolean } = {}): Promise { const { stdout } = await execa( 'yarn', [ 'workspaces', 'list', ...(includePrivate ? [] : ['--no-private']), '--json', ], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }, ); return stdout .trim() .split('\n') .map((line) => JSON.parse(line) as Workspace) .filter(({ location }) => location !== '.'); } /** * Get dependency and dependant maps for all workspaces. * * @param workspaces - The workspaces to build the graph for. * @returns Maps of package name to dependants and package name to dependencies. */ export async function getWorkspaceDependencies( workspaces: Workspace[], ): Promise { const dependants: Record> = Object.fromEntries( workspaces.map(({ name }) => [name, new Set()]), ); const dependencies: Record> = Object.fromEntries( workspaces.map(({ name }) => [name, new Set()]), ); const packages = await Promise.all( workspaces.map(async ({ location }) => readFile(join(ROOT_WORKSPACE, location, 'package.json'), { encoding: 'utf-8', }).then(JSON.parse), ), ); for (const [index, workspace] of workspaces.entries()) { const pkg = packages[index]; for (const dependency of Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, })) { if (dependants[dependency] !== undefined) { const dependencyWorkspace = workspaces.find( (item) => item.name === dependency, ); if (dependencyWorkspace) { dependants[dependency].add(workspace); dependencies[workspace.name].add(dependencyWorkspace); } } } } return { dependants, dependencies }; } /** * Get the list of files changed between the merge base and the PR head. * * @param mergeBase - The merge base SHA. * @param headRef - The PR branch tip SHA (or "HEAD" as fallback). * @returns A list of changed file paths. */ export async function getChangedFiles( mergeBase: string, headRef: string, ): Promise { const { stdout } = await execa( 'git', ['diff', '--name-only', `${mergeBase}...${headRef}`], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }, ); return stdout.trim().split('\n').filter(Boolean); } /** * Get the set of package names whose entries changed in yarn.lock between * `mergeBase` and `headRef`. * * @param mergeBase - The merge base SHA. * @param headRef - The PR branch tip SHA (or "HEAD"). * @returns The set of changed package names. */ async function getChangedLockfilePackages( mergeBase: string, headRef: string, ): Promise> { const [{ stdout: baseLockContent }, { stdout: currentLockContent }] = await Promise.all([ execa('git', ['show', `${mergeBase}:yarn.lock`], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }), execa('git', ['show', `${headRef}:yarn.lock`], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }), ]); const baseLock = parseSyml(baseLockContent); const currentLock = parseSyml(currentLockContent); const changedPackageNames = new Set(); const allKeys = new Set([ ...Object.keys(baseLock), ...Object.keys(currentLock), ]); for (const key of allKeys) { // Ignore metadata. if (key.startsWith('__')) { continue; } if (baseLock[key]?.checksum === currentLock[key]?.checksum) { continue; } // A key may be a comma-separated list of descriptors resolving to the same // version (e.g. "lodash@npm:^4.0.0, lodash@npm:^4.17.0"). const descriptorKeys = key .split(',') .map((descriptorKey) => descriptorKey.trim()); for (const descriptorKey of descriptorKeys) { const descriptor = structUtils.parseDescriptor(descriptorKey); changedPackageNames.add(structUtils.stringifyIdent(descriptor)); } } return changedPackageNames; } /** * Check whether the root `package.json` changed only in its `version` field * between `mergeBase` and `headRef`. * * Release PRs bump only `version`; any other change (scripts, dependencies, * etc.) requires a full rebuild. * * @param mergeBase - The merge base SHA. * @param headRef - The PR branch tip SHA (or "HEAD"). * @returns `true` if only the `version` field differs. */ async function isRootPackageVersionOnlyChange( mergeBase: string, headRef: string, ): Promise { const [{ stdout: baseContent }, { stdout: currentContent }] = await Promise.all([ execa('git', ['show', `${mergeBase}:package.json`], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }), execa('git', ['show', `${headRef}:package.json`], { cwd: ROOT_WORKSPACE, encoding: 'utf8', }), ]); const base = JSON.parse(baseContent); const current = JSON.parse(currentContent); delete base.version; delete current.version; return JSON.stringify(base) === JSON.stringify(current); } /** * Build a map from each workspace name to the full set of its transitive * dependencies, by walking the resolved lockfile graph via `@yarnpkg/core`. * * @returns A map from workspace name to the set of all transitive dependency * names. */ async function buildWorkspaceTransitiveDependencies(): Promise< Map> > { const workingDirectory = ppath.cwd(); const configuration = await Configuration.find( workingDirectory, getPluginConfiguration(), { // `@yarnpkg/core` is outdated and with `strict: true` fails with // "Unrecognized or legacy configuration settings found: // approvedGitRepositories". strict: false, }, ); const { project } = await Project.find(configuration, workingDirectory); await project.resolveEverything({ lockfileOnly: true, report: new ThrowReport(), }); const graph = new Map>(); for (const workspace of project.workspaces) { const name = workspace.manifest.name ? structUtils.stringifyIdent(workspace.manifest.name) : 'root'; const allTransitiveDependencies = new Set(); const visitedLocatorHashes = new Set(); function walkDependencies(locatorHash: LocatorHash): void { if (visitedLocatorHashes.has(locatorHash)) { return; } visitedLocatorHashes.add(locatorHash); const packageConfig = project.storedPackages.get(locatorHash); if (!packageConfig) { return; } for (const descriptor of packageConfig.dependencies.values()) { const depName = structUtils.stringifyIdent(descriptor); allTransitiveDependencies.add(depName); const resolvedLocatorHash = project.storedResolutions.get( descriptor.descriptorHash, ); if (resolvedLocatorHash) { walkDependencies(resolvedLocatorHash); } } } walkDependencies(workspace.anchoredLocator.locatorHash); graph.set(name, allTransitiveDependencies); } return graph; } /** * Given a merge base SHA and head ref, determine which workspaces are affected * by changes to `yarn.lock` between those two commits. * * A workspace is considered affected if any package that changed in the * lockfile appears in its transitive dependency closure. * * @param mergeBase - The merge base SHA. * @param headRef - The PR branch tip SHA (or "HEAD"). * @param workspaces - The workspace set to check against. * @returns The set of workspace names whose transitive dependencies include * any package that changed in the lockfile. */ async function getLockfileAffectedWorkspaces( mergeBase: string, headRef: string, workspaces: Workspace[], ): Promise> { const [changedPackages, workspaceGraph] = await Promise.all([ getChangedLockfilePackages(mergeBase, headRef), buildWorkspaceTransitiveDependencies(), ]); const result = new Set(); for (const workspace of workspaces) { const transitiveDeps = workspaceGraph.get(workspace.name); if (!transitiveDeps) { continue; } for (const pkg of changedPackages) { if (transitiveDeps.has(pkg)) { result.add(workspace); break; } } } return result; } /** * Check whether any changed file lives outside all package directories and * is not in the ignored root files list. When true, a full * rebuild/test/lint run is required. * * @param workspaces - The workspace set to check against. * @param changedFiles - The list of changed file paths. * @returns Whether any non-ignored root file changed. */ export function checkRootChange( workspaces: Workspace[], changedFiles: string[], ): boolean { return changedFiles.some( (file) => !IGNORED_ROOT_FILES.has(file) && !workspaces.some(({ location }) => file.startsWith(`${location}/`)), ); } /** * Compute the set of workspace names that need to be checked given a merge * base, by finding changed packages and expanding to transitive dependants. * * When `includeDependencies` is true, also expands to transitive dependencies. * This is needed for TypeScript project reference builds, where every * referenced project's dist output must already exist on disk. * * When `yarn.lock` appears in `changedFiles`, the lockfile is diffed against * `mergeBase` to identify which workspaces have an affected transitive * dependency, and those are seeded into the result before dependant expansion. * * @param options - Options. * @param options.mergeBase - The merge base SHA, used to diff `yarn.lock` when * it changed. * @param options.headRef - The PR branch tip SHA (or "HEAD"), used to read the * current side of `yarn.lock` when diffing. * @param options.includeDependencies - Whether to also expand to transitive * dependencies. * @returns The set of workspace names to check. */ export async function computeChangedWorkspaces({ mergeBase, headRef, includeDependencies, }: { mergeBase: string; headRef: string; includeDependencies: boolean; }): Promise<{ workspaces: Workspace[]; hasRootChange: boolean; }> { const changedFiles = await getChangedFiles(mergeBase, headRef); const workspaces = await getAllWorkspaces(); // If any changed file lives outside all package directories (e.g., root // configs, workflow files, scripts), rebuild and test everything. if (checkRootChange(workspaces, changedFiles)) { return { workspaces, hasRootChange: true, }; } // The root package.json is ignored by `checkRootChange` (release PRs bump // only version), but any non-version changes (scripts, dependencies, etc.) // still require a full rebuild. if ( changedFiles.includes('package.json') && !(await isRootPackageVersionOnlyChange(mergeBase, headRef)) ) { return { workspaces, hasRootChange: true, }; } const result = new Set( changedFiles.flatMap((file) => { const workspace = workspaces.find(({ location }) => file.startsWith(`${location}/`), ); return workspace ? [workspace] : []; }), ); // When the lockfile changed, diff it to find which workspaces have an // affected transitive dependency, and seed them into the result before // the dependant expansion below. if (changedFiles.includes('yarn.lock')) { for (const pkg of await getLockfileAffectedWorkspaces( mergeBase, headRef, workspaces, )) { result.add(pkg); } } const { dependants, dependencies } = await getWorkspaceDependencies(workspaces); // Expand to transitive dependants (packages that depend on what changed). for (const workspace of result) { for (const dependant of dependants[workspace.name] ?? []) { result.add(dependant); } } if (includeDependencies) { // Expand to transitive dependencies (dist files must exist to build dependants). for (const workspace of result) { for (const dependency of dependencies[workspace.name] ?? []) { result.add(dependency); } } } return { workspaces: Array.from(result), hasRootChange: false, }; }