diff --git a/packages/server/src/server/diff/git.test.ts b/packages/server/src/server/diff/git.test.ts index d84214d7a..54499334b 100644 --- a/packages/server/src/server/diff/git.test.ts +++ b/packages/server/src/server/diff/git.test.ts @@ -778,3 +778,40 @@ test.each([ } }, ); + +test("an uninitialized submodule below a bare repository layout does not fail the comparison", async () => { + const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-submodule-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const { mkdir } = await import("node:fs/promises"); + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, "README.md"), "base\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + const base = git("rev-parse", "HEAD"); + git("update-index", "--add", "--cacheinfo", `160000,${base},vendor/sub`); + git("-c", "commit.gpgsign=false", "commit", "-m", "record submodule"); + // `vendor/` holds files shaped like a bare repository; git discovery from the + // uninitialized `vendor/sub` would stop there before reaching the superproject. + git("init", "--bare", "-q", "vendor"); + await mkdir(join(cwd, "vendor", "sub")); + const comparison = await listComparison({ + cwd, + base: { kind: "rev", rev: base }, + head: { kind: "worktree" }, + highlight: false, + }); + try { + expect(comparison.files.map((file) => [file.entry.path, file.entry.change])).toContainEqual([ + "vendor/sub", + "added", + ]); + } finally { + await comparison.close(); + } + } finally { + await rm(cwd, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/diff/git.ts b/packages/server/src/server/diff/git.ts index d09c7ce5a..5fb8d82dc 100644 --- a/packages/server/src/server/diff/git.ts +++ b/packages/server/src/server/diff/git.ts @@ -12,7 +12,7 @@ import { type CheckoutDiffCompare, } from "../../utils/checkout-git.js"; import { lstat, readFile, readlink } from "node:fs/promises"; -import { resolve } from "node:path"; +import { join, resolve } from "node:path"; import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages"; import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index"; import { runGitCommand, type GitCommandOptions } from "../../utils/run-git-command.js"; @@ -444,15 +444,36 @@ async function readWorktreeContent({ if (value.isSymbolicLink()) return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` }; if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) { - const submodule = await runGitCommand( - ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], - { cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } }, - ); - return { hashed: false, literal: `submodule:${submodule.stdout}` }; + return { hashed: false, literal: await readSubmoduleIdentity(path, absolutePath, options) }; } return { hashed: value.isFile() && text, literal: null }; } +// An uninitialized submodule has no `.git`; running git there would discover +// whichever repository sits above it. Its content is the commit the index +// records. Pinning GIT_DIR keeps an initialized submodule's status on its own `.git`. +async function readSubmoduleIdentity( + path: string, + submodulePath: string, + options: GitCommandOptions, +): Promise { + try { + await lstat(join(submodulePath, ".git")); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + const recorded = await runGitCommand(["rev-parse", "--verify", "--quiet", `:0:${path}`], { + ...options, + acceptExitCodes: [0, 1], + }); + return `submodule-uninitialized:${recorded.stdout.trim()}`; + } + const status = await runGitCommand( + ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], + { cwd: submodulePath, envOverlay: { GIT_DIR: ".git", GIT_OPTIONAL_LOCKS: "0" } }, + ); + return `submodule:${status.stdout}`; +} + function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] { const revisions: string[] = []; if (compare.base.kind !== "index") revisions.push(baseSha); diff --git a/packages/server/src/server/diff/subscriptions.test.ts b/packages/server/src/server/diff/subscriptions.test.ts index e42f32834..0589fba35 100644 --- a/packages/server/src/server/diff/subscriptions.test.ts +++ b/packages/server/src/server/diff/subscriptions.test.ts @@ -534,6 +534,61 @@ test("submodule commits invalidate cached worktree gitlink bodies", async () => } }); +// Windows paths cannot contain `:`. +const uninitializedSubmodulePaths = process.platform === "win32" ? ["sub"] : ["sub", "0:sub"]; + +test.each(uninitializedSubmodulePaths)( + "staged commits invalidate cached bodies for an uninitialized submodule at %s", + async (submodule) => { + const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-gitlink-cache-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + const commit = (message: string) => { + git("-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", message); + return git("rev-parse", "HEAD"); + }; + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + const [a, b, c] = [commit("A"), commit("B"), commit("C")]; + git("update-index", "--add", "--cacheinfo", `160000,${a},${submodule}`); + git("-c", "commit.gpgsign=false", "commit", "-m", "record A"); + await mkdir(join(cwd, submodule)); + git("update-index", "--cacheinfo", `160000,${b},${submodule}`); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + expect(frames.at(-1)).toMatchObject({ opcode: DiffOpcode.End, error: null }); + frames.length = 0; + git("update-index", "--cacheinfo", `160000,${c},${submodule}`); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + const bodies = frames.flatMap((frame) => + frame.opcode === DiffOpcode.Bodies ? frame.files : [], + ); + expect(bodies.flatMap((file) => file.hunks.flatMap((hunk) => hunk.lines))).toContainEqual( + expect.objectContaining({ type: "add", content: `Subproject commit ${c}` }), + ); + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } + }, +); + test("stat-only changes reuse cached bodies and send no body frames", async () => { const { utimes } = await import("node:fs/promises"); const cwd = await mkdtemp(join(tmpdir(), "diff-stat-only-")); diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index 16a59dcd6..e6bd5c423 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -296,8 +296,23 @@ function createGitRepository(): { tempDir: string; repoDir: string } { return { tempDir, repoDir }; } -async function createBaseRecoveryFixture(baseBranch: string | null) { - const { tempDir, repoDir } = createGitRepository(); +async function createBaseRecoveryFixture( + baseBranch: string | null, + options: { bareSource?: boolean } = {}, +) { + const { tempDir, repoDir: checkoutDir } = createGitRepository(); + const repoDir = options.bareSource ? join(realpathSync(tempDir), "repo.git") : checkoutDir; + if (options.bareSource) { + execFileSync("git", ["clone", "--bare", "-q", checkoutDir, repoDir], { stdio: "pipe" }); + // A bare clone does not copy the checkout's local config; its linked worktrees share this one. + for (const [key, value] of [ + ["user.name", "Paseo Test"], + ["user.email", "test@example.com"], + ["core.autocrlf", "false"], + ]) { + execFileSync("git", ["--git-dir", repoDir, "config", key, value], { stdio: "pipe" }); + } + } const paseoHome = join(tempDir, "paseo-home"); const created = await createWorktree({ cwd: repoDir, @@ -648,6 +663,23 @@ test("restore rejects a branch checked out elsewhere without inventing another b ).toBe("* feature"); }); +test("restores a workspace after the last checkout of a bare repository is archived", async () => { + const fixture = await createBaseRecoveryFixture("main", { bareSource: true }); + await fixture.archiveAndRemove(); + + await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({ + workspaceId: fixture.workspace.workspaceId, + action: "restore", + }); + expect(readFileSync(join(fixture.workspace.cwd, "feature.txt"), "utf8")).toBe("feature\n"); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature"); +}); + test("restores a user-created worktree at its recorded path outside Paseo's root", async () => { const { tempDir, repoDir } = createGitRepository(); const worktreeRoot = join(realpathSync(tempDir), "external-worktree"); diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index 0a0786c70..7e7935050 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { basename } from "node:path"; import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js"; +import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js"; import { createRealpathAwarePathMatcher } from "../../../utils/path.js"; import { runGitCommand } from "../../../utils/run-git-command.js"; import { @@ -156,7 +157,10 @@ export function createWorkspaceRecoveryService(deps: { let workspaceToUnarchive = resolved.workspace; let recreated: { worktreePath: string; pluginId: string | null } | null = null; if (resolved.kind === "restore") { - recreated = await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot); + const { workspace, sourceRepoRoot } = resolved; + recreated = await runWithRepositoryRoot(sourceRepoRoot, () => + recreateArchivedWorktree(workspace, sourceRepoRoot), + ); if ((resolved.workspace.worktreeManagerPluginId ?? null) !== recreated.pluginId) { const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace; workspaceToUnarchive = recreated.pluginId diff --git a/packages/server/src/server/workspace-git-fetch.test.ts b/packages/server/src/server/workspace-git-fetch.test.ts index de9e69959..b2f8ee04f 100644 --- a/packages/server/src/server/workspace-git-fetch.test.ts +++ b/packages/server/src/server/workspace-git-fetch.test.ts @@ -190,7 +190,7 @@ async function withAuthenticatedRemote( { cwd }, ); await run(["clone", "--bare", cwd, remote], { cwd: root }); - await run(["update-server-info"], { cwd: remote }); + await run(["--git-dir", remote, "update-server-info"], { cwd: root }); await run(["config", "credential.helper", ""], { cwd }); await run(["config", "core.askPass", askpassCommand], { cwd }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); diff --git a/packages/server/src/server/worktree-core.posix.test.ts b/packages/server/src/server/worktree-core.posix.test.ts index 239751aa3..9c2572757 100644 --- a/packages/server/src/server/worktree-core.posix.test.ts +++ b/packages/server/src/server/worktree-core.posix.test.ts @@ -18,7 +18,9 @@ import { createGitLabService } from "../services/gitlab-service.js"; import { getCheckoutSnapshotFacts, getCheckoutStatus, + getMainRepoRoot, pushCurrentBranch, + resolveRepositoryDefaultBranch, } from "../utils/checkout-git.js"; import { getPaseoWorktreeMetadataPath, @@ -26,6 +28,7 @@ import { } from "../utils/worktree-metadata.js"; import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js"; import { + createWorktree, isPaseoOwnedWorktreeCwd, listGitWorktrees, listPaseoWorktrees, @@ -88,11 +91,13 @@ function createGitHubServiceStub(): ForgeService { function createCoreDeps(options?: { github?: ForgeService; forge?: { forge: string; service: ForgeService }; + resolveDefaultBranch?: (repoRoot: string) => Promise; + resolveRepoRoot?: (cwd: string) => Promise; }) { return { github: options?.github ?? createGitHubServiceStub(), workspaceGitService: { - resolveRepoRoot: async (cwd: string) => cwd, + resolveRepoRoot: options?.resolveRepoRoot ?? (async (cwd: string) => cwd), resolveForge: async () => options?.forge ? { @@ -102,7 +107,7 @@ function createCoreDeps(options?: { } : null, }, - resolveDefaultBranch: async () => "main", + resolveDefaultBranch: options?.resolveDefaultBranch ?? (async () => "main"), }; } @@ -445,6 +450,39 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(existsSync(first.worktree.worktreePath)).toBe(true); }); + test("creates a workspace from a checkout of a bare repository that only Paseo uses", async () => { + const { tempDir, repoDir, paseoHome } = createGitRepo(); + cleanupPaths.push(tempDir); + const bareRepo = path.join(tempDir, "repo.git"); + execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo], { stdio: "pipe" }); + const first = await createWorktree({ + cwd: bareRepo, + paseoHome, + worktreeSlug: "first", + source: { kind: "branch-off", branchName: "first", baseBranch: "main" }, + }); + expect(await getMainRepoRoot(first.worktreePath, { paseoHome })).toBe(bareRepo); + + const result = await createCoreWorktree( + { cwd: first.worktreePath, worktreeSlug: "second", paseoHome }, + createCoreDeps({ + resolveRepoRoot: (cwd) => getMainRepoRoot(cwd, { paseoHome }), + resolveDefaultBranch: async (root) => + (await resolveRepositoryDefaultBranch(root)) ?? "unresolved", + }), + ); + + expect(result.repoRoot).toBe(bareRepo); + expect(result.intent).toEqual({ + kind: "branch-off", + baseBranch: "main", + branchName: "second", + }); + expect(readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8")).toBe( + "hello\n", + ); + }); + test("creates branch-off worktrees from origin main without tracking origin main", async () => { const { tempDir, repoDir, paseoHome } = createGitRepoWithOriginMain(); cleanupPaths.push(tempDir); diff --git a/packages/server/src/server/worktree-core.ts b/packages/server/src/server/worktree-core.ts index 34681ac35..1589f53d6 100644 --- a/packages/server/src/server/worktree-core.ts +++ b/packages/server/src/server/worktree-core.ts @@ -27,6 +27,7 @@ import { } from "./resolve-worktree-creation-intent.js"; import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages"; import type { WorkspaceGitService } from "./workspace-git-service.js"; +import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js"; import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js"; import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js"; @@ -78,6 +79,16 @@ async function createWorktreeCoreWithPriority( deps: CreateWorktreeCoreDeps, ): Promise { const repoRoot = await resolveWorktreeRepoRoot(input, deps.workspaceGitService); + return runWithRepositoryRoot(repoRoot, () => + createWorktreeAtRepositoryRoot(input, deps, repoRoot), + ); +} + +async function createWorktreeAtRepositoryRoot( + input: CreateWorktreeCoreInput, + deps: CreateWorktreeCoreDeps, + repoRoot: string, +): Promise { const requestedWorktreeSlug = input.worktreeSlug ? normalizeWorktreeSlug(input.worktreeSlug) : undefined; diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index 916d75ebb..e9875cb08 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -907,6 +907,8 @@ describe("ForgeService", () => { ttlMs: 0, runner: runner.runner, resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => null, now: () => now, }); const reads = recordCurrentPullRequestStatusReads(service); @@ -980,6 +982,8 @@ describe("ForgeService", () => { ttlMs: 0, runner: runner.runner, resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => null, now: () => now, }); const reads = recordCurrentPullRequestStatusReads(service); @@ -1026,6 +1030,8 @@ describe("ForgeService", () => { ttlMs: 0, runner: runner.runner, resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => null, now: () => now, }); const reads = recordCurrentPullRequestStatusReads(service); @@ -1069,6 +1075,8 @@ describe("ForgeService", () => { ttlMs: 0, runner: runner.runner, resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => null, now: () => now, }); @@ -1098,6 +1106,8 @@ describe("ForgeService", () => { ttlMs: 0, runner: runner.runner, resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => null, now: () => now, }); diff --git a/packages/server/src/utils/git-repository-discovery.test.ts b/packages/server/src/utils/git-repository-discovery.test.ts new file mode 100644 index 000000000..71f2d4381 --- /dev/null +++ b/packages/server/src/utils/git-repository-discovery.test.ts @@ -0,0 +1,234 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + parseSafeBareRepositorySupport, + readRepositoryRootGitDir, + resolveGitDiscovery, + runWithRepositoryRoot, + type GitDiscovery, +} from "./git-repository-discovery.js"; + +const EXPLICIT = ["-c", "safe.bareRepository=explicit"]; +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +}); + +function git(args: string[], cwd?: string): string { + return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim(); +} + +function makeTempDir(): string { + const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-"))); + tempDirs.push(dir); + return dir; +} + +function createBareRepositoryWithLinkedWorktree(root: string): string { + const source = path.join(root, "source"); + git(["init", "-q", "-b", "main", source]); + git( + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "-q", + "--allow-empty", + "-m", + "base", + ], + source, + ); + const bareRepo = path.join(root, "repo.git"); + git(["clone", "-q", "--bare", source, bareRepo]); + git(["worktree", "add", "-q", path.join(root, "main"), "main"], bareRepo); + return bareRepo; +} + +// Runs git with only the discovery environment, as a Git release that ignores +// `safe.bareRepository` would see it. +function gitDirWithoutConfig(cwd: string, discovery: GitDiscovery): string { + try { + const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { + cwd, + encoding: "utf8", + stdio: "pipe", + env: { ...process.env, ...discovery.envOverlay }, + }).trim(); + return path.resolve(gitDir); + } catch (error) { + return String((error as { stderr?: string }).stderr).trim(); + } +} + +describe("resolveGitDiscovery before Git 2.38", () => { + const legacy = { + gitDirSet: false, + repositoryRootGitDir: null, + safeBareRepositorySupported: false, + }; + + it("stops git at a bare repository layout in the working directory", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + + const discovery = await resolveGitDiscovery({ cwd: layout, ...legacy }); + + expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(layout, ".git") }); + expect(gitDirWithoutConfig(layout, discovery)).toMatch(/not a git repository/); + }); + + it("stops git at a bare repository layout in a parent directory", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + const nested = path.join(layout, "a", "b"); + mkdirSync(nested, { recursive: true }); + + const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy }); + + expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(nested, ".git") }); + expect(gitDirWithoutConfig(nested, discovery)).toMatch(/not a git repository/); + }); + + it("leaves discovery alone when a checkout sits between the directory and the layout", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + const checkout = path.join(layout, "checkout"); + git(["init", "-q", checkout]); + const nested = path.join(checkout, "src"); + mkdirSync(nested); + + const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy }); + + expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} }); + expect(gitDirWithoutConfig(nested, discovery)).toBe(path.join(checkout, ".git")); + }); + + it("leaves discovery alone inside a checkout's own .git directory", async () => { + const checkout = path.join(makeTempDir(), "checkout"); + git(["init", "-q", checkout]); + const gitDir = path.join(checkout, ".git"); + + const discovery = await resolveGitDiscovery({ cwd: gitDir, ...legacy }); + + expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} }); + }); + + it("stops git at a bare repository with linked worktrees unless its root is named", async () => { + const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir()); + + const unnamed = await resolveGitDiscovery({ cwd: bareRepo, ...legacy }); + const named = await resolveGitDiscovery({ + cwd: bareRepo, + ...legacy, + repositoryRootGitDir: bareRepo, + }); + + expect(unnamed.envOverlay).toEqual({ GIT_DIR: path.join(bareRepo, ".git") }); + expect(named).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: bareRepo } }); + expect(gitDirWithoutConfig(bareRepo, named)).toBe(bareRepo); + }); + + it("stops git below a bare repository with linked worktrees", async () => { + const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir()); + const refs = path.join(bareRepo, "refs"); + + const discovery = await resolveGitDiscovery({ cwd: refs, ...legacy }); + + expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(refs, ".git") }); + }); + + it("keeps a GIT_DIR the caller already chose", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + + const discovery = await resolveGitDiscovery({ + cwd: layout, + gitDirSet: true, + repositoryRootGitDir: layout, + safeBareRepositorySupported: false, + }); + + expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} }); + }); +}); + +describe("resolveGitDiscovery on Git 2.38 and later", () => { + it("relies on safe.bareRepository instead of walking the directory tree", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + + const discovery = await resolveGitDiscovery({ + cwd: layout, + gitDirSet: false, + repositoryRootGitDir: null, + safeBareRepositorySupported: true, + }); + + expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} }); + }); + + it("names a bare repository root that the caller scoped", async () => { + const layout = path.join(makeTempDir(), "layout"); + git(["init", "--bare", "-q", layout]); + + const discovery = await resolveGitDiscovery({ + cwd: layout, + gitDirSet: false, + repositoryRootGitDir: layout, + safeBareRepositorySupported: true, + }); + + expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: layout } }); + }); +}); + +describe("runWithRepositoryRoot", () => { + it("names a bare repository root only for commands at that root", async () => { + const bareRepo = path.join(makeTempDir(), "repo.git"); + git(["init", "--bare", "-q", bareRepo]); + + const inside = await runWithRepositoryRoot(bareRepo, async () => ({ + root: readRepositoryRootGitDir(bareRepo), + below: readRepositoryRootGitDir(path.join(bareRepo, "refs")), + })); + + expect(inside).toEqual({ root: bareRepo, below: null }); + expect(readRepositoryRootGitDir(bareRepo)).toBeNull(); + }); + + it("leaves a checkout root to normal discovery", async () => { + const checkout = path.join(makeTempDir(), "checkout"); + git(["init", "-q", checkout]); + + const named = await runWithRepositoryRoot(checkout, async () => + readRepositoryRootGitDir(checkout), + ); + + expect(named).toBeNull(); + }); +}); + +describe("parseSafeBareRepositorySupport", () => { + it.each([ + ["git version 2.53.0", true], + ["git version 2.38.0", true], + ["git version 2.45.1.windows.1", true], + ["git version 3.0.0", true], + ["git version 2.37.1 (Apple Git-137)", false], + ["git version 2.34.1", false], + ["git version 1.9.5", false], + ["unexpected output", false], + ])("%s → %s", (output, supported) => { + expect(parseSafeBareRepositorySupport(output)).toBe(supported); + }); +}); diff --git a/packages/server/src/utils/git-repository-discovery.ts b/packages/server/src/utils/git-repository-discovery.ts new file mode 100644 index 000000000..f56c2c123 --- /dev/null +++ b/packages/server/src/utils/git-repository-discovery.ts @@ -0,0 +1,172 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { lstat, realpath, stat } from "node:fs/promises"; +import { basename, dirname, join, resolve } from "node:path"; +import type { ProcessEnvRecord } from "../server/paseo-env.js"; +import { execCommand } from "./spawn.js"; + +const EXPLICIT_BARE_REPOSITORY = ["-c", "safe.bareRepository=explicit"]; + +/** How a git command finds its repository. */ +export interface GitDiscovery { + configArgs: string[]; + envOverlay: ProcessEnvRecord; +} + +export interface GitDiscoveryInput { + cwd: string; + /** The command already names its repository through `GIT_DIR`. */ + gitDirSet: boolean; + /** From `readRepositoryRootGitDir`, read when the command was submitted. */ + repositoryRootGitDir: string | null; + safeBareRepositorySupported: boolean; +} + +interface RepositoryRoot { + paths: readonly string[]; + gitDir: string; +} + +const repositoryRoots = new AsyncLocalStorage(); + +/** + * Runs `operation` with `root` named as the repository of every git command + * whose cwd is exactly `root`. + * + * Paseo records a bare repository as a repository root when only its linked + * checkouts use it. Git has no `.git` to find there, so those commands receive + * the bare repository through `GIT_DIR`. A root with a `.git` keeps normal + * discovery, and directories below `root` are not affected. + */ +export async function runWithRepositoryRoot( + root: string, + operation: () => Promise, +): Promise { + const current = repositoryRoots.getStore() ?? []; + if (findRepositoryRoot(current, root)) return operation(); + const named = await readBareRepositoryRoot(root); + if (!named) return operation(); + return repositoryRoots.run([...current, named], operation); +} + +/** The bare repository `runWithRepositoryRoot` named for `cwd` in this async context. */ +export function readRepositoryRootGitDir(cwd: string): string | null { + return findRepositoryRoot(repositoryRoots.getStore() ?? [], cwd)?.gitDir ?? null; +} + +function findRepositoryRoot( + roots: readonly RepositoryRoot[], + cwd: string, +): RepositoryRoot | undefined { + const path = resolve(cwd); + return roots.find((root) => root.paths.includes(path)); +} + +async function readBareRepositoryRoot(root: string): Promise { + const dotGit = await lstat(join(root, ".git")).catch(() => null); + if (dotGit || !(await looksLikeBareRepository(root))) return null; + const gitDir = await realpath(root).catch(() => null); + if (!gitDir) return null; + return { paths: [...new Set([resolve(root), gitDir])], gitDir }; +} + +/** + * Keeps git from adopting a directory that only looks like a bare repository + * (`HEAD`, `objects/`, `refs/`), at `cwd` or above it. + * + * A caller that works on a bare repository names it with `GIT_DIR`, directly or + * through `runWithRepositoryRoot`. + * + * - Git 2.38 and later: `safe.bareRepository=explicit`. + * - Earlier releases ignore that setting. When discovery from `cwd` would reach + * such a directory before any `.git`, `GIT_DIR` is pinned to the missing + * `/.git`, so git reports that no repository was found. + */ +export async function resolveGitDiscovery(input: GitDiscoveryInput): Promise { + if (!input.gitDirSet && input.repositoryRootGitDir) { + return { + configArgs: EXPLICIT_BARE_REPOSITORY, + envOverlay: { GIT_DIR: input.repositoryRootGitDir }, + }; + } + if (input.gitDirSet || input.safeBareRepositorySupported) { + return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} }; + } + if (!(await discoveryReachesImplicitBareRepository(input.cwd))) { + return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} }; + } + return { + configArgs: EXPLICIT_BARE_REPOSITORY, + envOverlay: { GIT_DIR: join(input.cwd, ".git") }, + }; +} + +/** `safe.bareRepository` arrived in Git 2.38. */ +export function parseSafeBareRepositorySupport(versionOutput: string): boolean { + const match = /git version (\d+)\.(\d+)/.exec(versionOutput); + if (!match) return false; + const major = Number(match[1]); + const minor = Number(match[2]); + return major > 2 || (major === 2 && minor >= 38); +} + +let safeBareRepositorySupport: Promise | null = null; + +/** Reads `git --version` once per process. */ +export function readSafeBareRepositorySupport(): Promise { + safeBareRepositorySupport ??= execCommand("git", ["--version"]).then( + ({ stdout }) => parseSafeBareRepositorySupport(stdout), + () => false, + ); + return safeBareRepositorySupport; +} + +// Follows git's discovery order: `/.git` first, then `` itself as a +// bare repository, then the parent. Git itself accepts a bare-looking directory +// that is a checkout's `.git`, or sits in its `worktrees/` or `modules/`. +async function discoveryReachesImplicitBareRepository(cwd: string): Promise { + let dir: string; + try { + dir = await realpath(cwd); + } catch { + return false; + } + while (true) { + const dotGit = join(dir, ".git"); + if ((await isFile(dotGit)) || (await looksLikeBareRepository(dotGit))) return false; + if (await looksLikeBareRepository(dir)) return !isInsideDotGit(dir); + const parent = dirname(dir); + if (parent === dir) return false; + dir = parent; + } +} + +function isInsideDotGit(dir: string): boolean { + const path = dir.replaceAll("\\", "/"); + return ( + basename(dir) === ".git" || path.includes("/.git/worktrees/") || path.includes("/.git/modules/") + ); +} + +async function looksLikeBareRepository(dir: string): Promise { + return ( + (await isFile(join(dir, "HEAD"))) && + (await isDirectory(join(dir, "objects"))) && + (await isDirectory(join(dir, "refs"))) + ); +} + +async function isFile(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} diff --git a/packages/server/src/utils/run-git-command.posix.test.ts b/packages/server/src/utils/run-git-command.posix.test.ts index c336adc2f..51172cc20 100644 --- a/packages/server/src/utils/run-git-command.posix.test.ts +++ b/packages/server/src/utils/run-git-command.posix.test.ts @@ -1,8 +1,18 @@ -import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { runWithRepositoryRoot } from "./git-repository-discovery.js"; import { runGitCommand } from "./run-git-command.js"; const tempDirs: string[] = []; @@ -49,3 +59,112 @@ describe("runGitCommand fsmonitor isolation", () => { expect(result.stdout.trim()).toBe("false"); }); }); + +function git(args: string[], cwd?: string): string { + return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim(); +} + +function makeTempDir(): string { + const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-"))); + tempDirs.push(dir); + return dir; +} + +// Files shaped like a bare repository (`HEAD`, `config`, `objects/`, `refs/`) that +// git would adopt implicitly, with a clean filter that leaves a marker when run. +function createBareRepositoryLayout(root: string, name: string): { dir: string; marker: string } { + const dir = path.join(root, name); + git(["init", "--bare", "-q", dir]); + const marker = path.join(root, `${name}.marker`); + writeFileSync(path.join(dir, "info", "attributes"), "* filter=probe\n"); + git(["config", "-f", path.join(dir, "config"), "filter.probe.clean", `touch '${marker}'; cat`]); + return { dir, marker }; +} + +function createBareRepositoryWithLinkedWorktree(root: string): { + bareRepo: string; + worktree: string; +} { + const source = path.join(root, "source"); + git(["init", "-q", "-b", "main", source]); + git( + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "-q", + "--allow-empty", + "-m", + "base", + ], + source, + ); + const bareRepo = path.join(root, "repo.git"); + git(["clone", "-q", "--bare", source, bareRepo]); + const worktree = path.join(root, "main"); + git(["worktree", "add", "-q", worktree, "main"], bareRepo); + return { bareRepo, worktree }; +} + +function listedWorktreePaths(porcelain: string): string[] { + return porcelain + .split("\n") + .filter((line) => line.startsWith("worktree ")) + .map((line) => path.resolve(line.slice("worktree ".length))); +} + +describe("runGitCommand repository discovery", () => { + it("does not adopt a bare repository layout at the working directory", async () => { + const root = makeTempDir(); + const layout = createBareRepositoryLayout(root, "layout"); + writeFileSync(path.join(layout.dir, "f.txt"), "contents\n"); + + await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: layout.dir }); + + expect(existsSync(layout.marker)).toBe(false); + await expect( + runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }), + ).rejects.toThrow(/cannot use bare repository/); + }); + + it("does not adopt a bare repository layout in a parent directory", async () => { + const root = makeTempDir(); + const layout = createBareRepositoryLayout(root, "layout"); + const nested = path.join(layout.dir, "nested"); + mkdirSync(nested); + writeFileSync(path.join(nested, "f.txt"), "contents\n"); + + await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: nested }); + + expect(existsSync(layout.marker)).toBe(false); + await expect( + runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: nested }), + ).rejects.toThrow(/cannot use bare repository/); + }); + + it("does not adopt a bare repository at the working directory even with linked worktrees", async () => { + const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir()); + + await expect( + runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }), + ).rejects.toThrow(/cannot use bare repository/); + const fromWorktree = await runGitCommand(["rev-parse", "--git-common-dir"], { cwd: worktree }); + expect(path.resolve(worktree, fromWorktree.stdout.trim())).toBe(bareRepo); + }); + + it("runs at a bare repository root named with runWithRepositoryRoot", async () => { + const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir()); + + const fromRoot = await runWithRepositoryRoot(bareRepo, () => + runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }), + ); + const belowRoot = await runWithRepositoryRoot(bareRepo, () => + runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: path.join(bareRepo, "refs") }), + ).catch((error: unknown) => error); + + expect(listedWorktreePaths(fromRoot.stdout)).toContain(worktree); + expect(String(belowRoot)).toMatch(/cannot use bare repository/); + }); +}); diff --git a/packages/server/src/utils/run-git-command.ts b/packages/server/src/utils/run-git-command.ts index e1f6fc718..b6d54ce25 100644 --- a/packages/server/src/utils/run-git-command.ts +++ b/packages/server/src/utils/run-git-command.ts @@ -11,6 +11,11 @@ import { startGitCommandTrace, submitGitCommandTrace, } from "./git-command-trace.js"; +import { + readRepositoryRootGitDir, + readSafeBareRepositorySupport, + resolveGitDiscovery, +} from "./git-repository-discovery.js"; import { spawnProcess } from "./spawn.js"; import { GitProcessScheduler, @@ -296,13 +301,15 @@ function executeGitCommand( submission: GitCommandSubmission, ): Promise> { const priority = submission.priority ?? gitCommandPriority.getStore() ?? "normal"; + // Read at submission: the scheduler may start the process from another async context. + const repositoryRootGitDir = readRepositoryRootGitDir(options.cwd); const metricsState = submitGitCommandMetric(args, options.cwd, priority); const commandTrace = submitGitCommandTrace(args, options.cwd, { active: gitProcessScheduler.activeCount, pending: gitProcessScheduler.pendingCount, }); const runtimeMetric = gitRuntimeMetrics.submit(getGitOperation(args), submission.provenance); - const startCommand = () => { + const spawnCommand = (launch: GitLaunch) => { let releaseProcessSlot!: () => void; const exited = new Promise((resolve) => { releaseProcessSlot = resolve; @@ -317,7 +324,10 @@ function executeGitCommand( const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; const acceptExitCodes = options.acceptExitCodes ?? [0]; const command = formatGitCommand(args); - const envOverlay = mergeEnvOverlays(options.env, options.envOverlay); + const envOverlay = mergeEnvOverlays( + mergeEnvOverlays(options.env, options.envOverlay), + launch.envOverlay, + ); const startedAt = Date.now(); beginGitCommandMetric(metricsState); const logger = typeof options.logger?.trace === "function" ? options.logger : undefined; @@ -407,19 +417,12 @@ function executeGitCommand( let child: ReturnType; try { - // `core.quotepath=false` makes git emit raw UTF-8 paths instead of - // octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`). - // `core.fsmonitor=false` prevents repository config from launching a command. - child = spawnProcess( - "git", - ["-c", "core.quotepath=false", "-c", "core.fsmonitor=false", ...args], - { - cwd: options.cwd, - envOverlay, - shell: false, - stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], - }, - ); + child = spawnProcess("git", [...launch.configArgs, ...args], { + cwd: options.cwd, + envOverlay, + shell: false, + stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], + }); spawnGitCommandTrace(commandTrace, child.pid); } catch (error) { rejectSpawnFailure(error); @@ -574,6 +577,15 @@ function executeGitCommand( }); return { result: resultPromise, exited }; }; + // The process slot stays held through the launch lookup because `exited` + // settles only after the spawned process exits. `resolveGitLaunch` never rejects. + const startCommand = () => { + const spawned = resolveGitLaunch(options, repositoryRootGitDir).then(spawnCommand); + return { + result: spawned.then((scheduled) => scheduled.result), + exited: spawned.then((scheduled) => scheduled.exited), + }; + }; const promise = gitProcessScheduler.run(startCommand, { priority }); gitRuntimeMetrics.observeLimiter( gitProcessScheduler.activeCount, @@ -582,6 +594,36 @@ function executeGitCommand( return promise; } +interface GitLaunch { + configArgs: string[]; + envOverlay: ProcessEnvRecord; +} + +// `core.quotepath=false` makes git emit raw UTF-8 paths instead of +// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`). +// `core.fsmonitor=false` prevents repository config from launching a command. +async function resolveGitLaunch( + options: GitCommandOptions, + repositoryRootGitDir: string | null, +): Promise { + const discovery = await resolveGitDiscovery({ + cwd: options.cwd, + repositoryRootGitDir, + gitDirSet: Boolean(options.envOverlay?.GIT_DIR ?? options.env?.GIT_DIR ?? process.env.GIT_DIR), + safeBareRepositorySupported: await readSafeBareRepositorySupport(), + }); + return { + configArgs: [ + "-c", + "core.quotepath=false", + "-c", + "core.fsmonitor=false", + ...discovery.configArgs, + ], + envOverlay: discovery.envOverlay, + }; +} + export const runGitCommand: RunGitCommand = (args, options) => executeGitCommand(args, options, decodeUtf8, {}); diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index 4f0a1d5ef..a3ce36d17 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -5,6 +5,7 @@ import { deletePaseoWorktree, readWorktreeHead, isPaseoOwnedWorktreeCwd, + listPaseoWorktrees, mapWorkspaceCwdToWorktree, runWorktreeTeardownCommands, slugify, @@ -97,6 +98,14 @@ describe("paseo worktree manager", () => { await rm(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }); + function cloneBareRepository(): string { + const bareRepo = join(tempDir, "bare.git"); + execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo]); + // A bare clone does not copy the checkout's local config; its linked worktrees share this one. + execFileSync("git", ["--git-dir", bareRepo, "config", "core.autocrlf", "false"]); + return bareRepo; + } + it.each([ { existing: [], preferred: "main/patch-1", expected: "main-1/patch-1" }, { existing: ["main-1"], preferred: "main/patch-1", expected: "main-2/patch-1" }, @@ -303,6 +312,44 @@ describe("paseo worktree manager", () => { }); }); + it("creates and removes a worktree from a bare repository with no linked checkouts", async () => { + const bareRepo = cloneBareRepository(); + + const created = await createLegacyWorktreeForTest({ + branchName: "from-bare", + cwd: bareRepo, + baseBranch: "main", + worktreeSlug: "from-bare", + paseoHome, + }); + expect(readFileSync(join(created.worktreePath, "file.txt"), "utf8")).toBe("hello\n"); + + await deletePaseoWorktree({ cwd: bareRepo, worktreePath: created.worktreePath, paseoHome }); + expect(existsSync(created.worktreePath)).toBe(false); + expect( + execFileSync("git", ["--git-dir", bareRepo, "worktree", "list", "--porcelain"], { + encoding: "utf8", + }), + ).not.toContain(created.worktreePath); + }); + + it("lists the worktrees of a bare repository that only Paseo checkouts use", async () => { + const bareRepo = cloneBareRepository(); + const created = await createLegacyWorktreeForTest({ + branchName: "listed", + cwd: bareRepo, + baseBranch: "main", + worktreeSlug: "listed", + paseoHome, + }); + + const worktrees = await listPaseoWorktrees({ cwd: bareRepo, paseoHome }); + + expect(worktrees.map((entry) => [entry.path, entry.branchName])).toEqual([ + [realpathSync.native(created.worktreePath), "listed"], + ]); + }); + it("deletes a worktree whose .git admin dir has already been removed", async () => { const created = await createLegacyWorktreeForTest({ branchName: "orphan-delete-branch", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 94191f53f..ee587f14e 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -34,6 +34,7 @@ import { writePaseoWorktreeMetadata, writePaseoWorktreeRuntimeMetadata, } from "./worktree-metadata.js"; +import { runWithRepositoryRoot } from "./git-repository-discovery.js"; import { runGitCommand } from "./run-git-command.js"; import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js"; import { spawnProcess } from "./spawn.js"; @@ -1217,15 +1218,23 @@ export async function listGitWorktrees({ cwd }: { cwd: string }): Promise { +} + +export function listPaseoWorktrees( + options: ListPaseoWorktreesOptions, +): Promise { + return runWithRepositoryRoot(options.cwd, () => listPaseoWorktreesAtRepositoryRoot(options)); +} + +async function listPaseoWorktreesAtRepositoryRoot({ + cwd, + paseoHome, + worktreesRoot, +}: ListPaseoWorktreesOptions): Promise { const projectWorktreesRoot = await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot); const { entries } = await readGitWorktreeEntries(cwd); @@ -1325,7 +1334,12 @@ export async function readWorktreeHeadReference(worktreePath: string): Promise { + const operation = () => deletePaseoWorktreeAtRepositoryRoot(options); + return options.cwd ? runWithRepositoryRoot(options.cwd, operation) : operation(); +} + +async function deletePaseoWorktreeAtRepositoryRoot({ cwd, worktreePath, teardownCwds, @@ -1660,7 +1674,13 @@ export function createWorktree( export function createWorktree( options: CreateWorktreeOptions, ): Promise & { branchName: string | null }>; -export async function createWorktree({ +export function createWorktree( + options: CreateWorktreeOptions, +): Promise & { branchName: string | null }> { + return runWithRepositoryRoot(options.cwd, () => createWorktreeAtRepositoryRoot(options)); +} + +async function createWorktreeAtRepositoryRoot({ cwd, source, preparedBranchOff, @@ -1775,7 +1795,15 @@ export function runPluginWorktreeManagerCheckout( export function runPluginWorktreeManagerCheckout( options: RunPluginWorktreeManagerCheckoutOptions, ): Promise<(Omit & { branchName: string | null }) | null>; -export async function runPluginWorktreeManagerCheckout( +export function runPluginWorktreeManagerCheckout( + options: RunPluginWorktreeManagerCheckoutOptions, +): Promise<(Omit & { branchName: string | null }) | null> { + return runWithRepositoryRoot(options.cwd, () => + runPluginWorktreeManagerCheckoutAtRepositoryRoot(options), + ); +} + +async function runPluginWorktreeManagerCheckoutAtRepositoryRoot( options: RunPluginWorktreeManagerCheckoutOptions, ): Promise<(Omit & { branchName: string | null }) | null> { const { @@ -2321,7 +2349,17 @@ async function resolveRestoredWorktreeFromBasePlan( }; } -export async function prepareWorktreeBranchOff( +export function prepareWorktreeBranchOff( + cwd: string, + source: Extract, + previous?: PreparedWorktreeBranchOff, +): Promise { + return runWithRepositoryRoot(cwd, () => + prepareWorktreeBranchOffAtRepositoryRoot(cwd, source, previous), + ); +} + +async function prepareWorktreeBranchOffAtRepositoryRoot( cwd: string, source: Extract, previous?: PreparedWorktreeBranchOff, @@ -2551,11 +2589,19 @@ async function configureWorktreePushRemote(options: { * Fetches the first of `sources` a remote serves into the local ref `destination`, and returns * the name of that remote. */ -export async function fetchFirstAvailableRef(options: { +export interface FetchFirstAvailableRefOptions { cwd: string; sources: WorktreeCheckoutRef[]; destination: string; -}): Promise { +} + +export function fetchFirstAvailableRef(options: FetchFirstAvailableRefOptions): Promise { + return runWithRepositoryRoot(options.cwd, () => fetchFirstAvailableRefAtRepositoryRoot(options)); +} + +async function fetchFirstAvailableRefAtRepositoryRoot( + options: FetchFirstAvailableRefOptions, +): Promise { let lastResult: | Awaited> | { stderr: string; stdout: string; exitCode: number | null } diff --git a/plugins/worktree-include/server/copy.test.ts b/plugins/worktree-include/server/copy.test.ts index 30ada0c06..98f472e52 100644 --- a/plugins/worktree-include/server/copy.test.ts +++ b/plugins/worktree-include/server/copy.test.ts @@ -1,6 +1,6 @@ import { execFileSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; @@ -54,6 +54,19 @@ afterEach(async () => { }); describe("copyWorktreeIncludes", () => { + it("does not run a command the source repository configures as its fsmonitor", async () => { + const marker = join(root, "fsmonitor.marker"); + const hook = join(root, "fsmonitor-hook.sh"); + await writeFile(hook, `#!/bin/sh\n: > '${marker}'\nprintf '1\\n'\n`); + await chmod(hook, 0o755); + await writeSource({ ".gitignore": ".env\n", ".worktreeinclude": ".env\n", ".env": "A=1" }); + execFileSync("git", ["add", ".gitignore", ".worktreeinclude"], { cwd: source }); + execFileSync("git", ["config", "core.fsmonitor", hook], { cwd: source }); + + expect(await copied()).toEqual([".env"]); + expect(existsSync(marker)).toBe(false); + }); + it("does not search inside an ignored directory that no pattern names", async () => { await writeSource({ ".gitignore": "node_modules/\n.env\n", diff --git a/plugins/worktree-include/server/copy.ts b/plugins/worktree-include/server/copy.ts index 1b8cab3cb..ef336e86a 100644 --- a/plugins/worktree-include/server/copy.ts +++ b/plugins/worktree-include/server/copy.ts @@ -14,8 +14,13 @@ export type CopyResult = | { kind: "no-include-file" } | { kind: "copied"; copied: string[]; skipped: string[] }; +// `core.fsmonitor=false` prevents repository config from launching a command. +// `safe.bareRepository=explicit` stops git from adopting a directory that only +// looks like a bare repository. +const GIT_CONFIG_ARGS = ["-c", "core.fsmonitor=false", "-c", "safe.bareRepository=explicit"]; + async function git(cwd: string, args: string[], input?: string): Promise { - const child = exec("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 }); + const child = exec("git", [...GIT_CONFIG_ARGS, ...args], { cwd, maxBuffer: 64 * 1024 * 1024 }); if (input !== undefined) { child.child.stdin?.end(input); }