MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / getOrCreateWorktree

Function getOrCreateWorktree

source code/utils/worktree.ts:237–377  ·  view source on GitHub ↗

* Creates a new git worktree for the given slug, or resumes it if it already exists. * Named worktrees reuse the same path across invocations, so the existence check * prevents unconditionally running `git fetch` (which can hang waiting for credentials) * on every resume.

(
  repoRoot: string,
  slug: string,
  options?: { prNumber?: number },
)

Source from the content-addressed store, hash-verified

235 * on every resume.
236 */
237async function getOrCreateWorktree(
238 repoRoot: string,
239 slug: string,
240 options?: { prNumber?: number },
241): Promise<WorktreeCreateResult> {
242 const worktreePath = worktreePathFor(repoRoot, slug)
243 const worktreeBranch = worktreeBranchName(slug)
244
245 // Fast resume path: if the worktree already exists skip fetch and creation.
246 // Read the .git pointer file directly (no subprocess, no upward walk) — a
247 // subprocess `rev-parse HEAD` burns ~15ms on spawn overhead even for a 2ms
248 // task, and the await yield lets background spawnSyncs pile on (seen at 55ms).
249 const existingHead = await readWorktreeHeadSha(worktreePath)
250 if (existingHead) {
251 return {
252 worktreePath,
253 worktreeBranch,
254 headCommit: existingHead,
255 existed: true,
256 }
257 }
258
259 // New worktree: fetch base branch then add
260 await mkdir(worktreesDir(repoRoot), { recursive: true })
261
262 const fetchEnv = { ...process.env, ...GIT_NO_PROMPT_ENV }
263
264 let baseBranch: string
265 let baseSha: string | null = null
266 if (options?.prNumber) {
267 const { code: prFetchCode, stderr: prFetchStderr } =
268 await execFileNoThrowWithCwd(
269 gitExe(),
270 ['fetch', 'origin', `pull/${options.prNumber}/head`],
271 { cwd: repoRoot, stdin: 'ignore', env: fetchEnv },
272 )
273 if (prFetchCode !== 0) {
274 throw new Error(
275 `Failed to fetch PR #${options.prNumber}: ${prFetchStderr.trim() || 'PR may not exist or the repository may not have a remote named "origin"'}`,
276 )
277 }
278 baseBranch = 'FETCH_HEAD'
279 } else {
280 // If origin/<branch> already exists locally, skip fetch. In large repos
281 // (210k files, 16M objects) fetch burns ~6-8s on a local commit-graph
282 // scan before even hitting the network. A slightly stale base is fine —
283 // the user can pull in the worktree if they want latest.
284 // resolveRef reads the loose/packed ref directly; when it succeeds we
285 // already have the SHA, so the later rev-parse is skipped entirely.
286 const [defaultBranch, gitDir] = await Promise.all([
287 getDefaultBranch(),
288 resolveGitDir(repoRoot),
289 ])
290 const originRef = `origin/${defaultBranch}`
291 const originSha = gitDir
292 ? await resolveRef(gitDir, `refs/remotes/origin/${defaultBranch}`)
293 : null
294 if (originSha) {

Callers 3

createWorktreeForSessionFunction · 0.85
createAgentWorktreeFunction · 0.85
execIntoTmuxWorktreeFunction · 0.85

Calls 11

worktreePathForFunction · 0.85
worktreeBranchNameFunction · 0.85
readWorktreeHeadShaFunction · 0.85
mkdirFunction · 0.85
worktreesDirFunction · 0.85
execFileNoThrowWithCwdFunction · 0.85
getDefaultBranchFunction · 0.85
resolveGitDirFunction · 0.85
resolveRefFunction · 0.85
getInitialSettingsFunction · 0.85
tearDownFunction · 0.85

Tested by

no test coverage detected