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 22, 14:30 UTC
fix(server): parallel worktree launches no longer fail on .git/config lock (#25700)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 15:42 UTC
3b22620a5cbbf1b6f6336d70e68696a14c36f382
10 files changed
+594
-80
apps/server/src/sourceControl/ServerSourceControlHost.ts
+2
@@ -29,6 +29,8 @@ export const layer = Layer.effect(
29
fetchRemoteBranch: git.fetchRemoteBranch,
30
fetchRemoteTrackingBranch: git.fetchRemoteTrackingBranch,
31
setBranchUpstream: git.setBranchUpstream,
32
+ createBranch: git.createBranch,
33
+ writeConfigValue: git.writeConfigValue,
34
switchRef: git.switchRef,
35
},
36
});
apps/server/src/vcs/GitVcsDriver.ts
+19
@@ -57,6 +57,8 @@ export interface ExecuteGitInput {
57
/** With appendTruncationMarker, line callbacks continue beyond the buffer cap for progress-only consumers. */
58
readonly keepLineCallbacksAfterTruncation?: boolean;
59
readonly progress?: ExecuteGitProgress;
60
+ /** Writes .git/config, which every worktree shares and Git locks without waiting. */
61
+ readonly writesSharedConfig?: boolean;
62
}
63
64
export interface ExecuteGitResult {
@@ -269,6 +271,18 @@ export interface GitFetchWorktreeBaseCommitInput {
271
refName: string;
272
}
273
274
+export interface GitCreateBranchInput {
275
+ readonly cwd: string;
276
+ readonly branch: string;
277
+ readonly startPoint: string;
278
+}
279
+
280
+export interface GitWriteConfigValueInput {
281
+ readonly cwd: string;
282
+ readonly key: string;
283
+ readonly value: string;
284
+}
285
+
286
export interface GitSetBranchUpstreamInput {
287
cwd: string;
288
branch: string;
@@ -387,6 +401,11 @@ export class GitVcsDriver extends Context.Service<
401
readonly setBranchUpstream: (
402
input: GitSetBranchUpstreamInput,
403
) => Effect.Effect<void, GitCommandError>;
404
+ /** Tracks the start point like `git branch` does. */
405
+ readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
406
+ readonly writeConfigValue: (
407
+ input: GitWriteConfigValueInput,
408
+ ) => Effect.Effect<void, GitCommandError>;
409
readonly removeWorktree: (
410
input: VcsRemoveWorktreeInput,
411
) => Effect.Effect<void, GitCommandError>;
apps/server/src/vcs/GitVcsDriverCore.test.ts
+303
-10
@@ -16,6 +16,7 @@ import * as Scope from "effect/Scope";
16
import * as Schema from "effect/Schema";
17
import * as Sink from "effect/Sink";
18
import * as Stream from "effect/Stream";
19
+import * as TestClock from "effect/testing/TestClock";
20
import { ChildProcess, ChildProcessSpawner } from "effect/process";
21
22
import {
@@ -87,6 +88,41 @@ const makeFailedHandle = (stderr: string) =>
88
stderr: Stream.encodeText(Stream.make(stderr)),
89
});
90
91
+// Releases the lock as soon as a matching git command fails on it, before the driver retries.
92
+const makeDriverReleasingLock = (
93
+ matches: (args: ReadonlyArray<string>) => boolean,
94
+ lockPath: string,
95
+) =>
96
+ Effect.gen(function* () {
97
+ const failures = yield* Ref.make(0);
98
+ const fileSystem = yield* FileSystem.FileSystem;
99
+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
100
+ const spawner = ChildProcessSpawner.make((command) =>
101
+ Effect.gen(function* () {
102
+ const handle = yield* delegate.spawn(command);
103
+ if (!ChildProcess.isStandardCommand(command) || !matches(command.args)) return handle;
104
+ return ChildProcessSpawner.makeHandle({
105
+ ...handle,
106
+ exitCode: handle.exitCode.pipe(
107
+ Effect.tap((exitCode) =>
108
+ exitCode === 0
109
+ ? Effect.void
110
+ : Ref.update(failures, (count) => count + 1).pipe(
111
+ Effect.andThen(fileSystem.remove(lockPath, { force: true })),
112
+ Effect.orDie,
113
+ ),
114
+ ),
115
+ ),
116
+ });
117
+ }),
118
+ );
119
+ const driver = yield* makeGitVcsDriverCore().pipe(
120
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
121
+ Effect.provide(layerServerConfig),
122
+ );
123
+ return { driver, failures };
124
+ });
125
+
126
describe("Git output collection", () => {
127
// Git writes in arbitrary chunk sizes; one byte per chunk splits every
128
// multibyte character across reads.
@@ -1057,6 +1093,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1093
1094
it.effect.each([
1095
{ action: "worktree add", detail: "git worktree add failed" },
1096
+ { action: "worktree add -b", detail: "git worktree add failed" },
1097
{ action: "switch", detail: "git checkout failed" },
1098
])(
1099
"reports a missing ref during $action with stable, redacted diagnostics",
@@ -1071,7 +1108,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1108
const spawner = ChildProcessSpawner.make((command) => {
1109
if (
1110
ChildProcess.isStandardCommand(command) &&
1074
- (command.args.includes("worktree") || command.args[0] === "checkout")
1111
+ (command.args.includes("worktree") ||
1112
+ command.args[0] === "branch" ||
1113
+ command.args[0] === "checkout")
1114
) {
1115
locales.push(command.options.env?.LC_ALL);
1116
}
@@ -1088,7 +1127,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1127
.createWorktree({
1128
cwd,
1129
refName,
1091
- newRefName: "t3/new-thread",
1130
+ ...(action === "worktree add -b" ? { newRefName: "t3/new-thread" } : {}),
1131
path: path.join(cwd, "worktree"),
1132
})
1133
.pipe(Effect.flip);
@@ -3026,6 +3065,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3065
yield* git(previous.worktree.path, ["branch", "--show-current"]),
3066
initialBranch,
3067
);
3068
+ const fromPrevious = yield* driver.createWorktree({
3069
+ cwd,
3070
+ path: pathService.join(worktrees, "from-previous"),
3071
+ refName: "-",
3072
+ newRefName: "from-previous",
3073
+ });
3074
+ assert.equal(
3075
+ yield* git(fromPrevious.worktree.path, ["rev-parse", "HEAD"]),
3076
+ yield* git(cwd, ["rev-parse", initialBranch]),
3077
+ );
3078
}),
3079
);
3080
});
@@ -3124,6 +3173,85 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3173
}),
3174
);
3175
3176
+ it.effect("creates parallel worktrees in one repository without racing on its config", () =>
3177
+ Effect.gen(function* () {
3178
+ const cwd = yield* makeTmpDir();
3179
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
3180
+ const remote = yield* makeTmpDir("git-remote-");
3181
+ yield* git(remote, ["init", "--bare"]);
3182
+ yield* git(cwd, ["remote", "add", "origin", remote]);
3183
+ yield* git(cwd, ["push", "origin", initialBranch]);
3184
+ const path = yield* Path.Path;
3185
+ const worktrees = yield* makeTmpDir("git-worktrees-");
3186
+
3187
+ // Git has no lock timeout for .git/config, which every worktree shares: a writer that
3188
+ // overlaps another fails, and a branch can then be left without its worktree.
3189
+ let configWriters = 0;
3190
+ let peakConfigWriters = 0;
3191
+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
3192
+ const countingSpawner = ChildProcessSpawner.make((command) =>
3193
+ Effect.gen(function* () {
3194
+ const args = ChildProcess.isStandardCommand(command) ? command.args : [];
3195
+ const writesConfig =
3196
+ (args.includes("worktree") && args.includes("add") && args.includes("-b")) ||
3197
+ (args[0] === "branch" &&
3198
+ (args[1] === "-m" || args[1]?.startsWith("--set-upstream-to"))) ||
3199
+ (args[0] === "config" && !args[1]?.startsWith("-"));
3200
+ if (!writesConfig) return yield* delegate.spawn(command);
3201
+ configWriters += 1;
3202
+ peakConfigWriters = Math.max(peakConfigWriters, configWriters);
3203
+ const handle = yield* delegate.spawn(command);
3204
+ return ChildProcessSpawner.makeHandle({
3205
+ ...handle,
3206
+ exitCode: handle.exitCode.pipe(
3207
+ Effect.ensuring(Effect.sync(() => (configWriters -= 1))),
3208
+ ),
3209
+ });
3210
+ }),
3211
+ );
3212
+ const driver = yield* makeGitVcsDriverCore().pipe(
3213
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner),
3214
+ Effect.provide(layerServerConfig),
3215
+ );
3216
+ const branches = Array.from({ length: 8 }, (_, index) => `feature/parallel-${index}`);
3217
+
3218
+ yield* Effect.forEach(
3219
+ branches,
3220
+ (branch) =>
3221
+ driver.createWorktree({
3222
+ cwd,
3223
+ path: path.join(worktrees, branch.replace("/", "-")),
3224
+ refName: `origin/${initialBranch}`,
3225
+ newRefName: branch,
3226
+ baseRefName: `origin/${initialBranch}`,
3227
+ }),
3228
+ { concurrency: "unbounded" },
3229
+ );
3230
+ // Launches rename their temporary branch from inside the new worktree.
3231
+ yield* Effect.forEach(
3232
+ branches,
3233
+ (branch) =>
3234
+ driver.renameBranch({
3235
+ cwd: path.join(worktrees, branch.replace("/", "-")),
3236
+ oldBranch: branch,
3237
+ newBranch: `${branch}-renamed`,
3238
+ exactName: true,
3239
+ }),
3240
+ { concurrency: "unbounded" },
3241
+ );
3242
+
3243
+ assert.equal(peakConfigWriters, 1);
3244
+ for (const branch of branches) {
3245
+ const renamed = `${branch}-renamed`;
3246
+ assert.equal(yield* git(cwd, ["config", `branch.${renamed}.remote`]), "origin");
3247
+ assert.equal(
3248
+ yield* git(cwd, ["config", `branch.${renamed}.t3-merge-base-ref`]),
3249
+ `refs/remotes/origin/${initialBranch}`,
3250
+ );
3251
+ }
3252
+ }),
3253
+ );
3254
+
3255
it.effect.each(["release/v2", "refs/heads/release/v2", "deadbeef"])(
3256
"records the branch name when creating a worktree from %s",
3257
(baseRef) =>
@@ -3433,7 +3561,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3561
}),
3562
);
3563
3436
- it.effect("still creates the worktree when the base-ref config is locked", () =>
3564
+ it.effect("still creates the worktree when the base-ref config stays locked", () =>
3565
Effect.gen(function* () {
3566
const cwd = yield* makeTmpDir();
3567
const { initialBranch } = yield* initRepoWithCommit(cwd);
@@ -3443,13 +3571,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3571
yield* writeTextFile(cwd, ".git/config.lock", "");
3572
const driver = yield* GitVcsDriver.GitVcsDriver;
3573
3446
- const created = yield* driver.createWorktree({
3447
- cwd,
3448
- path: worktreePath,
3449
- refName: initialBranch,
3450
- newRefName: "feature/locked-config",
3451
- baseRefName: initialBranch,
3452
- });
3574
+ // The base-ref write retries on the real clock before giving up.
3575
+ const created = yield* TestClock.withLive(
3576
+ driver.createWorktree({
3577
+ cwd,
3578
+ path: worktreePath,
3579
+ refName: initialBranch,
3580
+ newRefName: "feature/locked-config",
3581
+ baseRefName: initialBranch,
3582
+ }),
3583
+ );
3584
3585
assert.deepEqual(created.worktree, {
3586
path: worktreePath,
@@ -3698,6 +3829,129 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3829
}),
3830
);
3831
3832
+ it.effect("ensureRemote returns the remote a parallel call added for the same URL", () =>
3833
+ Effect.gen(function* () {
3834
+ const cwd = yield* makeTmpDir();
3835
+ yield* git(cwd, ["init"]);
3836
+ // Hold the first add until both calls have listed remotes, so both decide to add.
3837
+ let listings = 0;
3838
+ const bothListed = yield* Deferred.make<void>();
3839
+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
3840
+ const spawner = ChildProcessSpawner.make((command) =>
3841
+ Effect.gen(function* () {
3842
+ const args = ChildProcess.isStandardCommand(command) ? command.args : [];
3843
+ if (args[0] === "remote" && args[1] === "-v") {
3844
+ listings += 1;
3845
+ if (listings === 2) yield* Deferred.succeed(bothListed, undefined);
3846
+ }
3847
+ if (args[0] === "remote" && args[1] === "add") yield* Deferred.await(bothListed);
3848
+ return yield* delegate.spawn(command);
3849
+ }),
3850
+ );
3851
+ const driver = yield* makeGitVcsDriverCore().pipe(
3852
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
3853
+ Effect.provide(layerServerConfig),
3854
+ );
3855
+ const input = { cwd, preferredName: "fork", url: "https://github.com/fork/t3code.git" };
3856
+
3857
+ const names = yield* Effect.all([driver.ensureRemote(input), driver.ensureRemote(input)], {
3858
+ concurrency: "unbounded",
3859
+ });
3860
+
3861
+ assert.deepEqual(names, ["fork", "fork"]);
3862
+ }),
3863
+ );
3864
+
3865
+ it.effect("retries a config write while another process holds the config lock", () =>
3866
+ Effect.gen(function* () {
3867
+ const cwd = yield* makeTmpDir();
3868
+ yield* initRepoWithCommit(cwd);
3869
+ const fileSystem = yield* FileSystem.FileSystem;
3870
+ const path = yield* Path.Path;
3871
+ const lockPath = path.join(cwd, ".git", "config.lock");
3872
+ yield* fileSystem.writeFileString(lockPath, "");
3873
+ const { driver, failures } = yield* makeDriverReleasingLock(
3874
+ (args) => args[1] === "t3.test",
3875
+ lockPath,
3876
+ );
3877
+
3878
+ // The retry waits on the real clock; the lock is already gone by then.
3879
+ yield* TestClock.withLive(
3880
+ driver.writeConfigValue({ cwd, key: "t3.test", value: "written" }),
3881
+ );
3882
+
3883
+ assert.equal(yield* Ref.get(failures), 1);
3884
+ assert.equal(yield* git(cwd, ["config", "t3.test"]), "written");
3885
+ }),
3886
+ );
3887
+
3888
+ it.effect("tracks a remote start point once another process releases the config lock", () =>
3889
+ Effect.gen(function* () {
3890
+ const cwd = yield* makeTmpDir();
3891
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
3892
+ const remote = yield* makeTmpDir("git-remote-");
3893
+ yield* git(remote, ["init", "--bare"]);
3894
+ yield* git(cwd, ["remote", "add", "origin", remote]);
3895
+ yield* git(cwd, ["push", "origin", initialBranch]);
3896
+ const fileSystem = yield* FileSystem.FileSystem;
3897
+ const path = yield* Path.Path;
3898
+ const lockPath = path.join(cwd, ".git", "config.lock");
3899
+ yield* fileSystem.writeFileString(lockPath, "");
3900
+ const { driver, failures } = yield* makeDriverReleasingLock(
3901
+ (args) => args.some((arg) => arg.startsWith("--set-upstream-to")),
3902
+ lockPath,
3903
+ );
3904
+
3905
+ // The upstream retry waits on the real clock; the lock is already gone by then.
3906
+ yield* TestClock.withLive(
3907
+ driver.createWorktree({
3908
+ cwd,
3909
+ path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"),
3910
+ refName: `origin/${initialBranch}`,
3911
+ newRefName: "feature/tracked",
3912
+ }),
3913
+ );
3914
+
3915
+ assert.equal(yield* Ref.get(failures), 1);
3916
+ assert.equal(
3917
+ yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]),
3918
+ `origin/${initialBranch}`,
3919
+ );
3920
+ }),
3921
+ );
3922
+
3923
+ it.effect("fetches a remote branch into a tracking branch past another process's lock", () =>
3924
+ Effect.gen(function* () {
3925
+ const cwd = yield* makeTmpDir();
3926
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
3927
+ const remote = yield* makeTmpDir("git-remote-");
3928
+ yield* git(remote, ["init", "--bare"]);
3929
+ yield* git(cwd, ["remote", "add", "origin", remote]);
3930
+ yield* git(cwd, ["push", "origin", `${initialBranch}:refs/heads/pr-head`]);
3931
+ const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock");
3932
+ yield* (yield* FileSystem.FileSystem).writeFileString(lockPath, "");
3933
+ const { driver, failures } = yield* makeDriverReleasingLock(
3934
+ (args) => args.some((arg) => arg.startsWith("--set-upstream-to")),
3935
+ lockPath,
3936
+ );
3937
+
3938
+ yield* TestClock.withLive(
3939
+ driver.fetchRemoteBranch({
3940
+ cwd,
3941
+ remoteName: "origin",
3942
+ remoteBranch: "pr-head",
3943
+ localBranch: "review/pr-head",
3944
+ }),
3945
+ );
3946
+
3947
+ assert.equal(yield* Ref.get(failures), 1);
3948
+ assert.equal(
3949
+ yield* git(cwd, ["rev-parse", "--abbrev-ref", "review/pr-head@{upstream}"]),
3950
+ "origin/pr-head",
3951
+ );
3952
+ }),
3953
+ );
3954
+
3955
// regression: #12485 explain fetch failures without exposing remote output
3956
it.effect("explains a real fetch failure for a missing local remote", () =>
3957
Effect.gen(function* () {
@@ -4211,6 +4465,45 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4465
}),
4466
);
4467
4468
+ it.effect("rebases a pushed branch's pulls when branch.autoSetupRebase asks for it", () =>
4469
+ Effect.gen(function* () {
4470
+ const cwd = yield* makeTmpDir();
4471
+ const remote = yield* makeTmpDir("git-remote-");
4472
+ yield* initRepoWithCommit(cwd);
4473
+ yield* git(remote, ["init", "--bare"]);
4474
+ yield* git(cwd, ["remote", "add", "origin", remote]);
4475
+ yield* git(cwd, ["config", "branch.autoSetupRebase", "always"]);
4476
+ yield* git(cwd, ["checkout", "-q", "-b", "feature/rebase"]);
4477
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4478
+
4479
+ assert.deepInclude(yield* driver.pushCurrentBranch(cwd, null), { setUpstream: true });
4480
+ assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/rebase.rebase"), "true");
4481
+ }),
4482
+ );
4483
+
4484
+ it.effect("reports a push whose upstream could not be recorded", () =>
4485
+ Effect.gen(function* () {
4486
+ const cwd = yield* makeTmpDir();
4487
+ const remote = yield* makeTmpDir("git-remote-");
4488
+ yield* initRepoWithCommit(cwd);
4489
+ yield* git(remote, ["init", "--bare"]);
4490
+ yield* git(cwd, ["remote", "add", "origin", remote]);
4491
+ yield* git(cwd, ["checkout", "-q", "-b", "feature/locked"]);
4492
+ yield* writeTextFile(cwd, ".git/config.lock", "");
4493
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4494
+
4495
+ // Recording the upstream retries on the real clock before giving up.
4496
+ const pushed = yield* TestClock.withLive(driver.pushCurrentBranch(cwd, null));
4497
+
4498
+ assert.deepInclude(pushed, { status: "pushed", setUpstream: false });
4499
+ assert.include(
4500
+ yield* git(cwd, ["ls-remote", "origin", "refs/heads/feature/locked"]),
4501
+ yield* git(cwd, ["rev-parse", "HEAD"]),
4502
+ );
4503
+ assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/locked.remote"), null);
4504
+ }),
4505
+ );
4506
+
4507
it.effect.each(["feature/push", "origin/feature/push"])(
4508
"publishes %s when the configured diff base already contains HEAD",
4509
(branch) =>
apps/server/src/vcs/GitVcsDriverCore.ts
+227
-63
@@ -16,6 +16,7 @@ import * as PlatformError from "effect/PlatformError";
16
import * as Ref from "effect/Ref";
17
import * as Result from "effect/Result";
18
import * as Schema from "effect/Schema";
19
+import * as Schedule from "effect/Schedule";
20
import * as Scope from "effect/Scope";
21
import * as Semaphore from "effect/Semaphore";
22
import * as Stream from "effect/Stream";
@@ -185,6 +186,7 @@ interface ExecuteGitOptions {
186
maxOutputBytes?: number | undefined;
187
appendTruncationMarker?: boolean | undefined;
188
progress?: GitVcsDriver.ExecuteGitProgress | undefined;
189
+ writesSharedConfig?: boolean | undefined;
190
}
191
192
function parseBranchAb(value: string): { ahead: number; behind: number } {
@@ -435,6 +437,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai
437
[/would clobber existing tag/i, "tag_would_be_clobbered"],
438
[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
439
[/a branch named .+ already exists/i, "branch_already_exists"],
440
+ // The same prefix also reports permission errors, which retrying cannot fix.
441
+ [/could not lock config file .+: File exists/i, "config_locked"],
442
[
443
/(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,
444
"authentication_failed",
@@ -469,6 +473,8 @@ const GIT_FAILURE_REASON_DETAILS: Partial<Record<GitCommandFailureReason, string
473
"The remote rejected the push. Push this branch from a terminal to see the server's message.",
474
push_rejected_non_fast_forward:
475
"The remote has commits this branch doesn't have. Pull or rebase, then push again.",
476
+ config_locked:
477
+ "Another Git process kept the repository's config locked. Wait for it to finish, then retry.",
478
};
479
480
function gitFailureDetail(reason: GitCommandFailureReason | null): string {
@@ -1072,6 +1078,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1078
},
1079
);
1080
1081
+ const sharedConfigLocks = new Map<string, Semaphore.Semaphore>();
1082
+ const withSharedConfigLock = <A, E>(cwd: string, effect: Effect.Effect<A, E>) =>
1083
+ resolveRepositoryPaths(cwd).pipe(
1084
+ Effect.orElseSucceed(() => null),
1085
+ Effect.flatMap((repositoryPaths) => {
1086
+ if (repositoryPaths === null) return effect;
1087
+ let lock = sharedConfigLocks.get(repositoryPaths.gitCommonDir);
1088
+ if (lock === undefined) {
1089
+ lock = Semaphore.makeUnsafe(1);
1090
+ sharedConfigLocks.set(repositoryPaths.gitCommonDir, lock);
1091
+ }
1092
+ return lock.withPermit(effect);
1093
+ }),
1094
+ );
1095
+
1096
const execute: GitVcsDriver.GitVcsDriver["Service"]["execute"] = (input) =>
1097
executeRaw(input).pipe(
1098
withMetrics({
@@ -1093,6 +1114,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1114
"git.args_count": input.args.length,
1115
},
1116
}),
1117
+ // Outside the process permit: resolving the repository may itself need one.
1118
+ (execution) =>
1119
+ input.writesSharedConfig ? withSharedConfigLock(input.cwd, execution) : execution,
1120
);
1121
1122
const executeGit = (
@@ -1117,6 +1141,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1141
? { appendTruncationMarker: options.appendTruncationMarker }
1142
: {}),
1143
...(options.progress ? { progress: options.progress } : {}),
1144
+ ...(options.writesSharedConfig ? { writesSharedConfig: true } : {}),
1145
}).pipe(
1146
Effect.flatMap((result) => {
1147
if (options.allowNonZeroExit || result.exitCode === 0) {
@@ -1698,17 +1723,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1723
)(function* (input) {
1724
const preferredName = sanitizeRemoteName(input.preferredName);
1725
const normalizedTargetUrl = sourceControlDefinitions.repositoryKeyFromRemote(input.url);
1701
- const remoteFetchUrls = yield* runGitStdout(
1726
+ const listRemoteFetchUrls = runGitStdout(
1727
"GitVcsDriver.ensureRemote.listRemoteUrls",
1728
input.cwd,
1729
["remote", "-v"],
1730
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
1731
+ const findMatchingRemote = (remoteFetchUrls: Map<string, string>) =>
1732
+ Array.from(remoteFetchUrls.entries()).find(
1733
+ ([, remoteUrl]) =>
1734
+ sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl,
1735
+ )?.[0];
1736
1707
- for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
1708
- if (sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl) {
1709
- return remoteName;
1710
- }
1711
- }
1737
+ const remoteFetchUrls = yield* listRemoteFetchUrls;
1738
+ const existing = findMatchingRemote(remoteFetchUrls);
1739
+ if (existing !== undefined) return existing;
1740
1741
let remoteName = preferredName;
1742
let suffix = 1;
@@ -1717,14 +1745,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1745
suffix += 1;
1746
}
1747
1720
- yield* runGit("GitVcsDriver.ensureRemote.add", input.cwd, [
1721
- "remote",
1722
- "add",
1723
- "--",
1724
- remoteName,
1725
- input.url,
1726
- ]);
1727
- return remoteName;
1748
+ return yield* executeGitWithStableDiagnostics(
1749
+ "GitVcsDriver.ensureRemote.add",
1750
+ input.cwd,
1751
+ ["remote", "add", "--", remoteName, input.url],
1752
+ { writesSharedConfig: true },
1753
+ ).pipe(
1754
+ retryWhileConfigLocked,
1755
+ Effect.as(remoteName),
1756
+ // A parallel launch for the same fork may have added it since the listing above.
1757
+ Effect.catch((error) =>
1758
+ listRemoteFetchUrls.pipe(
1759
+ Effect.flatMap((current) => {
1760
+ const added = findMatchingRemote(current);
1761
+ return added === undefined ? Effect.fail(error) : Effect.succeed(added);
1762
+ }),
1763
+ ),
1764
+ ),
1765
+ );
1766
});
1767
1768
const resolveComparisonBaseRef = Effect.fn("resolveComparisonBaseRef")(function* (
@@ -2476,6 +2514,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2514
return { commitSha };
2515
});
2516
2517
+ // `push -u` exits 0 without the upstream when another writer holds the config lock.
2518
+ const recordPushedUpstream = Effect.fn("recordPushedUpstream")(
2519
+ function* (cwd: string, branch: string, remoteName: string, publishBranch: string) {
2520
+ // Without a prior upstream, Git ignores a merge ref with no remote, so losing the second
2521
+ // write leaves none rather than a wrong one.
2522
+ yield* writeConfigValue({
2523
+ cwd,
2524
+ key: `branch.${branch}.merge`,
2525
+ value: `refs/heads/${publishBranch}`,
2526
+ });
2527
+ yield* writeConfigValue({ cwd, key: `branch.${branch}.remote`, value: remoteName });
2528
+ // Matches what `push -u` sets for a remote upstream.
2529
+ const autoSetupRebase = yield* readConfigValue(cwd, "branch.autoSetupRebase");
2530
+ if (autoSetupRebase === "always" || autoSetupRebase === "remote") {
2531
+ yield* writeConfigValue({ cwd, key: `branch.${branch}.rebase`, value: "true" });
2532
+ }
2533
+ return true;
2534
+ },
2535
+ Effect.catch((cause) =>
2536
+ Effect.logWarning("pushed, but could not record the branch upstream", { cause }).pipe(
2537
+ Effect.as(false),
2538
+ ),
2539
+ ),
2540
+ );
2541
+
2542
const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn(
2543
"pushCurrentBranch",
2544
)(function* (cwd, fallbackBranch, options) {
@@ -2498,14 +2561,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2561
yield* runGit(
2562
"GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
2563
cwd,
2501
- ["push", "-u", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],
2564
+ ["push", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],
2565
{ timeoutMs: null },
2566
);
2567
return {
2568
status: "pushed" as const,
2569
branch,
2570
upstreamBranch: `${requestedRemoteName}/${publishBranch}`,
2508
- setUpstream: true,
2571
+ setUpstream: yield* recordPushedUpstream(cwd, branch, requestedRemoteName, publishBranch),
2572
};
2573
}
2574
@@ -2574,14 +2637,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2637
yield* runGit(
2638
"GitVcsDriver.pushCurrentBranch.pushWithUpstream",
2639
cwd,
2577
- ["push", "-u", "--", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],
2640
+ ["push", "--", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],
2641
{ timeoutMs: null },
2642
);
2643
return {
2644
status: "pushed" as const,
2645
branch,
2646
upstreamBranch: `${publishRemoteName}/${publishBranch}`,
2584
- setUpstream: true,
2647
+ setUpstream: yield* recordPushedUpstream(cwd, branch, publishRemoteName, publishBranch),
2648
};
2649
}
2650
@@ -2602,30 +2665,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2665
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
2666
// Publishing retargets the upstream, so preserve its comparison base first.
2667
if ((yield* readBranchBase(cwd, branch)) === null) {
2605
- yield* runGit("GitVcsDriver.pushCurrentBranch.recordMergeBase", cwd, [
2606
- "config",
2607
- branchBaseConfigKey(branch),
2608
- currentUpstream.branchName,
2609
- ]);
2668
+ yield* writeConfigValue({
2669
+ cwd,
2670
+ key: branchBaseConfigKey(branch),
2671
+ value: currentUpstream.branchName,
2672
+ });
2673
if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {
2611
- yield* runGit("GitVcsDriver.pushCurrentBranch.recordComparisonRef", cwd, [
2612
- "config",
2613
- `branch.${branch}.t3-merge-base-ref`,
2614
- `refs/remotes/${currentUpstream.upstreamRef}`,
2615
- ]);
2674
+ yield* writeConfigValue({
2675
+ cwd,
2676
+ key: `branch.${branch}.t3-merge-base-ref`,
2677
+ value: `refs/remotes/${currentUpstream.upstreamRef}`,
2678
+ });
2679
}
2680
}
2681
yield* runGit(
2682
"GitVcsDriver.pushCurrentBranch.pushOwnBranch",
2683
cwd,
2621
- ["push", "-u", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],
2684
+ ["push", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],
2685
{ timeoutMs: null },
2686
);
2687
return {
2688
status: "pushed" as const,
2689
branch,
2690
upstreamBranch: `${remoteName}/${publishBranch}`,
2628
- setUpstream: true,
2691
+ setUpstream: yield* recordPushedUpstream(cwd, branch, remoteName, publishBranch),
2692
};
2693
}
2694
@@ -3325,6 +3388,70 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3388
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
3389
);
3390
3391
+ // Git never waits for .git/config.lock, and git run outside T3, such as an agent's, can hold it.
3392
+ // Only writes that are safe to repeat retry.
3393
+ const retryWhileConfigLocked = <A>(effect: Effect.Effect<A, GitCommandError>) =>
3394
+ effect.pipe(
3395
+ Effect.retry({
3396
+ while: (error) => error.reason === "config_locked",
3397
+ times: 10,
3398
+ schedule: Schedule.spaced("50 millis"),
3399
+ }),
3400
+ );
3401
+
3402
+ const writeConfigValue: GitVcsDriver.GitVcsDriver["Service"]["writeConfigValue"] = Effect.fn(
3403
+ "writeConfigValue",
3404
+ )(function* (input) {
3405
+ yield* executeGitWithStableDiagnostics(
3406
+ "GitVcsDriver.writeConfigValue",
3407
+ input.cwd,
3408
+ ["config", input.key, input.value],
3409
+ { writesSharedConfig: true },
3410
+ ).pipe(retryWhileConfigLocked);
3411
+ });
3412
+
3413
+ // `git branch` writes a remote start point's upstream itself and fails outright if the
3414
+ // config is locked, so tracking is recorded afterwards by a write that retries.
3415
+ const createBranchAt = Effect.fn("createBranchAt")(function* (
3416
+ operation: string,
3417
+ input: GitVcsDriver.GitCreateBranchInput,
3418
+ fallbackErrorDetail: string,
3419
+ ) {
3420
+ // `git branch` does not read a lone - as the previous checkout.
3421
+ const startPoint = input.startPoint === "-" ? "@{-1}" : input.startPoint;
3422
+ yield* executeGitWithStableDiagnostics(
3423
+ operation,
3424
+ input.cwd,
3425
+ ["branch", "--no-track", "--", input.branch, startPoint],
3426
+ { fallbackErrorDetail },
3427
+ );
3428
+ const startRef = yield* executeGit(
3429
+ `${operation}.resolveStartPoint`,
3430
+ input.cwd,
3431
+ ["rev-parse", "--symbolic-full-name", startPoint],
3432
+ { allowNonZeroExit: true },
3433
+ ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : "")));
3434
+ if (!startRef.startsWith("refs/remotes/")) return;
3435
+ yield* executeGitWithStableDiagnostics(
3436
+ `${operation}.track`,
3437
+ input.cwd,
3438
+ ["branch", `--set-upstream-to=${startRef}`, "--", input.branch],
3439
+ { writesSharedConfig: true },
3440
+ ).pipe(
3441
+ retryWhileConfigLocked,
3442
+ Effect.catch((cause) =>
3443
+ Effect.logWarning("created the branch without tracking its start point", { cause }),
3444
+ ),
3445
+ );
3446
+ });
3447
+
3448
+ const createBranch: GitVcsDriver.GitVcsDriver["Service"]["createBranch"] = Effect.fn(
3449
+ "createBranch",
3450
+ )(function* (input) {
3451
+ yield* refuseOptionLikeRefName("GitVcsDriver.createBranch", input.cwd, input.startPoint);
3452
+ yield* createBranchAt("GitVcsDriver.createBranch", input, "git branch create failed");
3453
+ });
3454
+
3455
const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn(
3456
"GitVcsDriver.readBranchBase",
3457
)(function* (cwd, branch) {
@@ -3700,9 +3827,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3827
}
3828
worktreePath = path.join(parentDir, repoName, sanitizedBranch);
3829
}
3703
- const args = input.newRefName
3704
- ? ["worktree", "add", "-b", input.newRefName, "--", worktreePath, input.refName]
3705
- : ["worktree", "add", "--", worktreePath, input.refName];
3830
+ if (input.newRefName) {
3831
+ // Kept apart from the checkout so the shared-config lock only covers the tracking write.
3832
+ yield* createBranchAt(
3833
+ "GitVcsDriver.createWorktree.createBranch",
3834
+ { cwd: input.cwd, branch: input.newRefName, startPoint: input.refName },
3835
+ "git worktree add failed",
3836
+ );
3837
+ }
3838
+ const args = ["worktree", "add", "--", worktreePath, input.newRefName ?? input.refName];
3839
const progress = options?.progress;
3840
const onCheckoutProgress = progress?.onCheckoutProgress;
3841
@@ -3767,19 +3900,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3900
yield* progress.onSubmodulesStarted();
3901
}
3902
const onSubmoduleLine = progress?.onSubmoduleLine;
3903
+ // Registering submodule URLs writes the shared config; the clones that follow do not.
3904
yield* runGit(
3771
- "GitVcsDriver.createWorktree.updateSubmodules",
3905
+ "GitVcsDriver.createWorktree.initSubmodules",
3906
worktreePath,
3773
- submoduleMode.value === "recursive"
3774
- ? ["submodule", "update", "--init", "--recursive"]
3775
- : ["submodule", "update", "--init"],
3776
- onSubmoduleLine
3777
- ? {
3778
- env: { LC_ALL: "C" },
3779
- progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine },
3780
- }
3781
- : {},
3907
+ ["submodule", "init"],
3908
+ { writesSharedConfig: true },
3909
).pipe(
3910
+ Effect.andThen(
3911
+ runGit(
3912
+ "GitVcsDriver.createWorktree.updateSubmodules",
3913
+ worktreePath,
3914
+ submoduleMode.value === "recursive"
3915
+ ? ["submodule", "update", "--init", "--recursive"]
3916
+ : ["submodule", "update", "--init"],
3917
+ onSubmoduleLine
3918
+ ? {
3919
+ env: { LC_ALL: "C" },
3920
+ progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine },
3921
+ }
3922
+ : {},
3923
+ ),
3924
+ ),
3925
Effect.matchEffect({
3926
onFailure: (cause) =>
3927
Effect.logWarning("worktree submodule checkout failed; submodule paths are empty", {
@@ -3805,18 +3947,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3947
const base = yield* resolveBranchBase(input.cwd, input.baseRefName);
3948
if (base) {
3949
yield* Effect.gen(function* () {
3808
- yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
3809
- "config",
3810
- branchBaseConfigKey(newRefName),
3811
- base.branchName,
3812
- ]);
3950
+ yield* writeConfigValue({
3951
+ cwd: input.cwd,
3952
+ key: branchBaseConfigKey(newRefName),
3953
+ value: base.branchName,
3954
+ });
3955
if (base.baseRef.startsWith("refs/remotes/")) {
3956
// The base key names a branch on the host; this one keeps the remote it came from.
3815
- yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
3816
- "config",
3817
- `branch.${input.newRefName}.t3-merge-base-ref`,
3818
- base.baseRef,
3819
- ]);
3957
+ yield* writeConfigValue({
3958
+ cwd: input.cwd,
3959
+ key: `branch.${input.newRefName}.t3-merge-base-ref`,
3960
+ value: base.baseRef,
3961
+ });
3962
}
3963
}).pipe(
3964
Effect.catchTags({
@@ -4103,12 +4245,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4245
4246
const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch);
4247
const targetRef = `${input.remoteName}/${input.remoteBranch}`;
4248
+ if (!localBranchAlreadyExists) {
4249
+ return yield* createBranchAt(
4250
+ "GitVcsDriver.fetchRemoteBranch.materialize",
4251
+ { cwd: input.cwd, branch: input.localBranch, startPoint: targetRef },
4252
+ "git branch create failed",
4253
+ );
4254
+ }
4255
yield* runGit(
4256
"GitVcsDriver.fetchRemoteBranch.materialize",
4257
input.cwd,
4109
- localBranchAlreadyExists
4110
- ? ["branch", "--force", "--", input.localBranch, targetRef]
4111
- : ["branch", "--", input.localBranch, targetRef],
4258
+ ["branch", "--force", "--", input.localBranch, targetRef],
4259
+ { writesSharedConfig: true },
4260
);
4261
});
4262
@@ -4125,13 +4273,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4273
});
4274
4275
const setBranchUpstream: GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"] = (input) =>
4128
- runGit("GitVcsDriver.setBranchUpstream", input.cwd, [
4129
- "branch",
4130
- "--set-upstream-to",
4131
- `${input.remoteName}/${input.remoteBranch}`,
4132
- "--",
4133
- input.branch,
4134
- ]);
4276
+ executeGitWithStableDiagnostics(
4277
+ "GitVcsDriver.setBranchUpstream",
4278
+ input.cwd,
4279
+ [
4280
+ "branch",
4281
+ "--set-upstream-to",
4282
+ `${input.remoteName}/${input.remoteBranch}`,
4283
+ "--",
4284
+ input.branch,
4285
+ ],
4286
+ { writesSharedConfig: true },
4287
+ ).pipe(retryWhileConfigLocked, Effect.asVoid);
4288
4289
/**
4290
* Unlinks links under `target` without following them and removes the
@@ -4240,6 +4393,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4393
{
4394
timeoutMs: 10_000,
4395
fallbackErrorDetail: "git branch delete failed",
4396
+ // Under contention Git deletes the ref but keeps its config section.
4397
+ writesSharedConfig: true,
4398
},
4399
);
4400
});
@@ -4261,6 +4416,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4416
{
4417
timeoutMs: 10_000,
4418
fallbackErrorDetail: "git branch rename failed",
4419
+ writesSharedConfig: true,
4420
},
4421
);
4422
@@ -4346,6 +4502,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4502
{
4503
timeoutMs: 10_000,
4504
fallbackErrorDetail: "git checkout failed",
4505
+ // Checking out a remote branch creates a local one that tracks it.
4506
+ writesSharedConfig: !localInputExists,
4507
},
4508
);
4509
@@ -4363,6 +4521,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4521
yield* executeGit("GitVcsDriver.createRef", input.cwd, ["branch", "--", input.refName], {
4522
timeoutMs: 10_000,
4523
fallbackErrorDetail: "git branch create failed",
4524
+ // `branch.autoSetupMerge=always` records HEAD's branch as the upstream.
4525
+ writesSharedConfig: true,
4526
});
4527
if (input.switchRef) {
4528
yield* switchRef({ cwd: input.cwd, refName: input.refName });
@@ -4507,6 +4667,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4667
setBranchUpstream: Effect.fnUntraced(function* (input) {
4668
return yield* withListRefsInvalidation(input.cwd, setBranchUpstream(input));
4669
}),
4670
+ createBranch: Effect.fnUntraced(function* (input) {
4671
+ return yield* withListRefsInvalidation(input.cwd, createBranch(input));
4672
+ }),
4673
+ writeConfigValue,
4674
removeWorktree: Effect.fnUntraced(function* (input) {
4675
return yield* withListRefsInvalidation(input.cwd, removeWorktree(input));
4676
}),
packages/contracts/src/git.ts
+1
@@ -354,6 +354,7 @@ export const GitCommandFailureReason = Schema.Literals([
354
"authentication_failed",
355
"branch_already_exists",
356
"branch_checked_out_in_worktree",
357
+ "config_locked",
358
"host_key_unverified",
359
"not_a_repository",
360
"path_already_exists",
packages/source-control-core/src/server/SourceControlHost.ts
+14
@@ -109,6 +109,20 @@ export class SourceControlHost extends Context.Service<
109
readonly setBranchUpstream: (
110
input: SourceControlGitRemoteBranch & { readonly branch: string },
111
) => Effect.Effect<void, GitCommandError>;
112
+ /**
113
+ * Writes to .git/config, which every worktree shares, go through these rather than
114
+ * `execute`: the host serializes them per repository.
115
+ */
116
+ readonly createBranch: (input: {
117
+ readonly cwd: string;
118
+ readonly branch: string;
119
+ readonly startPoint: string;
120
+ }) => Effect.Effect<void, GitCommandError>;
121
+ readonly writeConfigValue: (input: {
122
+ readonly cwd: string;
123
+ readonly key: string;
124
+ readonly value: string;
125
+ }) => Effect.Effect<void, GitCommandError>;
126
readonly switchRef: (
127
input: VcsSwitchRefInput,
128
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts
+2
@@ -492,8 +492,10 @@ export const make = Effect.gen(function* () {
492
yield* git.execute({
493
operation: "GitCafeSourceControlProvider.checkoutChangeRequest",
494
cwd: input.cwd,
495
+ // The upstream is recorded next, through the host's serialized config write.
496
args: [
497
"checkout",
498
+ "--no-track",
499
"-B",
500
localBranch,
501
`refs/remotes/${remoteName}/${pull.headRefName}`,
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+20
@@ -182,6 +182,8 @@ function harness(input: {
182
}),
183
fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
184
setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
185
+ createBranch: (args) => record("createBranch", undefined)(args),
186
+ writeConfigValue: (args) => record("writeConfigValue", undefined)(args),
187
switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
188
listLocalBranchNames: () =>
189
input.gitFailure === undefined
@@ -526,6 +528,19 @@ describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
528
}).pipe(Effect.provide(layer));
529
});
530
531
+ it.effect("records the branch base for gh through the host's config write", () => {
532
+ const { layer, git } = harness({
533
+ remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
534
+ });
535
+ return Effect.gen(function* () {
536
+ const gh = yield* GitHubSourceControlProvider.make;
537
+ yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });
538
+ assert.deepStrictEqual(git, [
539
+ ["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],
540
+ ]);
541
+ }).pipe(Effect.provide(layer));
542
+ });
543
+
544
it("names the local branch the way gh pr checkout does", () => {
545
const name = (headRefName: string, isCrossRepository: boolean) =>
546
GitHubSourceControlProvider.pullRequestCheckoutBranchName({
@@ -949,6 +964,11 @@ it.live.each([
964
["github.com", "repos/team/explicit"],
965
],
966
);
967
+ assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {
968
+ cwd: "/repo",
969
+ branch: "feature",
970
+ startPoint: "refs/remotes/enterprise/feature",
971
+ });
972
assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
973
cwd: "/repo",
974
remoteName: "enterprise",
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+4
-7
@@ -750,7 +750,9 @@ export const make = Effect.gen(function* () {
750
);
751
752
yield* Effect.gen(function* () {
753
- if (!exists) yield* runGit(input.cwd, "branch", ["branch", "--", localBranch, target.ref]);
753
+ if (!exists) {
754
+ yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
755
+ }
756
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
757
if (exists) {
758
yield* runGit(
@@ -891,13 +893,8 @@ export const make = Effect.gen(function* () {
893
baseBranch,
894
}) {
895
return git
894
- .execute({
895
- operation: "GitHubSourceControlProvider.recordBranchBase",
896
- cwd,
897
- args: ["config", `branch.${branch}.gh-merge-base`, baseBranch],
898
- })
896
+ .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
897
.pipe(
900
- Effect.asVoid,
898
Effect.catch((cause) =>
899
Effect.logWarning("Could not record the branch base for gh", { cause }),
900
),
packages/source-control-testing/src/TestSourceControlHost.ts
+2
@@ -44,6 +44,8 @@ const failingGit: Git = {
44
fetchRemoteBranch: unexpectedGit("fetchRemoteBranch"),
45
fetchRemoteTrackingBranch: unexpectedGit("fetchRemoteTrackingBranch"),
46
setBranchUpstream: unexpectedGit("setBranchUpstream"),
47
+ createBranch: unexpectedGit("createBranch"),
48
+ writeConfigValue: unexpectedGit("writeConfigValue"),
49
switchRef: unexpectedGit("switchRef"),
50
};
51