-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathisomorphic-git-service.ts
More file actions
1185 lines (1007 loc) · 45.2 KB
/
isomorphic-git-service.ts
File metadata and controls
1185 lines (1007 loc) · 45.2 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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {StatusRow} from 'isomorphic-git'
import * as git from 'isomorphic-git'
import fs from 'node:fs'
import {join} from 'node:path'
import type {
AbortMergeGitParams,
AddGitParams,
AddRemoteGitParams,
AheadBehind,
BaseGitParams,
CheckoutGitParams,
CloneGitParams,
CommitGitParams,
CreateBranchGitParams,
DeleteBranchGitParams,
FetchGitParams,
GetAheadBehindParams,
GetRemoteUrlGitParams,
GetTrackingBranchParams,
GitBranch,
GitCommit,
GitConflict,
GitRemote,
GitStatus,
GitStatusFile,
IGitService,
InitGitParams,
ListBranchesGitParams,
LogGitParams,
MergeGitParams,
MergeResult,
PullGitParams,
PullResult,
PushGitParams,
PushResult,
RemoveRemoteGitParams,
ResetGitParams,
ResetResult,
SetTrackingBranchParams,
TrackingBranch,
} from '../../core/interfaces/services/i-git-service.js'
import type {IAuthStateStore} from '../../core/interfaces/state/i-auth-state-store.js'
import {GitAuthError, GitError} from '../../core/domain/errors/git-error.js'
import {gitHttpWrapper as http} from './git-http-wrapper.js'
/** Max commit depth for ahead/behind calculation. Counts beyond this are truncated. */
const MAX_AHEAD_BEHIND_DEPTH = 500
/** Shape of isomorphic-git's MergeConflictError.data property. */
type IsomorphicGitConflictData = {
bothModified: string[]
deleteByTheirs: string[]
deleteByUs: string[]
filepaths: string[]
}
/** isomorphic-git's MergeConflictError — extends Error with a typed `data` property. */
type IsomorphicGitMergeConflictError = Error & {data?: IsomorphicGitConflictData}
export class IsomorphicGitService implements IGitService {
public constructor(private readonly authStateStore: IAuthStateStore) {}
private static isConflictError(error: Error): error is IsomorphicGitMergeConflictError {
return error.name === 'MergeConflictError' && 'data' in error
}
private static isMergeConflictData(data: unknown): data is IsomorphicGitConflictData {
if (typeof data !== 'object' || data === null) return false
return 'filepaths' in data && Array.isArray(data.filepaths)
}
async abortMerge(params: AbortMergeGitParams): Promise<void> {
const dir = this.requireDirectory(params)
const mergeHeadPath = join(dir, '.git', 'MERGE_HEAD')
const mergeMsgPath = join(dir, '.git', 'MERGE_MSG')
// Identify files introduced by the merge source (in MERGE_HEAD tree but not in HEAD tree).
// These files appeared on disk during merge and must be removed on abort.
// We compare tree contents (not statusMatrix) because merge-introduced files and
// pre-existing untracked files both show as [0,2,0] in the status matrix.
// Get current branch BEFORE checkout to avoid detached HEAD
const branch = await this.getCurrentBranch(params)
let mergeIntroducedFiles: string[] = []
const mergeHeadOid = await fs.promises
.readFile(mergeHeadPath, 'utf8')
.then((s) => s.trim())
.catch(() => null)
if (mergeHeadOid) {
const headFiles = new Set(await git.listFiles({dir, fs, ref: branch ?? 'HEAD'}))
const mergeFiles = await git.listFiles({dir, fs, ref: mergeHeadOid})
mergeIntroducedFiles = mergeFiles.filter((f) => !headFiles.has(f))
}
await git.checkout({dir, force: true, fs, ref: branch ?? 'HEAD'})
// Clean up files that the merge brought in (exist in MERGE_HEAD but not in HEAD)
for (const filepath of mergeIntroducedFiles) {
// eslint-disable-next-line no-await-in-loop
await fs.promises.unlink(join(dir, filepath)).catch(() => {})
}
await fs.promises.unlink(mergeHeadPath).catch(() => {})
await fs.promises.unlink(mergeMsgPath).catch(() => {})
}
async add(params: AddGitParams): Promise<void> {
const dir = this.requireDirectory(params)
// Identify deleted files (exist in HEAD + index but not on disk: [1,0,1])
// git.add() silently ignores missing files; git.remove() is required to stage deletions
const matrix = await git.statusMatrix({dir, fs})
// Covers [1,0,1] (unstaged deletion) and [1,0,2] (post-merge-conflict absent file).
// stage !== 0 excludes [1,0,0] which is already staged as deletion — no git.remove() needed.
const deletedInIndex = new Set(
matrix
.filter(([, head, workdir, stage]) => head === 1 && workdir === 0 && stage !== 0)
.map(([filepath]) => String(filepath)),
)
// Files not present on disk at all (workdir=0): covers both [1,0,1] (unstaged deletion)
// and [1,0,0] (already staged deletion). git.add() on these exact paths throws; skip toAdd.
const notOnDisk = new Set(matrix.filter((row) => row[2] === 0).map((row) => String(row[0])))
const toRemove: string[] = []
const toAdd: string[] = []
for (const rp of params.filePaths) {
const matchesDelete = (filepath: string) => {
if (rp === '.') return true
if (filepath === rp) return true
const prefix = rp.endsWith('/') ? rp : `${rp}/`
return filepath.startsWith(prefix)
}
for (const deleted of deletedInIndex) {
if (matchesDelete(deleted)) toRemove.push(deleted)
}
// Don't call git.add() for exact paths not on disk — git.remove() handles [1,0,1] above,
// and [1,0,0] (already staged deletion) needs no further action.
// git.add('.') and directory patterns are fine (silently skip missing files).
if (!notOnDisk.has(rp)) {
toAdd.push(rp)
}
}
const results = await Promise.allSettled([
...toRemove.map((filepath) => git.remove({dir, filepath, fs})),
...toAdd.map((filepath) => git.add({dir, filepath, fs})),
])
const allPaths = [...toRemove, ...toAdd]
const failed = results
.map((r, i) => ({path: allPaths[i], result: r}))
.filter((x): x is {path: string; result: PromiseRejectedResult} => x.result.status === 'rejected')
if (failed.length > 0) {
const paths = failed.map((f) => f.path).join(', ')
throw new GitError(`Failed to stage: ${paths}`)
}
}
async addRemote(params: AddRemoteGitParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.addRemote({dir, fs, remote: params.remote, url: params.url})
}
async checkout(params: CheckoutGitParams): Promise<void> {
const dir = this.requireDirectory(params)
// Snapshot tracked files in current branch BEFORE checkout.
// isomorphic-git's checkout only restores target files but does NOT remove
// files that are tracked in the source branch but absent in the target.
// Native git removes them, so we do it manually after checkout.
const sourceBranch = await this.getCurrentBranch(params)
const sourceFiles = sourceBranch ? new Set(await git.listFiles({dir, fs, ref: sourceBranch})) : new Set<string>()
// isomorphic-git's checkout detects unstaged conflicts (CheckoutConflictError)
// but silently overwrites staged changes — a data-loss bug. Guard staged
// conflicts here to match native git behavior.
if (!params.force && sourceBranch) {
await this.guardStagedConflicts(dir, sourceBranch, params.ref)
}
try {
await git.checkout({dir, force: params.force, fs, ref: params.ref})
} catch (error) {
if (error instanceof git.Errors.CheckoutConflictError) {
throw new GitError(
'Your local changes to the following files would be overwritten by checkout. ' +
'Commit your changes or stash them before you switch branches.',
)
}
throw error
}
// Remove files tracked in source but not in target (matches native git behavior).
// Untracked files are not in either set, so they are preserved.
if (sourceFiles.size > 0) {
const targetFiles = new Set(await git.listFiles({dir, fs, ref: params.ref}))
for (const filepath of sourceFiles) {
if (!targetFiles.has(filepath)) {
// eslint-disable-next-line no-await-in-loop
await fs.promises.unlink(join(dir, filepath)).catch(() => {})
}
}
}
}
async clone(params: CloneGitParams): Promise<void> {
const dir = this.requireDirectory(params)
const token = this.requireToken()
await git.clone({
dir,
fs,
headers: this.buildBasicAuthHeaders(token.userId, token.sessionKey),
http,
onAuth: this.getOnAuth(),
onAuthFailure: this.getOnAuthFailure(),
onProgress: params.onProgress,
url: params.url,
})
}
async commit(params: CommitGitParams): Promise<GitCommit> {
const dir = this.requireDirectory(params)
const author = params.author ?? this.getAuthor()
// If MERGE_HEAD exists, create a proper merge commit with two parents
const mergeHeadPath = join(dir, '.git', 'MERGE_HEAD')
const mergeMsgPath = join(dir, '.git', 'MERGE_MSG')
const mergeHeadContent = await fs.promises.readFile(mergeHeadPath, 'utf8').catch(() => null)
const mergeHead = mergeHeadContent?.trim() ?? null
let parent: string[] | undefined
if (mergeHead) {
const headSha = await git.resolveRef({dir, fs, ref: 'HEAD'})
parent = [headSha, mergeHead]
}
let sha: string
try {
sha = await git.commit({author, dir, fs, message: params.message, ...(parent ? {parent} : {})})
} catch (error) {
if (error instanceof git.Errors.UnmergedPathsError) {
const paths = error.data.filepaths.join(', ')
throw new GitError(`Unmerged files must be resolved before committing: ${paths}`)
}
throw error
}
const {commit: commitObj} = await git.readCommit({dir, fs, oid: sha})
// Clean up MERGE_HEAD and MERGE_MSG (isomorphic-git does not remove them automatically)
await fs.promises.unlink(mergeHeadPath).catch(() => {})
await fs.promises.unlink(mergeMsgPath).catch(() => {})
return {
author,
message: params.message,
sha,
timestamp: new Date(commitObj.author.timestamp * 1000),
}
}
async createBranch(params: CreateBranchGitParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.branch({checkout: params.checkout, dir, fs, ref: params.branch})
}
async deleteBranch(params: DeleteBranchGitParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.deleteBranch({dir, fs, ref: params.branch})
}
async fetch(params: FetchGitParams): Promise<void> {
const dir = this.requireDirectory(params)
const token = this.requireToken()
await git.fetch({
dir,
fs,
headers: this.buildBasicAuthHeaders(token.userId, token.sessionKey),
http,
onAuth: this.getOnAuth(),
onAuthFailure: this.getOnAuthFailure(),
ref: params.ref,
remote: params.remote ?? 'origin',
})
}
async getAheadBehind(params: GetAheadBehindParams): Promise<AheadBehind> {
const dir = this.requireDirectory(params)
const localSha = await git.resolveRef({dir, fs, ref: params.localRef}).catch(() => null)
const remoteSha = await git.resolveRef({dir, fs, ref: params.remoteRef}).catch(() => null)
if (!localSha || !remoteSha) return {ahead: 0, behind: 0}
if (localSha === remoteSha) return {ahead: 0, behind: 0}
const [localLog, remoteLog] = await Promise.all([
git.log({depth: MAX_AHEAD_BEHIND_DEPTH, dir, fs, ref: params.localRef}).catch(() => []),
git.log({depth: MAX_AHEAD_BEHIND_DEPTH, dir, fs, ref: params.remoteRef}).catch(() => []),
])
const localShas = new Set(localLog.map((c) => c.oid))
const remoteShas = new Set(remoteLog.map((c) => c.oid))
const ahead = localLog.filter((c) => !remoteShas.has(c.oid)).length
const behind = remoteLog.filter((c) => !localShas.has(c.oid)).length
return {ahead, behind}
}
async getConflicts(params: BaseGitParams): Promise<GitConflict[]> {
const dir = this.requireDirectory(params)
// Only report conflicts when a merge is actually in progress
const mergeInProgress = await fs.promises
.access(join(dir, '.git', 'MERGE_HEAD'))
.then(() => true)
.catch(() => false)
if (!mergeInProgress) return []
const matrix = await git.statusMatrix({dir, fs})
const conflicts: GitConflict[] = []
await Promise.all(
matrix.map(async ([filepath, head, workdir, stage]) => {
const path = String(filepath)
// deleted_modified: file was in HEAD but gone from workdir
if (head === 1 && workdir === 0) {
conflicts.push({path, type: 'deleted_modified'})
return
}
// deleted_modified (isomorphic-git variant): file in HEAD, on disk unchanged,
// but index differs from both (stage=3). This happens when the other branch
// deletes a file that we modified — isomorphic-git keeps our version on disk.
if (head === 1 && workdir === 1 && stage === 3) {
conflicts.push({path, type: 'deleted_modified'})
return
}
// both_added or both_modified: look for conflict markers in file content
if (workdir === 2) {
try {
const content = await fs.promises.readFile(join(dir, path), 'utf8')
if (content.includes('<<<<<<<')) {
const type: GitConflict['type'] = head === 0 ? 'both_added' : 'both_modified'
conflicts.push({path, type})
}
} catch {
// skip binary or unreadable files
}
}
}),
)
return conflicts.sort((a, b) => a.path.localeCompare(b.path))
}
async getCurrentBranch(params: BaseGitParams): Promise<string | undefined> {
const dir = this.requireDirectory(params)
const branch = await git.currentBranch({dir, fs})
return branch ?? undefined
}
async getFilesWithConflictMarkers(params: BaseGitParams): Promise<string[]> {
const dir = this.requireDirectory(params)
const matrix = await git.statusMatrix({dir, fs})
const conflicted: string[] = []
await Promise.all(
matrix.map(async ([filepath, , workdir]) => {
const path = String(filepath)
// Only check files that exist in the working directory
if (workdir === 0) return
try {
const content = await fs.promises.readFile(join(dir, path), 'utf8')
if (content.includes('<<<<<<<') && content.includes('=======') && content.includes('>>>>>>>')) {
conflicted.push(path)
}
} catch {
// skip binary or unreadable files
}
}),
)
return conflicted.sort()
}
async getRemoteUrl(params: GetRemoteUrlGitParams): Promise<string | undefined> {
const dir = this.requireDirectory(params)
const result = await git.getConfig({dir, fs, path: `remote.${params.remote}.url`})
return result === undefined || result === null ? undefined : String(result)
}
async getTrackingBranch(params: GetTrackingBranchParams): Promise<TrackingBranch | undefined> {
const dir = this.requireDirectory(params)
const remote = await git.getConfig({dir, fs, path: `branch.${params.branch}.remote`})
if (remote === undefined || remote === null) return undefined
const merge = await git.getConfig({dir, fs, path: `branch.${params.branch}.merge`})
if (merge === undefined || merge === null) return undefined
// merge is stored as refs/heads/<branch> — extract the branch name
const mergeStr = String(merge)
const remoteBranch = mergeStr.startsWith('refs/heads/') ? mergeStr.slice('refs/heads/'.length) : mergeStr
return {remote: String(remote), remoteBranch}
}
async init(params: InitGitParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.init({defaultBranch: params.defaultBranch ?? 'main', dir, fs})
}
async isAncestor(params: BaseGitParams & {ancestor: string; commit: string}): Promise<boolean> {
const dir = this.requireDirectory(params)
const commitOid = await git.resolveRef({dir, fs, ref: params.commit})
const ancestorOid = await git.resolveRef({dir, fs, ref: params.ancestor})
if (commitOid === ancestorOid) return true
return git.isDescendent({ancestor: ancestorOid, depth: -1, dir, fs, oid: commitOid})
}
async isEmptyRepository(params: BaseGitParams): Promise<boolean> {
const dir = this.requireDirectory(params)
const commits = await this.log({depth: 1, directory: dir})
if (commits.length > 0) return false
const remotes = await this.listRemotes({directory: dir})
if (remotes.length > 0) return false
const branches = await git.listBranches({dir, fs})
if (branches.length > 0) return false
const tags = await git.listTags({dir, fs})
if (tags.length > 0) return false
const {isClean} = await this.status({directory: dir})
return isClean
}
async isInitialized(params: BaseGitParams): Promise<boolean> {
const dir = this.requireDirectory(params)
return fs.promises
.access(join(dir, '.git'))
.then(() => true)
.catch(() => false)
}
async listBranches(params: ListBranchesGitParams): Promise<GitBranch[]> {
const dir = this.requireDirectory(params)
const current = await this.getCurrentBranch(params)
const branches = await git.listBranches({dir, fs})
const result: GitBranch[] = branches.map((name) => ({isCurrent: name === current, isRemote: false, name}))
if (params.remote) {
try {
const remoteBranches = await git.listBranches({dir, fs, remote: params.remote})
for (const name of remoteBranches) {
if (name === 'HEAD') continue
result.push({isCurrent: false, isRemote: true, name: `${params.remote}/${name}`})
}
} catch {
// No remote configured or no refs fetched yet — return local-only.
// Mirrors `git branch -a`: never auto-fetches, reads cached refs only.
}
}
return result
}
async listRemotes(params: BaseGitParams): Promise<GitRemote[]> {
const dir = this.requireDirectory(params)
const remotes = await git.listRemotes({dir, fs})
return remotes.map((r) => ({remote: r.remote, url: r.url}))
}
async log(params: LogGitParams): Promise<GitCommit[]> {
const dir = this.requireDirectory(params)
try {
const commits = await git.log({depth: params.depth, dir, fs, ref: params.ref})
return commits.map((c) => ({
author: {email: c.commit.author.email, name: c.commit.author.name},
message: c.commit.message.trim(),
sha: c.oid,
timestamp: new Date(c.commit.author.timestamp * 1000),
}))
} catch (error) {
// No commits yet — HEAD ref does not exist
if (error instanceof git.Errors.NotFoundError) return []
throw error
}
}
async merge(params: MergeGitParams): Promise<MergeResult> {
const dir = this.requireDirectory(params)
const mergeHeadPath = join(dir, '.git', 'MERGE_HEAD')
const mergeMsgPath = join(dir, '.git', 'MERGE_MSG')
const author = params.author ?? this.getAuthor()
const message = params.message ?? `Merge branch '${params.branch}'`
const currentBranch = await git.currentBranch({dir, fs})
const localSha = currentBranch
? await git.resolveRef({dir, fs, ref: `refs/heads/${currentBranch}`}).catch(() => null)
: null
try {
const mergeResult = await git.merge({
abortOnConflict: false,
author,
committer: author,
dir,
fs,
message,
theirs: params.branch,
})
if (mergeResult.alreadyMerged) {
return {alreadyUpToDate: true, success: true}
}
// isomorphic-git merge only updates refs — checkout to apply changes to working tree
if (currentBranch) {
await git.checkout({dir, fs, ref: currentBranch})
}
return {success: true}
} catch (error) {
if (error instanceof git.Errors.CheckoutConflictError) {
// Undo the merge commit — restore HEAD to pre-merge state so repo is left clean
if (localSha && currentBranch) {
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${currentBranch}`, value: localSha})
}
throw new GitError('Local changes would be overwritten by merge. Commit or discard your changes first.')
}
if (error instanceof git.Errors.MergeConflictError) {
// isomorphic-git does not write MERGE_HEAD/MERGE_MSG — write them so
// getConflicts() and --continue work post-restart
const theirsOid = await git.resolveRef({dir, fs, ref: params.branch})
await fs.promises.writeFile(mergeHeadPath, `${theirsOid}\n`)
await fs.promises.writeFile(mergeMsgPath, `${message}\n`)
// isomorphic-git uses the branch name as marker label (<<<<<<< main);
// native git uses HEAD — rewrite markers to match git convention
if (currentBranch) {
await this.rewriteConflictMarkers(dir, currentBranch, this.conflictsFromError(error))
}
return {conflicts: this.conflictsFromError(error), success: false}
}
if (error instanceof git.Errors.MergeNotSupportedError) {
if (!params.allowUnrelatedHistories) {
throw new GitError('Refusing to merge unrelated histories. Use --allow-unrelated-histories to force.')
}
const oursRef = (await git.currentBranch({dir, fs})) ?? 'HEAD'
return this.mergeUnrelatedHistories({author, dir, message, oursRef, theirsRef: params.branch})
}
throw error
}
}
async pull(params: PullGitParams): Promise<PullResult> {
const dir = this.requireDirectory(params)
const token = this.requireToken()
const remote = params.remote ?? 'origin'
// Guard: if MERGE_HEAD exists, a previous merge is unresolved — refuse to pull
const hasPendingMerge = await fs.promises
.readFile(join(dir, '.git', 'MERGE_HEAD'), 'utf8')
.then(() => true)
.catch(() => false)
if (hasPendingMerge) {
throw new GitError(
'You have unresolved merge conflicts. Resolve them, stage the files, and commit before pulling again.',
)
}
// Fetch from remote
await git.fetch({
dir,
fs,
headers: this.buildBasicAuthHeaders(token.userId, token.sessionKey),
http,
onAuth: this.getOnAuth(),
onAuthFailure: this.getOnAuthFailure(),
remote,
...(params.branch ? {remoteRef: params.branch} : {}),
})
// Determine which remote-tracking branch to merge
const localBranch = params.branch ?? (await this.getCurrentBranch(params))
if (!localBranch) throw new GitError('Cannot determine branch for pull')
// After fetch, check if already up to date
const localSha = await git.resolveRef({dir, fs, ref: `refs/heads/${localBranch}`}).catch(() => null)
const remoteSha = await git.resolveRef({dir, fs, ref: `refs/remotes/${remote}/${localBranch}`}).catch(() => null)
if (localSha && remoteSha && localSha === remoteSha) {
return {alreadyUpToDate: true, success: true}
}
// Empty local repo — fast-forward HEAD to remote tip (like native git pull on empty repo)
if (!localSha && remoteSha) {
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${localBranch}`, value: remoteSha})
await git.checkout({dir, fs, ref: localBranch})
return {alreadyUpToDate: false, success: true}
}
// Step 2: working tree safety check (isomorphic-git does not do this automatically)
// Abort if any dirty local file would be overwritten by the incoming changes
if (localSha && remoteSha) {
const matrix = await git.statusMatrix({dir, fs})
const dirtyFiles = matrix.filter((row) => row[2] !== 1 || row[3] !== 1).map((row) => String(row[0]))
const localRef = localSha
const remoteRef = remoteSha
const wouldBeOverwritten = await Promise.all(
dirtyFiles.map(async (filepath) => {
const [localFileOid, remoteFileOid] = await Promise.all([
git
.readBlob({dir, filepath, fs, oid: localRef})
.then((r) => r.oid)
.catch(() => null),
git
.readBlob({dir, filepath, fs, oid: remoteRef})
.then((r) => r.oid)
.catch(() => null),
])
return localFileOid !== remoteFileOid
}),
)
if (wouldBeOverwritten.some(Boolean)) {
throw new GitError('Local changes would be overwritten by pull. Commit or discard your changes first.')
}
}
const author = params.author ?? this.getAuthor()
try {
const mergeResult = await git.merge({
abortOnConflict: false,
author,
committer: author,
dir,
fs,
theirs: `${remote}/${localBranch}`,
})
// isomorphic-git merge only updates refs/commits — checkout to apply file changes to workdir.
await git.checkout({dir, fs, ref: localBranch})
return {alreadyUpToDate: mergeResult.alreadyMerged, success: true}
} catch (error) {
if (error instanceof git.Errors.MergeConflictError) {
// isomorphic-git does not write MERGE_HEAD/MERGE_MSG — write them so
// getConflicts() and --continue work post-restart
const theirsOid = await git.resolveRef({dir, fs, ref: `refs/remotes/${remote}/${localBranch}`})
await fs.promises.writeFile(join(dir, '.git', 'MERGE_HEAD'), `${theirsOid}\n`)
await fs.promises.writeFile(
join(dir, '.git', 'MERGE_MSG'),
`Merge remote-tracking branch '${remote}/${localBranch}'\n`,
)
// Rewrite conflict markers: isomorphic-git uses branch name, git uses HEAD
await this.rewriteConflictMarkers(dir, localBranch, this.conflictsFromError(error))
return {conflicts: this.conflictsFromError(error), success: false}
}
if (error instanceof git.Errors.MergeNotSupportedError) {
if (!params.allowUnrelatedHistories) {
throw new GitError('Refusing to merge unrelated histories. Use --allow-unrelated-histories to force.')
}
const result = await this.mergeUnrelatedHistories({
author,
dir,
message: `Merge remote-tracking branch '${remote}/${localBranch}'`,
oursRef: localBranch,
theirsRef: `${remote}/${localBranch}`,
})
if (result.success) {
await git.checkout({dir, fs, ref: localBranch})
}
return result
}
if (error instanceof git.Errors.CheckoutConflictError) {
// Undo the merge commit — restore HEAD to pre-merge state so repo is left clean
if (localSha) {
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${localBranch}`, value: localSha})
}
throw new GitError('Local changes would be overwritten by pull. Commit or discard your changes first.')
}
throw error
}
}
async push(params: PushGitParams): Promise<PushResult> {
const dir = this.requireDirectory(params)
const token = this.requireToken()
try {
const branch = params.branch ?? (await git.currentBranch({dir, fs})) ?? 'main'
const remote = params.remote ?? 'origin'
const localSha = await git.resolveRef({dir, fs, ref: `refs/heads/${branch}`}).catch(() => null)
const remoteSha = await git.resolveRef({dir, fs, ref: `refs/remotes/${remote}/${branch}`}).catch(() => null)
if (localSha && remoteSha && localSha === remoteSha) {
return {alreadyUpToDate: true, success: true}
}
await git.push({
dir,
fs,
headers: this.buildBasicAuthHeaders(token.userId, token.sessionKey),
http,
onAuth: this.getOnAuth(),
onAuthFailure: this.getOnAuthFailure(),
ref: branch,
remote,
})
return {alreadyUpToDate: false, success: true}
} catch (error) {
if (error instanceof git.Errors.PushRejectedError) {
return {message: error.message, reason: 'non_fast_forward', success: false}
}
throw error
}
}
async removeRemote(params: RemoveRemoteGitParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.deleteRemote({dir, fs, remote: params.remote})
}
async reset(params: ResetGitParams): Promise<ResetResult> {
const dir = this.requireDirectory(params)
const mode = params.mode ?? 'mixed'
const ref = params.ref ?? 'HEAD'
// Case 1: Path-scoped unstage — always mixed, ignores mode/ref
if (params.filePaths && params.filePaths.length > 0) {
return this.resetUnstage(dir, params.filePaths)
}
// Case 2: Whole-tree unstage (mixed mode, ref=HEAD, no filePaths)
if (mode === 'mixed' && ref === 'HEAD') {
return this.resetUnstage(dir)
}
// Cases 3-5: Reset to a specific ref (soft/mixed/hard)
// Empty repo (no commits) — HEAD doesn't exist. Git treats this as a silent no-op.
const headExists = await git.resolveRef({dir, fs, ref: 'HEAD'}).then(() => true, () => false)
if (!headExists) {
return {filesChanged: 0, headSha: ''}
}
const targetSha = await this.resolveRefExpression(dir, ref)
const branch = await this.getCurrentBranch(params)
if (!branch) {
throw new GitError('Cannot reset in detached HEAD state.')
}
const previousSha = await git.resolveRef({dir, fs, ref: 'HEAD'})
if (mode === 'soft') {
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${branch}`, value: targetSha})
return {filesChanged: 0, headSha: targetSha}
}
if (mode === 'hard') {
// Snapshot files in current HEAD to detect orphans after reset
const currentFiles = new Set(await git.listFiles({dir, fs, ref: previousSha}))
const targetFiles = new Set(await git.listFiles({dir, fs, ref: targetSha}))
// Move branch pointer
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${branch}`, value: targetSha})
// Restore working tree + index
await git.checkout({dir, force: true, fs, ref: branch})
// Delete orphaned files (tracked in old HEAD but not in target)
for (const filepath of currentFiles) {
if (!targetFiles.has(filepath)) {
// eslint-disable-next-line no-await-in-loop
await fs.promises.unlink(join(dir, filepath)).catch(() => {})
}
}
// Clean up merge state if present
await fs.promises.unlink(join(dir, '.git', 'MERGE_HEAD')).catch(() => {})
await fs.promises.unlink(join(dir, '.git', 'MERGE_MSG')).catch(() => {})
const filesChanged =
[...currentFiles].filter((f) => !targetFiles.has(f)).length +
[...targetFiles].filter((f) => !currentFiles.has(f)).length
return {filesChanged, headSha: targetSha}
}
// mode === 'mixed' with ref !== HEAD
// Move branch pointer, then reset index to match new HEAD (working tree untouched)
await git.writeRef({dir, force: true, fs, ref: `refs/heads/${branch}`, value: targetSha})
// Reset every file in the index to match the target
const targetFiles = await git.listFiles({dir, fs, ref: targetSha})
const matrix = await git.statusMatrix({dir, fs})
const allPaths = new Set<string>([...matrix.map((row) => String(row[0])), ...targetFiles])
await Promise.all([...allPaths].map((filepath) => git.resetIndex({dir, filepath, fs, ref: targetSha})))
return {filesChanged: allPaths.size, headSha: targetSha}
}
async setTrackingBranch(params: SetTrackingBranchParams): Promise<void> {
const dir = this.requireDirectory(params)
await git.setConfig({dir, fs, path: `branch.${params.branch}.remote`, value: params.remote})
await git.setConfig({dir, fs, path: `branch.${params.branch}.merge`, value: `refs/heads/${params.remoteBranch}`})
}
async status(params: BaseGitParams): Promise<GitStatus> {
const dir = this.requireDirectory(params)
const matrix = await git.statusMatrix({dir, fs})
const files = this.parseMatrix(matrix)
return {files, isClean: files.length === 0}
}
private buildBasicAuthHeaders(userId: string, sessionKey: string): Record<string, string> {
const credentials = Buffer.from(`${userId}:${sessionKey}`).toString('base64')
return {Authorization: `Basic ${credentials}`}
}
private conflictsFromError(error: Error): GitConflict[] {
if (!IsomorphicGitService.isConflictError(error)) return []
const conflictData = error.data
if (!IsomorphicGitService.isMergeConflictData(conflictData)) return []
const deletedPaths = new Set([...(conflictData.deleteByTheirs ?? []), ...(conflictData.deleteByUs ?? [])])
const bothModifiedPaths = new Set(conflictData.bothModified ?? [])
return conflictData.filepaths
.map(
(path): GitConflict => ({
path,
type: deletedPaths.has(path)
? 'deleted_modified'
: bothModifiedPaths.has(path)
? 'both_modified'
: 'both_added',
}),
)
.sort((a, b) => a.path.localeCompare(b.path))
}
private getAuthor(): {email: string; name: string} {
const token = this.authStateStore.getToken()
if (!token) throw new GitAuthError()
return {
email: token.userEmail,
name: token.userName ?? token.userEmail,
}
}
private getOnAuth() {
return () => {
const token = this.authStateStore.getToken()
if (!token) throw new GitAuthError()
return {
password: token.sessionKey,
username: token.userId,
}
}
}
private getOnAuthFailure() {
return () => {
throw new GitAuthError('Authentication failed. Try /login again.')
}
}
/**
* Guard against staged changes that would be overwritten by checkout.
* isomorphic-git's checkout only detects unstaged conflicts — it silently
* overwrites staged changes, causing data loss. This method fills that gap
* to match native git behavior.
*/
private async guardStagedConflicts(dir: string, sourceBranch: string, targetRef: string): Promise<void> {
const matrix = await git.statusMatrix({dir, fs})
// Staged files: index (col 3) differs from HEAD (col 1)
// [1,_,2] modified+staged, [1,_,0] deleted+staged, [0,_,2] new+staged
const stagedFiles = matrix.filter(([, head, , stage]) => stage !== head).map(([filepath]) => String(filepath))
if (stagedFiles.length === 0) return
const sourceOid = await git.resolveRef({dir, fs, ref: sourceBranch})
const targetOid = await git.resolveRef({dir, fs, ref: targetRef})
const conflicting: string[] = []
/* eslint-disable no-await-in-loop -- sequential file I/O is intentional here */
for (const filepath of stagedFiles) {
const sourceBlobOid = await this.readBlobOid(dir, sourceOid, filepath)
const targetBlobOid = await this.readBlobOid(dir, targetOid, filepath)
if (sourceBlobOid !== targetBlobOid) {
conflicting.push(filepath)
}
}
/* eslint-enable no-await-in-loop */
if (conflicting.length > 0) {
throw new GitError(
'Your local changes to the following files would be overwritten by checkout:\n' +
conflicting.map((f) => `\t${f}`).join('\n') +
'\nPlease commit your changes or stash them before you switch branches.',
)
}
}
/**
* Manual merge for unrelated histories (no common ancestor).
* isomorphic-git throws MergeNotSupportedError because it can't handle
* base=null at the root tree level. We bypass by combining both trees directly.
*/
private async mergeUnrelatedHistories(params: {
author: {email: string; name: string}
dir: string
message: string
oursRef: string
theirsRef: string
}): Promise<MergeResult> {
const {author, dir, message, oursRef, theirsRef} = params
const mergeHeadPath = join(dir, '.git', 'MERGE_HEAD')
const mergeMsgPath = join(dir, '.git', 'MERGE_MSG')
const oursSha = await git.resolveRef({dir, fs, ref: oursRef})
const theirsSha = await git.resolveRef({dir, fs, ref: theirsRef})
// List all files from both sides
const oursFiles = await git.listFiles({dir, fs, ref: oursSha})
const theirsFiles = await git.listFiles({dir, fs, ref: theirsSha})
const theirsSet = new Set(theirsFiles)
// Detect conflicts: same filepath on both sides with different content
const conflicts: GitConflict[] = []
/* eslint-disable no-await-in-loop -- sequential file I/O is intentional here */
for (const filepath of oursFiles) {
if (!theirsSet.has(filepath)) continue
const oursBlob = await git.readBlob({dir, filepath, fs, oid: oursSha})
const theirsBlob = await git.readBlob({dir, filepath, fs, oid: theirsSha})
if (oursBlob.oid !== theirsBlob.oid) {
conflicts.push({path: filepath, type: 'both_added'})
}
}
/* eslint-enable no-await-in-loop */
if (conflicts.length > 0) {
// Write MERGE_HEAD/MERGE_MSG so --continue works
await fs.promises.writeFile(mergeHeadPath, `${theirsSha}\n`)
await fs.promises.writeFile(mergeMsgPath, `${message}\n`)
// Write conflict markers to working tree for each conflicted file
/* eslint-disable no-await-in-loop -- sequential per-file conflict marker writes */
for (const conflict of conflicts) {
const oursBlob = await git.readBlob({dir, filepath: conflict.path, fs, oid: oursSha})
const theirsBlob = await git.readBlob({dir, filepath: conflict.path, fs, oid: theirsSha})
const oursContent = Buffer.from(oursBlob.blob).toString('utf8')
const theirsContent = Buffer.from(theirsBlob.blob).toString('utf8')
const conflictContent =
`<<<<<<< HEAD\n` +
oursContent +
(oursContent.endsWith('\n') ? '' : '\n') +
`=======\n` +
theirsContent +
(theirsContent.endsWith('\n') ? '' : '\n') +
`>>>>>>> ${theirsRef}\n`
await fs.promises.writeFile(join(dir, conflict.path), conflictContent)
}
/* eslint-enable no-await-in-loop */
return {conflicts, success: false}
}
// No conflicts — write all remote files to working tree and stage them
const oursSet = new Set(oursFiles)
/* eslint-disable no-await-in-loop -- sequential file writes + git add */