Skip to content

Commit 193ebd2

Browse files
authored
Merge pull request #64 from henrychu04/t3code/fix-starting-screen-branch-switch
fix(server): resolve remote-tracking refs when switching branches
2 parents c3e62e1 + d85fb4e commit 193ebd2

2 files changed

Lines changed: 140 additions & 2 deletions

File tree

‎apps/server/src/vcs/GitVcsDriver.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -876,3 +876,67 @@ it.effect("GitVcsDriver checks out the requested commit and records the worktree
876876
yield* driver.removeWorktree({ cwd: repo, path: worktreePath, force: true });
877877
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
878878
);
879+
880+
it.effect("GitVcsDriver switchRef resolves remote-tracking refs to local branches", () =>
881+
Effect.gen(function* () {
882+
const fileSystem = yield* FileSystem.FileSystem;
883+
const path = yield* Path.Path;
884+
const driver = yield* GitVcsDriver.GitVcsDriver;
885+
const fixtureRoot = yield* fileSystem.makeTempDirectoryScoped({
886+
prefix: "t3-git-switch-ref-",
887+
});
888+
const upstream = path.join(fixtureRoot, "upstream");
889+
const repo = path.join(fixtureRoot, "repo");
890+
yield* fileSystem.makeDirectory(upstream);
891+
yield* fileSystem.makeDirectory(repo);
892+
yield* runGit(upstream, ["init", "--initial-branch=main"]);
893+
yield* runGit(upstream, ["config", "user.email", "[email protected]"]);
894+
yield* runGit(upstream, ["config", "user.name", "Test"]);
895+
yield* fileSystem.writeFileString(path.join(upstream, "README.md"), "base\n");
896+
yield* runGit(upstream, ["add", "README.md"]);
897+
yield* runGit(upstream, ["commit", "-m", "Initial"]);
898+
yield* runGit(upstream, ["branch", "feature/only-remote"]);
899+
yield* runGit(upstream, ["branch", "feature/existing-local"]);
900+
yield* runGit(upstream, ["branch", "feature/twin"]);
901+
yield* runGit(upstream, ["branch", "feature/untracked"]);
902+
yield* runGit(repo, ["clone", upstream, "."]);
903+
yield* runGit(repo, ["config", "user.email", "[email protected]"]);
904+
yield* runGit(repo, ["config", "user.name", "Test"]);
905+
yield* runGit(repo, ["branch", "feature/existing-local", "origin/feature/existing-local"]);
906+
yield* runGit(repo, ["branch", "twin-alias", "origin/feature/twin"]);
907+
yield* runGit(repo, ["branch", "feature/untracked", "origin/feature/untracked"]);
908+
yield* runGit(repo, ["branch", "--unset-upstream", "feature/untracked"]);
909+
910+
// Remote-only ref: creates and checks out a local branch tracking it.
911+
const created = yield* driver.switchRef({ cwd: repo, refName: "origin/feature/only-remote" });
912+
assert.strictEqual(created.refName, "feature/only-remote");
913+
assert.strictEqual(
914+
yield* readGit(repo, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]),
915+
"origin/feature/only-remote",
916+
);
917+
918+
// Remote ref tracked by a differently-named local branch: checks that out.
919+
const alias = yield* driver.switchRef({ cwd: repo, refName: "origin/feature/twin" });
920+
assert.strictEqual(alias.refName, "twin-alias");
921+
922+
// Local twin exists but does not track the remote ref: upstream checks out
923+
// the remote ref directly (detached HEAD, so no branch name comes back).
924+
const untracked = yield* driver.switchRef({ cwd: repo, refName: "origin/feature/untracked" });
925+
assert.strictEqual(untracked.refName, null);
926+
927+
// Remote ref tracked by a same-named local branch: checks that out.
928+
const existing = yield* driver.switchRef({
929+
cwd: repo,
930+
refName: "origin/feature/existing-local",
931+
});
932+
assert.strictEqual(existing.refName, "feature/existing-local");
933+
assert.strictEqual(
934+
yield* readGit(repo, ["symbolic-ref", "--short", "HEAD"]),
935+
"feature/existing-local",
936+
);
937+
938+
// Plain local ref: unchanged behavior.
939+
const local = yield* driver.switchRef({ cwd: repo, refName: "main" });
940+
assert.strictEqual(local.refName, "main");
941+
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
942+
);

‎apps/server/src/vcs/GitVcsDriver.ts‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ import {
3737
type VcsStatusInput,
3838
type VcsStatusResult,
3939
} from "@t3tools/contracts";
40-
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
40+
import {
41+
dedupeRemoteBranchesWithLocalMatches,
42+
deriveLocalBranchNameFromRemoteRef,
43+
} from "@t3tools/shared/git";
4144
import * as VcsDriver from "./VcsDriver.ts";
4245
import * as VcsProcess from "./VcsProcess.ts";
4346
import * as ServerConfig from "../config.ts";
@@ -362,6 +365,27 @@ function parseRemoteRef(
362365
return null;
363366
}
364367

368+
// Ported from upstream GitVcsDriverCore.
369+
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
370+
for (const line of stdout.split("\n")) {
371+
const trimmedLine = line.trim();
372+
if (trimmedLine.length === 0) {
373+
continue;
374+
}
375+
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
376+
const branchName = branchNameRaw?.trim() ?? "";
377+
const candidateUpstreamRef = upstreamBranchRaw.trim();
378+
if (branchName.length === 0 || candidateUpstreamRef.length === 0) {
379+
continue;
380+
}
381+
if (candidateUpstreamRef === upstreamRef) {
382+
return branchName;
383+
}
384+
}
385+
386+
return null;
387+
}
388+
365389
function parseGitRemoteVerboseOutput(
366390
output: string,
367391
): Map<string, { url?: string; pushUrl?: string }> {
@@ -1787,7 +1811,57 @@ const makeLocalGitService = Effect.gen(function* () {
17871811

17881812
const switchRef: GitVcsDriver["Service"]["switchRef"] = Effect.fn("GitVcsDriver.switchRef")(
17891813
function* (input) {
1790-
yield* run("GitVcsDriver.switchRef", input.cwd, ["switch", input.refName], {
1814+
// Ported from upstream GitVcsDriverCore.switchRef: the picked ref may be
1815+
// a local branch or a remote-tracking branch such as "origin/feature",
1816+
// which git cannot check out directly. Resolve the checkout target the
1817+
// same way upstream does: prefer the local branch of the same name, then
1818+
// a local branch that already tracks the remote ref, then a fresh
1819+
// tracking branch created from the remote ref.
1820+
const [localInputExists, remoteExists] = yield* Effect.all(
1821+
[
1822+
localBranchExists(input.cwd, input.refName),
1823+
run(
1824+
"GitVcsDriver.switchRef.remoteExists",
1825+
input.cwd,
1826+
["show-ref", "--verify", "--quiet", `refs/remotes/${input.refName}`],
1827+
{ allowNonZeroExit: true },
1828+
).pipe(Effect.map((result) => result.exitCode === 0)),
1829+
],
1830+
{ concurrency: "unbounded" },
1831+
);
1832+
1833+
const localTrackingBranch = remoteExists
1834+
? yield* run(
1835+
"GitVcsDriver.switchRef.localTrackingBranch",
1836+
input.cwd,
1837+
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
1838+
{ allowNonZeroExit: true },
1839+
).pipe(
1840+
Effect.map((result) =>
1841+
result.exitCode === 0
1842+
? parseTrackingBranchByUpstreamRef(result.stdout, input.refName)
1843+
: null,
1844+
),
1845+
)
1846+
: null;
1847+
1848+
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName);
1849+
const localTrackedBranchTargetExists =
1850+
remoteExists && localTrackedBranchCandidate
1851+
? yield* localBranchExists(input.cwd, localTrackedBranchCandidate)
1852+
: false;
1853+
1854+
const checkoutArgs = localInputExists
1855+
? ["checkout", input.refName]
1856+
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
1857+
? ["checkout", input.refName]
1858+
: remoteExists && !localTrackingBranch
1859+
? ["checkout", "--track", input.refName]
1860+
: remoteExists && localTrackingBranch
1861+
? ["checkout", localTrackingBranch]
1862+
: ["checkout", input.refName];
1863+
1864+
yield* run("GitVcsDriver.switchRef.checkout", input.cwd, checkoutArgs, {
17911865
timeoutMs: 300_000,
17921866
});
17931867
return { refName: yield* currentBranch(input.cwd) };

0 commit comments

Comments
 (0)