Repository navigation
Expand file tree
/
Copy pathgit.ts
More file actions
1609 lines (1521 loc) · 65.6 KB
/
Copy pathgit.ts
File metadata and controls
1609 lines (1521 loc) · 65.6 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
export * as Git from "./git.js"
import os from "os"
import path from "path"
import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Schedule, Schema } from "effect"
import { ChildProcess } from "effect/process"
import { AbsolutePath, RelativePath } from "./schema.js"
import { FSUtil } from "@opencode/util/fs-util"
import { AppProcess } from "@opencode/util/process"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { FileDiff } from "@opencode/schema/file-diff"
import { KeyedMutex } from "./effect/keyed-mutex.js"
import { VcsPatch } from "./vcs/patch.js"
import { gitExecutable } from "./util/git-executable.js"
export class Repository extends Schema.Class<Repository>("Git.Repository")({
worktree: AbsolutePath,
gitDirectory: AbsolutePath,
commonDirectory: AbsolutePath,
}) {}
// Included from $GIT_DIR/config via include.path (git >= 1.7.10); OpenCode owns
// this file entirely, so updates are plain rewrites with no config parsing.
const snapshotConfigFile = "opencode.gitconfig"
const snapshotConfigInclude = `[include]
path = ${snapshotConfigFile}
`
const snapshotConfig = `[core]
autocrlf = false
longpaths = true
symlinks = true
fsmonitor = false
untrackedCache = true
# A split index cannot name its shared file once manyFiles skips index checksums.
splitIndex = false
[feature]
manyFiles = true
[index]
version = 4
threads = true
`
export const TreeID = Schema.String.pipe(Schema.brand("Git.TreeID"))
export type TreeID = typeof TreeID.Type
const temporaryIndexPrefix = "index.opencode-"
// Like `git gc --auto`, pack once loose objects accumulate, and combine packs before lookups slow down.
// Room for paths on one Git command line after the Git path, repository flags, and quoting. Windows caps a command
// line at 32,767 characters. macOS caps arguments plus environment at 1 MiB, and Linux caps them at 2 MiB by default.
const argumentBudget = process.platform === "win32" ? 24_000 : 128 * 1024
const looseObjectLimit = 2048
const packCountLimit = 16
export interface CaptureInput {
readonly repository: Repository
readonly scopes: readonly RelativePath[]
/**
* Source repository whose ignore rules decide which paths are recorded. Its index also
* rebuilds an unreadable snapshot index without rehashing every tracked file.
*/
readonly ignores?: Repository
readonly maximumUntrackedFileBytes?: number
}
export class OperationError extends Schema.TaggedError<OperationError>()("Git.OperationError", {
operation: Schema.Literals([
"clone",
"fetch",
"checkout",
"reset",
"create",
"refresh",
"write_tree",
"list_files",
"diff",
"restore",
"pack",
]),
message: Schema.String,
directory: Schema.optional(AbsolutePath),
cause: Schema.optional(Schema.Defect()),
}) {}
/** Git could not answer: the spawn failed or it exited with an unexpected status. */
export class CommandError extends Schema.TaggedError<CommandError>()("Git.CommandError", {
args: Schema.Array(Schema.String),
exitCode: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
}) {}
export class Worktree extends Schema.Class<Worktree>("Git.Worktree")({
directory: AbsolutePath,
kind: Schema.Literals(["main", "linked"]),
}) {}
export class WorktreeError extends Schema.TaggedError<WorktreeError>()("Git.WorktreeError", {
operation: Schema.Literals(["create", "remove", "list"]),
message: Schema.String,
directory: Schema.optional(AbsolutePath),
forceRequired: Schema.optional(Schema.Boolean),
cause: Schema.optional(Schema.Defect()),
}) {}
export interface Interface {
readonly repo: {
readonly discover: (input: AbsolutePath) => Effect.Effect<Repository | undefined>
/**
* Spawn-free stamp of the metadata that `discover`, `remote.get` and `history.rootCommits`
* read for the `.git` entry at `dotGit`: undefined when it isn't a readable repository.
*/
readonly fingerprint: (dotGit: AbsolutePath) => Effect.Effect<string | undefined>
readonly clone: (input: {
remote: string
directory: AbsolutePath
branch?: string
depth?: number
}) => Effect.Effect<Repository, OperationError>
readonly create: (input: {
worktree: AbsolutePath
gitDirectory: AbsolutePath
seed?: Repository
}) => Effect.Effect<Repository, OperationError>
}
readonly remote: {
/** Undefined when the remote doesn't exist. */
readonly get: (repository: Repository, name?: string) => Effect.Effect<string | undefined, CommandError>
}
readonly history: {
readonly head: (repository: Repository) => Effect.Effect<string | undefined>
readonly branch: (repository: Repository) => Effect.Effect<string | undefined>
readonly defaultRemoteBranch: (repository: Repository, remote?: string) => Effect.Effect<string | undefined>
/** Empty when HEAD is unborn. */
readonly rootCommits: (repository: Repository) => Effect.Effect<readonly string[], CommandError>
}
readonly sync: {
readonly fetchRemotes: (repository: Repository, input?: { prune?: boolean }) => Effect.Effect<void, OperationError>
readonly fetchBranch: (
repository: Repository,
input: { remote?: string; branch: string; force?: boolean },
) => Effect.Effect<void, OperationError>
readonly checkoutRemoteBranch: (
repository: Repository,
input: { remote?: string; branch: string; reset?: boolean },
) => Effect.Effect<void, OperationError>
readonly resetHard: (repository: Repository, revision: string) => Effect.Effect<void, OperationError>
}
readonly worktree: {
readonly create: (input: {
repository: Repository
directory: AbsolutePath
ref?: string
}) => Effect.Effect<Repository, WorktreeError>
readonly remove: (input: {
repository: Repository
directory: AbsolutePath
force: boolean
}) => Effect.Effect<void, WorktreeError>
readonly list: (repository: Repository) => Effect.Effect<readonly Worktree[], WorktreeError>
}
readonly index: {
/** Refresh only the requested project-relative scope, preserving all other entries. */
readonly refresh: (input: {
repository: Repository
scope: RelativePath
ignores?: Repository
maximumUntrackedFileBytes?: number
}) => Effect.Effect<{ readonly skipped: readonly RelativePath[] }, OperationError>
readonly ignored: (input: {
repository: Repository
paths: readonly RelativePath[]
}) => Effect.Effect<ReadonlySet<RelativePath>, OperationError>
}
readonly tree: {
readonly capture: (input: CaptureInput) => Effect.Effect<TreeID, OperationError>
readonly write: (repository: Repository) => Effect.Effect<TreeID, OperationError>
readonly files: (input: {
repository: Repository
from: TreeID
to: TreeID
}) => Effect.Effect<readonly RelativePath[], OperationError>
readonly diff: (input: {
repository: Repository
from: TreeID
to: TreeID
context?: number
paths?: readonly RelativePath[]
}) => Effect.Effect<readonly FileDiff.Info[], OperationError>
readonly restore: (input: {
repository: Repository
files: ReadonlyMap<RelativePath, TreeID>
}) => Effect.Effect<void, OperationError>
}
readonly objects: {
/**
* Pack loose objects and combine small packs without dropping any object,
* reachable or not. Returns without work below the thresholds; safe to run
* concurrently with captures and with other processes.
*/
readonly pack: (repository: Repository) => Effect.Effect<void, OperationError>
}
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Git") {}
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const proc = yield* AppProcess.Service
const locks = KeyedMutex.makeUnsafe<string>()
const locked = <A, E, R>(repository: Repository, effect: Effect.Effect<A, E, R>) =>
locks.withLock(repository.gitDirectory)(effect)
const discover = Effect.fn("Git.repo.discover")(function* (input: AbsolutePath) {
const dotgit = yield* fs.up({ targets: [".git"], start: input, mode: "first" }).pipe(
Effect.map((matches) => matches[0]),
Effect.orElseSucceed(() => undefined),
)
if (!dotgit) return undefined
const cwd = path.dirname(dotgit)
const result = yield* run(cwd, proc, ["rev-parse", "--git-dir", "--git-common-dir", "--show-toplevel"])
const [gitDir, commonDir, topLevel] = result.text.split(/\r?\n/)
if (!gitDir || !commonDir) return undefined
return new Repository({
worktree: AbsolutePath.make(topLevel ? resolvePath(cwd, topLevel) : cwd),
gitDirectory: AbsolutePath.make(resolvePath(cwd, gitDir)),
commonDirectory: AbsolutePath.make(resolvePath(cwd, commonDir)),
})
})
const stamp = (target: string) =>
fs.stat(target).pipe(
Effect.map((info) =>
[info.type, Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(
":",
),
),
Effect.orElseSucceed(() => "missing"),
)
const readText = (target: string) => fs.readFileStringSafe(target).pipe(Effect.orElseSucceed(() => undefined))
// Covers linked worktrees (gitdir file + commondir), HEAD and the ref it points at,
// loose/packed/reftable refs, repository/worktree/global/XDG/system config, and the
// cached `opencode` project id, so external `git init`, a first commit or `git remote`
// edits change the stamp.
const fingerprint = Effect.fn("Git.repo.fingerprint")(function* (dotGit: AbsolutePath) {
const dot = yield* fs.stat(dotGit).pipe(Effect.orElseSucceed(() => undefined))
if (!dot || (dot.type !== "File" && dot.type !== "Directory")) return undefined
const gitFile = dot.type === "File" ? (yield* readText(dotGit))?.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim() : ""
if (gitFile === undefined) return undefined
const gitDir = gitFile ? yield* fs.resolve(path.resolve(path.dirname(dotGit), gitFile)) : dotGit
const commondir = (yield* readText(path.join(gitDir, "commondir")))?.trim()
const commonDir = commondir ? yield* fs.resolve(path.resolve(gitDir, commondir)) : gitDir
const head = (yield* readText(path.join(gitDir, "HEAD")))?.trim()
if (head === undefined) return undefined
const ref = head.startsWith("ref:") ? head.slice(4).trim() : undefined
const home = process.env.HOME || os.homedir()
const nosystem = ["1", "true", "yes", "on"].includes((process.env.GIT_CONFIG_NOSYSTEM ?? "").toLowerCase())
const files = [
path.join(gitDir, "HEAD"),
path.join(commonDir, "config"),
path.join(commonDir, "config.worktree"),
path.join(gitDir, "config.worktree"),
path.join(commonDir, "packed-refs"),
path.join(commonDir, "reftable", "tables.list"),
path.join(commonDir, "opencode"),
...(ref ? [path.join(commonDir, ref), path.join(gitDir, ref)] : []),
process.env.GIT_CONFIG_GLOBAL || path.join(home, ".gitconfig"),
path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "config"),
...(nosystem ? [] : [process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig"]),
]
const stamps = yield* Effect.forEach([dotGit, ...files], stamp, { concurrency: "unbounded" })
return [gitDir, commonDir, head, ...files, ...stamps].join("\0")
})
const command = (cwd: string, args: string[]) =>
execute(cwd, proc, args).pipe(Effect.mapError((cause) => new CommandError({ args, cause })))
const remote = Effect.fn("Git.remote.get")(function* (repository: Repository, name = "origin") {
const args = ["remote", "get-url", name]
const result = yield* command(repository.worktree, args)
// Exit 2: no such remote.
if (result.exitCode === 2) return undefined
if (result.exitCode !== 0) return yield* new CommandError({ args, exitCode: result.exitCode })
return result.text.trim() || undefined
})
const roots = Effect.fn("Git.history.rootCommits")(function* (repository: Repository) {
const args = ["rev-list", "--max-parents=0", "HEAD"]
const result = yield* command(repository.worktree, args)
if (result.exitCode === 0)
return result.text
.split("\n")
.map((item) => item.trim())
.filter(Boolean)
.toSorted()
// `rev-parse -q --verify` exits 1 only when HEAD doesn't resolve, i.e. it is unborn.
const verify = yield* command(repository.worktree, ["rev-parse", "-q", "--verify", "HEAD"])
if (verify.exitCode === 1) return []
return yield* new CommandError({ args, exitCode: result.exitCode })
})
const head = Effect.fn("Git.history.head")(function* (repository: Repository) {
const result = yield* run(repository.worktree, proc, ["rev-parse", "HEAD"])
if (result.exitCode !== 0) return undefined
return result.text.trim() || undefined
})
const branch = Effect.fn("Git.history.branch")(function* (repository: Repository) {
const result = yield* run(repository.worktree, proc, ["symbolic-ref", "--quiet", "--short", "HEAD"])
if (result.exitCode !== 0) return undefined
return result.text.trim() || undefined
})
const remoteHead = Effect.fn("Git.history.defaultRemoteBranch")(function* (
repository: Repository,
remoteName = "origin",
) {
const result = yield* run(repository.worktree, proc, ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`])
if (result.exitCode !== 0) return undefined
return result.text.trim().replace(new RegExp(`^refs/remotes/${remoteName}/`), "") || undefined
})
const operation = Effect.fnUntraced(function* (
operation: OperationError["operation"],
directory: AbsolutePath,
args: string[],
) {
const result = yield* execute(directory, proc, args).pipe(Effect.mapError(spawnFailure(operation, directory)))
if (result.exitCode === 0) return
return yield* commandFailure(operation, directory, result)
})
const clone = Effect.fn("Git.repo.clone")(function* (input: {
remote: string
directory: AbsolutePath
branch?: string
depth?: number
}) {
yield* operation("clone", AbsolutePath.make(path.dirname(input.directory)), [
"clone",
"--depth",
String(input.depth ?? 100),
...(input.branch ? ["--branch", input.branch] : []),
"--",
input.remote,
input.directory,
])
const repository = yield* discover(input.directory)
if (repository) return repository
return yield* new OperationError({
operation: "clone",
directory: input.directory,
message: "Cloned repository could not be opened",
})
})
const fetch = Effect.fn("Git.sync.fetchRemotes")(function* (
repository: Repository,
input: { prune?: boolean } = {},
) {
yield* operation("fetch", repository.worktree, ["fetch", "--all", ...(input.prune === false ? [] : ["--prune"])])
})
const fetchBranch = Effect.fn("Git.sync.fetchBranch")(function* (
repository: Repository,
input: { remote?: string; branch: string; force?: boolean },
) {
const remoteName = input.remote ?? "origin"
const spec = `refs/heads/${input.branch}:refs/remotes/${remoteName}/${input.branch}`
yield* operation("fetch", repository.worktree, ["fetch", remoteName, input.force === false ? spec : `+${spec}`])
})
const checkout = Effect.fn("Git.sync.checkoutRemoteBranch")(function* (
repository: Repository,
input: { remote?: string; branch: string; reset?: boolean },
) {
const remoteName = input.remote ?? "origin"
yield* operation("checkout", repository.worktree, [
"checkout",
...(input.reset === false ? [input.branch] : ["-B", input.branch, `${remoteName}/${input.branch}`]),
])
})
const reset = Effect.fn("Git.sync.resetHard")(function* (repository: Repository, revision: string) {
yield* operation("reset", repository.worktree, ["reset", "--hard", revision])
})
const repositoryArgs = (repository: Repository, args: string[]) => [
"--git-dir",
repository.gitDirectory,
"--work-tree",
repository.worktree,
...args,
]
const repositoryRun = (
operationName: OperationError["operation"],
repository: Repository,
args: string[],
options?: RepositoryOptions,
) =>
proc
.run(
ChildProcess.make(gitExecutable(), repositoryArgs(repository, args), {
cwd: repository.worktree,
env: options?.index ? { ...options.env, GIT_INDEX_FILE: options.index } : options?.env,
extendEnv: true,
}),
{ stdin: options?.stdin, maxOutputBytes: options?.maxOutputBytes },
)
.pipe(Effect.mapError(spawnFailure(operationName, repository.worktree)))
const repositoryOperation = Effect.fnUntraced(function* (
operationName: OperationError["operation"],
repository: Repository,
args: string[],
options?: RepositoryOptions,
) {
const result = yield* repositoryRun(operationName, repository, args, options)
const text = result.stdout.toString("utf8")
const stderr = result.stderr.toString("utf8")
if (result.exitCode === 0) return { text, stderr, truncated: result.stdoutTruncated }
return yield* commandFailure(operationName, repository.worktree, { text, stderr })
})
/**
* On Windows, Git exits non-zero instead of reusing a loose object that another process is finalizing at the
* same moment. Objects are content-addressed, so one of at most two retries finds that copy in place. Only a Git
* exit is retried, never a failure to start Git, and other platforms fail on the first attempt.
*/
const retryConcurrentObjectWrite = <A, R>(effect: Effect.Effect<A, OperationError, R>) =>
process.platform === "win32"
? effect.pipe(
Effect.retry({
times: 2,
schedule: Schedule.spaced("50 millis"),
while: (error) => error.cause === undefined,
}),
)
: effect
/**
* A new store is initialized in a temporary sibling directory and renamed into
* place, so processes racing to create the same store never observe or write a
* half-initialized one; the loser discards its copy and adopts the winner's.
*/
const create = Effect.fn("Git.repo.create")(function* (input: {
worktree: AbsolutePath
gitDirectory: AbsolutePath
seed?: Repository
}) {
const repository = new Repository({
worktree: input.worktree,
gitDirectory: input.gitDirectory,
commonDirectory: input.gitDirectory,
})
if (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD"))) {
yield* initRepository({ ...input, directory: input.gitDirectory })
return repository
}
const temporaryDirectory = AbsolutePath.make(`${input.gitDirectory}.init-${uniqueSuffix()}`)
yield* Effect.gen(function* () {
yield* initRepository({ ...input, directory: temporaryDirectory })
const renamed = yield* fs.rename(temporaryDirectory, input.gitDirectory).pipe(Effect.exit)
if (Exit.isSuccess(renamed) || (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD")))) return
return yield* new OperationError({
operation: "create",
directory: input.gitDirectory,
message: "Failed to move Git storage into place",
cause: Cause.squash(renamed.cause),
})
}).pipe(Effect.ensuring(fs.remove(temporaryDirectory, { recursive: true, force: true }).pipe(Effect.ignore)))
return repository
})
const initRepository = Effect.fnUntraced(function* (input: {
worktree: AbsolutePath
gitDirectory: AbsolutePath
directory: AbsolutePath
seed?: Repository
}) {
const operationError = (message: string) => (cause: unknown) =>
new OperationError({ operation: "create", directory: input.gitDirectory, message, cause })
yield* fs.ensureDir(input.directory).pipe(Effect.mapError(operationError("Failed to create Git storage")))
yield* repositoryOperation(
"create",
new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
["init"],
)
yield* Effect.gen(function* () {
yield* fs.writeFileString(path.join(input.directory, snapshotConfigFile), snapshotConfig)
const config = path.join(input.directory, "config")
const current = yield* fs.readFileString(config)
if (current.includes(snapshotConfigInclude)) return
yield* fs.writeFileString(config, `${current.endsWith("\n") ? "\n" : "\n\n"}${snapshotConfigInclude}`, {
flag: "a",
})
}).pipe(Effect.mapError(operationError("Failed to configure Git storage")))
if (!input.seed) return
yield* fs
.ensureDir(path.join(input.directory, "objects", "info"))
.pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
yield* fs
.writeFileString(
path.join(input.directory, "objects", "info", "alternates"),
path.join(input.seed.commonDirectory, "objects") + "\n",
)
.pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
const index = path.join(input.directory, "index")
yield* seedIndex(
new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
input.seed,
index,
).pipe(
Effect.catch(() => fs.remove(index, { force: true })),
Effect.ignore,
)
})
/**
* Both commands only read the index, so they never take `index.lock`. Two parallel processes beat one combined
* `ls-files -m -o`, whose lstat pass is not threaded like diff-files'.
*/
const listChanges = Effect.fnUntraced(function* (
repository: Repository,
scope: RelativePath,
index?: string,
excludeFrom?: string,
) {
const list = (args: string[]) =>
repositoryOperation("refresh", repository, args, { index }).pipe(
// Embedded repositories are listed as `dir/`; update-index records them as gitlinks.
Effect.map((result) => nuls(result.text).map((file) => RelativePath.make(file.replace(/\/$/, "")))),
)
const [tracked, untracked] = yield* Effect.all(
[
list(["diff-files", "--name-only", "-z", "--", literalPathspec(scope)]),
list([
"ls-files",
"--others",
...(excludeFrom ? [`--exclude-from=${excludeFrom}`] : []),
"--exclude-standard",
"-z",
"--",
literalPathspec(scope),
]),
],
{ concurrency: 2 },
)
return { tracked, untracked }
})
const updateIndex = Effect.fnUntraced(function* (input: {
repository: Repository
changes: { tracked: readonly RelativePath[]; untracked: readonly RelativePath[] }
ignores?: Repository
maximumUntrackedFileBytes?: number
index?: string
excluded?: ReadonlySet<RelativePath>
}) {
const candidates = [...input.changes.tracked, ...input.changes.untracked]
if (!candidates.length) return { skipped: [] }
const excluded =
input.excluded ??
(input.ignores ? yield* ignored({ repository: input.ignores, paths: candidates }) : new Set<RelativePath>())
const maximum = input.maximumUntrackedFileBytes
const skipped = maximum
? (yield* Effect.forEach(
input.changes.untracked.filter((item) => !excluded.has(item)),
(item) =>
fs.stat(path.join(input.repository.worktree, item)).pipe(
Effect.map((info) => (info.type === "File" && Number(info.size) > maximum ? item : undefined)),
Effect.orElseSucceed(() => undefined),
),
{ concurrency: 8 },
)).filter((item): item is RelativePath => item !== undefined)
: []
const skip = new Set(skipped)
const added = candidates.filter((item) => !excluded.has(item) && !skip.has(item))
// Untracked paths are not in the index, so only tracked paths that are now ignored need removing.
const removed = input.changes.tracked.filter((item) => excluded.has(item))
// update-index takes literal paths, so large lists avoid add's quadratic pathspec matching.
if (removed.length)
yield* repositoryOperation("refresh", input.repository, ["update-index", "--force-remove", "-z", "--stdin"], {
stdin: removed.join("\0") + "\0",
index: input.index,
})
// update-index drops a tracked file replaced by an embedded repository; a second line for the same path,
// in the same call, records its gitlink. For a path that already is a gitlink the repeat is a no-op.
const embedded = (yield* Effect.forEach(
input.changes.tracked.filter((item) => !excluded.has(item)),
(item) =>
fs
.existsSafe(path.join(input.repository.worktree, item, ".git"))
.pipe(Effect.map((found) => (found ? item : undefined))),
{ concurrency: 8 },
)).filter((item): item is RelativePath => item !== undefined)
if (added.length)
yield* retryConcurrentObjectWrite(
repositoryOperation(
"refresh",
input.repository,
["update-index", "--add", "--remove", "--replace", "-z", "--stdin"],
{ stdin: [...added, ...embedded].join("\0") + "\0", index: input.index },
),
)
return { skipped }
})
const refresh = Effect.fn("Git.index.refresh")(function* (input: {
repository: Repository
scope: RelativePath
ignores?: Repository
maximumUntrackedFileBytes?: number
}) {
return yield* updateIndex({ ...input, changes: yield* listChanges(input.repository, input.scope) })
})
const ignored = Effect.fn("Git.index.ignored")(function* (input: {
repository: Repository
paths: readonly RelativePath[]
}) {
if (!input.paths.length) return new Set<RelativePath>()
const result = yield* repositoryRun(
"list_files",
input.repository,
["check-ignore", "--no-index", "--stdin", "-z"],
{ stdin: input.paths.join("\0") + "\0" },
)
// Exit 1: none of the paths are ignored.
if (result.exitCode !== 0 && result.exitCode !== 1)
return yield* new OperationError({
operation: "list_files",
directory: input.repository.worktree,
message: result.stderr.toString("utf8").trim() || "Failed to check ignored paths",
})
return new Set(nuls(result.stdout.toString("utf8")).map((file) => RelativePath.make(file)))
})
const writeTree = Effect.fn("Git.tree.write")(function* (repository: Repository, index?: string) {
const tree = (yield* retryConcurrentObjectWrite(
repositoryOperation("write_tree", repository, ["write-tree"], { index }),
)).text.trim()
if (/^[0-9a-f]{40,64}$/.test(tree)) return TreeID.make(tree)
return yield* new OperationError({
operation: "write_tree",
directory: repository.worktree,
message: `Invalid tree ID: ${tree}`,
})
})
const indexFile = (repository: Repository) => path.join(repository.gitDirectory, "index")
/** Git only replaces an index by renaming a new file into place, so every write changes its inode. */
const indexFingerprint = (file: string) =>
fs.stat(file).pipe(
Effect.map((info) =>
[Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(":"),
),
Effect.orElseSucceed(() => undefined),
)
/** A copied index must keep the timestamp Git uses to detect racily clean entries. */
const copyIndex = Effect.fnUntraced(function* (from: string, to: string) {
const info = yield* fs.stat(from)
yield* fs.copyFile(from, to)
const mtime = Option.getOrUndefined(info.mtime)
if (mtime)
yield* fs
.utimes(
to,
Option.getOrElse(info.atime, () => mtime),
mtime,
)
.pipe(Effect.ignore)
})
/**
* Copy the source index into the store. A split index names a shared index file in
* its own Git directory, so those files are linked in just long enough to rewrite the
* copy as a complete index.
*/
const seedIndex = Effect.fnUntraced(function* (store: Repository, source: Repository, target: string) {
yield* copyIndex(path.join(source.gitDirectory, "index"), target)
const shared = (yield* fs.readDirectory(source.gitDirectory)).filter((entry) => entry.startsWith("sharedindex."))
if (shared.length === 0) return
yield* Effect.forEach(shared, (entry) => {
const from = path.join(source.gitDirectory, entry)
const to = path.join(store.gitDirectory, entry)
return fs.link(from, to).pipe(Effect.catch(() => fs.copyFile(from, to)))
}).pipe(
Effect.andThen(repositoryOperation("refresh", store, ["update-index", "--no-split-index"], { index: target })),
Effect.ensuring(
Effect.forEach(shared, (entry) =>
fs.remove(path.join(store.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
),
),
)
})
/**
* Run index writes against a temporary index, then rename it over the store's
* index. Processes never contend on `index.lock`, an interrupted or killed
* writer cannot leave a partial index behind, and a stale lock is irrelevant.
* Git never writes an index in place, it writes a lock file and renames it over
* the temporary name, so a hard-linked temporary index leaves the store's index
* untouched; a copy is the fallback when linking fails. The index is only a stat
* cache over the object store; when writers race, the last rename wins and the
* next capture reconciles against the worktree.
*/
const withTemporaryIndex = <A, E, R>(repository: Repository, use: (index: string) => Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
Effect.gen(function* () {
const current = indexFile(repository)
const index = temporaryIndex(repository)
if (!(yield* fs.existsSafe(current))) return index
const linked = yield* fs.link(current, index).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
)
if (linked) return index
yield* copyIndex(current, index).pipe(
Effect.mapError(
(cause) =>
new OperationError({
operation: "refresh",
directory: repository.gitDirectory,
message: "Failed to prepare a temporary index",
cause,
}),
),
)
return index
}),
(index) =>
Effect.gen(function* () {
const value = yield* use(index)
const installed = yield* Effect.uninterruptible(
Effect.gen(function* () {
// Fingerprint before the rename, so a concurrent writer's index can never be paired with this tree.
const fingerprint = yield* indexFingerprint(index)
const renamed = yield* fs.rename(index, indexFile(repository)).pipe(
// Windows reports a transient sharing violation while another process reads the index.
Effect.retry({ times: 3, schedule: Schedule.spaced("20 millis") }),
Effect.as(true),
Effect.orElseSucceed(() => false),
)
return renamed ? fingerprint : undefined
}),
)
return { value, installed }
}),
(index) => fs.remove(index, { force: true }).pipe(Effect.ignore),
)
// A clean capture returns the tree last written from the exact index it scanned.
const lastCaptures = new Map<string, { readonly fingerprint: string; readonly tree: TreeID }>()
const preparedStores = new Set<string>()
const pendingCaptures = new Map<string, Deferred.Deferred<TreeID, OperationError>>()
// Untracked files skipped for size, by path, with the stamp they had when skipped.
const oversizedFiles = new Map<string, Map<RelativePath, string>>()
/**
* Changes are listed against the temporary index they are written to, never the
* store's index, which another process may replace at any moment. Each tree is
* therefore exactly its own index plus the worktree changes against it.
*/
const attemptCapture = Effect.fnUntraced(function* (input: CaptureInput) {
const sourceExclude = input.ignores ? path.join(input.ignores.commonDirectory, "info", "exclude") : undefined
const excludeFrom = sourceExclude && (yield* fs.existsSafe(sourceExclude)) ? sourceExclude : undefined
const result = yield* withTemporaryIndex(input.repository, (index) =>
Effect.gen(function* () {
const scanned = yield* indexFingerprint(index)
const changes = yield* Effect.forEach(
input.scopes,
(scope) => listChanges(input.repository, scope, index, excludeFrom),
{ concurrency: "unbounded" },
)
const last = lastCaptures.get(input.repository.gitDirectory)
const untracked = changes.flatMap((change) => change.untracked)
const oversized = oversizedFiles.get(input.repository.gitDirectory)
const stillOversized = new Set(
oversized
? (yield* Effect.forEach(
untracked.filter((file) => oversized.has(file)),
(file) =>
oversizedStamp(input, file).pipe(
Effect.map((current) => (current && current === oversized.get(file) ? file : undefined)),
),
{ concurrency: 8 },
)).filter((file): file is RelativePath => file !== undefined)
: [],
)
// Paths the source ignores are listed as untracked on every scan; they leave the index unchanged.
const excluded =
scanned && last?.fingerprint === scanned && changes.every((change) => !change.tracked.length)
? input.ignores
? yield* ignored({
repository: input.ignores,
paths: untracked.filter((file) => !stillOversized.has(file)),
})
: new Set<RelativePath>()
: undefined
if (last && excluded && untracked.every((file) => excluded.has(file) || stillOversized.has(file)))
return last.tree
const skipped = (yield* Effect.forEach(changes, (change) =>
updateIndex({ ...input, changes: change, index, excluded }),
)).flatMap((update) => update.skipped)
oversizedFiles.set(
input.repository.gitDirectory,
new Map(
(yield* Effect.forEach(
skipped,
(file) => oversizedStamp(input, file).pipe(Effect.map((value) => [file, value] as const)),
{ concurrency: 8 },
)).filter((entry): entry is readonly [RelativePath, string] => entry[1] !== undefined),
),
)
return yield* writeTree(input.repository, index)
}),
)
if (result.installed)
lastCaptures.set(input.repository.gitDirectory, { fingerprint: result.installed, tree: result.value })
if (!result.installed) lastCaptures.delete(input.repository.gitDirectory)
return result.value
})
const oversizedStamp = (input: CaptureInput, file: RelativePath) =>
fs.stat(path.join(input.repository.worktree, file)).pipe(
Effect.map((info) =>
input.maximumUntrackedFileBytes && info.type === "File" && Number(info.size) > input.maximumUntrackedFileBytes
? `${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`
: undefined,
),
Effect.orElseSucceed(() => undefined),
)
/**
* Callers queued behind a running capture share the next one, which starts after they all asked, so it still
* sees every change made before each call.
*/
const captureTree = Effect.fn("Git.tree.capture")(function* (input: CaptureInput) {
const key = JSON.stringify([
input.repository.gitDirectory,
input.repository.worktree,
input.scopes,
input.ignores?.gitDirectory,
input.maximumUntrackedFileBytes,
])
const pending = pendingCaptures.get(key)
if (pending) {
const exit = yield* Effect.exit(Deferred.await(pending))
if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) return yield* exit
}
const deferred = Deferred.makeUnsafe<TreeID, OperationError>()
const release = () => {
if (pendingCaptures.get(key) === deferred) pendingCaptures.delete(key)
}
return yield* Effect.uninterruptibleMask((restore) => {
pendingCaptures.set(key, deferred)
return restore(captureLocked(input, release)).pipe(
Effect.onExit((exit) => {
release()
return Deferred.done(deferred, exit)
}),
)
})
})
const captureLocked = (input: CaptureInput, onStart: () => void) =>
locked(
input.repository,
Effect.gen(function* () {
onStart()
if (!preparedStores.has(input.repository.gitDirectory)) {
preparedStores.add(input.repository.gitDirectory)
yield* sweepTemporaryIndexes(input.repository)
yield* ensureSnapshotConfig(input.repository)
}
return yield* attemptCapture(input).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
if (!(yield* isIndexUnreadable(input.repository))) return yield* error
yield* Effect.logWarning("rebuilding unreadable snapshot index", {
directory: input.repository.gitDirectory,
message: error.message,
})
yield* rebuildIndex(input.repository, input.ignores)
return yield* attemptCapture(input)
}),
),
)
}),
)
/**
* Only an index Git itself cannot read is rebuilt, decided by exit status rather
* than by localized messages. Other failures, such as an unreadable worktree
* file or a process that could not start, surface unchanged.
*/
const isIndexUnreadable = Effect.fnUntraced(function* (repository: Repository) {
if (!(yield* fs.existsSafe(indexFile(repository)))) return false
return yield* repositoryOperation("refresh", repository, [
"ls-files",
"-z",
"--",
literalPathspec(".opencode-probe"),
]).pipe(Effect.match({ onSuccess: () => false, onFailure: (error) => error.cause === undefined }))
})
const rebuildIndex = Effect.fnUntraced(function* (repository: Repository, source?: Repository) {
lastCaptures.delete(repository.gitDirectory)
const temporary = temporaryIndex(repository)
// The source's stat cache and cache-tree spare recovery from rehashing every tracked file.
const copied = source
? yield* seedIndex(repository, source, temporary).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
)
: false
yield* (
copied ? fs.rename(temporary, indexFile(repository)) : fs.remove(indexFile(repository), { force: true })
).pipe(Effect.ignore, Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)))
})
// Stores created by earlier releases would otherwise keep their original settings; only OpenCode's include file is rewritten, never `config`.
const ensureSnapshotConfig = Effect.fnUntraced(function* (repository: Repository) {
const file = path.join(repository.gitDirectory, snapshotConfigFile)
const current = yield* fs.readFileStringSafe(file).pipe(Effect.orElseSucceed(() => undefined))
if (current === undefined || current === snapshotConfig) return
// Concurrent Git processes must never read a partially written file.
const temporary = `${file}.${uniqueSuffix()}`
yield* fs
.writeFileString(temporary, snapshotConfig)
.pipe(
Effect.andThen(fs.rename(temporary, file)),
Effect.ignore,
Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)),
)
})
const temporaryIndex = (repository: Repository) =>
path.join(repository.gitDirectory, `${temporaryIndexPrefix}${Date.now()}-${uniqueSuffix()}`)
/**
* Temporary indexes left by killed processes. Age comes from the creation time in
* the name, because a hard-linked index keeps the store index's old mtime; live
* captures finish long before the cutoff.
*/
const sweepTemporaryIndexes = Effect.fnUntraced(function* (repository: Repository) {
const cutoff = Date.now() - 60 * 60 * 1000
const entries = yield* fs.readDirectory(repository.gitDirectory).pipe(Effect.orElseSucceed(() => []))
yield* Effect.forEach(
entries.filter(
(entry) =>
entry.startsWith(temporaryIndexPrefix) &&
Number(entry.slice(temporaryIndexPrefix.length).split("-")[0]) < cutoff,
),
(entry) => fs.remove(path.join(repository.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
{ discard: true },
)
})
const treeFiles = Effect.fn("Git.tree.files")(function* (input: {
repository: Repository
from: TreeID
to: TreeID
}) {
// Undo needs both paths of a rename, not only its destination.
return nuls(
(yield* repositoryOperation("list_files", input.repository, [
"diff",
"--name-only",
"--no-renames",
"-z",
input.from,
input.to,
])).text,
).map((file) => RelativePath.make(file))
})
const treeDiff = Effect.fn("Git.tree.diff")(function* (input: {
repository: Repository
from: TreeID
to: TreeID
context?: number
paths?: readonly RelativePath[]
}) {
if (input.paths?.length === 0) return []
const groups = input.paths ? pathGroups(input.paths) : [undefined]
const diffs: FileDiff.Info[] = []
let patchBudget = VcsPatch.MAX_TOTAL_PATCH_BYTES
for (const paths of groups) {
const group = yield* diffGroup({ ...input, paths }, patchBudget)
diffs.push(...group.diffs)
patchBudget = group.truncated ? 0 : patchBudget - group.patchBytes
}