Keep git commands from adopting bare-repository-shaped directories (#10587)

* fix(server): keep git from adopting bare-repository-shaped directories

Git discovery treats any directory holding `HEAD`, `config`, `objects/` and
`refs/` as a bare repository, at the working directory or in a parent. Daemon
git commands then ran with that directory's config. They now pass
`-c safe.bareRepository=explicit`. The flag is left off only when the working
directory is a bare repository that a linked worktree's `.git` file points back
to, so the bare + linked-worktree layout keeps working.

The diff reader ran `git status` inside every submodule path. An uninitialized
submodule has no `.git`, so git walked up to whatever repository sat above it.
The reader now skips submodules without `.git` and pins `GIT_DIR=.git` for
initialized ones.

The worktree-include plugin spawns git directly and gets the same flags.

* fix(server): stop bare-repository discovery on Git before 2.38

Git releases before 2.38 ignore `safe.bareRepository`, so the runner's flag
did nothing there. On those releases the runner now follows git's discovery
order from `cwd` itself. If it reaches a directory that looks like a bare
repository before any `.git`, it pins `GIT_DIR` to the missing `<cwd>/.git`
and git reports that no repository was found, which matches what newer
releases do with the flag. The git version is read once per process.

The worktree-include plugin needs no fallback: it runs git at a checkout
root, where discovery stops at that checkout's own `.git`.

* test(server): keep fixtures independent of git discovery timing

The fetch fixture ran `update-server-info` from inside a plain bare remote.
With `safe.bareRepository=explicit`, git now refuses that unless the
repository is named, so the fixture passes `--git-dir`.

The slow-cadence poll test let the service read `remote.origin.url` through
real git while timers were faked. The runner now checks the working directory
before it spawns, and fake timers do not wait for that file-system work. The
test now injects the repository host and slug like its neighbors do.

* fix(server): refresh live diffs when an uninitialized submodule's commit changes

Skipping `git status` for an uninitialized submodule left its worktree
identity empty, so staging a different commit kept the same identity. Open
diffs then reused the previous patch. The identity is now the commit that the
comparison's index records for that path.

* fix(server): read an uninitialized submodule's commit at stage 0 explicitly

A path such as `0:sub` made `:<path>` read as stage 0 of `sub`. Naming stage 0 keeps the rest of the argument as the full path.

* test(server): supply repository identity to fake-timer poll tests

The poll tests advance a fake clock, but their repository host and slug
lookups ran real git. Git launches now read the filesystem before
spawning, so that real work could finish after the clock had already
advanced, and the expected reads were missed intermittently.

* fix(server): name a recorded bare repository root explicitly for git

Git commands at a bare repository root used to run only while a linked
worktree pointed back to it. After the last checkout of a bare repository
was archived, that link was gone, so Restore failed with "cannot use bare
repository". A bare repository with no checkouts has the same files on disk
as a bare-repository-shaped directory, so the files cannot tell them apart.

Git now never discovers a bare repository by its directory. Worktree
creation, archive, and Restore receive their repository root from Paseo's
records, and they run inside runWithRepositoryRoot. That scope names a bare
root through GIT_DIR, for commands at that exact root only. It is read when
a command is submitted, because the git scheduler can start the process
from another async context.

* fix(server): list worktrees of a bare repository that only Paseo checkouts use

Archiving by slug or branch lists worktrees at the recorded repository root.
When that root is a bare repository with no `.git`, explicit bare-repository
handling made `git worktree list` fail there. Listing, branch-off preparation
and ref fetching now name the recorded root the same way creating and
removing worktrees already do.

* test(server): give the bare-repository restore fixture a commit identity

A bare clone does not copy the source checkout's local user.name and user.email, so the fixture commit failed on runners without a global identity.

* test(server): make bare-repository tests hold on Windows runners

The tests compared 8.3 short temp paths with the long paths that git and
async realpath report, compared git's forward-slash paths as raw strings, and
read files that the runner's core.autocrlf had converted to CRLF. Temp
directories now resolve through realpathSync.native, git paths go through
path.resolve, and the bare fixtures set their config on the bare repository,
because a bare clone does not copy the source checkout's local config.
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-23 17:50:47 +07:00
1 parent 8fa709532c
commit 182c1aa192
17 files changed
+928 -42

No files matched your search

@@ -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 });
}
});
+27 -6
View File
@@ -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<string> {
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);
@@ -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-"));
@@ -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");
@@ -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
@@ -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<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
@@ -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<string>;
resolveRepoRoot?: (cwd: string) => Promise<string>;
}) {
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);
@@ -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<CreateWorktreeCoreResult> {
const repoRoot = await resolveWorktreeRepoRoot(input, deps.workspaceGitService);
return runWithRepositoryRoot(repoRoot, () =>
createWorktreeAtRepositoryRoot(input, deps, repoRoot),
);
}
async function createWorktreeAtRepositoryRoot(
input: CreateWorktreeCoreInput,
deps: CreateWorktreeCoreDeps,
repoRoot: string,
): Promise<CreateWorktreeCoreResult> {
const requestedWorktreeSlug = input.worktreeSlug
? normalizeWorktreeSlug(input.worktreeSlug)
: undefined;
@@ -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,
});
@@ -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);
});
});
@@ -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<readonly RepositoryRoot[]>();
/**
* 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<T>(
root: string,
operation: () => Promise<T>,
): Promise<T> {
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<RepositoryRoot | null> {
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
* `<cwd>/.git`, so git reports that no repository was found.
*/
export async function resolveGitDiscovery(input: GitDiscoveryInput): Promise<GitDiscovery> {
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<boolean> | null = null;
/** Reads `git --version` once per process. */
export function readSafeBareRepositorySupport(): Promise<boolean> {
safeBareRepositorySupport ??= execCommand("git", ["--version"]).then(
({ stdout }) => parseSafeBareRepositorySupport(stdout),
() => false,
);
return safeBareRepositorySupport;
}
// Follows git's discovery order: `<dir>/.git` first, then `<dir>` 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<boolean> {
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<boolean> {
return (
(await isFile(join(dir, "HEAD"))) &&
(await isDirectory(join(dir, "objects"))) &&
(await isDirectory(join(dir, "refs")))
);
}
async function isFile(path: string): Promise<boolean> {
try {
return (await stat(path)).isFile();
} catch {
return false;
}
}
async function isDirectory(path: string): Promise<boolean> {
try {
return (await stat(path)).isDirectory();
} catch {
return false;
}
}
@@ -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/);
});
});
+57 -15
View File
@@ -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<Output>(
submission: GitCommandSubmission,
): Promise<GitCommandResult<Output>> {
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<void>((resolve) => {
releaseProcessSlot = resolve;
@@ -317,7 +324,10 @@ function executeGitCommand<Output>(
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<Output>(
let child: ReturnType<typeof spawnProcess>;
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<Output>(
});
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<Output>(
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<GitLaunch> {
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, {});
@@ -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",
+58 -12
View File
@@ -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<GitWor
return worktrees;
}
export async function listPaseoWorktrees({
cwd,
paseoHome,
worktreesRoot,
}: {
export interface ListPaseoWorktreesOptions {
cwd: string;
paseoHome?: string;
worktreesRoot?: string;
}): Promise<PaseoWorktreeInfo[]> {
}
export function listPaseoWorktrees(
options: ListPaseoWorktreesOptions,
): Promise<PaseoWorktreeInfo[]> {
return runWithRepositoryRoot(options.cwd, () => listPaseoWorktreesAtRepositoryRoot(options));
}
async function listPaseoWorktreesAtRepositoryRoot({
cwd,
paseoHome,
worktreesRoot,
}: ListPaseoWorktreesOptions): Promise<PaseoWorktreeInfo[]> {
const projectWorktreesRoot = await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot);
const { entries } = await readGitWorktreeEntries(cwd);
@@ -1325,7 +1334,12 @@ export async function readWorktreeHeadReference(worktreePath: string): Promise<s
}
}
export async function deletePaseoWorktree({
export function deletePaseoWorktree(options: DeletePaseoWorktreeOptions): Promise<void> {
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<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function createWorktree({
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { 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<CreatedWorktree, "branchName"> & { branchName: string | null }) | null>;
export async function runPluginWorktreeManagerCheckout(
export function runPluginWorktreeManagerCheckout(
options: RunPluginWorktreeManagerCheckoutOptions,
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
return runWithRepositoryRoot(options.cwd, () =>
runPluginWorktreeManagerCheckoutAtRepositoryRoot(options),
);
}
async function runPluginWorktreeManagerCheckoutAtRepositoryRoot(
options: RunPluginWorktreeManagerCheckoutOptions,
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
const {
@@ -2321,7 +2349,17 @@ async function resolveRestoredWorktreeFromBasePlan(
};
}
export async function prepareWorktreeBranchOff(
export function prepareWorktreeBranchOff(
cwd: string,
source: Extract<WorktreeSource, { kind: "branch-off" }>,
previous?: PreparedWorktreeBranchOff,
): Promise<PreparedWorktreeBranchOff> {
return runWithRepositoryRoot(cwd, () =>
prepareWorktreeBranchOffAtRepositoryRoot(cwd, source, previous),
);
}
async function prepareWorktreeBranchOffAtRepositoryRoot(
cwd: string,
source: Extract<WorktreeSource, { kind: "branch-off" }>,
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<string> {
}
export function fetchFirstAvailableRef(options: FetchFirstAvailableRefOptions): Promise<string> {
return runWithRepositoryRoot(options.cwd, () => fetchFirstAvailableRefAtRepositoryRoot(options));
}
async function fetchFirstAvailableRefAtRepositoryRoot(
options: FetchFirstAvailableRefOptions,
): Promise<string> {
let lastResult:
| Awaited<ReturnType<typeof runGitCommand>>
| { stderr: string; stdout: string; exitCode: number | null }
+14 -1
View File
@@ -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",
+6 -1
View File
@@ -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<string> {
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);
}