#!/usr/bin/env node // Classify changed paths for CI. import { execFileSync } from 'node:child_process'; import { appendFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; export const ZERO_SHA = '0000000000000000000000000000000000000000'; export const TRUNK_REFS = Object.freeze( new Set([ 'darksky/np/mobile', 'canary', 'darksky/native-playground', 'main', 'refs/heads/darksky/np/mobile', 'refs/heads/canary', 'refs/heads/darksky/native-playground', 'refs/heads/main', ]) ); // Events that always run every lane, Apple jobs included. const FULL_RUN_EVENTS = Object.freeze( new Set(['pull_request', 'workflow_dispatch']) ); // A change under these paths runs the macOS and iOS jobs on topic branches. const APPLE_PATH_PREFIXES = ['.cargo/']; const APPLE_PATHS = new Set([ '.github/workflows/native-playground.yml', '.github/workflows/np-mobile.yml', 'packages/ui/ui/tests/metal_atlas_fence.rs', 'scripts/ci/classify-web-host-only.mjs', 'scripts/ci/classify-web-host-only.test.mjs', ]); const APPLE_SEGMENT_OR_MANIFEST_RE = /(?:^|\/)(?:macos|ios|apple)\/|\.(?:swift|metal|m|mm)$|(?:^|\/)(?:Cargo\.toml|Cargo\.lock|build\.rs|rust-toolchain\.toml)$/; // Source text that compiles only for Apple targets. export const APPLE_TARGET_CFG_RE = /\btarget_os\s*=\s*"(?:macos|ios)"|\btarget_vendor\s*=\s*"apple"/; export function isAppleSpecificPath(filePath) { return ( APPLE_PATHS.has(filePath) || APPLE_PATH_PREFIXES.some(prefix => filePath.startsWith(prefix)) || APPLE_SEGMENT_OR_MANIFEST_RE.test(filePath) ); } export const WEB_HOST_ONLY_ALLOWLIST = Object.freeze( new Set([ 'packages/frontend/hosts/web/src/idb-storage.js', 'packages/frontend/hosts/web/desktop/boot.js', 'packages/frontend/hosts/web/desktop/start.js', 'packages/frontend/hosts/web/desktop/index.html', 'packages/frontend/hosts/web/tests/idb-storage.test.mjs', 'packages/frontend/hosts/web/tests/desktop.test.mjs', 'packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs', ]) ); const DESKTOP_LEAF_DIRS = [ 'packages/frontend/desktop/src/', 'packages/frontend/desktop/tests/', ]; function noFastLane(reason) { return { webHostOnly: false, desktopLeafOnly: false, desktopRsOnly: false, backendOnly: false, webWrapperOnly: false, appleSpecific: true, reason, checkedPaths: [], }; } function fullRunReason(forceAll, ref, event) { if (forceAll === true || forceAll === 'true') return 'force_all'; if (isTrunkRef(ref)) return 'trunk_ref'; if (event === 'pull_request' || ref.trim().startsWith('refs/pull/')) { return 'pull_request'; } if (FULL_RUN_EVENTS.has(event)) return event; return null; } export function isTrunkRef(ref) { return typeof ref === 'string' && TRUNK_REFS.has(ref.trim()); } export function isValidBaseSha(baseSha) { if (typeof baseSha !== 'string') return false; const trimmed = baseSha.trim(); return /^[0-9a-f]{7,64}$/i.test(trimmed) && !/^0+$/.test(trimmed); } function parseNulTokens(raw) { if (raw === '') return { valid: true, entries: [] }; const tokens = raw.split('\0'); if (tokens[tokens.length - 1] === '') { tokens.pop(); } const entries = []; let i = 0; while (i < tokens.length) { const status = tokens[i++]; if (/^[RC]\d*$/.test(status)) { const oldPath = tokens[i++]; const newPath = tokens[i++]; if (!oldPath || !newPath) { return { valid: false, entries: [] }; } entries.push({ status, paths: [oldPath, newPath] }); } else if (/^[AMDT]$/.test(status)) { const filePath = tokens[i++]; if (!filePath) { return { valid: false, entries: [] }; } entries.push({ status, paths: [filePath] }); } else { return { valid: false, entries: [] }; } } return { valid: true, entries }; } function parseTabLines(lines) { const entries = []; for (const rawLine of lines) { if (typeof rawLine !== 'string') { return { valid: false, entries: [] }; } if (rawLine.length === 0) continue; const parts = rawLine.split('\t'); const status = parts[0]; if (/^[RC]\d*$/.test(status)) { if (parts.length !== 3 || !parts[1] || !parts[2]) { return { valid: false, entries: [] }; } entries.push({ status, paths: [parts[1], parts[2]] }); } else if (/^[AMDT]$/.test(status)) { if (parts.length !== 2 || !parts[1]) { return { valid: false, entries: [] }; } entries.push({ status, paths: [parts[1]] }); } else { return { valid: false, entries: [] }; } } return { valid: true, entries }; } export function parseNameStatus(input) { if (Buffer.isBuffer(input)) { return parseNulTokens(input.toString('utf8')); } if (typeof input === 'string') { if (input.includes('\0')) { return parseNulTokens(input); } return parseTabLines(input.split(/\r?\n/)); } if (Array.isArray(input)) { return parseTabLines(input); } return { valid: false, entries: [] }; } export function classifyWebHostOnly(options = {}) { const { nameStatus, nameStatusLines, forceAll = false, baseSha, ref = '', event = '', contentTouchesApple = false, } = options; const fullRun = fullRunReason(forceAll, ref, event); if (fullRun) { return noFastLane(fullRun); } if (baseSha !== undefined && !isValidBaseSha(baseSha)) { return noFastLane('invalid_base'); } const rawInput = nameStatus !== undefined ? nameStatus : nameStatusLines; if (rawInput === undefined || rawInput === null) { return noFastLane('missing_diff'); } const parsed = parseNameStatus(rawInput); if (!parsed.valid) { return noFastLane('invalid_name_status'); } if (parsed.entries.length === 0) { return noFastLane('empty_diff'); } const checkedPaths = parsed.entries.flatMap(entry => entry.paths); const webHostOnly = checkedPaths.every(filePath => WEB_HOST_ONLY_ALLOWLIST.has(filePath) ); const isDesktopRustPath = filePath => filePath.endsWith('.rs') && DESKTOP_LEAF_DIRS.some(dir => filePath.startsWith(dir)); const desktopRsOnly = checkedPaths.every(isDesktopRustPath); const appleSpecific = contentTouchesApple === true || checkedPaths.some( filePath => isAppleSpecificPath(filePath) || (contentTouchesApple instanceof Set && contentTouchesApple.has(filePath)) ); return { webHostOnly, desktopLeafOnly: !webHostOnly && checkedPaths.every( filePath => WEB_HOST_ONLY_ALLOWLIST.has(filePath) || isDesktopRustPath(filePath) ), desktopRsOnly, backendOnly: checkedPaths.every(filePath => filePath.startsWith('packages/backend/') ), webWrapperOnly: checkedPaths.every(filePath => filePath.startsWith('packages/frontend/hosts/web/') ), appleSpecific, reason: webHostOnly ? 'allowlist_only' : 'non_allowlist_path', checkedPaths, }; } function runGitDiff(cwd, args) { return execFileSync('git', ['diff', '--name-status', '-z', ...args], { cwd, encoding: 'buffer', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], }); } // Returns the changed paths whose old or new text has an Apple target cfg, or // true when a blob cannot be read. function findAppleCfgPaths(cwd, oldRev, newRev, entries) { const hits = new Set(); const textHasAppleCfg = (rev, filePath) => APPLE_TARGET_CFG_RE.test( execFileSync('git', ['cat-file', '-p', `${rev}:${filePath}`], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], }) ); try { for (const { status, paths } of entries) { const oldPath = paths[0]; const newPath = paths[paths.length - 1]; const blobs = status === 'A' ? [[newRev, newPath]] : status === 'D' ? [[oldRev, oldPath]] : [ [oldRev, oldPath], [newRev, newPath], ]; if (blobs.some(([rev, filePath]) => textHasAppleCfg(rev, filePath))) { paths.forEach(filePath => hits.add(filePath)); } } } catch { return true; } return hits; } export function classifyGitDiff({ baseSha, head = 'HEAD', forceAll = false, ref = '', event = '', cwd = process.cwd(), } = {}) { const fullRun = fullRunReason(forceAll, ref, event); if (fullRun) { return noFastLane(fullRun); } if (!isValidBaseSha(baseSha)) { return noFastLane('invalid_base'); } const trimmedBase = baseSha.trim(); const gitOpts = { cwd, encoding: 'buffer', stdio: ['ignore', 'pipe', 'pipe'], }; let mergeBase; try { execFileSync( 'git', ['rev-parse', '--verify', '--quiet', `${trimmedBase}^{commit}`], gitOpts ); execFileSync( 'git', ['rev-parse', '--verify', '--quiet', `${head}^{commit}`], gitOpts ); mergeBase = execFileSync('git', ['merge-base', trimmedBase, head], gitOpts) .toString('utf8') .trim(); } catch { return noFastLane('unreachable_base'); } const diffRange = `${trimmedBase}...${head}`; let diffBuf; try { diffBuf = runGitDiff(cwd, [diffRange]); } catch { return noFastLane('git_diff_error'); } const parsed = parseNameStatus(diffBuf); const contentTouchesApple = parsed.valid && !parsed.entries.some(entry => entry.paths.some(isAppleSpecificPath)) ? findAppleCfgPaths(cwd, mergeBase, head, parsed.entries) : false; const classify = nameStatus => classifyWebHostOnly({ nameStatus, forceAll, baseSha: trimmedBase, ref, event, contentTouchesApple, }); const initial = classify(diffBuf); if ( !initial.webHostOnly && !initial.desktopLeafOnly && !initial.backendOnly && !initial.webWrapperOnly ) { return initial; } if (!parsed.entries.some(entry => entry.status === 'A')) { return initial; } // Check both paths when Git detects a copy from a file that did not change. let copyDiffBuf; try { copyDiffBuf = runGitDiff(cwd, ['-C', '--find-copies-harder', diffRange]); } catch { return noFastLane('git_diff_error'); } return classify(copyDiffBuf); } function parseCliArgs(argv) { const args = { baseSha: process.env.BASE ?? '', head: 'HEAD', forceAll: process.env.FORCE_ALL ?? 'false', ref: process.env.GITHUB_REF ?? process.env.GITHUB_REF_NAME ?? '', event: process.env.GITHUB_EVENT_NAME ?? '', githubOutput: process.env.GITHUB_OUTPUT ?? '', cwd: process.cwd(), }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const value = argv[i + 1]; if (flag === '--base' && value !== undefined) { args.baseSha = value; i++; } else if (flag === '--head' && value !== undefined) { args.head = value; i++; } else if (flag === '--force-all' && value !== undefined) { args.forceAll = value; i++; } else if (flag === '--ref' && value !== undefined) { args.ref = value; i++; } else if (flag === '--event' && value !== undefined) { args.event = value; i++; } else if (flag === '--github-output' && value !== undefined) { args.githubOutput = value; i++; } else if (flag === '--cwd' && value !== undefined) { args.cwd = value; i++; } else { throw new Error(`Unknown or incomplete argument: ${flag}`); } } return args; } function main() { const args = parseCliArgs(process.argv.slice(2)); const result = classifyGitDiff({ baseSha: args.baseSha, head: args.head, forceAll: args.forceAll, ref: args.ref, event: args.event, cwd: args.cwd, }); if (args.githubOutput) { appendFileSync( args.githubOutput, `web_host_only=${result.webHostOnly}\n` + `desktop_leaf_only=${result.desktopLeafOnly}\n` + `desktop_rs_only=${result.desktopRsOnly}\n` + `backend_only=${result.backendOnly}\n` + `web_wrapper_only=${result.webWrapperOnly}\n` + `apple_specific=${result.appleSpecific}\n` ); } const summary = `web_host_only=${result.webHostOnly} ` + `(${result.reason}, ${result.checkedPaths.length} path(s))`; console.log(summary); console.log(`desktop_leaf_only=${result.desktopLeafOnly}`); console.log(`desktop_rs_only=${result.desktopRsOnly}`); console.log(`apple_specific=${result.appleSpecific}`); } const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; if (isMain) { main(); }