diff --git a/src/git/diff.ts b/src/git/diff.ts index 1e6d84d..7ff98d3 100644 --- a/src/git/diff.ts +++ b/src/git/diff.ts @@ -1,4 +1,4 @@ -import { execFile, execFileSync, spawnSync } from 'node:child_process'; +import { execFile, execFileSync, spawnSync, type ExecFileSyncOptionsWithStringEncoding } from 'node:child_process'; import { accessSync, copyFileSync, @@ -121,6 +121,12 @@ export function getGitExecutable(): string { return gitExecutable; } +type GitSyncOptions = Omit & { encoding?: 'utf-8' }; + +export function runGitSync(args: string[], options: GitSyncOptions = {}): string { + return execFileSync(getGitExecutable(), args, { encoding: 'utf-8', ...options }); +} + function toGitRepoCheckError(err: unknown): Error { const nodeErr = err as NodeJS.ErrnoException & { stderr?: string }; if (hasErrorCode(err, 'ENOENT')) { @@ -139,9 +145,9 @@ function toDiffResult(diff: string): DiffResult { } export function checkGitRepo(): void { - const executable = getGitExecutable(); + getGitExecutable(); try { - execFileSync(executable, ['rev-parse', '--git-dir'], { encoding: 'utf-8', stdio: 'pipe' }); + runGitSync(['rev-parse', '--git-dir'], { stdio: 'pipe' }); } catch (err) { throw toGitRepoCheckError(err); } @@ -195,20 +201,14 @@ export async function getStagedDiffWithSignal( function isUnbornHead(): boolean { let headRef: string; try { - headRef = execFileSync(getGitExecutable(), ['symbolic-ref', '--quiet', 'HEAD'], { - encoding: 'utf-8', - stdio: 'pipe', - }).trim(); + headRef = runGitSync(['symbolic-ref', '--quiet', 'HEAD'], { stdio: 'pipe' }).trim(); } catch { // A detached or malformed HEAD is not the normal empty-repository state. return false; } try { - const refs = execFileSync(getGitExecutable(), ['for-each-ref', '--format=%(refname)', headRef], { - encoding: 'utf-8', - stdio: 'pipe', - }) + const refs = runGitSync(['for-each-ref', '--format=%(refname)', headRef], { stdio: 'pipe' }) .split(/\r?\n/) .filter(Boolean); @@ -221,10 +221,7 @@ function isUnbornHead(): boolean { export function hasCommits(): boolean { try { - const count = execFileSync(getGitExecutable(), ['rev-list', '--count', 'HEAD'], { - encoding: 'utf-8', - stdio: 'pipe', - }).trim(); + const count = runGitSync(['rev-list', '--count', 'HEAD'], { stdio: 'pipe' }).trim(); return Number.parseInt(count, 10) > 0; } catch (err) { @@ -240,11 +237,7 @@ export function hasCommits(): boolean { export function getStagedDiff(cwd = process.cwd(), indexFile?: string): DiffResult { return toDiffResult( - execFileSync( - getGitExecutable(), - ['diff', '--cached', '--no-color', '--no-ext-diff'], - stagedDiffOptions(cwd, indexFile), - ), + runGitSync(['diff', '--cached', '--no-color', '--no-ext-diff'], stagedDiffOptions(cwd, indexFile)), ); } @@ -279,9 +272,8 @@ export function createIndexSnapshot(cwd = process.cwd()): IndexSnapshot { * constructing the full untracked-aware diff. */ export function hasUnstagedChanges(cwd = process.cwd()): boolean { - const status = execFileSync(getGitExecutable(), ['status', '--porcelain=v1', '--untracked-files=all'], { + const status = runGitSync(['status', '--porcelain=v1', '--untracked-files=all'], { cwd, - encoding: 'utf-8', env: getGitEnv(), maxBuffer: GIT_DIFF_MAX_BUFFER, }); @@ -291,9 +283,8 @@ export function hasUnstagedChanges(cwd = process.cwd()): boolean { function getGitPath(path: string, cwd: string): string { return resolve( cwd, - execFileSync(getGitExecutable(), ['rev-parse', '--git-path', path], { + runGitSync(['rev-parse', '--git-path', path], { cwd, - encoding: 'utf-8', env: getGitEnv(), stdio: 'pipe', }).trim(), @@ -301,9 +292,8 @@ function getGitPath(path: string, cwd: string): string { } function getUntrackedDiff(cwd = process.cwd()): string { - const untrackedEntries = execFileSync(getGitExecutable(), ['ls-files', '--others', '--exclude-standard', '-z'], { + const untrackedEntries = runGitSync(['ls-files', '--others', '--exclude-standard', '-z'], { cwd, - encoding: 'utf-8', env: getGitEnv(), maxBuffer: GIT_DIFF_MAX_BUFFER, }) @@ -316,9 +306,8 @@ function getUntrackedDiff(cwd = process.cwd()): string { } try { - execFileSync(getGitExecutable(), ['rev-parse', '--verify', 'HEAD'], { + runGitSync(['rev-parse', '--verify', 'HEAD'], { cwd: resolve(cwd, entry), - encoding: 'utf-8', env: getGitEnv(), stdio: 'pipe', }); @@ -353,16 +342,11 @@ function getUntrackedDiff(cwd = process.cwd()): string { throw new Error(detail || `git add --intent-to-add exited with code ${addResult.status}`); } - return execFileSync( - getGitExecutable(), - ['--literal-pathspecs', 'diff', '--no-color', '--no-ext-diff', '--', ...pathspecs], - { - cwd, - encoding: 'utf-8', - env, - maxBuffer: GIT_DIFF_MAX_BUFFER, - }, - ); + return runGitSync(['--literal-pathspecs', 'diff', '--no-color', '--no-ext-diff', '--', ...pathspecs], { + cwd, + env, + maxBuffer: GIT_DIFF_MAX_BUFFER, + }); } finally { rmSync(tempDir, { recursive: true, force: true }); } @@ -370,9 +354,8 @@ function getUntrackedDiff(cwd = process.cwd()): string { export function getUnstagedDiff(cwd = process.cwd()): DiffResult { const untrackedAwareDiff = getUntrackedDiff(cwd); - const trackedDiff = execFileSync(getGitExecutable(), ['diff', '--no-color', '--no-ext-diff'], { + const trackedDiff = runGitSync(['diff', '--no-color', '--no-ext-diff'], { cwd, - encoding: 'utf-8', env: getGitEnv(), maxBuffer: GIT_DIFF_MAX_BUFFER, }); @@ -431,18 +414,12 @@ export function getHeadHash(cwd = process.cwd()): string | undefined { * against their first parent, matching the base the staged diff was taken from. */ export function getCommitDiff(hash: string, cwd = process.cwd()): string { - const options = { cwd, encoding: 'utf-8' as const, env: getGitEnv(), maxBuffer: GIT_DIFF_MAX_BUFFER }; - const [, firstParent] = execFileSync(getGitExecutable(), ['rev-list', '--parents', '-n', '1', hash], options) - .trim() - .split(' '); + const options = { cwd, env: getGitEnv(), maxBuffer: GIT_DIFF_MAX_BUFFER }; + const [, firstParent] = runGitSync(['rev-list', '--parents', '-n', '1', hash], options).trim().split(' '); if (firstParent) { - return execFileSync(getGitExecutable(), ['diff', '--no-color', '--no-ext-diff', firstParent, hash], options); + return runGitSync(['diff', '--no-color', '--no-ext-diff', firstParent, hash], options); } - return execFileSync( - getGitExecutable(), - ['show', '--no-color', '--no-ext-diff', '--format=', '--root', '-p', hash], - options, - ); + return runGitSync(['show', '--no-color', '--no-ext-diff', '--format=', '--root', '-p', hash], options); } const MERGE_STATE_FILES = ['MERGE_HEAD', 'MERGE_MSG', 'MERGE_MODE']; @@ -467,21 +444,20 @@ export function rollbackHead( mergeState: MergeState = [], ): void { const args = previousHash ? ['update-ref', 'HEAD', previousHash, newHash] : ['update-ref', '-d', 'HEAD', newHash]; - execFileSync(getGitExecutable(), args, { cwd, encoding: 'utf-8', env: getGitEnv() }); + runGitSync(args, { cwd, env: getGitEnv() }); for (const { path, content } of mergeState) { writeFileSync(path, content, 'utf-8'); } } export function getRepoRoot(): string { - return normalize(execFileSync(getGitExecutable(), ['rev-parse', '--show-toplevel'], { encoding: 'utf-8' }).trim()); + return normalize(runGitSync(['rev-parse', '--show-toplevel']).trim()); } export function getBranchName(cwd = process.cwd()): string { try { - return execFileSync(getGitExecutable(), ['rev-parse', '--abbrev-ref', 'HEAD'], { + return runGitSync(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, - encoding: 'utf-8', env: getGitEnv(), }).trim(); } catch { @@ -491,9 +467,8 @@ export function getBranchName(cwd = process.cwd()): string { export function getLastCommitMessage(cwd = process.cwd()): string { try { - return execFileSync(getGitExecutable(), ['log', '-1', '--format=%s'], { + return runGitSync(['log', '-1', '--format=%s'], { cwd, - encoding: 'utf-8', env: getGitEnv(), stdio: 'pipe', }).trim(); diff --git a/src/git/hook.ts b/src/git/hook.ts index 124c528..b9caa9a 100644 --- a/src/git/hook.ts +++ b/src/git/hook.ts @@ -1,10 +1,9 @@ -import { execFileSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { chmod, copyFile, lstat, mkdir, readFile, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { dirname, resolve } from 'node:path'; import type { CommitEntry, Config, Suggestion, StyleProfile } from '../types.js'; -import { checkGitRepo, checkGitRepoWithSignal, getGitExecutable, getStagedDiffWithSignal } from './diff.js'; +import { checkGitRepo, checkGitRepoWithSignal, getStagedDiffWithSignal, runGitSync } from './diff.js'; import type { DiffResult } from './diff.js'; import { loadConfig } from '../config/store.js'; import { appendEntry, buildProfile } from '../history/store.js'; @@ -61,7 +60,7 @@ export interface UninstalledCommitHooks { } function resolveGitPath(gitPath: string): string { - return execFileSync(getGitExecutable(), ['rev-parse', '--git-path', gitPath], { encoding: 'utf-8' }).trim(); + return runGitSync(['rev-parse', '--git-path', gitPath]).trim(); } function resolveHookPath(hookName: string): string { @@ -824,8 +823,7 @@ export async function runPrepareCommitMsgHook( export async function runPostCommitHook( deps: PostCommitHookDeps = { checkGitRepo, - readLatestCommitMessage: () => - execFileSync(getGitExecutable(), ['log', '-1', '--pretty=%B'], { encoding: 'utf-8' }).trim(), + readLatestCommitMessage: () => runGitSync(['log', '-1', '--pretty=%B']).trim(), readPendingEntryFile: async () => readFile(resolvePendingEntryPath(), 'utf-8'), appendHistoryEntry: appendEntry, removePendingEntryFile: async () => rm(resolvePendingEntryPath(), { force: true }),