Skip to content

The agent that grows with you

fix(desktop): convert origin/<branch> on tag-pinned narrow clones

kshitijk4poor0fe470b1f7bf
diff --git a/apps/desktop/electron/git-worktree-ops.test.ts b/apps/desktop/electron/git-worktree-ops.test.ts
index 20af7c7755b..053ee5369a7 100644
--- a/apps/desktop/electron/git-worktree-ops.test.ts
+++ b/apps/desktop/electron/git-worktree-ops.test.ts
@@ -364,6 +364,100 @@ test('addWorktree: base origin/main resolves on a tag-pinned narrow clone', asyn
}
})
+// A tag-pinned narrow clone (`--single-branch --branch v0`), the shape older
+// installers made: remote.origin.fetch maps only the tag, so no branch has a
+// tracking ref. The remote has `main` and `feature` one commit past the tag.
+// Returns both paths and the tip. The caller must remove them.
+function seedNarrowClone(label) {
+ const remoteDir = fs.mkdtempSync(path.join(os.tmpdir(), `hermes-${label}-remote-`))
+ const cloneDir = fs.mkdtempSync(path.join(os.tmpdir(), `hermes-${label}-clone-`))
+ const ident = ['-c', 'user.email=hermes@localhost', '-c', 'user.name=Hermes']
+
+ execFileSync('git', ['init', '-q', '-b', 'main', remoteDir])
+ execFileSync('git', ['-C', remoteDir, ...ident, 'commit', '-q', '--allow-empty', '-m', 'root'])
+ execFileSync('git', ['-C', remoteDir, 'tag', 'v0'])
+ execFileSync('git', ['-C', remoteDir, ...ident, 'commit', '-q', '--allow-empty', '-m', 'tip'])
+ execFileSync('git', ['-C', remoteDir, 'branch', 'feature'])
+ const tip = execFileSync('git', ['-C', remoteDir, 'rev-parse', 'HEAD']).toString().trim()
+
+ execFileSync('git', ['clone', '-q', '--single-branch', '--branch', 'v0', remoteDir, cloneDir])
+
+ return { cloneDir, remoteDir, tip }
+}
+
+const fetchConfig = cloneDir =>
+ execFileSync('git', ['-C', cloneDir, 'config', '--get-all', 'remote.origin.fetch']).toString().trim()
+
+test('addWorktree: a remote branch on a tag-pinned narrow clone becomes a tracking local branch', async () => {
+ const { cloneDir, remoteDir, tip } = seedNarrowClone('narrow-convert')
+
+ try {
+ const result = await addWorktree(cloneDir, { existingBranch: 'origin/feature' }, 'git')
+
+ const inTree = (...args) =>
+ execFileSync('git', ['-C', result.path, ...args])
+ .toString()
+ .trim()
+
+ assert.equal(result.branch, 'feature')
+ assert.equal(inTree('rev-parse', 'HEAD'), tip)
+ assert.equal(inTree('rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'), 'origin/feature')
+ } finally {
+ fs.rmSync(remoteDir, { recursive: true, force: true })
+ fs.rmSync(cloneDir, { recursive: true, force: true })
+ }
+})
+
+test('addWorktree: a remote branch that does not exist leaves the fetch config alone', async () => {
+ // A configured refspec whose source is missing makes every later plain
+ // `git fetch` fail, so a typo must never be registered on the remote.
+ const narrow = seedNarrowClone('narrow-typo')
+ const normal = seedRemoteAndClone('normal-typo', [])
+
+ try {
+ for (const cloneDir of [narrow.cloneDir, normal.cloneDir]) {
+ const before = fetchConfig(cloneDir)
+
+ await assert.rejects(addWorktree(cloneDir, { existingBranch: 'origin/typo' }, 'git'))
+ assert.equal(fetchConfig(cloneDir), before)
+ execFileSync('git', ['-C', cloneDir, 'fetch', '-q'])
+ }
+ } finally {
+ for (const dir of [narrow.remoteDir, narrow.cloneDir, normal.remoteDir, normal.cloneDir]) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ }
+})
+
+test('addWorktree: converting a remote branch on a normal clone adds no fetch refspec', async () => {
+ const { cloneDir, remoteDir } = seedRemoteAndClone('normal-convert-config', ['teammate-work'])
+
+ try {
+ const before = fetchConfig(cloneDir)
+
+ await addWorktree(cloneDir, { existingBranch: 'origin/teammate-work' }, 'git')
+ assert.equal(fetchConfig(cloneDir), before)
+ } finally {
+ fs.rmSync(remoteDir, { recursive: true, force: true })
+ fs.rmSync(cloneDir, { recursive: true, force: true })
+ }
+})
+
+test('addWorktree: a glob base is not turned into a fetch of every branch', async () => {
+ const { cloneDir, remoteDir } = seedNarrowClone('narrow-glob')
+
+ try {
+ await assert.rejects(addWorktree(cloneDir, { base: 'origin/*', name: 'glob' }, 'git'))
+
+ const remoteRefs = execFileSync('git', ['-C', cloneDir, 'for-each-ref', 'refs/remotes']).toString().trim()
+
+ assert.equal(remoteRefs, '')
+ } finally {
+ fs.rmSync(remoteDir, { recursive: true, force: true })
+ fs.rmSync(cloneDir, { recursive: true, force: true })
+ }
+})
+
// A pair of repos: a bare "remote" with `main` and the extra branches in
// `branches`, plus a clone of it. Returns both paths. The caller must remove
// them.
diff --git a/apps/desktop/electron/git-worktree-ops.ts b/apps/desktop/electron/git-worktree-ops.ts
index 87825cd2a6b..d70ee853ff2 100644
--- a/apps/desktop/electron/git-worktree-ops.ts
+++ b/apps/desktop/electron/git-worktree-ops.ts
@@ -21,6 +21,15 @@ function runGit(gitBin, args, cwd): Promise<string> {
})
}
+// Fetch `<remote>/<branch>` by explicit refspec; true when the remote has the
+// branch. A tag-pinned narrow clone maps only the tag in remote.<remote>.fetch,
+// so a by-name fetch writes FETCH_HEAD without creating the tracking ref
+// (#125686). Same refspec as `hermes update`: the `+` matters on a depth-1
+// clone, where the new tip need not descend from the old one.
+async function fetchTrackingRef(gitBin, root, remote, branch): Promise<boolean> {
+ return gitOk(gitBin, ['fetch', remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], root)
+}
+
// Parse `git worktree list --porcelain`. The first record is the main worktree.
function parseWorktrees(out) {
const trees = []
@@ -246,7 +255,25 @@ async function addExistingBranchWorktree(gitBin, root, name) {
// check out. `git worktree add <dir> origin/feature` detaches HEAD. Make a
// local branch with the same short name that tracks the remote ref. This is
// what `git switch feature` does for a branch on exactly one remote.
- const remote = await remoteOfRef(gitBin, root, requested)
+ let remote = await remoteOfRef(gitBin, root, requested)
+ let fetched = false
+
+ if (!remote && requested.includes('/')) {
+ // A tag-pinned narrow clone has no tracking ref for any branch, so the
+ // ref-based reading above misreads "origin/feature" as a local branch. When
+ // the remote carries the branch, fetching it creates the ref; otherwise
+ // keep the local-branch reading and its error.
+ const maybeRemote = requested.slice(0, requested.indexOf('/'))
+
+ if (
+ (await gitLine(gitBin, ['remote', 'get-url', maybeRemote], root)) &&
+ (await fetchTrackingRef(gitBin, root, maybeRemote, requested.slice(maybeRemote.length + 1)))
+ ) {
+ remote = maybeRemote
+ fetched = true
+ }
+ }
+
const branch = remote ? requested.slice(remote.length + 1) : requested
if (!remote && branch === (await defaultBranch(gitBin, root))) {
@@ -258,18 +285,24 @@ async function addExistingBranchWorktree(gitBin, root, name) {
const dir = uniqueDir(path.join(root, '.worktrees', slugify(branch)))
if (remote) {
- // The remote-tracking ref is stale if the user did not fetch recently. This
- // fetch is best effort: after a failure, the last known ref is still there
- // to branch from.
- try {
- await runGit(gitBin, ['fetch', remote, branch], root)
- } catch {
- // The user is offline, or the branch is gone from the remote. Use the ref
- // that the repo already has.
+ // Best effort freshness: after a failure (offline, branch gone from the
+ // remote) the last known ref is still there to branch from.
+ fetched = fetched || (await fetchTrackingRef(gitBin, root, remote, branch))
+
+ if (!(await gitOk(gitBin, ['worktree', 'add', '--track', '-b', branch, dir, requested], root))) {
+ // `--track` needs remote.<remote>.fetch to map the ref back to a remote
+ // branch; a narrow clone maps only its tag. Branch untracked, then
+ // register the branch and wire upstream, but only for a branch the fetch
+ // just proved exists: a configured refspec whose source is gone makes
+ // every later plain `git fetch` fail.
+ await runGit(gitBin, ['worktree', 'add', '-b', branch, dir, requested], root)
+
+ if (fetched) {
+ await gitOk(gitBin, ['remote', 'set-branches', '--add', remote, branch], root)
+ await gitOk(gitBin, ['branch', `--set-upstream-to=${requested}`, branch], root)
+ }
}
- await runGit(gitBin, ['worktree', 'add', '--track', '-b', branch, dir, requested], root)
-
return { path: dir, branch, repoRoot: root }
}
@@ -306,18 +339,12 @@ async function addWorktree(repoPath, options, gitBin) {
if (base.startsWith('origin/')) {
const remoteBranch = base.slice('origin/'.length)
- try {
- // A by-name fetch writes only FETCH_HEAD on a tag-pinned narrow clone,
- // so origin/<branch> never appears (#125686). Same refspec as hermes update.
- await runGit(
- gitBin,
- ['fetch', 'origin', `+refs/heads/${remoteBranch}:refs/remotes/origin/${remoteBranch}`],
- root
- )
- } catch {
- // The fetch isn't mandatory, but it would be nice to do if possible.
- // If it's not possible, just use the local ref of the remote branch.
- // If it doesn't exist locally, we'll get an error
+ // `base` comes straight from IPC, and inside a refspec a glob such as
+ // "origin/*" would fetch every branch: only fetch names the sanitizer
+ // leaves alone. The fetch is best effort; git uses the local ref or
+ // raises a clear error below if it is entirely missing.
+ if (remoteBranch === sanitizeBranch(remoteBranch)) {
+ await fetchTrackingRef(gitBin, root, 'origin', remoteBranch)
}
// When branching off a remote-tracking ref, git auto-sets up tracking