GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — perf(core): coalesce snapshot captures and skip repeat ignore work (#… · abn/opencode@cdaba26

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src
      • git.ts
    • test
      • git.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/git.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/git.ts
+103-14Lines changed: 103 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ export * as Git from "./git.js"
22

33
import os from "os"
44
import path from "path"
5-
import { Cause, Context, Effect, Exit, Layer, Option, Schedule, Schema } from "effect"
5+
import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Schedule, Schema } from "effect"
66
import { ChildProcess } from "effect/process"
77
import { AbsolutePath, RelativePath } from "./schema.js"
88
import { FSUtil } from "@opencode/util/fs-util"
@@ -531,7 +531,12 @@ const layer = Layer.effect(
531531
* Both commands only read the index, so they never take `index.lock`. Two parallel processes beat one combined
532532
* `ls-files -m -o`, whose lstat pass is not threaded like diff-files'.
533533
*/
534-
const listChanges = Effect.fnUntraced(function* (repository: Repository, scope: RelativePath, index?: string) {
534+
const listChanges = Effect.fnUntraced(function* (
535+
repository: Repository,
536+
scope: RelativePath,
537+
index?: string,
538+
excludeFrom?: string,
539+
) {
535540
const list = (args: string[]) =>
536541
repositoryOperation("refresh", repository, args, { index }).pipe(
537542
// Embedded repositories are listed as `dir/`; update-index records them as gitlinks.
@@ -540,7 +545,15 @@ const layer = Layer.effect(
540545
const [tracked, untracked] = yield* Effect.all(
541546
[
542547
list(["diff-files", "--name-only", "-z", "--", literalPathspec(scope)]),
543-
list(["ls-files", "--others", "--exclude-standard", "-z", "--", literalPathspec(scope)]),
548+
list([
549+
"ls-files",
550+
"--others",
551+
...(excludeFrom ? [`--exclude-from=${excludeFrom}`] : []),
552+
"--exclude-standard",
553+
"-z",
554+
"--",
555+
literalPathspec(scope),
556+
]),
544557
],
545558
{ concurrency: 2 },
546559
)
@@ -745,32 +758,66 @@ const layer = Layer.effect(
745758
// A clean capture returns the tree last written from the exact index it scanned.
746759
const lastCaptures = new Map<string, { readonly fingerprint: string; readonly tree: TreeID }>()
747760
const preparedStores = new Set<string>()
761+
const pendingCaptures = new Map<string, Deferred.Deferred<TreeID, OperationError>>()
762+
// Untracked files skipped for size, by path, with the stamp they had when skipped.
763+
const oversizedFiles = new Map<string, Map<RelativePath, string>>()
748764

749765
/**
750766
* Changes are listed against the temporary index they are written to, never the
751767
* store's index, which another process may replace at any moment. Each tree is
752768
* therefore exactly its own index plus the worktree changes against it.
753769
*/
754770
const attemptCapture = Effect.fnUntraced(function* (input: CaptureInput) {
771+
const sourceExclude = input.ignores ? path.join(input.ignores.commonDirectory, "info", "exclude") : undefined
772+
const excludeFrom = sourceExclude && (yield* fs.existsSafe(sourceExclude)) ? sourceExclude : undefined
755773
const result = yield* withTemporaryIndex(input.repository, (index) =>
756774
Effect.gen(function* () {
757775
const scanned = yield* indexFingerprint(index)
758-
const changes = yield* Effect.forEach(input.scopes, (scope) => listChanges(input.repository, scope, index), {
759-
concurrency: "unbounded",
760-
})
776+
const changes = yield* Effect.forEach(
777+
input.scopes,
778+
(scope) => listChanges(input.repository, scope, index, excludeFrom),
779+
{ concurrency: "unbounded" },
780+
)
761781
const last = lastCaptures.get(input.repository.gitDirectory)
762782
const untracked = changes.flatMap((change) => change.untracked)
783+
const oversized = oversizedFiles.get(input.repository.gitDirectory)
784+
const stillOversized = new Set(
785+
oversized
786+
? (yield* Effect.forEach(
787+
untracked.filter((file) => oversized.has(file)),
788+
(file) =>
789+
oversizedStamp(input, file).pipe(
790+
Effect.map((current) => (current && current === oversized.get(file) ? file : undefined)),
791+
),
792+
{ concurrency: 8 },
793+
)).filter((file): file is RelativePath => file !== undefined)
794+
: [],
795+
)
763796
// Paths the source ignores are listed as untracked on every scan; they leave the index unchanged.
764797
const excluded =
765798
scanned && last?.fingerprint === scanned && changes.every((change) => !change.tracked.length)
766799
? input.ignores
767-
? yield* ignored({ repository: input.ignores, paths: untracked })
800+
? yield* ignored({
801+
repository: input.ignores,
802+
paths: untracked.filter((file) => !stillOversized.has(file)),
803+
})
768804
: new Set<RelativePath>()
769805
: undefined
770-
if (last && excluded && untracked.every((file) => excluded.has(file))) return last.tree
771-
yield* Effect.forEach(changes, (change) => updateIndex({ ...input, changes: change, index, excluded }), {
772-
discard: true,
773-
})
806+
if (last && excluded && untracked.every((file) => excluded.has(file) || stillOversized.has(file)))
807+
return last.tree
808+
const skipped = (yield* Effect.forEach(changes, (change) =>
809+
updateIndex({ ...input, changes: change, index, excluded }),
810+
)).flatMap((update) => update.skipped)
811+
oversizedFiles.set(
812+
input.repository.gitDirectory,
813+
new Map(
814+
(yield* Effect.forEach(
815+
skipped,
816+
(file) => oversizedStamp(input, file).pipe(Effect.map((value) => [file, value] as const)),
817+
{ concurrency: 8 },
818+
)).filter((entry): entry is readonly [RelativePath, string] => entry[1] !== undefined),
819+
),
820+
)
774821
return yield* writeTree(input.repository, index)
775822
}),
776823
)
@@ -780,10 +827,53 @@ const layer = Layer.effect(
780827
return result.value
781828
})
782829

783-
const captureTree = Effect.fn("Git.tree.capture")((input: CaptureInput) =>
830+
const oversizedStamp = (input: CaptureInput, file: RelativePath) =>
831+
fs.stat(path.join(input.repository.worktree, file)).pipe(
832+
Effect.map((info) =>
833+
input.maximumUntrackedFileBytes && info.type === "File" && Number(info.size) > input.maximumUntrackedFileBytes
834+
? `${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`
835+
: undefined,
836+
),
837+
Effect.orElseSucceed(() => undefined),
838+
)
839+
840+
/**
841+
* Callers queued behind a running capture share the next one, which starts after they all asked, so it still
842+
* sees every change made before each call.
843+
*/
844+
const captureTree = Effect.fn("Git.tree.capture")(function* (input: CaptureInput) {
845+
const key = JSON.stringify([
846+
input.repository.gitDirectory,
847+
input.repository.worktree,
848+
input.scopes,
849+
input.ignores?.gitDirectory,
850+
input.maximumUntrackedFileBytes,
851+
])
852+
const pending = pendingCaptures.get(key)
853+
if (pending) {
854+
const exit = yield* Effect.exit(Deferred.await(pending))
855+
if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) return yield* exit
856+
}
857+
const deferred = Deferred.makeUnsafe<TreeID, OperationError>()
858+
const release = () => {
859+
if (pendingCaptures.get(key) === deferred) pendingCaptures.delete(key)
860+
}
861+
return yield* Effect.uninterruptibleMask((restore) => {
862+
pendingCaptures.set(key, deferred)
863+
return restore(captureLocked(input, release)).pipe(
864+
Effect.onExit((exit) => {
865+
release()
866+
return Deferred.done(deferred, exit)
867+
}),
868+
)
869+
})
870+
})
871+
872+
const captureLocked = (input: CaptureInput, onStart: () => void) =>
784873
locked(
785874
input.repository,
786875
Effect.gen(function* () {
876+
onStart()
787877
if (!preparedStores.has(input.repository.gitDirectory)) {
788878
preparedStores.add(input.repository.gitDirectory)
789879
yield* sweepTemporaryIndexes(input.repository)
@@ -803,8 +893,7 @@ const layer = Layer.effect(
803893
),
804894
)
805895
}),
806-
),
807-
)
896+
)
808897

809898
/**
810899
* Only an index Git itself cannot read is rebuilt, decided by exit status rather
Collapse file

‎packages/core/test/git.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/git.test.ts
+68Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { AbsolutePath, RelativePath } from "@opencode/core/schema"
99
import { VcsPatch } from "@opencode/core/vcs/patch"
1010
import { branch, commit, initGit, initRepo, read, withRemote } from "./fixture/git"
1111
import { tmpdir } from "./fixture/tmpdir"
12+
import { withEnv } from "./fixture/env"
1213
import { testEffect } from "./lib/effect"
1314

1415
const it = testEffect(LayerNode.compile(Git.node))
@@ -519,8 +520,75 @@ describe("Git capture", () => {
519520
)
520521
}),
521522
)
523+
524+
it.live("queued captures share one capture that still sees changes made before the call", () =>
525+
Effect.gen(function* () {
526+
const { root, project, repository, service, capture } = yield* captureSetup
527+
const before = yield* capture()
528+
yield* Effect.promise(() => Bun.write(path.join(project, "a.txt"), "changed\n"))
529+
const trace = path.join(root.path, "trace")
530+
const trees = yield* withEnv({ GIT_TRACE: trace }, () =>
531+
Effect.all(Array.from({ length: 4 }, capture), { concurrency: "unbounded" }),
532+
)
533+
expect(new Set(trees).size).toBe(1)
534+
expect(yield* service.tree.files({ repository, from: before, to: trees[0]! })).toEqual([
535+
RelativePath.make("a.txt"),
536+
])
537+
expect((yield* traced(trace)).filter((command) => command === "ls-files").length).toBeLessThanOrEqual(2)
538+
}),
539+
)
540+
541+
it.live("skips repeat ignore checks for oversized and info/exclude-only untracked files", () =>
542+
Effect.gen(function* () {
543+
const { root, project, capture } = yield* captureSetup
544+
yield* Effect.promise(async () => {
545+
await Bun.write(path.join(project, ".git", "info", "exclude"), "excluded.txt\n")
546+
await Bun.write(path.join(project, "excluded.txt"), "x\n")
547+
await Bun.write(path.join(project, "large.txt"), "too large\n")
548+
})
549+
const first = yield* capture({ maximumUntrackedFileBytes: 4 })
550+
const trace = path.join(root.path, "trace")
551+
expect(yield* withEnv({ GIT_TRACE: trace }, () => capture({ maximumUntrackedFileBytes: 4 }))).toBe(first)
552+
expect((yield* traced(trace)).toSorted()).toEqual(["diff-files", "ls-files"])
553+
const entries = yield* Effect.promise(() =>
554+
$`git --git-dir ${root.path}/storage ls-tree --name-only ${first}`.text(),
555+
)
556+
expect(entries.split("\n").filter(Boolean)).toEqual(["a.txt", "b.txt"])
557+
}),
558+
)
559+
})
560+
561+
const captureSetup = Effect.gen(function* () {
562+
const root = yield* Effect.acquireRelease(
563+
Effect.promise(() => tmpdir()),
564+
(dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
565+
)
566+
const project = path.join(root.path, "project")
567+
yield* Effect.promise(async () => {
568+
await fs.mkdir(project)
569+
await initRepo(project)
570+
await Bun.write(path.join(project, "a.txt"), "a\n")
571+
await Bun.write(path.join(project, "b.txt"), "b\n")
572+
await $`git add . && git commit -q -m initial`.cwd(project).quiet()
573+
})
574+
const service = yield* Git.Service
575+
const source = yield* service.repo.discover(AbsolutePath.make(project))
576+
if (!source) throw new Error("Repository not found")
577+
const repository = yield* service.repo.create({
578+
worktree: source.worktree,
579+
gitDirectory: AbsolutePath.make(path.join(root.path, "storage")),
580+
seed: source,
581+
})
582+
const capture = (options?: { maximumUntrackedFileBytes?: number }) =>
583+
service.tree.capture({ repository, scopes: [RelativePath.make(".")], ignores: source, ...options })
584+
return { root, project, repository, service, capture }
522585
})
523586

587+
const traced = (file: string) =>
588+
Effect.promise(async () =>
589+
(await Bun.file(file).text()).split("\n").flatMap((line) => line.match(/trace: built-in: git (\S+)/)?.[1] ?? []),
590+
)
591+
524592
describe("Git capture recovery", () => {
525593
const setup = Effect.gen(function* () {
526594
const root = yield* Effect.acquireRelease(

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.