Repository navigation
Expand file tree
/
Copy pathstatus.ts
More file actions
831 lines (756 loc) · 27.3 KB
/
Copy pathstatus.ts
File metadata and controls
831 lines (756 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
import { assertGitWorkingPath, markGitMutationDispatched } from './operation-context.js';
import { promises as fs } from 'fs';
import path from 'path';
import { GitDomainError } from './git-domain-error.js';
import { createLogger } from '../../common/log.js';
import { errorMessage, hasNodeErrorCode } from '../../common/errors.js';
import { chunkGitPathspecs, literalGitPathspec } from './pathspecs.js';
import { GIT_REF_RESULT_LIMITS, type GitCommandOptions } from './types.js';
import { DEFAULT_GIT_REF_SORT } from '../../../common/git-refs.js';
import { isExpectedMissingGitResult } from './comparison-errors.js';
import { commitSelectedFiles } from './selected-file-commit.js';
import { withRepositoryMutation } from './repository-coordination.js';
import { discard } from './discard.js';
import { parsePorcelainV1Z } from './porcelain-status.js';
import type {
BranchOptions,
CheckoutOptions,
CommitIndexOptions,
CommitMessageContextOptions,
GitStatus,
GitRemoteStatus,
GitMutationResult,
CommitOptions,
FileOptions,
GitCommitResult,
GitRefOption,
GitRefsResponse,
GitRefsOptions,
GitRefSort,
ProjectOptions,
PushOptions,
RemoteInfo,
RevertCommitOptions,
StagePathsOptions,
} from './types.js';
import {
assertGitRepository,
readOnlyGitOptions,
resolvePathWithinProject,
runGit,
runGitWithStdin,
} from './run.js';
import {
assertExistingCommitRef,
assertSafeBranchName,
assertSafeRemoteName,
} from './ref-validation.js';
const logger = createLogger('git:status');
const COMMIT_MESSAGE_DIFF_CONTEXT_LINES = 10;
const LOCAL_BRANCH_REF_PATTERN = 'refs/heads';
const WHOLE_INDEX_COMMIT_STATE_REFS = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD'];
const NETWORK_GIT_DEFAULT_TIMEOUT_MS = 30_000;
function networkGitOptions(): GitCommandOptions {
return {
timeoutMs: NETWORK_GIT_DEFAULT_TIMEOUT_MS,
// Fails fast on credential prompts instead of hanging until the timeout.
env: { GIT_TERMINAL_PROMPT: '0' },
};
}
type CommitMessageDiffRunner = (
cwd: string,
args: string[],
options?: GitCommandOptions,
) => Promise<{ stdout: string }>;
function normalizeRefResultLimit(limit: number | undefined): number {
if (!Number.isInteger(limit) || !limit || limit < 1) return GIT_REF_RESULT_LIMITS.default;
return Math.min(limit, GIT_REF_RESULT_LIMITS.max);
}
async function hasCommitStateRef(projectPath: string, ref: string): Promise<boolean> {
try {
await runGit(
projectPath,
['rev-parse', '--verify', '--quiet', ref],
readOnlyGitOptions(),
);
return true;
} catch (error) {
if (isExpectedMissingGitResult(error)) return false;
throw error;
}
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true;
} catch (error) {
if (hasNodeErrorCode(error, 'ENOENT')) return false;
throw error;
}
}
async function hasRebaseOrAmConflictState(projectPath: string): Promise<boolean> {
const { stdout } = await runGit(
projectPath,
[
'rev-parse',
'--git-path',
'rebase-merge/stopped-sha',
'--git-path',
'rebase-merge/amend',
'--git-path',
'rebase-apply',
],
readOnlyGitOptions(),
);
const [stoppedPath, amendPath, applyPath] = stdout
.trimEnd()
.split('\n')
.map((statePath) => path.resolve(projectPath, statePath));
if (await fileExists(applyPath)) return true;
// Interactive edit stops permit isolated commits; conflicted stops omit the amend marker.
return (await fileExists(stoppedPath)) && !(await fileExists(amendPath));
}
async function requiresWholeIndexCommit(projectPath: string): Promise<boolean> {
// Git continuation states require preserving the complete staged operation.
for (const ref of WHOLE_INDEX_COMMIT_STATE_REFS) {
if (await hasCommitStateRef(projectPath, ref)) return true;
}
return hasRebaseOrAmConflictState(projectPath);
}
function normalizeRefSearchQuery(query: string | undefined): string | null {
const trimmed = query?.trim() ?? '';
if (!trimmed) return '';
return /^[A-Za-z0-9._/@{}~^+-]+$/.test(trimmed) ? trimmed : null;
}
function refPatternsForQuery(query: string): string[] {
// Keeps opening the selector cheap by avoiding large remote/tag namespaces until search.
if (!query) return [LOCAL_BRANCH_REF_PATTERN];
if (query.startsWith('refs/')) return [`${query}*`];
if (query.includes('/')) {
return [
`refs/heads/${query}*`,
`refs/remotes/${query}*`,
`refs/tags/${query}*`,
];
}
return [
`refs/heads/${query}*`,
`refs/remotes/${query}*`,
`refs/remotes/*/${query}*`,
`refs/tags/${query}*`,
];
}
function gitRefDisplayName(refname: string): Pick<GitRefOption, 'name' | 'kind'> {
if (refname.startsWith('refs/heads/')) {
return { name: refname.slice('refs/heads/'.length), kind: 'local-branch' };
}
if (refname.startsWith('refs/remotes/')) {
return { name: refname.slice('refs/remotes/'.length), kind: 'remote-branch' };
}
if (refname.startsWith('refs/tags/')) {
return { name: refname.slice('refs/tags/'.length), kind: 'tag' };
}
return { name: refname, kind: 'other' };
}
function gitRefSortArgs(
sort: GitRefSort,
patterns: readonly string[],
): string[] {
const canUseDefaultRefOrder =
sort.key === 'name' &&
sort.direction === 'asc' &&
patterns.length === 1 &&
patterns[0] === LOCAL_BRANCH_REF_PATTERN;
// Git's full-refname order equals short-name order under this common prefix.
// Omitting --sort lets --count stop iteration early.
if (canUseDefaultRefOrder) return [];
const directionPrefix = sort.direction === 'desc' ? '-' : '';
const primary = sort.key === 'name' ? 'refname:lstrip=2' : 'creatordate';
return ['--sort=refname', `--sort=${directionPrefix}${primary}`];
}
function creatorDateIso(value: string | undefined): string | null {
if (!value || !/^-?\d+$/.test(value)) return null;
const milliseconds = Number(value) * 1_000;
if (!Number.isSafeInteger(milliseconds)) return null;
const timestamp = new Date(milliseconds);
return Number.isFinite(timestamp.getTime()) ? timestamp.toISOString() : null;
}
function parseGitRefLine(line: string, currentBranch: string | null, head: string): GitRefOption | null {
if (!line) return null;
const [refname, objectName, creatorDate] = line.split('\0');
if (!refname) return null;
if (refname.startsWith('refs/remotes/') && refname.endsWith('/HEAD')) return null;
const { name, kind } = gitRefDisplayName(refname);
const isCurrent =
kind === 'local-branch'
? currentBranch === name
: !currentBranch && Boolean(head) && objectName === head;
return {
name,
ref: refname,
kind,
updatedAt: creatorDateIso(creatorDate),
...(isCurrent ? { isCurrent: true } : {}),
};
}
interface GitHeadIdentity {
currentBranch: string | null;
head: string;
}
async function readGitHeadIdentity(
projectPath: string,
signal?: AbortSignal,
): Promise<GitHeadIdentity> {
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', 'HEAD', '--symbolic-full-name', 'HEAD'],
readOnlyGitOptions({ signal }),
);
const [head = '', symbolicHead = ''] = stdout.trim().split(/\r?\n/);
const prefix = 'refs/heads/';
return {
head,
currentBranch: symbolicHead.startsWith(prefix)
? symbolicHead.slice(prefix.length)
: null,
};
} catch (error) {
if (signal?.aborted) throw error;
return { currentBranch: null, head: '' };
}
}
async function resolveLocalBranchCheckoutName(
projectPath: string,
ref: string,
signal?: AbortSignal,
): Promise<string | null> {
const branch = ref.startsWith('refs/heads/')
? ref.slice('refs/heads/'.length)
: ref.startsWith('refs/')
? ''
: ref;
if (!branch) return null;
try {
await runGit(
projectPath,
['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`],
readOnlyGitOptions({ signal }),
);
return branch;
} catch {
return null;
}
}
async function resolveDetachedHeadLabel(projectPath: string, head: string, signal?: AbortSignal): Promise<string> {
try {
const { stdout } = await runGit(
projectPath,
[
'for-each-ref',
'--format=%(refname:short)',
'--points-at',
'HEAD',
'refs/remotes',
'refs/tags',
],
readOnlyGitOptions({ signal }),
);
const label = stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.endsWith('/HEAD'))[0];
if (label) return label;
} catch {
// Unknown detached refs fall through to a short SHA.
}
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', '--short', 'HEAD'],
readOnlyGitOptions({ signal }),
);
return stdout.trim() || head.slice(0, 7) || 'HEAD';
} catch {
return head.slice(0, 7) || 'HEAD';
}
}
export async function collectCommitMessageDiffContext(
projectPath: string,
files: string[],
runGitFn: CommitMessageDiffRunner = runGit,
signal?: AbortSignal,
): Promise<string> {
let diffContext = '';
for (const chunk of chunkGitPathspecs(files)) {
try {
const { stdout } = await runGitFn(projectPath, [
'diff',
'--cached',
'--no-ext-diff',
'--no-color',
`-U${COMMIT_MESSAGE_DIFF_CONTEXT_LINES}`,
'--',
...chunk,
], readOnlyGitOptions({ signal, maxStdoutBytes: 320_000, truncateStdout: true }));
if (stdout) {
diffContext = `${diffContext}${diffContext ? '\n' : ''}${stdout}`.slice(0, 80_000);
if (diffContext.length === 80_000) break;
}
} catch (error) {
if (signal?.aborted) throw error;
logger.error('Failed to collect staged diff', { fileCount: chunk.length });
}
}
return diffContext;
}
// Resolves the display branch and whether the repository has any commits.
// Detached HEAD falls back to a descriptive label.
async function resolveStatusBranch(projectPath: string): Promise<{ branch: string; hasCommits: boolean }> {
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', 'HEAD'],
readOnlyGitOptions(),
);
let branch = stdout.trim();
if (branch === 'HEAD') {
const { stdout: headOutput } = await runGit(
projectPath,
['rev-parse', '--verify', 'HEAD'],
readOnlyGitOptions(),
);
branch = await resolveDetachedHeadLabel(projectPath, headOutput.trim());
}
return { branch, hasCommits: true };
} catch (error) {
const message = errorMessage(error);
if (message.includes('unknown revision') || message.includes('ambiguous argument')) {
return { branch: 'main', hasCommits: false };
}
throw error;
}
}
export function createStatusOperations() {
async function getStatus({ projectPath }: ProjectOptions): Promise<GitStatus> {
await assertGitRepository(projectPath);
// Branch resolution and the working-tree scan are independent reads;
// run them concurrently instead of paying sequential spawn latency.
const [branchInfo, { stdout: statusOutput }] = await Promise.all([
resolveStatusBranch(projectPath),
runGit(projectPath, ['status', '--porcelain', '-z', '-uall'], readOnlyGitOptions()),
]);
const { branch, hasCommits } = branchInfo;
const modified: string[] = [];
const added: string[] = [];
const deleted: string[] = [];
const untracked: string[] = [];
parsePorcelainV1Z(statusOutput).forEach(({ path: file, indexStatus: staged, workTreeStatus: unstaged }) => {
if (!file) return;
// Classifies by letter so every porcelain variant lands somewhere:
// T (typechange) and U (unmerged) count as modifications of a tracked
// path, and any A wins because the index still holds an addition. Index
// intent also wins over worktree deletion, so AD/MD read as added or
// modified rather than deleted. Renames and copies remain omitted from
// this projection; the workbench represents their two-path identity.
if (staged === 'R' || staged === 'C' || unstaged === 'R' || unstaged === 'C') return;
if (staged === 'A' || unstaged === 'A') {
added.push(file);
} else if (
staged === 'U' || unstaged === 'U' ||
staged === 'M' || unstaged === 'M' ||
staged === 'T' || unstaged === 'T'
) {
modified.push(file);
} else if (staged === 'D' || unstaged === 'D') {
deleted.push(file);
} else if (staged === '?' && unstaged === '?') {
untracked.push(file);
}
});
return { branch, hasCommits, modified, added, deleted, untracked };
}
async function initialCommit({ projectPath }: ProjectOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
try {
await runGit(projectPath, ['rev-parse', 'HEAD'], readOnlyGitOptions());
throw new GitDomainError('INVALID_INPUT', 'Initial commit is only available for repositories with no existing commits.');
} catch (e) {
if (e instanceof GitDomainError) throw e;
// Expected: rev-parse fails when there are no commits
}
await runGit(projectPath, ['add', '.']);
const { stdout } = await runGit(projectPath, ['commit', '-m', 'Initial commit']);
return { success: true, output: stdout, message: 'Initial commit created successfully' };
}
async function commit({ projectPath, message, files }: CommitOptions): Promise<GitCommitResult> {
await assertGitRepository(projectPath);
for (const file of files) {
if (!file) throw new GitDomainError('INVALID_INPUT', 'Pathspecs cannot be empty.');
if (file.includes('\0')) {
throw new GitDomainError('INVALID_INPUT', 'Pathspecs cannot contain NUL bytes.');
}
try {
resolvePathWithinProject(projectPath, file);
} catch {
throw new GitDomainError(
'INVALID_INPUT',
'Pathspecs must resolve inside the project root.',
);
}
}
return withRepositoryMutation(projectPath, async () => {
if (!(await requiresWholeIndexCommit(projectPath))) {
const result = await commitSelectedFiles(projectPath, message, files);
return { success: true, ...result, commitScope: 'selected-files' };
}
for (const file of files) {
await runGit(projectPath, ['add', '--', literalGitPathspec(file)]);
}
const { stdout } = await runGit(projectPath, ['commit', '-m', message]);
return {
success: true,
output: stdout,
commitScope: 'whole-index',
indexSynchronized: true,
};
});
}
async function getRefs({
projectPath,
query,
limit,
sort = DEFAULT_GIT_REF_SORT,
signal,
}: GitRefsOptions): Promise<GitRefsResponse> {
const normalizedQuery = normalizeRefSearchQuery(query);
if (normalizedQuery === null) {
await assertGitRepository(projectPath, signal);
return { refs: [] };
}
const refPatterns = refPatternsForQuery(normalizedQuery);
const refArgs = [
'for-each-ref',
`--count=${normalizeRefResultLimit(limit)}`,
...gitRefSortArgs(sort, refPatterns),
'--format=%(refname)%00%(objectname)%00%(creatordate:unix)',
...refPatterns,
];
const [repositoryResult, identityResult, refResult] =
await Promise.allSettled([
assertGitRepository(projectPath, signal),
readGitHeadIdentity(projectPath, signal),
runGit(projectPath, refArgs, readOnlyGitOptions({ signal })),
]);
// Preserves repository validation as the canonical failure; failures wait for every command to settle.
if (repositoryResult.status === 'rejected') throw repositoryResult.reason;
if (identityResult.status === 'rejected') throw identityResult.reason;
if (refResult.status === 'rejected') throw refResult.reason;
const identity = identityResult.value;
const refs = refResult.value.stdout
.split('\n')
.map((line) => parseGitRefLine(line, identity.currentBranch, identity.head))
.filter((ref): ref is GitRefOption => Boolean(ref));
return { refs };
}
async function getBranches(options: ProjectOptions): Promise<{ branches: string[] }> {
const { refs } = await getRefs(options);
const branches = refs
.filter((ref) => ref.kind === 'local-branch')
.map((ref) => ref.name)
.filter((branch, index, self) => self.indexOf(branch) === index);
return { branches };
}
async function checkout({ projectPath, ref, refKind, signal }: CheckoutOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
await assertExistingCommitRef(projectPath, ref, 'checkout', signal);
const localBranch = refKind === undefined || refKind === 'local-branch'
? await resolveLocalBranchCheckoutName(projectPath, ref, signal)
: null;
if (refKind === 'local-branch' && !localBranch) {
throw new GitDomainError('INVALID_INPUT', 'Invalid local branch ref.');
}
const args = localBranch
? ['checkout', localBranch]
: ['checkout', '--detach', ref];
const { stdout } = await runGit(projectPath, args);
return { success: true, output: stdout };
}
async function createBranch({ projectPath, branch, baseRef, signal }: BranchOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
await assertSafeBranchName(projectPath, branch, 'branch name', signal);
if (baseRef) await assertExistingCommitRef(projectPath, baseRef, 'base', signal);
const args = ['checkout', '-b', branch];
if (baseRef) args.push(baseRef);
const { stdout } = await runGit(projectPath, args);
return { success: true, output: stdout };
}
async function collectCommitMessageContext({ projectPath, files, signal }: CommitMessageContextOptions) {
const diff = await collectCommitMessageDiffContext(projectPath, files, runGit, signal);
return { diff };
}
async function getRemoteStatus({ projectPath }: ProjectOptions): Promise<GitRemoteStatus> {
await assertGitRepository(projectPath);
const { stdout: currentBranch } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', 'HEAD'],
readOnlyGitOptions(),
);
const branch = currentBranch.trim();
let trackingBranch: string;
let remoteName: string;
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', `${branch}@{upstream}`],
readOnlyGitOptions(),
);
trackingBranch = stdout.trim();
remoteName = trackingBranch.split('/')[0];
} catch {
let hasRemote = false;
let foundRemoteName: string | null = null;
try {
const { stdout } = await runGit(projectPath, ['remote'], readOnlyGitOptions());
const remotes = stdout.trim().split('\n').filter((r) => r.trim());
if (remotes.length > 0) {
hasRemote = true;
foundRemoteName = remotes.includes('origin') ? 'origin' : remotes[0];
}
} catch { }
return {
hasRemote,
hasUpstream: false,
branch,
remoteName: foundRemoteName,
message: 'No remote tracking branch configured',
};
}
const { stdout: countOutput } = await runGit(
projectPath,
['rev-list', '--count', '--left-right', `${trackingBranch}...HEAD`],
readOnlyGitOptions(),
);
const [behind, ahead] = countOutput.trim().split('\t').map(Number);
return {
hasRemote: true,
hasUpstream: true,
branch,
remoteBranch: trackingBranch,
remoteName,
ahead: ahead || 0,
behind: behind || 0,
isUpToDate: ahead === 0 && behind === 0,
};
}
async function fetch({ projectPath }: ProjectOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const { stdout: fetchBranch } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', 'HEAD'],
readOnlyGitOptions(),
);
const branch = fetchBranch.trim();
let remoteName = 'origin';
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', `${branch}@{upstream}`],
readOnlyGitOptions(),
);
remoteName = stdout.trim().split('/')[0];
} catch {
logger.info('No upstream configured, using origin as fallback');
}
const { stdout } = await runGit(projectPath, ['fetch', remoteName], networkGitOptions());
return { success: true, output: stdout || 'Fetch completed successfully', remoteName };
}
async function pull({ projectPath }: ProjectOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const { stdout: pullBranch } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', 'HEAD'],
readOnlyGitOptions(),
);
const branch = pullBranch.trim();
let remoteName = 'origin';
let remoteBranch = branch;
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', `${branch}@{upstream}`],
readOnlyGitOptions(),
);
const tracking = stdout.trim();
remoteName = tracking.split('/')[0];
remoteBranch = tracking.split('/').slice(1).join('/');
} catch {
logger.info('No upstream configured, using origin/branch as fallback');
}
const { stdout } = await runGit(
projectPath,
['pull', remoteName, remoteBranch],
networkGitOptions(),
);
return {
success: true,
output: stdout || 'Pull completed successfully',
remoteName,
remoteBranch,
};
}
// Returns list of configured remotes with their fetch URLs.
async function getRemotes({ projectPath }: ProjectOptions): Promise<{ remotes: RemoteInfo[] }> {
await assertGitRepository(projectPath);
const { stdout } = await runGit(projectPath, ['remote', '-v'], readOnlyGitOptions());
const seen = new Map<string, RemoteInfo>();
for (const line of stdout.trim().split('\n')) {
if (!line.trim()) continue;
const parts = line.split(/\s+/);
if (parts.length >= 2 && !seen.has(parts[0])) {
seen.set(parts[0], { name: parts[0], url: parts[1] });
}
}
return { remotes: Array.from(seen.values()) };
}
// Pushes to a specific remote. Never sets upstream tracking.
async function push({ projectPath, remote, remoteBranch }: PushOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const { stdout: headBranch } = await runGit(
projectPath,
['rev-parse', '--abbrev-ref', 'HEAD'],
readOnlyGitOptions(),
);
const branch = headBranch.trim();
const targetRemote = remote || 'origin';
const targetBranch = remoteBranch || branch;
assertSafeRemoteName(targetRemote);
if (remoteBranch) {
await assertSafeBranchName(projectPath, remoteBranch, 'remote branch name');
if (remoteBranch !== branch) {
throw new GitDomainError('INVALID_INPUT', 'Remote branch must match the current local branch.');
}
}
const { stdout } = await runGit(
projectPath,
['push', targetRemote, `${branch}:${targetBranch}`],
networkGitOptions(),
);
return {
success: true,
output: stdout || 'Push completed successfully',
remoteName: targetRemote,
remoteBranch: targetBranch,
};
}
async function deleteUntracked({ projectPath, file }: FileOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const filePath = resolvePathWithinProject(projectPath, file);
if (filePath === path.resolve(projectPath)) {
throw new GitDomainError('INVALID_INPUT', 'The project directory cannot be deleted as an untracked file.');
}
const pathspec = literalGitPathspec(file);
// Clean tracked descendants do not appear in porcelain status.
const { stdout: indexedPaths } = await runGit(
projectPath,
['ls-files', '-z', '--', pathspec],
readOnlyGitOptions(),
);
if (indexedPaths.length > 0) {
throw new GitDomainError('INVALID_INPUT', 'The path contains files tracked by Git. Use discard for tracked files.');
}
const { stdout: statusOutput } = await runGit(
projectPath,
['status', '--porcelain', '--', pathspec],
readOnlyGitOptions(),
);
if (!statusOutput.trim()) {
throw new GitDomainError('INVALID_INPUT', 'The file is either tracked already or does not exist on disk.');
}
const status = statusOutput.substring(0, 2);
if (status !== '??') {
throw new GitDomainError('INVALID_INPUT', 'The file is tracked by Git. Use discard for tracked files.');
}
await assertGitWorkingPath(filePath);
const stats = await fs.lstat(filePath);
markGitMutationDispatched();
if (stats.isDirectory()) {
await fs.rm(filePath, { recursive: true, force: true });
return { success: true, message: `Untracked directory ${file} deleted successfully` };
}
await fs.unlink(filePath);
return { success: true, message: `Untracked file ${file} deleted successfully` };
}
async function commitIndex({ projectPath, message }: CommitIndexOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
return withRepositoryMutation(projectPath, async () => {
const { stdout } = await runGit(projectPath, ['commit', '-m', message]);
return { success: true, output: stdout };
});
}
function pathspecStdin(paths: string[]): string {
return paths.map((filePath) => `${literalGitPathspec(filePath)}\0`).join('');
}
async function stagePaths({ projectPath, paths, mode }: StagePathsOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
if (paths.length === 0) {
throw new GitDomainError('INVALID_INPUT', 'At least one path is required.');
}
for (const filePath of paths) {
if (filePath.length === 0) {
throw new GitDomainError('INVALID_INPUT', 'Pathspecs cannot be empty.');
}
if (filePath.includes('\0')) {
throw new GitDomainError('INVALID_INPUT', 'Pathspecs cannot contain NUL bytes.');
}
resolvePathWithinProject(projectPath, filePath);
}
const input = pathspecStdin(paths);
if (mode === 'stage') {
await runGitWithStdin(projectPath, ['add', '--pathspec-from-file=-', '--pathspec-file-nul'], input);
} else {
await runGitWithStdin(
projectPath,
['reset', '-q', 'HEAD', '--pathspec-from-file=-', '--pathspec-file-nul'],
input,
);
}
return { success: true };
}
async function revertCommit({ projectPath, commit }: RevertCommitOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
await assertExistingCommitRef(projectPath, commit, 'commit');
const { stdout: parentLine } = await runGit(
projectPath,
['rev-list', '--parents', '-n', '1', commit],
readOnlyGitOptions(),
);
const parentCount = parentLine.trim().split(/\s+/).filter(Boolean).length - 1;
// Uses first parent for merge commits to match the commit screen default diff.
const args = parentCount > 1
? ['revert', '--no-edit', '-m', '1', commit]
: ['revert', '--no-edit', commit];
const { stdout } = await runGit(projectPath, args);
return { success: true, output: stdout || `Commit ${commit.slice(0, 7)} reverted` };
}
return {
getStatus,
initialCommit,
commit,
getBranches,
getRefs,
checkout,
createBranch,
collectCommitMessageContext,
getRemoteStatus,
getRemotes,
fetch,
pull,
push,
discard,
deleteUntracked,
commitIndex,
stagePaths,
revertCommit,
};
}