mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-06 07:06:16 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4b3d8b683 | ||
|
|
2d384fed49 | ||
|
|
03f1cb60cb | ||
|
|
b4a38eb9b3 | ||
|
|
9b5690f35c | ||
|
|
4b6433c19c | ||
|
|
cc9c431441 |
@@ -1,11 +1,23 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmod, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
||||
import {
|
||||
chmod,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readdir,
|
||||
readFile,
|
||||
realpath,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, test } from "vitest";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../utils/path.js";
|
||||
import { readPaseoWorktreeMetadata } from "../../utils/worktree-metadata.js";
|
||||
|
||||
const REPO_ROOT = path.resolve(fileURLToPath(new URL("../../../../..", import.meta.url)));
|
||||
@@ -1149,6 +1161,68 @@ export default function contribute(server) {
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test.each(["current", "before upgrade"])(
|
||||
"archiving a built-in worktree preserves its project directory after a placement hook used it (%s)",
|
||||
async (placement) => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-hook-owner-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
const otherRepository = await createRepo(path.join(root, "other-repo"));
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
const builtin = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "builtin-checkout" },
|
||||
});
|
||||
expect(builtin.error).toBeNull();
|
||||
const projectDirectory = path.dirname(builtin.workspace!.workspaceDirectory);
|
||||
const hookPath = path.join(projectDirectory, "hook-checkout");
|
||||
|
||||
const pluginDir = path.join(root, "placement-hook");
|
||||
await mkdir(pluginDir);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "placement-hook", requirements: { paseo: ">=0.17.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "index.server.ts"),
|
||||
`export default function contribute(server) {
|
||||
return server.addHook("worktree.create.before", ({ request }) => ({
|
||||
...request,
|
||||
path: ${JSON.stringify(hookPath)},
|
||||
}));
|
||||
}
|
||||
`,
|
||||
);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(pluginDir)).status).toBe("running");
|
||||
|
||||
const placed = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: otherRepository, branchName: "hook-checkout" },
|
||||
});
|
||||
expect(placed.error).toBeNull();
|
||||
expect(createRealpathAwarePathMatcher(hookPath)(placed.workspace!.workspaceDirectory)).toBe(
|
||||
true,
|
||||
);
|
||||
await client.disablePlugin("placement-hook");
|
||||
if (placement === "before upgrade") {
|
||||
// Older versions saved the checkout but did not record its parent directory.
|
||||
await rm(path.join(daemon.paseoHome, "worktree-project-owners"), { recursive: true });
|
||||
}
|
||||
|
||||
expect((await client.archiveWorkspace(placed.workspace!.id)).error).toBeNull();
|
||||
await expect(stat(hookPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await client.archiveWorkspace(builtin.workspace!.id)).error).toBeNull();
|
||||
expect(await readdir(projectDirectory)).toEqual([]);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
test("git fallback restore clears manager ownership across sibling workspaces sharing a checkout", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-sibling-owner-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
@@ -1167,13 +1241,14 @@ test("git fallback restore clears manager ownership across sibling workspaces sh
|
||||
await writeFile(
|
||||
path.join(pluginDir, "index.server.ts"),
|
||||
`import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { appendFileSync, mkdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export default function contribute(server) {
|
||||
return server.registerWorktreeManager({
|
||||
async create(request) {
|
||||
const target = path.join(path.dirname(request.repoRoot), "managed-" + request.branch);
|
||||
const target = request.path;
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
|
||||
cwd: request.repoRoot,
|
||||
stdio: "pipe",
|
||||
@@ -1195,6 +1270,7 @@ export default function contribute(server) {
|
||||
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
let readOnlyWorktreesRoot: string | undefined;
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
@@ -1206,6 +1282,8 @@ export default function contribute(server) {
|
||||
expect(created.error).toBeNull();
|
||||
const firstWorkspaceId = created.workspace!.id;
|
||||
const worktreePath = created.workspace!.workspaceDirectory;
|
||||
const projectDirectory = path.dirname(worktreePath);
|
||||
const matchesProjectDirectory = createRealpathAwarePathMatcher(projectDirectory);
|
||||
|
||||
// Create a second workspace on a subdirectory of the same managed checkout, sharing ownership.
|
||||
const secondCreated = await client.createWorkspace({
|
||||
@@ -1214,11 +1292,18 @@ export default function contribute(server) {
|
||||
expect(secondCreated.error).toBeNull();
|
||||
const secondWorkspaceId = secondCreated.workspace!.id;
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
const worktreesRoot = path.dirname(projectDirectory);
|
||||
await chmod(worktreesRoot, 0o555);
|
||||
readOnlyWorktreesRoot = worktreesRoot;
|
||||
}
|
||||
|
||||
// Persist the same manager owner on both records, disable the plugin, archive both, and restore via Git fallback.
|
||||
await client.disablePlugin("owner-tracking-manager");
|
||||
const archived = await client.archivePaseoWorktree({ worktreePath, scope: "worktree" });
|
||||
expect(archived.success).toBe(true);
|
||||
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await stat(projectDirectory)).isDirectory()).toBe(true);
|
||||
|
||||
// First restore recreates via Git fallback; second restore joins the existing checkout.
|
||||
await client.restoreWorkspace(firstWorkspaceId);
|
||||
@@ -1230,8 +1315,56 @@ export default function contribute(server) {
|
||||
expect((await client.archiveWorkspace(firstWorkspaceId)).error).toBeNull();
|
||||
expect((await client.archiveWorkspace(secondWorkspaceId)).error).toBeNull();
|
||||
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await stat(projectDirectory)).isDirectory()).toBe(true);
|
||||
// A sibling can recreate the checkout on the next restore.
|
||||
await client.restoreWorkspace(secondWorkspaceId);
|
||||
expect((await client.archiveWorkspace(secondWorkspaceId)).error).toBeNull();
|
||||
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await stat(projectDirectory)).isDirectory()).toBe(true);
|
||||
await expect(readFile(removeCallsFile, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
if (readOnlyWorktreesRoot) {
|
||||
await chmod(readOnlyWorktreesRoot, 0o755);
|
||||
readOnlyWorktreesRoot = undefined;
|
||||
}
|
||||
|
||||
// A built-in checkout can share the project directory with a plugin checkout.
|
||||
const pluginCheckout = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "plugin-checkout" },
|
||||
});
|
||||
expect(pluginCheckout.error).toBeNull();
|
||||
await client.disablePlugin("owner-tracking-manager");
|
||||
const builtinCheckout = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "builtin-checkout" },
|
||||
});
|
||||
expect(builtinCheckout.error).toBeNull();
|
||||
expect(
|
||||
matchesProjectDirectory(path.dirname(builtinCheckout.workspace!.workspaceDirectory)),
|
||||
).toBe(true);
|
||||
|
||||
expect((await client.archiveWorkspace(pluginCheckout.workspace!.id)).error).toBeNull();
|
||||
expect((await client.archiveWorkspace(builtinCheckout.workspace!.id)).error).toBeNull();
|
||||
await expect(stat(pluginCheckout.workspace!.workspaceDirectory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
await expect(stat(builtinCheckout.workspace!.workspaceDirectory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
expect(await readdir(projectDirectory)).toEqual([]);
|
||||
|
||||
// A replacement directory at the same path does not inherit the previous directory's owner.
|
||||
await rename(projectDirectory, projectDirectory + "-old");
|
||||
const replacement = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "replacement-checkout" },
|
||||
});
|
||||
expect(replacement.error).toBeNull();
|
||||
expect(matchesProjectDirectory(path.dirname(replacement.workspace!.workspaceDirectory))).toBe(
|
||||
true,
|
||||
);
|
||||
expect((await client.archiveWorkspace(replacement.workspace!.id)).error).toBeNull();
|
||||
await expect(stat(projectDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
if (readOnlyWorktreesRoot) await chmod(readOnlyWorktreesRoot, 0o755);
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
|
||||
@@ -358,6 +358,7 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
}
|
||||
|
||||
const result = await createWorktree({
|
||||
preserveProjectDirectory: Boolean(managerPluginId && hasRecordedWorktreePath),
|
||||
cwd: sourceRepoRoot,
|
||||
worktreeSlug: basename(previousWorktreePath),
|
||||
source,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import assert from "node:assert/strict";
|
||||
import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -103,6 +104,45 @@ test("workspace.create worktree source forwards action=checkout + refName into t
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test("archiving the last worktree removes its empty project directory", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.1.82",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
const first = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, action: "branch-off", worktreeSlug: "first" },
|
||||
});
|
||||
const last = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, action: "branch-off", worktreeSlug: "last" },
|
||||
});
|
||||
expect(first.error).toBeNull();
|
||||
expect(last.error).toBeNull();
|
||||
assert(first.workspace && last.workspace);
|
||||
|
||||
const firstPath = first.workspace.workspaceDirectory;
|
||||
const lastPath = last.workspace.workspaceDirectory;
|
||||
const projectDirectory = path.dirname(firstPath);
|
||||
expect(path.dirname(lastPath)).toBe(projectDirectory);
|
||||
|
||||
expect((await client.archiveWorkspace(first.workspace.id)).error).toBeNull();
|
||||
expect(existsSync(firstPath)).toBe(false);
|
||||
expect(existsSync(lastPath)).toBe(true);
|
||||
|
||||
expect((await client.archiveWorkspace(last.workspace.id)).error).toBeNull();
|
||||
expect(existsSync(lastPath)).toBe(false);
|
||||
expect(existsSync(projectDirectory)).toBe(false);
|
||||
expect(existsSync(path.dirname(projectDirectory))).toBe(true);
|
||||
}, 180000);
|
||||
|
||||
test("checkout.worktrees.list returns git worktrees Paseo did not create", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
|
||||
@@ -36,6 +36,7 @@ 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 { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
|
||||
import { normalizePathForIdentity } from "../utils/path.js";
|
||||
|
||||
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
|
||||
@@ -172,6 +173,9 @@ async function createWorktreeAtRepositoryRoot(
|
||||
cwd: repoRoot,
|
||||
worktreeSlug: normalizedSlug,
|
||||
worktreePath: transformed.path,
|
||||
preserveProjectDirectory:
|
||||
transformed.path !== defaultPath &&
|
||||
normalizePathForIdentity(transformed.path) !== normalizePathForIdentity(defaultPath),
|
||||
source: intent,
|
||||
preparedBranchOff,
|
||||
paseoHome: input.paseoHome,
|
||||
|
||||
@@ -4735,7 +4735,8 @@ const x = 1;
|
||||
// A fork whose local main tracks upstream/main. Origin holds main as it was when the fork
|
||||
// was made, and upstream has moved on. The checkout sits on a feature branch off old main.
|
||||
function setupForkOnFeatureBranch(): void {
|
||||
const { cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
|
||||
const { cloneUpstream } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
|
||||
const cloneDir = cloneUpstream();
|
||||
execFileSync("git", ["remote", "add", "origin", join(tempDir, "fork.git")], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { realpath, lstat } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { realpath, lstat, readFile, rm, rmdir } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
|
||||
import { getRelativePathInsideRoot } from "./path.js";
|
||||
import pLimit from "p-limit";
|
||||
import { writeFileAtomic } from "../server/atomic-file.js";
|
||||
import { resolvePaseoHome } from "../server/paseo-home.js";
|
||||
import {
|
||||
areEquivalentPaths,
|
||||
getRelativePathInsideRoot,
|
||||
normalizePathForComparison,
|
||||
} from "./path.js";
|
||||
|
||||
async function normalizeAbsolute(path: string): Promise<string> {
|
||||
try {
|
||||
@@ -40,6 +48,88 @@ async function pathExists(path: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
// A plugin archive must record ownership before a sibling archive tests whether it can prune.
|
||||
const updateProjectDirectory = pLimit(1);
|
||||
|
||||
interface WorktreeProjectDirectoryOptions {
|
||||
worktreePath: string;
|
||||
worktreesBaseRoot: string;
|
||||
paseoHome?: string;
|
||||
}
|
||||
|
||||
async function inspectWorktreeProjectDirectory({
|
||||
worktreePath,
|
||||
worktreesBaseRoot,
|
||||
paseoHome = resolvePaseoHome(),
|
||||
}: WorktreeProjectDirectoryOptions) {
|
||||
const parent = dirname(worktreePath);
|
||||
const info = await lstat(parent, { bigint: true });
|
||||
if (!info.isDirectory()) return null;
|
||||
|
||||
const [directory, base] = await Promise.all([realpath(parent), realpath(worktreesBaseRoot)]);
|
||||
if (!areEquivalentPaths(dirname(directory), base)) return null;
|
||||
|
||||
const key = createHash("sha256")
|
||||
.update(normalizePathForComparison(directory, process.platform === "win32"))
|
||||
.digest("hex");
|
||||
return {
|
||||
directory,
|
||||
// Use daemon storage so neither the project directory nor its parent needs to be writable.
|
||||
ownershipFile: join(paseoHome, "worktree-project-owners", key),
|
||||
// A replacement directory at the same path has its own ownership.
|
||||
identity: `${info.dev}:${info.ino}:${info.birthtimeNs}`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function preserveWorktreeProjectDirectory(
|
||||
options: WorktreeProjectDirectoryOptions,
|
||||
): Promise<void> {
|
||||
await updateProjectDirectory(async () => {
|
||||
const project = await inspectWorktreeProjectDirectory(options).catch(
|
||||
(error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return null;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
if (project) await writeFileAtomic(project.ownershipFile, project.identity);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeEmptyWorktreeProjectDirectory(
|
||||
options: WorktreeProjectDirectoryOptions & { projectWorktreesRoot: string },
|
||||
): Promise<void> {
|
||||
const { projectWorktreesRoot } = options;
|
||||
await updateProjectDirectory(async () => {
|
||||
try {
|
||||
if (!(await lstat(projectWorktreesRoot)).isDirectory()) return;
|
||||
|
||||
const project = await inspectWorktreeProjectDirectory(options);
|
||||
if (
|
||||
!project ||
|
||||
!areEquivalentPaths(project.directory, await realpath(projectWorktreesRoot))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = await readFile(project.ownershipFile, "utf8").catch(
|
||||
(error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return null;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
if (owner === project.identity) return;
|
||||
|
||||
await rmdir(project.directory);
|
||||
if (owner !== null) await rm(project.ownershipFile, { force: true });
|
||||
} catch (error) {
|
||||
// An occupied or inaccessible parent does not make the completed archive fail.
|
||||
if (!(error instanceof Error && "code" in error && typeof error.code === "string")) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a worktree destination. Throws
|
||||
* with the reason on any violation; returns the normalized absolute path.
|
||||
|
||||
@@ -24,10 +24,11 @@ import {
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { join } from "path";
|
||||
import { dirname, join } from "path";
|
||||
import { createServer, type AddressInfo, type Socket } from "net";
|
||||
import { tmpdir } from "os";
|
||||
import { createRealpathAwarePathMatcher } from "./path";
|
||||
import { writePaseoWorktreeMetadata } from "./worktree-metadata";
|
||||
|
||||
interface LegacyCreateWorktreeTestOptions {
|
||||
branchName: string;
|
||||
@@ -548,6 +549,7 @@ describe("paseo worktree manager", () => {
|
||||
paseoHome,
|
||||
});
|
||||
expect(existsSync(created.worktreePath)).toBe(false);
|
||||
expect(existsSync(dirname(created.worktreePath))).toBe(false);
|
||||
|
||||
// Second call — nothing left on disk and no admin entry — must not throw.
|
||||
await expect(
|
||||
@@ -555,6 +557,30 @@ describe("paseo worktree manager", () => {
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the project directory of a plugin-managed checkout after fallback removal", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "managed-branch",
|
||||
cwd: repoDir,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "managed",
|
||||
paseoHome,
|
||||
});
|
||||
await writePaseoWorktreeMetadata(created.worktreePath, {
|
||||
baseRefName: "main",
|
||||
worktreeManagerPluginId: "test-manager",
|
||||
});
|
||||
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: created.worktreePath,
|
||||
paseoHome,
|
||||
worktreeManagerPluginId: null,
|
||||
});
|
||||
|
||||
expect(existsSync(created.worktreePath)).toBe(false);
|
||||
expect(existsSync(dirname(created.worktreePath))).toBe(true);
|
||||
});
|
||||
|
||||
it("deletes a worktree when the parent repo root is not available", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "no-cwd-branch",
|
||||
|
||||
@@ -62,7 +62,11 @@ import {
|
||||
normalizePathForIdentity,
|
||||
} from "./path.js";
|
||||
import { terminateWithTreeKill } from "./tree-kill.js";
|
||||
import { validateWorktreePath } from "./worktree-path.js";
|
||||
import {
|
||||
preserveWorktreeProjectDirectory,
|
||||
removeEmptyWorktreeProjectDirectory,
|
||||
validateWorktreePath,
|
||||
} from "./worktree-path.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js";
|
||||
|
||||
export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug";
|
||||
@@ -319,6 +323,7 @@ export interface CreateWorktreeOptions {
|
||||
paseoHome?: string;
|
||||
worktreesRoot?: string;
|
||||
worktreePath?: string;
|
||||
preserveProjectDirectory?: boolean;
|
||||
}
|
||||
|
||||
export class BranchAlreadyCheckedOutError extends Error {
|
||||
@@ -1603,42 +1608,52 @@ async function deletePaseoWorktreeAtRepositoryRoot({
|
||||
await assertWorktreeBelongsToRepo(cwd, resolvedWorktree);
|
||||
}
|
||||
|
||||
if (await pathExists(resolvedWorktree)) {
|
||||
const removedByPlugin = await prepareAndTryPluginWorktreeRemove({
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
force,
|
||||
untrusted,
|
||||
signal,
|
||||
});
|
||||
if (removedByPlugin) {
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!force) return removeCleanWorktree(cwd, resolvedWorktree);
|
||||
|
||||
if (cwd) {
|
||||
try {
|
||||
await runGitCommand(["worktree", "remove", resolvedWorktree, "--force"], {
|
||||
const baseRoot = resolvePaseoWorktreesBaseRoot({ paseoHome, worktreesRoot: worktreesBaseRoot });
|
||||
const removal = (await pathExists(resolvedWorktree))
|
||||
? await prepareWorktreeRemoval({
|
||||
cwd,
|
||||
timeout: 120_000,
|
||||
});
|
||||
} catch {
|
||||
// `git worktree remove` fails if the admin dir is already gone (e.g. a
|
||||
// prior archive attempt removed it before the working tree could be
|
||||
// fully cleaned up), or if the repo root has moved. Fall through to the
|
||||
// rm retry loop below so the operation stays idempotent.
|
||||
}
|
||||
resolvedWorktree,
|
||||
worktreesBaseRoot: baseRoot,
|
||||
paseoHome,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
force,
|
||||
untrusted,
|
||||
signal,
|
||||
})
|
||||
: "remove-checkout";
|
||||
if (removal === "removed-by-plugin") {
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
return;
|
||||
}
|
||||
|
||||
await removeDirectoryWithRetries(resolvedWorktree);
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
if (!force) {
|
||||
await removeCleanWorktree(cwd, resolvedWorktree);
|
||||
} else {
|
||||
if (cwd) {
|
||||
try {
|
||||
await runGitCommand(["worktree", "remove", resolvedWorktree, "--force"], {
|
||||
cwd,
|
||||
timeout: 120_000,
|
||||
});
|
||||
} catch {
|
||||
// Git's admin dir may already be gone; the rm fallback is idempotent.
|
||||
}
|
||||
}
|
||||
await removeDirectoryWithRetries(resolvedWorktree);
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
}
|
||||
|
||||
if (removal === "prune-project-directory") {
|
||||
await removeEmptyWorktreeProjectDirectory({
|
||||
worktreePath: resolvedWorktree,
|
||||
projectWorktreesRoot: resolvedWorktreesRoot,
|
||||
worktreesBaseRoot: baseRoot,
|
||||
paseoHome,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function assertCleanWorktree(worktreePath: string): Promise<void> {
|
||||
@@ -1726,9 +1741,11 @@ async function pruneWorktreesBestEffort(cwd: string | null): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
async function prepareWorktreeRemoval(options: {
|
||||
cwd: string | null;
|
||||
resolvedWorktree: string;
|
||||
worktreesBaseRoot: string;
|
||||
paseoHome?: string;
|
||||
teardownCwds?: string[];
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
@@ -1736,10 +1753,12 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
force: boolean;
|
||||
untrusted: boolean;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<boolean> {
|
||||
}): Promise<"remove-checkout" | "prune-project-directory" | "removed-by-plugin"> {
|
||||
const {
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
worktreesBaseRoot,
|
||||
paseoHome,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
@@ -1756,11 +1775,15 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
}
|
||||
if (!force) await assertCleanWorktree(resolvedWorktree);
|
||||
|
||||
// A legacy archive record can lack the manager ID even when the checkout marker has it.
|
||||
const metadata =
|
||||
worktreeManagerPluginId == null
|
||||
? await readPaseoWorktreeMetadata(resolvedWorktree).catch(() => undefined)
|
||||
: undefined;
|
||||
const effectiveManagerPluginId =
|
||||
worktreeManagerPluginId !== undefined
|
||||
? worktreeManagerPluginId
|
||||
: ((await readPaseoWorktreeMetadata(resolvedWorktree).catch(() => null))
|
||||
?.worktreeManagerPluginId ?? null);
|
||||
worktreeManagerPluginId === undefined
|
||||
? metadata?.worktreeManagerPluginId
|
||||
: worktreeManagerPluginId;
|
||||
if (effectiveManagerPluginId) {
|
||||
await assertNoNestedLinkedWorktrees(resolvedWorktree);
|
||||
}
|
||||
@@ -1773,9 +1796,19 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
cwd: resolvedWorktree,
|
||||
});
|
||||
}
|
||||
if (!effectiveManagerPluginId || !worktreeManagers) {
|
||||
return false;
|
||||
}
|
||||
const projectDirectoryRemoval =
|
||||
removeReason === "archive"
|
||||
? await prepareWorktreeProjectDirectoryArchive({
|
||||
cwd,
|
||||
worktreePath: resolvedWorktree,
|
||||
worktreesBaseRoot,
|
||||
paseoHome,
|
||||
managerPluginId: effectiveManagerPluginId ?? metadata?.worktreeManagerPluginId,
|
||||
metadataReadable: metadata !== undefined,
|
||||
})
|
||||
: "remove-checkout";
|
||||
if (!effectiveManagerPluginId) return projectDirectoryRemoval;
|
||||
if (!worktreeManagers) return "remove-checkout";
|
||||
const removedByPlugin = await worktreeManagers.removeWorktree(
|
||||
{
|
||||
repoRoot: cwd,
|
||||
@@ -1788,14 +1821,39 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
{ preferredPluginId: effectiveManagerPluginId, signal },
|
||||
);
|
||||
if (removedByPlugin === null) {
|
||||
return false;
|
||||
return "remove-checkout";
|
||||
}
|
||||
if (await pathExists(resolvedWorktree)) {
|
||||
throw new Error(
|
||||
`Plugin ${removedByPlugin.pluginId} worktree.remove reported removed, but the directory still exists: ${resolvedWorktree}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
return "removed-by-plugin";
|
||||
}
|
||||
|
||||
async function prepareWorktreeProjectDirectoryArchive(options: {
|
||||
cwd: string | null;
|
||||
worktreePath: string;
|
||||
worktreesBaseRoot: string;
|
||||
paseoHome?: string;
|
||||
managerPluginId: string | null | undefined;
|
||||
metadataReadable: boolean;
|
||||
}): Promise<"remove-checkout" | "prune-project-directory"> {
|
||||
const { cwd, paseoHome, worktreesBaseRoot, worktreePath } = options;
|
||||
// Older placement hooks left no ownership record. Git still identifies the
|
||||
// source repository, so a checkout in another project directory proves a
|
||||
// non-default placement.
|
||||
const sourceProjectDirectory = cwd
|
||||
? await getPaseoWorktreesRoot(cwd, paseoHome, worktreesBaseRoot)
|
||||
: null;
|
||||
const usesAnotherProjectDirectory =
|
||||
sourceProjectDirectory !== null &&
|
||||
!createRealpathAwarePathMatcher(sourceProjectDirectory)(dirname(worktreePath));
|
||||
if (options.managerPluginId || usesAnotherProjectDirectory) {
|
||||
await preserveWorktreeProjectDirectory(options);
|
||||
return "remove-checkout";
|
||||
}
|
||||
return options.metadataReadable ? "prune-project-directory" : "remove-checkout";
|
||||
}
|
||||
|
||||
export async function rollbackCreatedPaseoWorktree(
|
||||
@@ -1944,6 +2002,7 @@ async function createWorktreeAtRepositoryRoot({
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
worktreePath: explicitWorktreePath,
|
||||
preserveProjectDirectory,
|
||||
}: CreateWorktreeOptions): Promise<
|
||||
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
|
||||
> {
|
||||
@@ -1969,6 +2028,13 @@ async function createWorktreeAtRepositoryRoot({
|
||||
explicitWorktreePath ??
|
||||
(await resolveDefaultWorktreePath({ cwd, paseoHome, worktreesRoot, worktreeSlug }));
|
||||
await mkdir(dirname(worktreePath), { recursive: true });
|
||||
if (preserveProjectDirectory) {
|
||||
await preserveWorktreeProjectDirectory({
|
||||
worktreePath,
|
||||
worktreesBaseRoot: resolvePaseoWorktreesBaseRoot({ paseoHome, worktreesRoot }),
|
||||
paseoHome,
|
||||
});
|
||||
}
|
||||
|
||||
// Primitive owner for `git worktree add`; callers route through createWorktreeCore.
|
||||
await runGitCommand(["worktree", "add", worktreePath, ...sourcePlan.addArguments], {
|
||||
|
||||
Reference in New Issue
Block a user