Files
paseo/plugins/worktree-include/server/copy.test.ts
T
Mohamed Boudra 182c1aa192 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.
2026-11-23 17:50:47 +07:00

305 lines
10 KiB
TypeScript

import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
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";
import { copyWorktreeIncludes } from "./copy.js";
let root: string;
let source: string;
let worktree: string;
async function writeSource(files: Record<string, string>): Promise<void> {
for (const [file, contents] of Object.entries(files)) {
await mkdir(dirname(join(source, file)), { recursive: true });
await writeFile(join(source, file), contents);
}
}
// Total directories Git visits while listing files, read from its trace2 events.
async function directoriesVisited(run: () => Promise<unknown>): Promise<number> {
const trace = join(root, "trace.json");
process.env.GIT_TRACE2_EVENT = trace;
try {
await run();
} finally {
delete process.env.GIT_TRACE2_EVENT;
}
return (await readFile(trace, "utf8"))
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line) as { event: string; key?: string; value?: string })
.filter((event) => event.event === "data" && event.key === "directories-visited")
.reduce((total, event) => total + Number(event.value), 0);
}
async function copied(): Promise<string[]> {
const result = await copyWorktreeIncludes(worktree, source);
if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`);
return [...result.copied].sort();
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), "worktree-include-"));
source = join(root, "source");
worktree = join(root, "worktree");
await mkdir(source);
await mkdir(worktree);
execFileSync("git", ["init", "-q", source]);
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
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",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
"apps/web/.env": "SECRET=web",
"node_modules/pkg/.env": "SECRET=package",
});
expect(await copied()).toEqual([".env", "apps/web/.env"]);
expect(existsSync(join(worktree, "node_modules"))).toBe(false);
});
it("searches inside ignored directories for a pattern that starts with **/", async () => {
await writeSource({
".gitignore": "node_modules/\n.env\n",
".worktreeinclude": "**/.env\n",
".env": "SECRET=root",
"node_modules/pkg/.env": "SECRET=package",
});
expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]);
});
it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": "**/.env\nnew-package/.env\n",
"new-package/.env": "SECRET=new",
});
const result = await copyWorktreeIncludes(worktree, source);
expect(result).toEqual({
kind: "copied",
copied: ["new-package/.env"],
skipped: [],
});
});
it("copies a path a pattern names inside an ignored directory", async () => {
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "node_modules/pkg/.env\n",
"node_modules/pkg/.env": "SECRET=package",
"node_modules/other/.env": "SECRET=other",
});
expect(await copied()).toEqual(["node_modules/pkg/.env"]);
});
it("copies an ignored directory that a pattern names", async () => {
await writeSource({
".gitignore": ".secrets/\nbuild/\n",
".worktreeinclude": ".secrets/\n",
".secrets/a.key": "a",
".secrets/nested/b.key": "b",
"build/out.js": "built",
});
expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]);
});
it("searches inside an ignored directory for a path a pattern names", async () => {
await writeSource({
".gitignore": "config/\n",
".worktreeinclude": "config/*.local.json\n!config/production.local.json\n",
"config/dev.local.json": "dev",
"config/production.local.json": "production",
"config/defaults.json": "defaults",
});
expect(await copied()).toEqual(["config/dev.local.json"]);
expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev");
});
it("copies ignored files inside an untracked directory", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\n",
"new-package/.env": "SECRET=new",
});
expect(await copied()).toEqual(["new-package/.env"]);
});
it("copies nothing that is tracked or not ignored", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\nnotes.txt\n",
"notes.txt": "not ignored",
});
expect(await copied()).toEqual([]);
});
it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => {
const packages: Record<string, string> = {};
for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code";
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "node_modules/.cache\n",
"node_modules/.cache/state.json": "cache",
...packages,
});
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
const visited = await directoriesVisited(async () => {
result = await copyWorktreeIncludes(worktree, source);
});
expect(result).toEqual({
kind: "copied",
copied: ["node_modules/.cache/state.json"],
skipped: [],
});
expect(visited).toBeLessThan(10);
});
it.skipIf(process.platform === "win32")(
"copies includes when an ignored file is named like a Git pathspec",
async () => {
await writeSource({
".gitignore": "*.log\n.env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
":(oops.log": "log",
":!c.log": "log",
});
expect(await copied()).toEqual([".env"]);
},
);
it("ignores exclude patterns from the user's git template", async () => {
const template = join(root, "template");
await mkdir(join(template, "info"), { recursive: true });
await writeFile(join(template, "info", "exclude"), "*.log\n");
await writeSource({
".gitignore": "*.log\n.env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
"debug.log": "log",
});
process.env.GIT_TEMPLATE_DIR = template;
try {
expect(await copied()).toEqual([".env"]);
} finally {
delete process.env.GIT_TEMPLATE_DIR;
}
});
it("does not search an ignored directory deeper than a pattern without ** can reach", async () => {
const packages: Record<string, string> = {};
for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code";
await writeSource({
".gitignore": "node_modules/\n.env\n",
".worktreeinclude": "apps/*/.env\n",
"apps/web/.env": "SECRET=web",
...packages,
});
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
const visited = await directoriesVisited(async () => {
result = await copyWorktreeIncludes(worktree, source);
});
expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] });
expect(visited).toBeLessThan(10);
});
it("reads the first pattern after a UTF-8 byte order mark", async () => {
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "\uFEFFnode_modules/.cache/\n",
"node_modules/.cache/state.json": "cache",
});
expect(await copied()).toEqual(["node_modules/.cache/state.json"]);
});
it("matches patterns case-insensitively when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": ".env\nconfig/\n",
".worktreeinclude": ".ENV\nCONFIG/a.json\n",
".env": "SECRET=root",
"config/a.json": "a",
});
expect(await copied()).toEqual([".env", "config/a.json"]);
});
it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": "Config/\nÉTÉ/\n",
".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n",
"Config/a.json": "a",
"ÉTÉ/sub/.env": "SECRET=summer",
});
expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]);
});
// Each searched folder is one argument to Git. Windows caps a command line at 32,767
// characters and Linux at 2 MB, so each platform gets enough folders to exceed its own
// limit, with names short enough for Windows paths.
it("searches more ignored folders than fit on one command line", async () => {
const folders = process.platform === "win32" ? 300 : 15_000;
const name = (i: number) => `${"x".repeat(150)}${i}`;
await writeSource({
".gitignore": "x*/\n.env\n",
".worktreeinclude": "**/.env\n",
[`${name(folders - 1)}/.env`]: "SECRET=last",
});
for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i)));
await Promise.all(
Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")),
);
expect(await copied()).toEqual([`${name(folders - 1)}/.env`]);
}, 60_000);
it("copies ignored files inside an untracked directory a pattern names", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": "newdir/\n",
"newdir/.env": "SECRET=new",
"newdir/notes.txt": "untracked",
});
expect(await copied()).toEqual(["newdir/.env"]);
});
});