Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 31 additions & 56 deletions src/git/diff.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -121,6 +121,12 @@ export function getGitExecutable(): string {
return gitExecutable;
}

type GitSyncOptions = Omit<ExecFileSyncOptionsWithStringEncoding, 'encoding'> & { 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')) {
Expand All @@ -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' });
Comment thread
404-Page-Found marked this conversation as resolved.
Resolved
} catch (err) {
throw toGitRepoCheckError(err);
}
Expand Down Expand Up @@ -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);

Expand All @@ -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) {
Expand All @@ -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)),
);
}

Expand Down Expand Up @@ -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,
});
Expand All @@ -291,19 +283,17 @@ 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(),
);
}

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,
})
Expand All @@ -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',
});
Expand Down Expand Up @@ -353,26 +342,20 @@ 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 });
}
}

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,
});
Expand Down Expand Up @@ -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'];
Expand All @@ -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 {
Expand All @@ -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();
Expand Down
8 changes: 3 additions & 5 deletions src/git/hook.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 }),
Expand Down
Loading