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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions apps/server/src/git/GitManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,49 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);

it.effect("a branch tracking origin reads origin's URL once per PR lookup", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/origin-once"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/origin-once"]);

const gitConfigReads: string[] = [];
const { manager } = yield* makeManager({
gitConfigReads,
ghScenario: {
prListSequence: [
// Fake gh returns raw JSON stdout, matching the CLI boundary under test.
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 217,
title: "Origin once PR",
url: "https://github.com/pingdotgg/t3code/pull/217",
baseRefName: "main",
headRefName: "feature/origin-once",
state: "OPEN",
updatedAt: "2026-04-03T15:00:00Z",
},
]),
],
},
});

yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature/origin-once" });
gitConfigReads.length = 0;
const pullRequest = yield* manager.branchPullRequest({
cwd: repoDir,
branch: "feature/origin-once",
});

expect(pullRequest?.number).toBe(217);
expect(gitConfigReads.filter((key) => key === "remote.origin.url")).toHaveLength(1);
}),
);

it.effect("turn-end refresh finds a new PR and keeps known PRs cached", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
Expand Down
31 changes: 18 additions & 13 deletions apps/server/src/git/GitManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1398,17 +1398,25 @@ export const make = Effect.gen(function* () {
};
});

// Returns [head remote, origin]. Most branches track origin, so read it once.
const resolveHeadAndOriginContexts = (cwd: string, remoteName: string | null) =>
remoteName === "origin"
? resolveRemoteRepositoryContext(cwd, "origin").pipe(
Effect.map((origin) => [origin, origin] as const),
)
: Effect.all(
[
resolveRemoteRepositoryContext(cwd, remoteName),
resolveRemoteRepositoryContext(cwd, "origin"),
],
{ concurrency: "unbounded" },
);

const resolvePrLookupRepositoryIdentity = Effect.fn("resolvePrLookupRepositoryIdentity")(
function* (cwd: string, branch: string, remoteNameOverride?: string) {
const remoteName =
remoteNameOverride ?? (yield* readConfigValueNullable(cwd, `branch.${branch}.remote`));
const [headRemote, targetRemote] = yield* Effect.all(
[
resolveRemoteRepositoryContext(cwd, remoteName),
resolveRemoteRepositoryContext(cwd, "origin"),
],
{ concurrency: "unbounded" },
);
const [headRemote, targetRemote] = yield* resolveHeadAndOriginContexts(cwd, remoteName);
return {
remoteName,
headRemoteUrlKey:
Expand All @@ -1432,12 +1440,9 @@ export const make = Effect.gen(function* () {
const shouldProbeLocalBranchSelector =
headBranchFromUpstream.length === 0 || headBranch === details.branch;

const [remoteRepository, originRepository] = yield* Effect.all(
[
resolveRemoteRepositoryContext(cwd, remoteName),
resolveRemoteRepositoryContext(cwd, "origin"),
],
{ concurrency: "unbounded" },
const [remoteRepository, originRepository] = yield* resolveHeadAndOriginContexts(
cwd,
remoteName,
);

const isCrossRepository =
Expand Down
196 changes: 126 additions & 70 deletions apps/server/src/vcs/VcsDriverRegistry.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { ChildProcessSpawner } from "effect/process";

import * as VcsProcess from "./VcsProcess.ts";
Expand Down Expand Up @@ -43,9 +45,10 @@ describe("VcsDriverRegistry", () => {
}).pipe(Effect.provide(layer));
});

it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
const calls: VcsProcess.VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(
// Answers detection like git: the nearest folder at or above the cwd, up to
// `rootDir`, that holds `.git` is the repository.
const makeDiskBackedLayer = (rootDir: string, calls: string[]) =>
Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(
Layer.provide(NodeServices.layer),
Layer.provide(
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
Expand All @@ -55,86 +58,139 @@ describe("VcsDriverRegistry", () => {
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const normalizedArgs =
input.args[0] === "-C" && input.args.length >= 2 ? input.args.slice(2) : input.args;
const command = normalizedArgs.join(" ");
if (command === "rev-parse --is-inside-work-tree") {
return processOutput("true\n");
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const command = normalizeGitArgs(input.args).join(" ");
calls.push(command);
let repoDir: string | null = input.cwd;
while (repoDir !== null && !(yield* fs.exists(path.join(repoDir, ".git")))) {
repoDir = repoDir === rootDir ? null : path.dirname(repoDir);
}
if (command === "rev-parse --show-toplevel") {
return processOutput("/repo\n");
if (repoDir === null) {
return {
...processOutput(""),
exitCode: ChildProcessSpawner.ExitCode(128),
stderr: "fatal: not a git repository",
};
}
if (command === "rev-parse --is-inside-work-tree") return processOutput("true\n");
if (command === "rev-parse --show-toplevel") return processOutput(`${repoDir}\n`);
if (command === "rev-parse --git-common-dir") {
return processOutput("/repo/.git\n");
return processOutput(`${path.relative(input.cwd, path.join(repoDir, ".git"))}\n`);
}
return processOutput("");
}),
}).pipe(Effect.provide(NodeServices.layer), Effect.orDie),
}),
),
);

return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const first = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
const second = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });

assert.equal(first.repository.rootPath, "/repo");
assert.equal(second.repository.rootPath, "/repo");
assert.deepStrictEqual(
calls.map((call) => normalizeGitArgs(call.args).join(" ")),
[
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });
yield* fs.makeDirectory(path.join(repoDir, ".git"));
const calls: string[] = [];

yield* Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const first = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" });
const second = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" });

assert.equal(first.repository.rootPath, repoDir);
assert.equal(second.repository.rootPath, repoDir);
assert.deepStrictEqual(calls, [
"rev-parse --is-inside-work-tree",
"rev-parse --show-toplevel",
"rev-parse --git-common-dir",
],
);
}).pipe(Effect.provide(layer));
});
]);
}).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect("detects a repository created after a negative lookup", () => {
let insideWorkTreeChecks = 0;
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(
Layer.provide(NodeServices.layer),
Layer.provide(
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
const command = normalizeGitArgs(input.args).join(" ");
if (command === "rev-parse --is-inside-work-tree") {
insideWorkTreeChecks += 1;
return insideWorkTreeChecks === 1
? {
...processOutput(""),
exitCode: ChildProcessSpawner.ExitCode(128),
stderr: "fatal: not a git repository",
}
: processOutput("true\n");
}
if (command === "rev-parse --show-toplevel") {
return processOutput("/repo\n");
}
if (command === "rev-parse --git-common-dir") {
return processOutput("/repo/.git\n");
}
return processOutput("");
}),
}),
),
);
it.effect("detects again when a cached repository is removed from disk", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });
yield* fs.makeDirectory(path.join(repoDir, ".git"));
const calls: string[] = [];

return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
yield* Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
assert.equal((yield* registry.detect({ cwd: repoDir }))?.repository.rootPath, repoDir);

assert.equal(yield* registry.detect({ cwd: "/repo" }), null);
assert.equal((yield* registry.detect({ cwd: "/repo" }))?.repository.rootPath, "/repo");
assert.equal(insideWorkTreeChecks, 2);
}).pipe(Effect.provide(layer));
});
yield* fs.remove(path.join(repoDir, ".git"), { recursive: true });

assert.equal(yield* registry.detect({ cwd: repoDir }), null);
assert.equal(calls.filter((call) => call === "rev-parse --is-inside-work-tree").length, 2);
}).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect("detects again when git init creates a repository inside a cached one", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });
const projectDir = path.join(parentDir, "project");
yield* fs.makeDirectory(path.join(parentDir, ".git"));
yield* fs.makeDirectory(projectDir);
const calls: string[] = [];

yield* Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
assert.equal((yield* registry.detect({ cwd: projectDir }))?.repository.rootPath, parentDir);

yield* fs.makeDirectory(path.join(projectDir, ".git"));

assert.equal(
(yield* registry.detect({ cwd: projectDir }))?.repository.rootPath,
projectDir,
);
}).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls)));
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect("detects again when git init creates a repository between the cwd and its root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });
const middleDir = path.join(parentDir, "a");
const cwd = path.join(middleDir, "b");
yield* fs.makeDirectory(path.join(parentDir, ".git"));
yield* fs.makeDirectory(cwd, { recursive: true });
const calls: string[] = [];

yield* Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, parentDir);

yield* fs.makeDirectory(path.join(middleDir, ".git"));

assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, middleDir);
}).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls)));
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect("detects a repository created after a negative lookup", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });
const calls: string[] = [];

yield* Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
assert.equal(yield* registry.detect({ cwd: repoDir }), null);

yield* fs.makeDirectory(path.join(repoDir, ".git"));

assert.equal((yield* registry.detect({ cwd: repoDir }))?.repository.rootPath, repoDir);
assert.equal(calls.filter((call) => call === "rev-parse --is-inside-work-tree").length, 2);
}).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));
}).pipe(Effect.provide(NodeServices.layer)),
);
});
Loading
Loading