The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
refactor(server): route git config through one env helper and end option parsing before names (#20440)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 23:46 UTC
73d70a444b70c735d990252b453d9b7a4ca63e17
22 files changed
+672
-86
apps/server/src/git/GitManager.test.ts
+14
-6
@@ -1584,7 +1584,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1584
yield* runGit(repoDir, ["push", "-u", "upstream", "main"]);
1585
yield* runGit(repoDir, ["checkout", "-b", "develop"]);
1586
yield* runGit(repoDir, ["push", "-u", "upstream", "develop"]);
1587
- yield* runGit(remoteDir, ["symbolic-ref", "HEAD", "refs/heads/develop"]);
1587
+ yield* runGit(remoteDir, ["--git-dir=.", "symbolic-ref", "HEAD", "refs/heads/develop"]);
1588
yield* runGit(repoDir, ["remote", "set-head", "upstream", "develop"]);
1589
1590
const { manager } = yield* makeManager({
@@ -4198,9 +4198,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4198
),
4199
).toContain("?? .vercel/");
4200
expect(
4201
- yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
4202
- Effect.map((output) => output.stdout.trim()),
4203
- ),
4201
+ yield* runGit(remoteDir, [
4202
+ "--git-dir=.",
4203
+ "log",
4204
+ "-1",
4205
+ "--pretty=%s",
4206
+ "feature/push-dirty",
4207
+ ]).pipe(Effect.map((output) => output.stdout.trim())),
4208
).toBe("Push dirty branch");
4209
}),
4210
);
@@ -4249,7 +4253,11 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4253
expect(result.pr.number).toBe(303);
4254
expect((yield* runGit(repoDir, ["status", "--porcelain"])).stdout).toBe(statusBefore);
4255
expect(
4252
- (yield* runGit(remoteDir, ["rev-parse", "feature/create-pr-only"])).stdout.trim(),
4256
+ (yield* runGit(remoteDir, [
4257
+ "--git-dir=.",
4258
+ "rev-parse",
4259
+ "feature/create-pr-only",
4260
+ ])).stdout.trim(),
4261
).toBe(headBefore);
4262
expect(
4263
ghCalls.some((call) =>
@@ -5009,7 +5017,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5017
const remoteDir = yield* createBareRemote();
5018
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5019
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
5012
- yield* runGit(remoteDir, ["symbolic-ref", "HEAD", "refs/heads/main"]);
5020
+ yield* runGit(remoteDir, ["--git-dir=.", "symbolic-ref", "HEAD", "refs/heads/main"]);
5021
5022
const peerDir = yield* makeTempDir("t3code-git-peer-");
5023
yield* runGit(peerDir, ["clone", remoteDir, "."]);
apps/server/src/project/RepositoryIdentityResolver.ts
+4
@@ -11,6 +11,8 @@ import * as Exit from "effect/Exit";
11
import * as Layer from "effect/Layer";
12
13
import * as ProcessRunner from "../processRunner.ts";
14
+import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
15
+import * as HostProcess from "@t3tools/shared/HostProcess";
16
17
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
18
// Background sweeps resolve every project each minute. A long TTL keeps them
@@ -124,6 +126,7 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.
126
.run({
127
command: "git",
128
args: ["-C", cwd, "rev-parse", "--show-toplevel"],
129
+ env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
130
timeoutBehavior: "timedOutResult",
131
})
132
.pipe(Effect.option);
@@ -146,6 +149,7 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn(
149
.run({
150
command: "git",
151
args: ["-C", cacheKey, "remote", "-v"],
152
+ env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
153
timeoutBehavior: "timedOutResult",
154
})
155
.pipe(Effect.option);
apps/server/src/pullRequest/PullRequestReviewGuideService.ts
+1
-1
@@ -158,7 +158,7 @@ const make = Effect.gen(function* () {
158
git.execute({
159
operation: "PullRequestReviewGuideService.fetch",
160
cwd: workspaceRoot,
161
- args: ["fetch", "--quiet", "--no-tags", remote, ...args],
161
+ args: ["fetch", "--quiet", "--no-tags", "--", remote, ...args],
162
timeoutMs: 5 * 60_000,
163
});
164
// The host names the base branch. A name git rejects, or one that would change the refspec
apps/server/src/pullRequest/PullRequestService.test.ts
+120
@@ -7714,3 +7714,123 @@ it.effect.each([
7714
assert.deepStrictEqual(calls, [expected]);
7715
}),
7716
);
7717
+
7718
+it.effect("expands only files the change request changes, across every slice of its diff", () =>
7719
+ Effect.gen(function* () {
7720
+ const read: Array<string> = [];
7721
+ const service = yield* makeService({
7722
+ projects: [
7723
+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
7724
+ ],
7725
+ providers: [
7726
+ fakeProvider(SourceControlProviderKind.make("github"), {
7727
+ getDiff: (input) =>
7728
+ Effect.succeed(
7729
+ input.cursor === undefined
7730
+ ? {
7731
+ patch: [
7732
+ "diff --git a/src/old.ts b/src/new.ts",
7733
+ "rename from src/old.ts",
7734
+ "rename to src/new.ts",
7735
+ "--- a/src/old.ts",
7736
+ "+++ b/src/new.ts",
7737
+ "",
7738
+ ].join("\n"),
7739
+ truncated: false,
7740
+ nextCursor: "2",
7741
+ }
7742
+ : {
7743
+ patch: [
7744
+ "diff --git a/gone.md b/gone.md",
7745
+ "deleted file mode 100644",
7746
+ "--- a/gone.md",
7747
+ "+++ /dev/null",
7748
+ "",
7749
+ ].join("\n"),
7750
+ truncated: false,
7751
+ nextCursor: null,
7752
+ },
7753
+ ),
7754
+ getDiffFileContents: (input) =>
7755
+ Effect.sync(() => {
7756
+ read.push(`${input.oldPath}->${input.newPath}`);
7757
+ return { oldContents: "old", newContents: "new" };
7758
+ }),
7759
+ }),
7760
+ ],
7761
+ });
7762
+ const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
7763
+
7764
+ yield* service.diffFileContents({
7765
+ ...ref,
7766
+ changeType: "rename-changed",
7767
+ oldPath: "src/old.ts",
7768
+ newPath: "src/new.ts",
7769
+ });
7770
+ yield* service.diffFileContents({
7771
+ ...ref,
7772
+ changeType: "deleted",
7773
+ oldPath: "gone.md",
7774
+ newPath: "gone.md",
7775
+ });
7776
+ const outside = yield* service
7777
+ .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" })
7778
+ .pipe(Effect.flip);
7779
+ const halfRename = yield* service
7780
+ .diffFileContents({
7781
+ ...ref,
7782
+ changeType: "change",
7783
+ oldPath: "src/secret.ts",
7784
+ newPath: "src/new.ts",
7785
+ })
7786
+ .pipe(Effect.flip);
7787
+
7788
+ assert.strictEqual(outside._tag, "PullRequestOperationError");
7789
+ assert.strictEqual(halfRename._tag, "PullRequestOperationError");
7790
+ assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]);
7791
+ }),
7792
+);
7793
+
7794
+it.effect("checks expanded files against a diff too large to cache without fetching it again", () =>
7795
+ Effect.gen(function* () {
7796
+ let diffReads = 0;
7797
+ const filler = `+${"x".repeat(300 * 1024)}`;
7798
+ const service = yield* makeService({
7799
+ projects: [
7800
+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
7801
+ ],
7802
+ providers: [
7803
+ fakeProvider(SourceControlProviderKind.make("github"), {
7804
+ getDiff: () =>
7805
+ Effect.sync(() => {
7806
+ diffReads += 1;
7807
+ return {
7808
+ patch: ["a.ts", "b.ts"]
7809
+ .flatMap((name) => [
7810
+ `diff --git a/${name} b/${name}`,
7811
+ `--- a/${name}`,
7812
+ `+++ b/${name}`,
7813
+ "@@ -0,0 +1 @@",
7814
+ filler,
7815
+ ])
7816
+ .join("\n"),
7817
+ truncated: false,
7818
+ nextCursor: null,
7819
+ };
7820
+ }),
7821
+ getDiffFileContents: () => Effect.succeed({ oldContents: "old", newContents: "new" }),
7822
+ }),
7823
+ ],
7824
+ });
7825
+ const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
7826
+ for (const name of ["a.ts", "b.ts"]) {
7827
+ yield* service.diffFileContents({
7828
+ ...ref,
7829
+ changeType: "change",
7830
+ oldPath: name,
7831
+ newPath: name,
7832
+ });
7833
+ }
7834
+ assert.strictEqual(diffReads, 1);
7835
+ }),
7836
+);
apps/server/src/pullRequest/PullRequestService.ts
+87
-1
@@ -4,6 +4,7 @@ import {
4
sourceControlRepositorySelector,
5
} from "@t3tools/shared/sourceControl";
6
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
7
+import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions";
8
import * as Cache from "effect/Cache";
9
import * as Cause from "effect/Cause";
10
import * as Clock from "effect/Clock";
@@ -1717,7 +1718,7 @@ export const make = Effect.gen(function* () {
1718
),
1719
);
1720
1720
- const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) =>
1721
+ const readDiffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) =>
1722
requireProject(input).pipe(
1723
Effect.flatMap((project) => {
1724
const read = project.api.getDiffFileContents;
@@ -3248,6 +3249,91 @@ export const make = Effect.gen(function* () {
3249
);
3250
});
3251
3252
+ /**
3253
+ * The file names in each diff slice, keyed as the slice is. Names stay small when a patch is too
3254
+ * large to cache, so expanding a file in a large change request does not fetch its diff again.
3255
+ */
3256
+ const diffFiles = (() => {
3257
+ const held = new Map<
3258
+ string,
3259
+ {
3260
+ readonly at: number;
3261
+ readonly files: ReadonlySet<string>;
3262
+ readonly nextCursor: string | null;
3263
+ }
3264
+ >();
3265
+ const ttlMs = Duration.toMillis(DIFF_CACHE_TTL);
3266
+ const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);
3267
+ const sliceKey = (input: PullRequestDiffInput) =>
3268
+ JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);
3269
+ const read = (input: PullRequestDiffInput) =>
3270
+ Effect.gen(function* () {
3271
+ const key = sliceKey(input);
3272
+ const now = yield* Clock.currentTimeMillis;
3273
+ const cached = held.get(key);
3274
+ if (cached !== undefined && now - cached.at <= ttlMs) return cached;
3275
+ const slice = yield* diff(input);
3276
+ const entry = {
3277
+ at: now,
3278
+ files: new Set(
3279
+ parseDiffFilePaths(slice.patch).map((file) =>
3280
+ fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
3281
+ ),
3282
+ ),
3283
+ nextCursor: slice.nextCursor,
3284
+ };
3285
+ held.delete(key);
3286
+ if (held.size >= DIFF_CACHE_CAPACITY) {
3287
+ const oldest = held.keys().next().value;
3288
+ if (oldest !== undefined) held.delete(oldest);
3289
+ }
3290
+ held.set(key, entry);
3291
+ return entry;
3292
+ });
3293
+ return { read: credentialCached(read), fileKey };
3294
+ })();
3295
+ /**
3296
+ * Whether the change request, or the one commit asked for, changes this file under these names.
3297
+ * Walks the same slices the reader was shown, reading only their file names once held.
3298
+ */
3299
+ const changesFile = (input: PullRequestDiffFileContentsInput) => {
3300
+ const wanted = diffFiles.fileKey(input.oldPath, input.newPath);
3301
+ const walk = (cursor: string | undefined): Effect.Effect<boolean, PullRequestError> =>
3302
+ diffFiles
3303
+ .read({
3304
+ ...input,
3305
+ ...(cursor === undefined ? {} : { cursor }),
3306
+ ...(input.commit === undefined ? {} : { commit: input.commit }),
3307
+ })
3308
+ .pipe(
3309
+ Effect.flatMap((slice) =>
3310
+ slice.files.has(wanted)
3311
+ ? Effect.succeed(true)
3312
+ : slice.nextCursor === null
3313
+ ? Effect.succeed(false)
3314
+ : walk(slice.nextCursor),
3315
+ ),
3316
+ );
3317
+ return walk(undefined);
3318
+ };
3319
+ // Only the files the change request itself changes: these are read with the project's own
3320
+ // credential, and a reader who may look at the change request may not thereby read the rest of
3321
+ // the repository.
3322
+ const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) =>
3323
+ changesFile(input).pipe(
3324
+ Effect.flatMap((changed) =>
3325
+ changed
3326
+ ? readDiffFileContents(input)
3327
+ : Effect.fail(
3328
+ new PullRequestOperationError({
3329
+ operation: "diffFileContents",
3330
+ detail: "This file is not part of the change request.",
3331
+ reason: "not-found",
3332
+ }),
3333
+ ),
3334
+ ),
3335
+ );
3336
+
3337
return PullRequestService.of({
3338
routing,
3339
routingIdentity,
apps/server/src/sourceControl/githubStackRebase.test.ts
+2
-2
@@ -64,11 +64,11 @@ const setup = Effect.gen(function* () {
64
yield* git(work, "add", "-A");
65
yield* git(work, "commit", "--quiet", "-m", "Docs");
66
yield* git(work, "push", "--quiet", "origin", "main", "feat/answer-42", "feat/answer-doc");
67
- const head = (branch: string) => git(remote, "rev-parse", `refs/heads/${branch}`);
67
+ const head = (branch: string) => git(remote, "--git-dir=.", "rev-parse", `refs/heads/${branch}`);
68
return {
69
remote,
70
head,
71
- git: (...args: string[]) => git(remote, ...args),
71
+ git: (...args: string[]) => git(remote, "--git-dir=.", ...args),
72
layers: [
73
{ number: 1, headBranch: "feat/answer-42", headSha: yield* head("feat/answer-42") },
74
{ number: 2, headBranch: "feat/answer-doc", headSha: yield* head("feat/answer-doc") },
apps/server/src/storageCleanup.ts
+1
-1
@@ -835,7 +835,7 @@ const make = Effect.gen(function* () {
835
yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
836
yield* cleanupGit(
837
project.workspaceRoot,
838
- ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", worktreePath],
838
+ ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath],
839
"git worktree remove",
840
);
841
entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
apps/server/src/vcs/GitVcsDriverCore.test.ts
+179
-11
@@ -38,6 +38,7 @@ import {
38
windowsLongPathConfigEnv,
39
} from "./GitVcsDriverCore.ts";
40
import * as GitVcsDriver from "./GitVcsDriver.ts";
41
+import { gitConfigEnv } from "./VcsProcess.ts";
42
43
const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
44
@@ -643,7 +644,7 @@ it.effect("invalidates a ref snapshot when a mutation fails after changing Git",
644
if (!ChildProcess.isStandardCommand(command)) {
645
return yield* Effect.die("expected a standard Git command");
646
}
646
- if (command.args[0] === "branch" && command.args[1] === "feature/partial-failure") {
647
+ if (command.args[0] === "branch" && command.args.at(-1) === "feature/partial-failure") {
648
const handle = yield* delegate.spawn(command);
649
yield* handle.exitCode;
650
return makeNonRepositoryHandle();
@@ -1037,7 +1038,7 @@ it.effect.each([
1038
if (!ChildProcess.isStandardCommand(command))
1039
return yield* Effect.die("expected Git command");
1040
if (command.args[0] !== "fetch") return makeNonRepositoryHandle();
1040
- assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);
1041
+ assert.deepEqual(command.args, ["fetch", "--quiet", "--", "origin"]);
1042
assert.equal(command.options.env?.LC_ALL, "C");
1043
assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");
1044
yield* Ref.update(attempts, (count) => count + 1);
@@ -1517,7 +1518,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1518
_tag: "GitCommandError",
1519
operation: "GitVcsDriver.removeWorktree",
1520
command: "git",
1520
- argumentCount: 5,
1521
+ argumentCount: 6,
1522
cwd,
1523
});
1524
assert.notProperty(error, "cause");
@@ -2118,6 +2119,26 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2119
}),
2120
);
2121
2122
+ it.effect("reads a base ref that looks like an option as a revision", () =>
2123
+ Effect.gen(function* () {
2124
+ const cwd = yield* makeTmpDir();
2125
+ yield* initRepoWithCommit(cwd);
2126
+ const driver = yield* GitVcsDriver.GitVcsDriver;
2127
+ const fileSystem = yield* FileSystem.FileSystem;
2128
+ const output = (yield* Path.Path).join(yield* makeTmpDir(), "out");
2129
+
2130
+ yield* driver
2131
+ .getReviewDiffFileContents(
2132
+ makeReviewDiffFileContentsInput(cwd, { baseRef: `--output=${output}` }),
2133
+ )
2134
+ .pipe(Effect.flip);
2135
+ yield* driver.readRangeContext(cwd, `--output=${output}`).pipe(Effect.flip);
2136
+
2137
+ assert.isFalse(yield* fileSystem.exists(`${output}:README.md`));
2138
+ assert.isFalse(yield* fileSystem.exists(`${output}..HEAD`));
2139
+ }),
2140
+ );
2141
+
2142
it.effect("attributes working-tree filesystem failures to the failing operation", () =>
2143
Effect.gen(function* () {
2144
const cwd = yield* makeTmpDir();
@@ -2371,6 +2392,30 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2392
});
2393
2394
describe("repository status", () => {
2395
+ it.effect("does not open a project folder laid out as a bare repository", () =>
2396
+ Effect.gen(function* () {
2397
+ const cwd = yield* makeTmpDir();
2398
+ yield* initRepoWithCommit(cwd);
2399
+ const driver = yield* GitVcsDriver.GitVcsDriver;
2400
+ const fileSystem = yield* FileSystem.FileSystem;
2401
+ const pathService = yield* Path.Path;
2402
+ // Plain files a project save or a clone can hold. Git discovers them as a bare repository.
2403
+ const planted = pathService.join(cwd, "planted");
2404
+ yield* writeTextFile(planted, "HEAD", "ref: refs/heads/main\n");
2405
+ yield* writeTextFile(planted, "objects/info/keep", "");
2406
+ yield* writeTextFile(planted, "refs/heads/keep", "");
2407
+ yield* writeTextFile(
2408
+ planted,
2409
+ "config",
2410
+ '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
2411
+ );
2412
+
2413
+ yield* Effect.exit(driver.statusDetailsLocal(planted));
2414
+ assert.isFalse(yield* fileSystem.exists(pathService.join(planted, "fsmonitor-runs")));
2415
+ assert.isTrue((yield* driver.statusDetailsLocal(cwd)).isRepo);
2416
+ }),
2417
+ );
2418
+
2419
it.effect("reads Changes totals with untracked files when requested", () =>
2420
Effect.gen(function* () {
2421
const cwd = yield* makeTmpDir();
@@ -2947,6 +2992,71 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2992
}),
2993
);
2994
2995
+ it.effect("treats ref names that look like options as ref names", () =>
2996
+ Effect.gen(function* () {
2997
+ const cwd = yield* makeTmpDir();
2998
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
2999
+ const driver = yield* GitVcsDriver.GitVcsDriver;
3000
+ const fileSystem = yield* FileSystem.FileSystem;
3001
+ const pathService = yield* Path.Path;
3002
+ const remote = yield* makeTmpDir("git-remote-");
3003
+ yield* git(remote, ["init", "--bare"]);
3004
+ yield* git(cwd, ["remote", "add", "origin", remote]);
3005
+ yield* git(cwd, ["push", "origin", "HEAD:refs/heads/feature", "HEAD:refs/heads/-M"]);
3006
+ // Git refuses such branch names, but update-ref writes them, here tracking origin/feature.
3007
+ yield* git(cwd, ["update-ref", "refs/heads/-f", "HEAD"]);
3008
+ yield* git(cwd, ["config", "branch.-f.remote", "origin"]);
3009
+ yield* git(cwd, ["config", "branch.-f.merge", "refs/heads/feature"]);
3010
+ yield* git(cwd, ["branch", "keep"]);
3011
+ yield* writeTextFile(cwd, "README.md", "uncommitted work\n");
3012
+ const branches = yield* driver.listLocalBranchNames(cwd);
3013
+ const worktrees = yield* makeTmpDir("git-worktrees-");
3014
+
3015
+ yield* driver.switchRef({ cwd, refName: "-f" }).pipe(Effect.flip);
3016
+ yield* driver.switchRef({ cwd, refName: "origin/feature" }).pipe(Effect.flip);
3017
+ yield* driver.createRef({ cwd, refName: "--list" }).pipe(Effect.flip);
3018
+ for (const [refName, newRefName] of [
3019
+ ["--detach", undefined],
3020
+ ["-M", undefined],
3021
+ ["-M", "renamed"],
3022
+ ["-D", "keep"],
3023
+ ["keep", "-M"],
3024
+ ["keep", "-D"],
3025
+ ] as const) {
3026
+ yield* driver
3027
+ .createWorktree({
3028
+ cwd,
3029
+ path: pathService.join(worktrees, "wt"),
3030
+ refName,
3031
+ ...(newRefName ? { newRefName } : {}),
3032
+ })
3033
+ .pipe(Effect.flip);
3034
+ }
3035
+
3036
+ assert.equal(
3037
+ yield* fileSystem.readFileString(pathService.join(cwd, "README.md")),
3038
+ "uncommitted work\n",
3039
+ );
3040
+ assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch);
3041
+ assert.deepEqual(yield* driver.listLocalBranchNames(cwd), branches);
3042
+ assert.isFalse(yield* fileSystem.exists(pathService.join(worktrees, "wt")));
3043
+
3044
+ // A lone "-" is still the previous checkout.
3045
+ yield* git(cwd, ["checkout", "-q", "keep"]);
3046
+ yield* git(cwd, ["checkout", "-q", initialBranch]);
3047
+ assert.equal((yield* driver.switchRef({ cwd, refName: "-" })).refName, "keep");
3048
+ const previous = yield* driver.createWorktree({
3049
+ cwd,
3050
+ path: pathService.join(worktrees, "previous"),
3051
+ refName: "-",
3052
+ });
3053
+ assert.equal(
3054
+ yield* git(previous.worktree.path, ["branch", "--show-current"]),
3055
+ initialBranch,
3056
+ );
3057
+ }),
3058
+ );
3059
+
3060
it.effect("still creates and reuses remote tracking branches and allows detached refs", () =>
3061
Effect.gen(function* () {
3062
const cwd = yield* makeTmpDir();
@@ -3590,6 +3700,38 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3700
}),
3701
);
3702
3703
+ it.effect("fetches from a configured remote whose name looks like an option", () =>
3704
+ Effect.gen(function* () {
3705
+ const cwd = yield* makeTmpDir();
3706
+ const remote = yield* makeTmpDir("git-remote-");
3707
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
3708
+ const driver = yield* GitVcsDriver.GitVcsDriver;
3709
+ const fileSystem = yield* FileSystem.FileSystem;
3710
+ // Remote names come from .git/config. Read as an option, this one runs `touch` in cwd.
3711
+ const remoteName = "--upload-pack=touch${IFS}t3-marker;false";
3712
+ yield* git(remote, ["init", "--bare"]);
3713
+ yield* git(cwd, [
3714
+ "push",
3715
+ remote,
3716
+ `HEAD:refs/heads/${initialBranch}`,
3717
+ "HEAD:refs/pull/7/head",
3718
+ ]);
3719
+ yield* git(cwd, ["config", `remote.${remoteName}.url`, remote]);
3720
+
3721
+ assert.equal(yield* driver.resolvePrimaryRemoteName(cwd), remoteName);
3722
+ yield* driver.fetchRemoteTrackingBranch({ cwd, remoteName, remoteBranch: initialBranch });
3723
+ yield* driver.fetchRemote({ cwd, remoteName });
3724
+ const head = yield* driver.fetchPullRequestHeadCommit({ cwd, prNumber: 7 });
3725
+
3726
+ assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "t3-marker")));
3727
+ assert.equal(head.commitSha, yield* git(cwd, ["rev-parse", "HEAD"]));
3728
+ assert.equal(
3729
+ yield* git(cwd, ["rev-parse", `refs/remotes/${remoteName}/${initialBranch}`]),
3730
+ head.commitSha,
3731
+ );
3732
+ }),
3733
+ );
3734
+
3735
it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
3736
Effect.gen(function* () {
3737
const cwd = yield* makeTmpDir();
@@ -3839,7 +3981,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3981
yield* git(remote, ["init", "--bare"]);
3982
yield* git(cwd, ["remote", "add", "origin", remote]);
3983
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
3842
- yield* git(remote, ["symbolic-ref", "HEAD", `refs/heads/${initialBranch}`]);
3984
+ yield* git(remote, ["--git-dir=.", "symbolic-ref", "HEAD", `refs/heads/${initialBranch}`]);
3985
const beforeFetch = yield* git(cwd, ["rev-parse", `refs/remotes/origin/${initialBranch}`]);
3986
3987
yield* git(peer, ["clone", remote, "."]);
@@ -4031,13 +4173,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4173
setUpstream: false,
4174
});
4175
assert.equal(
4034
- yield* git(remote, ["log", "-1", "--pretty=%s", "main"]),
4176
+ yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "main"]),
4177
"Add upstream update",
4178
);
4179
const badBranch = yield* driver.execute({
4180
operation: "GitVcsDriver.test.showBadRemoteBranch",
4181
cwd: remote,
4040
- args: ["show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
4182
+ args: ["--git-dir=.", "show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
4183
allowNonZeroExit: true,
4184
timeoutMs: 10_000,
4185
});
@@ -4071,8 +4213,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4213
upstreamBranch: "origin/feature/x",
4214
setUpstream: true,
4215
});
4074
- assert.equal(yield* git(remote, ["log", "-1", "--pretty=%s", "feature/x"]), "Add feature");
4075
- assert.equal(yield* git(remote, ["rev-parse", "dev"]), devSha);
4216
+ assert.equal(
4217
+ yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "feature/x"]),
4218
+ "Add feature",
4219
+ );
4220
+ assert.equal(yield* git(remote, ["--git-dir=.", "rev-parse", "dev"]), devSha);
4221
assert.equal(
4222
yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
4223
"origin/feature/x",
@@ -4141,7 +4286,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4286
setUpstream: false,
4287
});
4288
assert.equal(
4144
- yield* git(remote, ["log", "-1", "--pretty=%s", "effect-atom"]),
4289
+ yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "effect-atom"]),
4290
"Add alias update",
4291
);
4292
}),
@@ -4169,13 +4314,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4314
setUpstream: true,
4315
});
4316
assert.equal(
4172
- yield* git(publishRemote, ["log", "-1", "--pretty=%s", "main"]),
4317
+ yield* git(publishRemote, ["--git-dir=.", "log", "-1", "--pretty=%s", "main"]),
4318
"initial commit",
4319
);
4320
const originMain = yield* driver.execute({
4321
operation: "GitVcsDriver.test.originMainMissing",
4322
cwd: originRemote,
4178
- args: ["show-ref", "--verify", "--quiet", "refs/heads/main"],
4323
+ args: ["--git-dir=.", "show-ref", "--verify", "--quiet", "refs/heads/main"],
4324
allowNonZeroExit: true,
4325
timeoutMs: 10_000,
4326
});
@@ -4238,6 +4383,29 @@ describe("Windows long path configuration", () => {
4383
});
4384
});
4385
4386
+ it("extends the per-command count when inherited and per-command casings differ", () => {
4387
+ assert.deepStrictEqual(
4388
+ windowsLongPathConfigEnv("win32", { GIT_CONFIG_COUNT: "0", git_config_count: "1" }),
4389
+ {
4390
+ GIT_CONFIG_COUNT: "2",
4391
+ git_config_count: "2",
4392
+ GIT_CONFIG_KEY_1: "core.longpaths",
4393
+ GIT_CONFIG_VALUE_1: "true",
4394
+ },
4395
+ );
4396
+ });
4397
+
4398
+ it("reads only the exact count name outside Windows", () => {
4399
+ assert.deepStrictEqual(
4400
+ gitConfigEnv({ git_config_count: "3" }, "safe.bareRepository", "explicit", "linux"),
4401
+ {
4402
+ GIT_CONFIG_COUNT: "1",
4403
+ GIT_CONFIG_KEY_0: "safe.bareRepository",
4404
+ GIT_CONFIG_VALUE_0: "explicit",
4405
+ },
4406
+ );
4407
+ });
4408
+
4409
it("appends after inherited entries, parsing the count as Git does", () => {
4410
for (const [count, next] of [
4411
[undefined, 0],
apps/server/src/vcs/GitVcsDriverCore.ts
+68
-46
@@ -37,6 +37,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
37
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
38
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
39
import * as GitVcsDriver from "./GitVcsDriver.ts";
40
+import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";
41
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
42
import {
43
parseRemoteNames,
@@ -331,6 +332,24 @@ export function splitNullSeparatedGitStdoutPaths(
332
return splitNullSeparatedPaths(result.stdout, result.stdoutTruncated);
333
}
334
335
+/**
336
+ * Refuses a ref name with a leading "-" before it reaches checkout or `worktree add`. Git refuses
337
+ * such branch and tag names, and both commands, or the `git branch` that `worktree add` runs, read
338
+ * one as an option. `--end-of-options` cannot guard them: Git before 2.44 reads it like `--`.
339
+ * A lone "-" is the previous checkout, which both commands read as a ref.
340
+ */
341
+const refuseOptionLikeRefName = (operation: string, cwd: string, refName: string | undefined) =>
342
+ refName !== undefined && refName !== "-" && refName.startsWith("-")
343
+ ? Effect.fail(
344
+ new GitCommandError({
345
+ operation,
346
+ command: "git",
347
+ cwd,
348
+ detail: "Ref names cannot start with '-'.",
349
+ }),
350
+ )
351
+ : Effect.void;
352
+
353
function sanitizeRemoteName(value: string): string {
354
const sanitized = value
355
.trim()
@@ -899,29 +918,8 @@ const collectOutput = Effect.fnUntraced(function* (
918
export const windowsLongPathConfigEnv = (
919
platform: NodeJS.Platform,
920
env: NodeJS.ProcessEnv,
902
-): NodeJS.ProcessEnv => {
903
- if (platform !== "win32") {
904
- return {};
905
- }
906
- const countKey =
907
- Object.keys(env).find((key) => key.toUpperCase() === "GIT_CONFIG_COUNT") ?? "GIT_CONFIG_COUNT";
908
- const inherited = env[countKey];
909
- if (
910
- inherited !== undefined &&
911
- inherited !== "" &&
912
- // Git parses the count with strtoul: leading whitespace, an optional sign
913
- // (only -0 is non-negative), digits, and nothing after them.
914
- /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited
915
- ) {
916
- return {};
917
- }
918
- const count = inherited === undefined || inherited === "" ? 0 : Number.parseInt(inherited, 10);
919
- return {
920
- [countKey]: String(count + 1),
921
- [`GIT_CONFIG_KEY_${count}`]: "core.longpaths",
922
- [`GIT_CONFIG_VALUE_${count}`]: "true",
923
- };
924
-};
921
+): NodeJS.ProcessEnv =>
922
+ platform === "win32" ? gitConfigEnv(env, "core.longpaths", "true", platform) : {};
923
924
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
925
const fileSystem = yield* FileSystem.FileSystem;
@@ -954,7 +952,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
952
}),
953
),
954
);
957
- const env = {
955
+ const baseEnv = {
956
...process.env,
957
// Status polling runs beside the user's own git commands; without this,
958
// `git status` takes index.lock to save its refreshed index.
@@ -962,6 +960,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
960
...input.env,
961
...trace2Monitor.env,
962
};
963
+ const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) };
964
const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) };
965
const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv });
966
// A git.cmd wrapper would need cmd.exe, which cuts multi-line commit
@@ -1270,7 +1269,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1269
return executeGit(
1270
"GitVcsDriver.fetchRemoteForStatus",
1271
fetchCwd,
1273
- ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", "--no-auto-gc", remoteName],
1272
+ [
1273
+ "--git-dir",
1274
+ gitCommonDir,
1275
+ "fetch",
1276
+ "--quiet",
1277
+ "--no-tags",
1278
+ "--no-auto-gc",
1279
+ "--",
1280
+ remoteName,
1281
+ ],
1282
{
1283
env: STATUS_UPSTREAM_REFRESH_ENV,
1284
fallbackErrorDetail: "Background Git fetch exited with a non-zero status.",
@@ -1553,9 +1561,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1561
).pipe(Effect.map((result) => result.exitCode === 0));
1562
1563
const remoteExists: GitVcsDriver.GitVcsDriver["Service"]["remoteExists"] = (input) =>
1556
- executeGit("GitVcsDriver.remoteExists", input.cwd, ["remote", "get-url", input.remoteName], {
1557
- allowNonZeroExit: true,
1558
- }).pipe(Effect.map((result) => result.exitCode === 0));
1564
+ executeGit(
1565
+ "GitVcsDriver.remoteExists",
1566
+ input.cwd,
1567
+ ["remote", "get-url", "--", input.remoteName],
1568
+ {
1569
+ allowNonZeroExit: true,
1570
+ },
1571
+ ).pipe(Effect.map((result) => result.exitCode === 0));
1572
1573
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
1574
remoteExists({ cwd, remoteName: "origin" });
@@ -1647,6 +1660,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1660
yield* runGit("GitVcsDriver.ensureRemote.add", input.cwd, [
1661
"remote",
1662
"add",
1663
+ "--",
1664
remoteName,
1665
input.url,
1666
]);
@@ -1737,7 +1751,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1751
const result = yield* executeGit(
1752
"GitVcsDriver.computeAheadCountAgainstBase",
1753
cwd,
1740
- ["rev-list", "--count", `${baseRef}..HEAD`],
1754
+ ["rev-list", "--count", "--end-of-options", `${baseRef}..HEAD`],
1755
{ allowNonZeroExit: true },
1756
);
1757
if (result.exitCode !== 0) {
@@ -2337,7 +2351,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2351
yield* runGit(
2352
"GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
2353
cwd,
2340
- ["push", "-u", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],
2354
+ ["push", "-u", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],
2355
{ timeoutMs: null },
2356
);
2357
return {
@@ -2402,7 +2416,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2416
yield* runGit(
2417
"GitVcsDriver.pushCurrentBranch.pushWithUpstream",
2418
cwd,
2405
- ["push", "-u", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],
2419
+ ["push", "-u", "--", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],
2420
{ timeoutMs: null },
2421
);
2422
return {
@@ -2451,7 +2465,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2465
yield* runGit(
2466
"GitVcsDriver.pushCurrentBranch.pushOwnBranch",
2467
cwd,
2454
- ["push", "-u", remoteName, `HEAD:refs/heads/${publishBranch}`],
2468
+ ["push", "-u", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],
2469
{ timeoutMs: null },
2470
);
2471
return {
@@ -2465,7 +2479,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2479
yield* runGit(
2480
"GitVcsDriver.pushCurrentBranch.pushUpstream",
2481
cwd,
2468
- ["push", currentUpstream.remoteName, `HEAD:refs/heads/${currentUpstream.branchName}`],
2482
+ ["push", "--", currentUpstream.remoteName, `HEAD:refs/heads/${currentUpstream.branchName}`],
2483
{ timeoutMs: null },
2484
);
2485
return {
@@ -2549,7 +2563,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2563
runGitStdoutWithOptions(
2564
"GitVcsDriver.readRangeContext.log",
2565
cwd,
2552
- ["log", "--oneline", commitRange],
2566
+ ["log", "--oneline", "--end-of-options", commitRange],
2567
{
2568
maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES,
2569
appendTruncationMarker: true,
@@ -2558,7 +2572,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2572
runGitStdoutWithOptions(
2573
"GitVcsDriver.readRangeContext.diffStat",
2574
cwd,
2561
- ["diff", "--stat", diffRange],
2575
+ ["diff", "--stat", "--end-of-options", diffRange],
2576
{
2577
maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES,
2578
appendTruncationMarker: true,
@@ -2567,7 +2581,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2581
runGitStdoutWithOptions(
2582
"GitVcsDriver.readRangeContext.diffPatch",
2583
cwd,
2570
- ["diff", "--no-ext-diff", "--patch", "--minimal", diffRange],
2584
+ ["diff", "--no-ext-diff", "--patch", "--minimal", "--end-of-options", diffRange],
2585
{
2586
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
2587
appendTruncationMarker: true,
@@ -2719,7 +2733,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2733
)
2734
: null);
2735
if (baseRef === null) return { baseRef, mergeBase: "HEAD" };
2722
- const args = ["merge-base", baseRef, "HEAD"];
2736
+ const args = ["merge-base", "--end-of-options", baseRef, "HEAD"];
2737
const result = yield* executeGit("GitVcsDriver.resolveReviewMergeBase", cwd, args, {
2738
allowNonZeroExit: true,
2739
});
@@ -2974,7 +2988,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2988
const result = yield* executeGit(
2989
"GitVcsDriver.getReviewDiffFileContents.revision",
2990
input.cwd,
2977
- ["show", `${revision}:${relativePath}`],
2991
+ ["show", "--end-of-options", `${revision}:${relativePath}`],
2992
{ maxOutputBytes: REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES },
2993
);
2994
if (result.stdout.includes("\0")) {
@@ -3409,6 +3423,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3423
const createWorktree: GitVcsDriver.GitVcsDriver["Service"]["createWorktree"] = Effect.fn(
3424
"createWorktree",
3425
)(function* (input, options) {
3426
+ yield* refuseOptionLikeRefName("GitVcsDriver.createWorktree", input.cwd, input.refName);
3427
+ yield* refuseOptionLikeRefName("GitVcsDriver.createWorktree", input.cwd, input.newRefName);
3428
const targetBranch = input.newRefName ?? input.refName;
3429
const sanitizedBranch = targetBranch.replace(/\//g, "-");
3430
// resolve: a cwd like `<repo>/sub/..` must not name the folder `..`.
@@ -3432,8 +3448,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3448
worktreePath = path.join(parentDir, repoName, sanitizedBranch);
3449
}
3450
const args = input.newRefName
3435
- ? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
3436
- : ["worktree", "add", worktreePath, input.refName];
3451
+ ? ["worktree", "add", "-b", input.newRefName, "--", worktreePath, input.refName]
3452
+ : ["worktree", "add", "--", worktreePath, input.refName];
3453
const progress = options?.progress;
3454
const onCheckoutProgress = progress?.onCheckoutProgress;
3455
@@ -3562,6 +3578,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3578
"fetch",
3579
"--quiet",
3580
"--no-tags",
3581
+ "--",
3582
remoteName,
3583
`+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,
3584
],
@@ -3591,7 +3608,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3608
yield* executeGit(
3609
"GitVcsDriver.fetchPullRequestHeadCommit",
3610
input.cwd,
3594
- ["fetch", "--quiet", "--no-tags", remoteName, `refs/pull/${input.prNumber}/head`],
3611
+ ["fetch", "--quiet", "--no-tags", "--", remoteName, `refs/pull/${input.prNumber}/head`],
3612
{
3613
fallbackErrorDetail: "git fetch pull request head failed",
3614
},
@@ -3662,7 +3679,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3679
3680
const fetchRemote: GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"] = Effect.fn("fetchRemote")(
3681
function* (input) {
3665
- const args = ["fetch", "--quiet", input.remoteName];
3682
+ const args = ["fetch", "--quiet", "--", input.remoteName];
3683
const options = {
3684
env: STATUS_UPSTREAM_REFRESH_ENV,
3685
fallbackErrorDetail: `git fetch ${input.remoteName} failed`,
@@ -3763,6 +3780,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3780
"fetch",
3781
"--quiet",
3782
"--no-tags",
3783
+ "--",
3784
input.remoteName,
3785
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
3786
]);
@@ -3773,8 +3791,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3791
"GitVcsDriver.fetchRemoteBranch.materialize",
3792
input.cwd,
3793
localBranchAlreadyExists
3776
- ? ["branch", "--force", input.localBranch, targetRef]
3777
- : ["branch", input.localBranch, targetRef],
3794
+ ? ["branch", "--force", "--", input.localBranch, targetRef]
3795
+ : ["branch", "--", input.localBranch, targetRef],
3796
);
3797
});
3798
@@ -3784,6 +3802,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3802
"fetch",
3803
"--quiet",
3804
"--no-tags",
3805
+ "--",
3806
input.remoteName,
3807
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
3808
]);
@@ -3794,6 +3813,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3813
"branch",
3814
"--set-upstream-to",
3815
`${input.remoteName}/${input.remoteBranch}`,
3816
+ "--",
3817
input.branch,
3818
]);
3819
@@ -3806,7 +3826,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3826
if (input.force) {
3827
args.push("--force");
3828
}
3809
- args.push(input.path);
3829
+ args.push("--", input.path);
3830
const result = yield* executeGitWithStableDiagnostics(
3831
"GitVcsDriver.removeWorktree",
3832
input.cwd,
@@ -3955,6 +3975,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3975
? ["checkout", localTrackingBranch]
3976
: ["checkout", input.refName];
3977
3978
+ yield* refuseOptionLikeRefName("GitVcsDriver.switchRef", input.cwd, checkoutArgs.at(-1));
3979
+
3980
// A stale ref must not turn into a path checkout that discards local edits.
3981
yield* executeGit("GitVcsDriver.switchRef.checkout", input.cwd, [...checkoutArgs, "--"], {
3982
timeoutMs: 10_000,
@@ -3972,7 +3994,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3994
3995
const createRef: GitVcsDriver.GitVcsDriver["Service"]["createRef"] = Effect.fn("createRef")(
3996
function* (input) {
3975
- yield* executeGit("GitVcsDriver.createRef", input.cwd, ["branch", input.refName], {
3997
+ yield* executeGit("GitVcsDriver.createRef", input.cwd, ["branch", "--", input.refName], {
3998
timeoutMs: 10_000,
3999
fallbackErrorDetail: "git branch create failed",
4000
});
apps/server/src/vcs/VcsProcess.test.ts
+28
@@ -7,7 +7,9 @@ import * as Effect from "effect/Effect";
7
import * as Exit from "effect/Exit";
8
import * as Cause from "effect/Cause";
9
import * as Fiber from "effect/Fiber";
10
+import * as FileSystem from "effect/FileSystem";
11
import * as Layer from "effect/Layer";
12
+import * as Path from "effect/Path";
13
import * as Queue from "effect/Queue";
14
import * as Ref from "effect/Ref";
15
import * as Schema from "effect/Schema";
@@ -292,6 +294,32 @@ describe("VcsProcess.run", () => {
294
}).pipe(provideLive),
295
);
296
297
+ it.effect("keeps git from opening a folder laid out as a bare repository", () =>
298
+ Effect.gen(function* () {
299
+ const fileSystem = yield* FileSystem.FileSystem;
300
+ const path = yield* Path.Path;
301
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
302
+ yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
303
+ yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
304
+ yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
305
+ yield* fileSystem.writeFileString(
306
+ path.join(cwd, "config"),
307
+ '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
308
+ );
309
+
310
+ const result = yield* run({
311
+ operation: "test.bare-repository",
312
+ command: "git",
313
+ args: ["status"],
314
+ cwd,
315
+ allowNonZeroExit: true,
316
+ });
317
+
318
+ expect(result.exitCode).not.toBe(0);
319
+ expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
320
+ }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
321
+ );
322
+
323
it.effect("writes stdin before waiting for exit", () =>
324
Effect.gen(function* () {
325
const result = yield* run({
apps/server/src/vcs/VcsProcess.ts
+55
-1
@@ -18,6 +18,8 @@ import {
18
VcsProcessStdinWriteError,
19
VcsProcessTimeoutError,
20
} from "@t3tools/contracts";
21
+import * as HostProcess from "@t3tools/shared/HostProcess";
22
+
23
import * as ProcessRunner from "../processRunner.ts";
24
25
export interface VcsProcessInput {
@@ -61,6 +63,54 @@ const GITHUB_PROCESS_CONCURRENCY = 4;
63
64
export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
65
66
+/**
67
+ * Appends `key=value` to the `GIT_CONFIG_*` entries git reads as command-line
68
+ * config, so argv stays the same on every platform and nothing is written to
69
+ * the user's config. The entry goes after any inherited ones. Windows env names
70
+ * are case-insensitive (elsewhere git reads only `GIT_CONFIG_COUNT`), so there the
71
+ * count is found regardless of casing, read from
72
+ * the last spelling (a per-command value spread over process.env), and updated
73
+ * under every spelling so the child sees it whichever one Node keeps. A count
74
+ * git would reject is left alone so git still reports it.
75
+ */
76
+export const gitConfigEnv = (
77
+ env: NodeJS.ProcessEnv,
78
+ key: string,
79
+ value: string,
80
+ platform: NodeJS.Platform,
81
+): NodeJS.ProcessEnv => {
82
+ const countKeys = Object.keys(env).filter((name) =>
83
+ platform === "win32" ? name.toUpperCase() === "GIT_CONFIG_COUNT" : name === "GIT_CONFIG_COUNT",
84
+ );
85
+ const countKey = countKeys.at(-1) ?? "GIT_CONFIG_COUNT";
86
+ const inherited = env[countKey];
87
+ if (
88
+ inherited !== undefined &&
89
+ inherited !== "" &&
90
+ // Git parses the count with strtoul: leading whitespace, an optional sign
91
+ // (only -0 is non-negative), digits, and nothing after them.
92
+ /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited
93
+ ) {
94
+ return {};
95
+ }
96
+ const count = inherited === undefined || inherited === "" ? 0 : Number.parseInt(inherited, 10);
97
+ return {
98
+ ...Object.fromEntries([...countKeys, countKey].map((name) => [name, String(count + 1)])),
99
+ [`GIT_CONFIG_KEY_${count}`]: key,
100
+ [`GIT_CONFIG_VALUE_${count}`]: value,
101
+ };
102
+};
103
+
104
+/**
105
+ * Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a
106
+ * bare repository and applies its `config`, including commands such as
107
+ * `core.fsmonitor`. Files saved in a project or checked out from a clone can
108
+ * form one, so git started by T3 (or by gh and friends) only opens a bare
109
+ * repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it.
110
+ */
111
+export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
112
+ gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
113
+
114
const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
115
const normalized = stderr.toLowerCase();
116
@@ -114,6 +164,7 @@ const isTransientGitExit = (stderr: string) =>
164
165
export const make = Effect.gen(function* () {
166
const processRunner = yield* ProcessRunner.ProcessRunner;
167
+ const hostPlatform = yield* HostProcess.Platform;
168
const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
169
const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
170
@@ -133,7 +184,10 @@ export const make = Effect.gen(function* () {
184
...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
185
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
186
...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
136
- ...(input.env !== undefined ? { env: input.env } : {}),
187
+ env: {
188
+ ...input.env,
189
+ ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform),
190
+ },
191
timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
192
maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
193
outputMode: input.outputMode ?? "truncate",
packages/source-control-core/src/server/diffFileRevisions.test.ts
+34
-1
@@ -1,6 +1,6 @@
1
import { assert, describe, it } from "@effect/vitest";
2
3
-import { parseDiffFileRevisions } from "./diffFileRevisions.ts";
3
+import { parseDiffFilePaths, parseDiffFileRevisions } from "./diffFileRevisions.ts";
4
5
function patchOf(...lines: ReadonlyArray<string>): string {
6
return `${lines.join("\n")}\n`;
@@ -278,3 +278,36 @@ describe("parseDiffFileRevisions", () => {
278
assert.deepStrictEqual([...revisions], [["one two", "eeeeeee"]]);
279
});
280
});
281
+
282
+describe("parseDiffFilePaths", () => {
283
+ it("names both sides of each file, with no side for an added or deleted one", () => {
284
+ const paths = parseDiffFilePaths(
285
+ [
286
+ "diff --git a/src/a.ts b/src/a.ts",
287
+ "--- a/src/a.ts",
288
+ "+++ b/src/a.ts",
289
+ "@@ -1 +1 @@",
290
+ "--- a/not/a/header.ts",
291
+ "diff --git a/added.md b/added.md",
292
+ "new file mode 100644",
293
+ "--- /dev/null",
294
+ "+++ b/added.md",
295
+ "diff --git a/gone.md b/gone.md",
296
+ "deleted file mode 100644",
297
+ "--- a/gone.md",
298
+ "+++ /dev/null",
299
+ 'diff --git "a/tab\\tname" b/moved.ts',
300
+ 'rename from "tab\\tname"',
301
+ "rename to moved.ts",
302
+ "",
303
+ ].join("\n"),
304
+ );
305
+
306
+ assert.deepStrictEqual(paths, [
307
+ { oldPath: "src/a.ts", newPath: "src/a.ts" },
308
+ { oldPath: null, newPath: "added.md" },
309
+ { oldPath: "gone.md", newPath: null },
310
+ { oldPath: "tab\tname", newPath: "moved.ts" },
311
+ ]);
312
+ });
313
+});
packages/source-control-core/src/server/diffFileRevisions.ts
+33
-6
@@ -76,16 +76,14 @@ function headRevision(rest: string): string | null {
76
return head.length === 0 ? null : head;
77
}
78
79
-export function parseDiffFileRevisions(patch: string): ReadonlyMap<string, string> {
80
- const revisions = new Map<string, string>();
79
+function parseEntries(patch: string): ReadonlyArray<Omit<Entry, "inBody">> {
80
+ const entries: Array<Omit<Entry, "inBody">> = [];
81
let entry: Entry | null = null;
82
83
const close = () => {
84
if (entry === null) return;
85
- const path = entry.deleted ? entry.oldPath : (entry.newPath ?? entry.oldPath);
86
- if (path !== null && path.length > 0 && entry.revision !== null) {
87
- revisions.set(path, entry.revision);
88
- }
85
+ const { inBody: _inBody, ...closed } = entry;
86
+ entries.push(closed);
87
entry = null;
88
};
89
@@ -116,5 +114,34 @@ export function parseDiffFileRevisions(patch: string): ReadonlyMap<string, strin
114
}
115
}
116
close();
117
+ return entries;
118
+}
119
+
120
+/**
121
+ * What the head has of each file, as the blob ids from a unified patch's `index <before>..<after>`
122
+ * line: Bitbucket exposes no blob id for a file anywhere else. Keyed by the head's name, except
123
+ * for a deletion where only the old name exists. An entry with no `index` line (most often one
124
+ * Bitbucket excluded by pattern) is left out.
125
+ */
126
+export function parseDiffFileRevisions(patch: string): ReadonlyMap<string, string> {
127
+ const revisions = new Map<string, string>();
128
+ for (const entry of parseEntries(patch)) {
129
+ const path = entry.deleted ? entry.oldPath : (entry.newPath ?? entry.oldPath);
130
+ if (path !== null && path.length > 0 && entry.revision !== null) {
131
+ revisions.set(path, entry.revision);
132
+ }
133
+ }
134
return revisions;
135
}
136
+
137
+/**
138
+ * The files a unified patch changes, as the name each side has. A side with no file (`/dev/null`
139
+ * for an added or a deleted file) is null; a rename is the only entry whose two names differ.
140
+ */
141
+export function parseDiffFilePaths(
142
+ patch: string,
143
+): ReadonlyArray<{ readonly oldPath: string | null; readonly newPath: string | null }> {
144
+ return parseEntries(patch).flatMap(({ oldPath, newPath }) =>
145
+ (oldPath ?? newPath) === null ? [] : [{ oldPath, newPath }],
146
+ );
147
+}
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts
+8
@@ -451,6 +451,14 @@ export const make = Effect.gen(function* () {
451
],
452
});
453
if (input.force) {
454
+ // The sha comes from the server and git would read anything but a commit as an option.
455
+ if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha))
456
+ return yield* new ForgejoCli.ForgejoCliError({
457
+ command: repo.command ?? "tea",
458
+ cwd: input.cwd,
459
+ detail: "Forgejo reported a pull request head that is not a commit.",
460
+ reason: "invalid-response",
461
+ });
462
// tea leaves an existing PR branch at its old tip. Keep dirty files safe
463
// while bringing the selected branch to the PR revision we fetched.
464
yield* process.run({
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+1
-1
@@ -719,7 +719,7 @@ describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
719
"fetchRemoteTrackingBranch",
720
{ cwd: "/repo", remoteName: "origin", remoteBranch: "feature/x" },
721
],
722
- ["execute", ["branch", "feature/x", "refs/remotes/origin/feature/x"]],
722
+ ["execute", ["branch", "--", "feature/x", "refs/remotes/origin/feature/x"]],
723
["switchRef", { cwd: "/repo", refName: "feature/x" }],
724
[
725
"setBranchUpstream",
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+2
-1
@@ -777,6 +777,7 @@ export const make = Effect.gen(function* () {
777
"fetch",
778
"--quiet",
779
"--no-tags",
780
+ "--",
781
yield* baseRemote,
782
`refs/pull/${pullRequest.number}/head`,
783
]);
@@ -791,7 +792,7 @@ export const make = Effect.gen(function* () {
792
);
793
794
yield* Effect.gen(function* () {
794
- if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
795
+ if (!exists) yield* runGit(input.cwd, "branch", ["branch", "--", localBranch, target.ref]);
796
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
797
if (exists) {
798
yield* runGit(
packages/source-control-gitlab/src/server/GitLabCli.test.ts
+2
-2
@@ -77,7 +77,7 @@ layer("GitLabCli.layer", (it) => {
77
expect.objectContaining({
78
command: "glab",
79
cwd: "/repo",
80
- args: ["mr", "view", "42", "--output", "json"],
80
+ args: ["mr", "view", "--output", "json", "--", "42"],
81
}),
82
);
83
}),
@@ -295,7 +295,7 @@ layer("GitLabCli.layer", (it) => {
295
expect.objectContaining({
296
command: "glab",
297
cwd: "/repo",
298
- args: ["mr", "checkout", "42"],
298
+ args: ["mr", "checkout", "--", "42"],
299
}),
300
);
301
}),
packages/source-control-gitlab/src/server/GitLabCli.ts
+2
-2
@@ -496,7 +496,7 @@ export const make = Effect.gen(function* () {
496
executeMergeRequest({
497
cwd: input.cwd,
498
reference: input.reference,
499
- args: ["mr", "view", input.reference, "--output", "json"],
499
+ args: ["mr", "view", "--output", "json", "--", input.reference],
500
}).pipe(
501
Effect.map((result) => result.stdout.trim()),
502
Effect.flatMap((raw) =>
@@ -652,7 +652,7 @@ export const make = Effect.gen(function* () {
652
executeMergeRequest({
653
cwd: input.cwd,
654
reference: input.reference,
655
- args: ["mr", "checkout", input.reference],
655
+ args: ["mr", "checkout", "--", input.reference],
656
}).pipe(Effect.asVoid),
657
});
658
});
packages/ssh/src/command.test.ts
+24
-1
@@ -8,7 +8,7 @@ import * as Result from "effect/Result";
8
import * as Sink from "effect/Sink";
9
import * as Stream from "effect/Stream";
10
import * as TestClock from "effect/testing/TestClock";
11
-import { ChildProcessSpawner } from "effect/process";
11
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
12
13
import {
14
baseSshArgs,
@@ -99,6 +99,29 @@ describe("ssh command", () => {
99
}),
100
);
101
102
+ it.effect("passes an option-shaped alias to ssh as the destination", () => {
103
+ const spawned: Array<ReadonlyArray<string>> = [];
104
+ const spawner = ChildProcessSpawner.make((command) => {
105
+ if (ChildProcess.isStandardCommand(command)) spawned.push(command.args);
106
+ return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" }));
107
+ });
108
+ return runSshCommand(
109
+ { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null },
110
+ { remoteCommandArgs: ["sh", "-s"] },
111
+ ).pipe(
112
+ Effect.flip,
113
+ Effect.map(() => {
114
+ assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]);
115
+ }),
116
+ Effect.provide(
117
+ Layer.merge(
118
+ NodeServices.layer,
119
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
120
+ ),
121
+ ),
122
+ );
123
+ });
124
+
125
// Remote servers store state under this key, so it must not change across releases.
126
it.effect("derives a stable remote state key", () =>
127
Effect.gen(function* () {
packages/ssh/src/command.ts
+1
@@ -202,6 +202,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
202
batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
203
}),
204
...(input.preHostArgs ?? []),
205
+ "--",
206
hostSpec,
207
...(input.remoteCommandArgs ?? []),
208
];
packages/ssh/src/tunnel.test.ts
+5
-3
@@ -507,7 +507,8 @@ describe("ssh tunnel scripts", () => {
507
kills += 1;
508
});
509
}
510
- if (args.includes("--")) return makeSuccessfulProcess('{"remotePort":3773}\n');
510
+ if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--"))
511
+ return makeSuccessfulProcess('{"remotePort":3773}\n');
512
if (args.includes("sh")) stops += 1;
513
return makeSuccessfulProcess("");
514
}),
@@ -558,7 +559,7 @@ describe("ssh tunnel scripts", () => {
559
tunnelKillCount += 1;
560
});
561
}
561
- if (args.includes("sh") && args.includes("--")) {
562
+ if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--")) {
563
return makeSuccessfulProcess('{"remotePort":3773}\n');
564
}
565
if (args.includes("sh")) {
@@ -602,6 +603,7 @@ describe("ssh tunnel scripts", () => {
603
assert.include(firstTunnelArgs, "ControlMaster=no");
604
assert.include(firstTunnelArgs, "ControlPath=none");
605
assert.include(firstTunnelArgs, "ControlPersist=no");
606
+ assert.deepEqual(firstTunnelArgs?.slice(-2), ["--", "julius@devbox"]);
607
608
const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
609
if (mode === "failed stop") {
@@ -679,7 +681,7 @@ describe("ssh tunnel scripts", () => {
681
}
682
return tunnel;
683
}
682
- if (args.includes("--")) {
684
+ if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--")) {
685
if (isTarget) {
686
launches += 1;
687
remoteRunning = true;
packages/ssh/src/tunnel.ts
+1
@@ -1180,6 +1180,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
1180
"-N",
1181
"-L",
1182
`${input.localPort}:127.0.0.1:${input.remotePort}`,
1183
+ "--",
1184
hostSpec,
1185
];
1186
const sshCommand = yield* resolveSshCommand;