mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-23 08:45:14 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0466204ff4 |
@@ -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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,28 @@ 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: `submodule:${await readSubmoduleStatus(absolutePath)}` };
|
||||
}
|
||||
return { hashed: value.isFile() && text, literal: null };
|
||||
}
|
||||
|
||||
// An uninitialized submodule has no `.git`; running git there would discover
|
||||
// whichever repository sits above it. Pinning GIT_DIR keeps an initialized
|
||||
// submodule's status on its own `.git`.
|
||||
async function readSubmoduleStatus(submodulePath: string): Promise<string> {
|
||||
try {
|
||||
await lstat(join(submodulePath, ".git"));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
|
||||
throw error;
|
||||
}
|
||||
const status = await runGitCommand(
|
||||
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
|
||||
{ cwd: submodulePath, envOverlay: { GIT_DIR: ".git", GIT_OPTIONAL_LOCKS: "0" } },
|
||||
);
|
||||
return status.stdout;
|
||||
}
|
||||
|
||||
function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] {
|
||||
const revisions: string[] = [];
|
||||
if (compare.base.kind !== "index") revisions.push(baseSha);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Dirent } from "node:fs";
|
||||
import { lstat, readdir, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
|
||||
const GITFILE_PREFIX = "gitdir:";
|
||||
|
||||
/**
|
||||
* True when `cwd` is a bare repository that a linked worktree checkout points
|
||||
* back to: some `<cwd>/worktrees/<name>/gitdir` names a real `.git` file whose
|
||||
* `gitdir:` line resolves to that same `worktrees/<name>` directory. A clone
|
||||
* cannot contain `.git` files, so a directory layout that only looks like a bare
|
||||
* repository never passes. Symlinked entries and unreadable files count as not
|
||||
* linked.
|
||||
*/
|
||||
export async function isLinkedBareRepository(cwd: string): Promise<boolean> {
|
||||
try {
|
||||
if (!(await lstat(join(cwd, "HEAD"))).isFile()) return false;
|
||||
const worktreesDir = join(await realpath(cwd), "worktrees");
|
||||
if (!(await lstat(worktreesDir)).isDirectory()) return false;
|
||||
const entries = await readdir(worktreesDir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (await isLinkedWorktreeAdminDir(worktreesDir, entry)) return true;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function isLinkedWorktreeAdminDir(worktreesDir: string, entry: Dirent): Promise<boolean> {
|
||||
if (!entry.isDirectory()) return false;
|
||||
const adminDir = join(worktreesDir, entry.name);
|
||||
try {
|
||||
const gitdirFile = join(adminDir, "gitdir");
|
||||
if (!(await lstat(gitdirFile)).isFile()) return false;
|
||||
const dotGitPath = resolve(adminDir, (await readFile(gitdirFile, "utf8")).trim());
|
||||
if (basename(dotGitPath) !== ".git") return false;
|
||||
if (!(await lstat(dotGitPath)).isFile()) return false;
|
||||
const firstLine = (await readFile(dotGitPath, "utf8")).split(/\r?\n/, 1)[0] ?? "";
|
||||
if (!firstLine.startsWith(GITFILE_PREFIX)) return false;
|
||||
const target = resolve(dirname(dotGitPath), firstLine.slice(GITFILE_PREFIX.length).trim());
|
||||
return (await realpath(target)) === adminDir;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,14 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
@@ -49,3 +59,116 @@ 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(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 };
|
||||
}
|
||||
|
||||
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 layout whose worktrees directory is a symlink", async () => {
|
||||
const root = makeTempDir();
|
||||
const { bareRepo } = createBareRepositoryWithLinkedWorktree(root);
|
||||
const layout = createBareRepositoryLayout(root, "layout");
|
||||
symlinkSync(path.join(bareRepo, "worktrees"), path.join(layout.dir, "worktrees"));
|
||||
|
||||
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 whose worktree entry belongs to another repository", async () => {
|
||||
const root = makeTempDir();
|
||||
const { worktree } = createBareRepositoryWithLinkedWorktree(root);
|
||||
const layout = createBareRepositoryLayout(root, "layout");
|
||||
const adminDir = path.join(layout.dir, "worktrees", "main");
|
||||
mkdirSync(adminDir, { recursive: true });
|
||||
writeFileSync(path.join(adminDir, "gitdir"), `${path.join(worktree, ".git")}\n`);
|
||||
|
||||
await expect(
|
||||
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
|
||||
).rejects.toThrow(/cannot use bare repository/);
|
||||
});
|
||||
|
||||
it("runs in a bare repository that a linked worktree points back to", async () => {
|
||||
const root = makeTempDir();
|
||||
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(root);
|
||||
|
||||
const fromBare = await runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo });
|
||||
const fromWorktree = await runGitCommand(["rev-parse", "--git-common-dir"], { cwd: worktree });
|
||||
|
||||
expect(fromBare.stdout).toContain(`worktree ${worktree}\n`);
|
||||
expect(path.resolve(worktree, fromWorktree.stdout.trim())).toBe(bareRepo);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
startGitCommandTrace,
|
||||
submitGitCommandTrace,
|
||||
} from "./git-command-trace.js";
|
||||
import { isLinkedBareRepository } from "./linked-bare-repository.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
import {
|
||||
GitProcessScheduler,
|
||||
@@ -302,7 +303,7 @@ function executeGitCommand<Output>(
|
||||
pending: gitProcessScheduler.pendingCount,
|
||||
});
|
||||
const runtimeMetric = gitRuntimeMetrics.submit(getGitOperation(args), submission.provenance);
|
||||
const startCommand = () => {
|
||||
const spawnCommand = (configArgs: string[]) => {
|
||||
let releaseProcessSlot!: () => void;
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
releaseProcessSlot = resolve;
|
||||
@@ -407,19 +408,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", [...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 +568,15 @@ function executeGitCommand<Output>(
|
||||
});
|
||||
return { result: resultPromise, exited };
|
||||
};
|
||||
// The process slot stays held through the config lookup because `exited`
|
||||
// settles only after the spawned process exits. `resolveGitConfigArgs` never rejects.
|
||||
const startCommand = () => {
|
||||
const spawned = resolveGitConfigArgs(options.cwd).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 +585,18 @@ function executeGitCommand<Output>(
|
||||
return promise;
|
||||
}
|
||||
|
||||
// `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.
|
||||
// `safe.bareRepository=explicit` stops git from adopting a directory that only
|
||||
// looks like a bare repository, at `cwd` or above it. A bare repository with
|
||||
// linked worktrees still works when `cwd` is that repository.
|
||||
async function resolveGitConfigArgs(cwd: string): Promise<string[]> {
|
||||
const args = ["-c", "core.quotepath=false", "-c", "core.fsmonitor=false"];
|
||||
if (await isLinkedBareRepository(cwd)) return args;
|
||||
return [...args, "-c", "safe.bareRepository=explicit"];
|
||||
}
|
||||
|
||||
export const runGitCommand: RunGitCommand = (args, options) =>
|
||||
executeGitCommand(args, options, decodeUtf8, {});
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user