// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import type * as child_process from 'node:child_process'; import { createHash } from 'node:crypto'; import { once } from 'node:events'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { Readable, pipeline } from 'node:stream'; import { Executable, type IExecutableSpawnOptions } from '@rushstack/node-core-library/lib/Executable'; import { FileSystem } from '@rushstack/node-core-library/lib/FileSystem'; export interface IGitVersion { major: number; minor: number; patch: number; } const MINIMUM_GIT_VERSION: IGitVersion = { major: 2, minor: 35, patch: 0 }; /** * The options for every read-only Git command. * @internal */ export const STANDARD_GIT_OPTIONS: readonly string[] = [ // Don't request any optional file locks '--no-optional-locks', // Ensure that commands don't run automatic maintenance, since performance of the command itself is paramount '-c', 'maintenance.auto=false' ]; // Windows reserved device names (case-insensitive). A file whose final path segment matches one // of these (with or without an extension) cannot be opened by name on Windows, so passing it to // `git hash-object` aborts the process. Such files are typically untracked artifacts left behind // by tooling (e.g. stray `nul` from a shell redirect). const WINDOWS_RESERVED_BASENAMES: ReadonlySet = new Set([ 'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9' ]); /** * Returns `true` if `filePath`'s final path segment is a Windows reserved device name * (with or without an extension), case-insensitively. Exported for tests. * @internal */ export function isWindowsReservedPath(filePath: string): boolean { const lastSlash: number = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')); const basename: string = lastSlash >= 0 ? filePath.slice(lastSlash + 1) : filePath; const dot: number = basename.indexOf('.'); const stem: string = (dot >= 0 ? basename.slice(0, dot) : basename).toUpperCase(); return WINDOWS_RESERVED_BASENAMES.has(stem); } const OBJECTMODE_SUBMODULE: '160000' = '160000'; const OBJECTMODE_SYMLINK: '120000' = '120000'; const OBJECTMODE_FILE_NONEXECUTABLE: '100644' = '100644'; const OBJECTMODE_FILE_EXECUTABLE: '100755' = '100755'; // Note that `type` is a stub that is being ignored by the parser in favor of using `mode` to infer, since `%(objecttype)` requires git 2.51.0+ // e.g. 10644 blob \t const GIT_LSTREE_FORMAT: string = '%(objectmode) type %(objectname)%x09%(path)'; /** * @internal */ export interface IGitTreeState { files: Map; // type "blob" symlinks: Map; // type "link" submodules: Map; // type "commit" } /** * Parses the output of the "git ls-tree -r -z" command or of other commands that have been coerced to match its format. * @internal */ export function parseGitLsTree(output: string): IGitTreeState { const files: Map = new Map(); const symlinks: Map = new Map(); const submodules: Map = new Map(); // Parse the output // With the -z modifier, paths are delimited by nulls // A line looks like: // \t\0 // 100644 blob a300ccb0b36bd2c85ef18e3c619a2c747f95959e\ttools/prettier-git/prettier-git.js\0 let last: number = 0; let index: number = output.indexOf('\0', last); while (index >= 0) { const item: string = output.slice(last, index); const tabIndex: number = item.indexOf('\t'); const filePath: string = item.slice(tabIndex + 1); // The newHash will be all zeros if the file is deleted, or a hash if it exists const hash: string = item.slice(tabIndex - 40, tabIndex); const mode: string = item.slice(0, item.indexOf(' ')); switch (mode) { case OBJECTMODE_SUBMODULE: { // This is a submodule submodules.set(filePath, hash); break; } case OBJECTMODE_SYMLINK: { // This is a symbolic link symlinks.set(filePath, hash); break; } case OBJECTMODE_FILE_NONEXECUTABLE: case OBJECTMODE_FILE_EXECUTABLE: default: { files.set(filePath, hash); break; } } last = index + 1; index = output.indexOf('\0', last); } return { files, symlinks, submodules }; } /** * Parses the output of `git hash-object` * yields [filePath, hash] pairs. * @internal */ export function* parseGitHashObject( output: string, filePaths: ReadonlyArray ): IterableIterator<[string, string]> { const expected: number = filePaths.length; if (expected === 0) { return; } output = output.trim(); let last: number = 0; let i: number = 0; let index: number = output.indexOf('\n', last); for (; i < expected && index > 0; i++) { const hash: string = output.slice(last, index); yield [filePaths[i], hash]; last = index + 1; index = output.indexOf('\n', last); } // Handle last line. Will be non-empty to due trim() call. if (index < 0) { const hash: string = output.slice(last); yield [filePaths[i], hash]; i++; } if (i !== expected) { throw new Error(`Expected ${expected} hashes from "git hash-object" but received ${i}`); } } /** * Information about the changes to a file. * @beta */ export interface IFileDiffStatus { mode: string; oldhash: string; newhash: string; status: 'A' | 'D' | 'M'; } /** * Parses the output of `git diff-index --color=never --no-renames --no-commit-id -z -- * Returns a map of file path to diff * @internal */ export function parseGitDiffIndex(output: string): Map { const result: Map = new Map(); // Parse the output // With the -z modifier, paths are delimited by nulls // A line looks like: // : \0\0 // :100644 100644 a300ccb0b36bd2c85ef18e3c619a2c747f95959e 0000000000000000000000000000000000000000 M\0tools/prettier-git/prettier-git.js\0 let last: number = 0; let index: number = output.indexOf('\0', last); while (index >= 0) { const header: string = output.slice(last, index); const status: IFileDiffStatus['status'] = header.slice(-1) as IFileDiffStatus['status']; last = index + 1; index = output.indexOf('\0', last); const filePath: string = output.slice(last, index); // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new. // The newHash will be all zeros if the file is deleted, or a hash if it exists const mode: string = header.slice(8, 14); const oldhash: string = header.slice(-83, -43); const newhash: string = header.slice(-42, -2); result.set(filePath, { mode, oldhash, newhash, status }); last = index + 1; index = output.indexOf('\0', last); } return result; } /** * What `git status` reports about a path: * - `deleted`: the path is deleted in the working tree, or deleted in the index and not modified in the working tree. * - `indexOnly`: only the index differs from HEAD. Git uses the object in the index for the working tree, and * doesn't read the file if sparse checkout leaves it out or if the index marks it "assume unchanged" or * "skip worktree", so the file may not be on disk. * - `workingTree`: the working tree differs from the index, or the path is untracked or unmerged. * @internal */ export type GitStatusKind = 'deleted' | 'indexOnly' | 'workingTree'; /** * Parses the output of `git status -z -u` to extract the set of files that have changed since HEAD. * * @param output - The raw output from Git * @returns a map of file path to what `git status` reports about it * @internal */ export function parseGitStatus(output: string): Map { const result: Map = new Map(); // Parse the output // With the -z modifier, paths are delimited by nulls // A line looks like: // XY \0 // M tools/prettier-git/prettier-git.js\0 let startOfLine: number = 0; let eolIndex: number = output.indexOf('\0', startOfLine); while (eolIndex >= 0) { // We passed --no-renames above, so a rename will be a delete of the old location and an add at the new. // charAt(startOfLine) is the index status, charAt(startOfLine + 1) is the working tree status const workingTreeStatus: string = output.charAt(startOfLine + 1); let kind: GitStatusKind; if (workingTreeStatus === 'D' || (workingTreeStatus === ' ' && output.charAt(startOfLine) === 'D')) { // Deleted in working tree, or not modified in working tree and deleted in index kind = 'deleted'; } else if (workingTreeStatus === ' ') { kind = 'indexOnly'; } else { kind = 'workingTree'; } const filePath: string = output.slice(startOfLine + 3, eolIndex); result.set(filePath, kind); startOfLine = eolIndex + 1; eolIndex = output.indexOf('\0', startOfLine); } return result; } const repoRootCache: Map = new Map(); /** * Strip GIT_DIR/GIT_WORK_TREE: git hooks in linked worktrees set GIT_DIR to the per-worktree metadata dir, causing * rev-parse --show-toplevel to return CWD instead of the worktree root. * @internal */ export function getCleanGitEnvironment(): NodeJS.ProcessEnv { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { GIT_DIR, GIT_WORK_TREE, ...trimmedEnv } = process.env; return trimmedEnv; } /** * Finds the root of the current Git repository * * @param currentWorkingDirectory - The working directory for which to locate the repository * @param gitPath - The path to the Git executable * * @returns The full path to the root directory of the Git repository * @beta */ export function getRepoRoot(currentWorkingDirectory: string, gitPath?: string): string { let cachedResult: string | undefined = repoRootCache.get(currentWorkingDirectory); if (!cachedResult) { const result: child_process.SpawnSyncReturns = Executable.spawnSync( gitPath || 'git', ['--no-optional-locks', 'rev-parse', '--show-toplevel'], { currentWorkingDirectory, environment: getCleanGitEnvironment() } ); if (result.status !== 0) { ensureGitMinimumVersion(gitPath); throw new Error(`git rev-parse exited with status ${result.status}: ${result.stderr}`); } cachedResult = result.stdout.trim(); repoRootCache.set(currentWorkingDirectory, cachedResult); // To ensure that calling getRepoRoot on the result is a no-op. repoRootCache.set(cachedResult, cachedResult); } return cachedResult; } /** * Helper function for async process invocation with optional stdin support. * @param gitPath - Path to the Git executable * @param args - The process arguments * @param currentWorkingDirectory - The working directory. Should be the repository root. * @param stdin - An optional Readable stream to use as stdin to the process. * @param environment - The environment of the process. Defaults to {@link getCleanGitEnvironment}. * @internal */ export async function spawnGitAsync( gitPath: string | undefined, args: string[], currentWorkingDirectory: string, stdin?: Readable, environment: NodeJS.ProcessEnv = getCleanGitEnvironment() ): Promise { const spawnOptions: IExecutableSpawnOptions = { currentWorkingDirectory, stdio: ['pipe', 'pipe', 'pipe'], environment }; let stdout: string = ''; let stderr: string = ''; const proc: child_process.ChildProcess = Executable.spawn(gitPath || 'git', args, spawnOptions); proc.stdout!.setEncoding('utf-8'); proc.stderr!.setEncoding('utf-8'); proc.stdout!.on('data', (chunk: string) => { stdout += chunk.toString(); }); proc.stderr!.on('data', (chunk: string) => { stderr += chunk.toString(); }); if (stdin) { /** * For `git hash-object` data is piped in asynchronously. In the event that one of the * passed filenames cannot be hashed, subsequent writes to `proc.stdin` will error. * Silence this error since it will be handled by the non-zero exit code of the process. */ pipeline(stdin, proc.stdin!, (err) => {}); } const [status] = await once(proc, 'close'); if (status !== 0) { ensureGitMinimumVersion(gitPath); throw new Error(`git ${getGitCommandName(args)} exited with code ${status}:\n${stderr}`); } return stdout; } /** * Returns the Git command in the arguments, rather than the first of the options in front of it. */ function getGitCommandName(args: ReadonlyArray): string | undefined { for (let i: number = 0; i < args.length; i++) { const arg: string = args[i]; if (arg === '-c') { // Skip the value of a configuration option i++; } else if (!arg.startsWith('-')) { return arg; } } return undefined; } function isIterable(value: Iterable | AsyncIterable): value is Iterable { return Symbol.iterator in value; } /** * Uses `git hash-object` to hash the provided files. Unlike `getGitHashForFiles`, this API is asynchronous, and also allows for * the input file paths to be specified as an async iterable. * * @param rootDirectory - The root directory to which paths are specified relative. Must be the root of the Git repository. * @param filesToHash - The file paths to hash using `git hash-object` * @param gitPath - The path to the Git executable * @returns An iterable of [filePath, hash] pairs * * @remarks * The input file paths must be specified relative to the Git repository root, or else be absolute paths. * @beta */ export async function hashFilesAsync( rootDirectory: string, filesToHash: Iterable | AsyncIterable, gitPath?: string ): Promise> { const hashPaths: string[] = []; const input: Readable = Readable.from( isIterable(filesToHash) ? (function* (): IterableIterator { for (const file of filesToHash) { hashPaths.push(file); yield `${file}\n`; } })() : (async function* (): AsyncIterableIterator { for await (const file of filesToHash) { hashPaths.push(file); yield `${file}\n`; } })(), { encoding: 'utf-8', objectMode: false, autoDestroy: true } ); const hashObjectResult: string = await spawnGitAsync( gitPath, STANDARD_GIT_OPTIONS.concat(['hash-object', '--stdin-paths']), rootDirectory, input ); return parseGitHashObject(hashObjectResult, hashPaths); } /** * If the path is a symbolic link that doesn't lead to a regular file, returns the object that `git add` records for * it: a blob of the text of the link. Otherwise returns `undefined`. * * @remarks * `git hash-object` follows symbolic links. It fails if the target is missing, is a folder or is a loop of links, and * it waits for a named pipe to be written. A symbolic link to a regular file is left to it. * @param fullPath - The full path of the file * @internal */ export async function tryGetSymbolicLinkHashAsync(fullPath: string): Promise { let linkText: Buffer; try { // The text may not be valid UTF-8 linkText = await fs.promises.readlink(fullPath, { encoding: 'buffer' }); } catch { // Not a symbolic link. "git hash-object" reports any error. return undefined; } try { if ((await fs.promises.stat(fullPath)).isFile()) { return undefined; } } catch { // The target is missing, or can't be reached } return createHash('sha1').update(`blob ${linkText.length}\0`).update(linkText).digest('hex'); } /** * The arguments of the `git ls-files` command that lists the files in the index in the format of `git ls-tree`. * @internal */ export function getGitLsFilesArgs(filterPath: ReadonlyArray | undefined): string[] { return [ 'ls-files', // Read from the index only '--cached', // Use NUL as the separator '-z', // Specify the full path to files relative to the root '--full-name', // Match the format of "git ls-tree". The %(objecttype) placeholder requires git 2.51.0+, so not using yet. `--format=${GIT_LSTREE_FORMAT}`, '--', ...(filterPath ?? []) ]; } /** * The arguments of the `git status` command that lists the files that differ from the index or from HEAD, and the * untracked files. Its output is parsed by {@link parseGitStatus}. * @internal */ export function getGitStatusArgs(filterPath: ReadonlyArray | undefined): string[] { return [ 'status', // Use NUL as the separator '-z', // Include untracked files '-u', // Disable rename detection so that renames show up as add + delete '--no-renames', // Don't process submodules with this command; they'll be handled individually '--ignore-submodules', // Don't compare against the remote '--no-ahead-behind', '--', ...(filterPath ?? []) ]; } /** * The locally modified files that `git status` reports, split into those to hash with `git hash-object` and those * to remove from the state of the repository. * @internal */ export interface ILocallyModifiedFiles { filesToHash: string[]; filesToRemove: string[]; } /** * Splits the locally modified files that `git status` reports into those to hash and those to remove from the * state of the repository: the deleted files and the files that the index records as symbolic links. A path whose * working tree column is blank is in neither list, so that it keeps the object that the index records for it. * @internal */ export function classifyLocallyModifiedFiles( locallyModified: ReadonlyMap, symlinks: ReadonlyMap ): ILocallyModifiedFiles { const filesToHash: string[] = []; const filesToRemove: string[] = []; const isWindows: boolean = process.platform === 'win32'; for (const [filePath, kind] of locallyModified) { if (kind === 'indexOnly') { // Git uses the object in the index, which the list of the index already has. The file may not be on disk. continue; } if (kind === 'workingTree' && !symlinks.has(filePath)) { // Skip Windows reserved device names. `git hash-object` cannot open them and would abort // the entire repo-state computation. These are almost always stray artifacts (e.g. a `nul` // file produced by a misdirected shell redirect) rather than meaningful inputs. if (!isWindows || !isWindowsReservedPath(filePath)) { filesToHash.push(filePath); } } else { filesToRemove.push(filePath); } } return { filesToHash, filesToRemove }; } /** * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state. * Uses async operations and runs all primary Git calls in parallel. * @param rootDirectory - The root directory of the Git repository * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results * @param gitPath - The path to the Git executable * @beta */ export async function getRepoStateAsync( rootDirectory: string, additionalRelativePathsToHash?: string[], gitPath?: string, filterPath?: string[] ): Promise> { const { files } = await getDetailedRepoStateAsync( rootDirectory, additionalRelativePathsToHash, gitPath, filterPath ); return files; } /** * Information about the detailed state of the Git repository. * @beta */ export interface IDetailedRepoState { /** * The Git file hashes for all files in the repository, including uncommitted changes. * * @remarks * A symbolic link that the index doesn't record as one, such as an untracked link, has the hash of the regular file * that it leads to. If it doesn't lead to a regular file, it has the hash of its text, which `git add` would record. */ files: Map; /** * The Git file hashes for all symbolic links in the repository, including uncommitted changes. */ symlinks: Map; /** * A boolean indicating whether the repository has submodules. */ hasSubmodules: boolean; /** * A boolean indicating whether the repository has uncommitted changes. */ hasUncommittedChanges: boolean; } /** * Gets the object hashes for all files in the Git repo, combining the current commit with working tree state. * Uses async operations and runs all primary Git calls in parallel. * @param rootDirectory - The root directory of the Git repository * @param additionalRelativePathsToHash - Root-relative file paths to have Git hash and include in the results * @param gitPath - The path to the Git executable * @beta */ export async function getDetailedRepoStateAsync( rootDirectory: string, additionalRelativePathsToHash?: string[], gitPath?: string, filterPath?: string[] ): Promise { const statePromise: Promise = spawnGitAsync( gitPath, STANDARD_GIT_OPTIONS.concat(getGitLsFilesArgs(filterPath)), rootDirectory ).then(parseGitLsTree); const locallyModifiedPromise: Promise> = spawnGitAsync( gitPath, STANDARD_GIT_OPTIONS.concat(getGitStatusArgs(filterPath)), rootDirectory ).then(parseGitStatus); // Every path to hash, in order, and the hashes of the symbolic links that "git hash-object" can't follow const pathsToHash: string[] = []; const symbolicLinkHashes: Map = new Map(); async function* filterSymbolicLinksAsync(filePaths: ReadonlyArray): AsyncIterableIterator { const linkHashes: (string | undefined)[] = await Promise.all( filePaths.map((filePath: string) => tryGetSymbolicLinkHashAsync(path.resolve(rootDirectory, filePath))) ); for (let i: number = 0; i < filePaths.length; i++) { const filePath: string = filePaths[i]; const linkHash: string | undefined = linkHashes[i]; pathsToHash.push(filePath); if (linkHash === undefined) { yield filePath; } else { symbolicLinkHashes.set(filePath, linkHash); } } } async function* getFilesToHash(): AsyncIterableIterator { if (additionalRelativePathsToHash) { yield* filterSymbolicLinksAsync(additionalRelativePathsToHash); } const [{ files, symlinks }, locallyModified] = await Promise.all([statePromise, locallyModifiedPromise]); const { filesToHash, filesToRemove } = classifyLocallyModifiedFiles(locallyModified, symlinks); for (const filePath of filesToRemove) { files.delete(filePath); symlinks.delete(filePath); } yield* filterSymbolicLinksAsync(filesToHash); } const hashObjectPromise: Promise> = hashFilesAsync( rootDirectory, getFilesToHash(), gitPath ); // Await all three at once. `git hash-object` can fail before the other two finish, for example on an additional // path that does not exist. Its rejection needs a handler right away, or Node reports it as unhandled and exits. const [{ files, symlinks, submodules }, locallyModifiedFiles, hashObjectResult] = await Promise.all([ statePromise, locallyModifiedPromise, hashObjectPromise ]); // The result of "git hash-object" will be a list of file hashes delimited by newlines. Set the hashes in the order // of the paths, so that new paths are in the same order as in RepoStateCache. const hashes: Map = new Map(hashObjectResult); for (const filePath of pathsToHash) { const hash: string | undefined = symbolicLinkHashes.get(filePath) ?? hashes.get(filePath); if (hash !== undefined) { files.set(filePath, hash); } } // Existence check for the .gitmodules file const hasSubmodules: boolean = submodules.size > 0 && FileSystem.exists(`${rootDirectory}/.gitmodules`); if (hasSubmodules) { // Submodules are not the normal critical path. Accept serial performance rather than investing in complexity. // Can revisit if submodules become more commonly used. for (const submodulePath of submodules.keys()) { const submoduleState: Map = await getRepoStateAsync( `${rootDirectory}/${submodulePath}`, [], gitPath ); for (const [filePath, hash] of submoduleState) { files.set(`${submodulePath}/${filePath}`, hash); } } } return { hasSubmodules, hasUncommittedChanges: locallyModifiedFiles.size > 0, files, symlinks }; } /** * Find all changed files tracked by Git, their current hashes, and the nature of the change. Only useful if all changes are staged or committed. * @param currentWorkingDirectory - The working directory. Only used to find the repository root. * @param revision - The Git revision specifier to detect changes relative to. Defaults to HEAD (i.e. will compare staged vs. committed) * If comparing against a different branch, call `git merge-base` first to find the target commit. * @param gitPath - The path to the Git executable * @returns A map from the Git file path to the corresponding file change metadata * @beta */ export function getRepoChanges( currentWorkingDirectory: string, revision: string = 'HEAD', gitPath?: string ): Map { const rootDirectory: string = getRepoRoot(currentWorkingDirectory, gitPath); const result: child_process.SpawnSyncReturns = Executable.spawnSync( gitPath || 'git', STANDARD_GIT_OPTIONS.concat([ 'diff-index', '--color=never', '--no-renames', '--no-commit-id', '--cached', '-z', revision, '--' ]), { currentWorkingDirectory: rootDirectory, environment: getCleanGitEnvironment() } ); if (result.status !== 0) { ensureGitMinimumVersion(gitPath); throw new Error(`git diff-index exited with status ${result.status}: ${result.stderr}`); } const changes: Map = parseGitDiffIndex(result.stdout); return changes; } /** * Checks the git version and throws an error if it is less than the minimum required version. * * @public */ export function ensureGitMinimumVersion(gitPath?: string): void { const gitVersion: IGitVersion = getGitVersion(gitPath); if ( gitVersion.major < MINIMUM_GIT_VERSION.major || (gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor < MINIMUM_GIT_VERSION.minor) || (gitVersion.major === MINIMUM_GIT_VERSION.major && gitVersion.minor === MINIMUM_GIT_VERSION.minor && gitVersion.patch < MINIMUM_GIT_VERSION.patch) ) { throw new Error( `The minimum Git version required is ` + `${MINIMUM_GIT_VERSION.major}.${MINIMUM_GIT_VERSION.minor}.${MINIMUM_GIT_VERSION.patch}. ` + `Your version is ${gitVersion.major}.${gitVersion.minor}.${gitVersion.patch}.` ); } } function getGitVersion(gitPath?: string): IGitVersion { const result: child_process.SpawnSyncReturns = Executable.spawnSync( gitPath || 'git', STANDARD_GIT_OPTIONS.concat(['version']) ); if (result.status !== 0) { throw new Error( `While validating the Git installation, the "git version" command failed with ` + `status ${result.status}: ${result.stderr}` ); } return parseGitVersion(result.stdout); } export function parseGitVersion(gitVersionOutput: string): IGitVersion { // This regexp matches output of "git version" that looks like `git version ..(+whatever)` // Examples: // - git version 1.2.3 // - git version 1.2.3.4.5 // - git version 1.2.3windows.1 // - git version 1.2.3.windows.1 const versionRegex: RegExp = /^git version (\d+)\.(\d+)\.(\d+)/; const match: RegExpMatchArray | null = versionRegex.exec(gitVersionOutput); if (!match) { throw new Error( `While validating the Git installation, the "git version" command produced ` + `unexpected output: "${gitVersionOutput}"` ); } const major: number = parseInt(match[1], 10); const minor: number = parseInt(match[2], 10); const patch: number = parseInt(match[3], 10); return { major, minor, patch }; }