mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-19 23:05:21 +00:00
feat(server): branch off a pull request and list every git worktree
A workspace.create worktree source with action "branch-off" and a checkoutSource used to check the pull request out, because core took any change request as a checkout. Branch-off now fetches the pull request's head into a remote-tracking ref (origin/<head> for a same-repo head, paseo-pr-<N>/<head> otherwise) and starts the new branch there, with no upstream and no remote added. A request with no action still checks the pull request out, as older clients expect. checkout.worktrees.list returns all git worktrees of the repository, not only the ones Paseo created, so the New workspace screen can offer any of them. Bare and prunable entries are left out. Hosts advertise both through server_info.features: worktreeRefActions and checkoutWorktreeList. Older hosts ignore the branch-off action on a pull request, so the app must gate on the flag.
This commit is contained in:
@@ -68,6 +68,7 @@ import type {
|
||||
GitSetupOptions,
|
||||
CheckoutStatusResponse,
|
||||
CheckoutCommit,
|
||||
CheckoutWorktree,
|
||||
ParsedDiffFile,
|
||||
CheckoutCommitResponse,
|
||||
CheckoutMergeResponse,
|
||||
@@ -5133,6 +5134,23 @@ export class DaemonClient {
|
||||
return { baseRef: payload.baseRef, commits: payload.commits };
|
||||
}
|
||||
|
||||
/** Every git worktree of the repository `cwd` is in, whoever created it. */
|
||||
async listCheckoutWorktrees(cwd: string, requestId?: string): Promise<CheckoutWorktree[]> {
|
||||
const payload =
|
||||
await this.sendNamespacedCorrelatedSessionRequest<"checkout.worktrees.list.response">({
|
||||
requestId,
|
||||
message: {
|
||||
type: "checkout.worktrees.list.request",
|
||||
cwd,
|
||||
},
|
||||
timeout: 60000,
|
||||
});
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error.message);
|
||||
}
|
||||
return payload.worktrees;
|
||||
}
|
||||
|
||||
async getCommitFileDiff(
|
||||
cwd: string,
|
||||
sha: string,
|
||||
|
||||
@@ -2612,6 +2612,12 @@ export const CheckoutCommitsListRequestSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const CheckoutWorktreesListRequestSchema = z.object({
|
||||
type: z.literal("checkout.worktrees.list.request"),
|
||||
cwd: z.string(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const CheckoutCommitFileDiffRequestSchema = z.object({
|
||||
type: z.literal("checkout.commits.file_diff.request"),
|
||||
cwd: z.string(),
|
||||
@@ -3654,6 +3660,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
CheckoutForgeSetAutoMergeRequestSchema,
|
||||
CheckoutGithubSetAutoMergeRequestSchema,
|
||||
CheckoutCommitsListRequestSchema,
|
||||
CheckoutWorktreesListRequestSchema,
|
||||
CheckoutCommitFileDiffRequestSchema,
|
||||
CheckoutForgeGetCheckDetailsRequestSchema,
|
||||
CheckoutGithubGetCheckDetailsRequestSchema,
|
||||
@@ -3945,6 +3952,11 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
terminalCollection: z.boolean().optional(),
|
||||
// COMPAT(workspaceBaseBranch): added after v0.11.2, remove gate after 2027-10-14.
|
||||
workspaceBaseBranch: z.boolean().optional(),
|
||||
// COMPAT(checkoutWorktreeList): added after v0.16.2, remove gate after 2027-11-19.
|
||||
checkoutWorktreeList: z.boolean().optional(),
|
||||
// COMPAT(worktreeRefActions): added after v0.16.2, remove gate after 2027-11-19.
|
||||
// Hosts without it check out a change request even when asked to branch off it.
|
||||
worktreeRefActions: z.boolean().optional(),
|
||||
// COMPAT(workspaceSetupRun): added in v0.8.0, remove gate after 2027-09-02.
|
||||
workspaceSetupRun: z.boolean().optional(),
|
||||
// COMPAT(workspaceTerminals): added in v0.8.0, remove gate after 2027-09-05.
|
||||
@@ -6088,6 +6100,26 @@ export const CheckoutCommitsListResponseSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const CheckoutWorktreeSchema = z.object({
|
||||
path: z.string(),
|
||||
// null when HEAD is detached
|
||||
branchName: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
createdAt: z.string(), // ISO 8601
|
||||
// true for the worktree the request's cwd is in
|
||||
containsCwd: z.boolean(),
|
||||
});
|
||||
|
||||
export const CheckoutWorktreesListResponseSchema = z.object({
|
||||
type: z.literal("checkout.worktrees.list.response"),
|
||||
payload: z.object({
|
||||
cwd: z.string(),
|
||||
worktrees: z.array(CheckoutWorktreeSchema),
|
||||
error: CheckoutErrorSchema.nullable(),
|
||||
requestId: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const CheckoutCommitFileDiffResponseSchema = z.object({
|
||||
type: z.literal("checkout.commits.file_diff.response"),
|
||||
payload: z.object({
|
||||
@@ -7588,6 +7620,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
CheckoutForgeSetAutoMergeResponseSchema,
|
||||
CheckoutGithubSetAutoMergeResponseSchema,
|
||||
CheckoutCommitsListResponseSchema,
|
||||
CheckoutWorktreesListResponseSchema,
|
||||
CheckoutCommitFileDiffResponseSchema,
|
||||
CheckoutForgeGetCheckDetailsResponseSchema,
|
||||
CheckoutGithubGetCheckDetailsResponseSchema,
|
||||
@@ -7972,6 +8005,9 @@ export type CheckoutCommitFile = z.infer<typeof CheckoutCommitFileSchema>;
|
||||
export type CheckoutCommit = z.infer<typeof CheckoutCommitSchema>;
|
||||
export type CheckoutCommitsListRequest = z.infer<typeof CheckoutCommitsListRequestSchema>;
|
||||
export type CheckoutCommitsListResponse = z.infer<typeof CheckoutCommitsListResponseSchema>;
|
||||
export type CheckoutWorktree = z.infer<typeof CheckoutWorktreeSchema>;
|
||||
export type CheckoutWorktreesListRequest = z.infer<typeof CheckoutWorktreesListRequestSchema>;
|
||||
export type CheckoutWorktreesListResponse = z.infer<typeof CheckoutWorktreesListResponseSchema>;
|
||||
export type CheckoutCommitFileDiffRequest = z.infer<typeof CheckoutCommitFileDiffRequestSchema>;
|
||||
export type CheckoutCommitFileDiffResponse = z.infer<typeof CheckoutCommitFileDiffResponseSchema>;
|
||||
export type ParsedDiffFile = z.infer<typeof ParsedDiffFileSchema>;
|
||||
|
||||
@@ -53,6 +53,7 @@ const INBOUND_PERMISSION = {
|
||||
"chat/wait": "workspace.read",
|
||||
"checkout.commits.file_diff.request": "workspace.read",
|
||||
"checkout.commits.list.request": "workspace.read",
|
||||
"checkout.worktrees.list.request": "workspace.read",
|
||||
"checkout.discard_changes.request": "workspace.write",
|
||||
"checkout.forge.get_check_details.request": "workspace.read",
|
||||
"checkout.forge.set_auto_merge.request": "workspace.write",
|
||||
@@ -303,6 +304,7 @@ const OUTBOUND_PERMISSION = {
|
||||
"chat/wait/response": "workspace.read",
|
||||
"checkout.commits.file_diff.response": "workspace.read",
|
||||
"checkout.commits.list.response": "workspace.read",
|
||||
"checkout.worktrees.list.response": "workspace.read",
|
||||
"checkout.discard_changes.response": "workspace.write",
|
||||
"checkout.forge.get_check_details.response": "workspace.read",
|
||||
"checkout.forge.set_auto_merge.response": "workspace.write",
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CheckoutSourceForgeMismatchError,
|
||||
MissingCheckoutTargetError,
|
||||
resolveWorktreeCreationIntent,
|
||||
type ResolveWorktreeCreationIntentDeps,
|
||||
UnsupportedForgeCheckoutTargetError,
|
||||
} from "./resolve-worktree-creation-intent.js";
|
||||
|
||||
@@ -19,6 +20,7 @@ interface ResolverHarness {
|
||||
forgeService: ForgeService;
|
||||
headRefLookups: GitHubHeadRefLookup[];
|
||||
resolveDefaultBranch: (repoRoot: string) => Promise<string>;
|
||||
fetchRef: ResolveWorktreeCreationIntentDeps["fetchRef"];
|
||||
}
|
||||
|
||||
function createResolverHarness(overrides?: {
|
||||
@@ -86,6 +88,7 @@ function createResolverHarness(overrides?: {
|
||||
forgeService,
|
||||
headRefLookups,
|
||||
resolveDefaultBranch: async () => "main",
|
||||
fetchRef: async () => {},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ForgeService, PullRequestCheckoutTarget } from "../services/forge-service.js";
|
||||
import type { WorktreeSource } from "../utils/worktree.js";
|
||||
import type { WorktreeCheckoutRef, WorktreeSource } from "../utils/worktree.js";
|
||||
|
||||
export type WorktreeCreationIntent = Exclude<
|
||||
WorktreeSource,
|
||||
@@ -29,6 +29,14 @@ export interface ResolveWorktreeCreationIntentDeps {
|
||||
forge: string;
|
||||
forgeService: ForgeService;
|
||||
resolveDefaultBranch: (repoRoot: string) => Promise<string>;
|
||||
/** Fetches the first ref a remote serves into a local ref. */
|
||||
fetchRef: (input: FetchRefInput) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface FetchRefInput {
|
||||
repoRoot: string;
|
||||
sources: WorktreeCheckoutRef[];
|
||||
destination: string;
|
||||
}
|
||||
|
||||
export class MissingCheckoutTargetError extends Error {
|
||||
@@ -70,9 +78,13 @@ export async function resolveWorktreeCreationIntent(
|
||||
deps: ResolveWorktreeCreationIntentDeps,
|
||||
): Promise<WorktreeCreationIntent> {
|
||||
if (input.action === "branch-off") {
|
||||
const changeRequest = resolveInputChangeRequest(input);
|
||||
const baseBranch = changeRequest
|
||||
? await fetchChangeRequestHead({ input, changeRequest, repoRoot, deps })
|
||||
: input.refName?.trim() || (await resolveDefaultBranch(repoRoot, deps));
|
||||
return {
|
||||
kind: "branch-off",
|
||||
baseBranch: input.refName?.trim() || (await resolveDefaultBranch(repoRoot, deps)),
|
||||
baseBranch,
|
||||
branchName: input.branchName ?? input.worktreeSlug ?? "worktree",
|
||||
};
|
||||
}
|
||||
@@ -126,6 +138,34 @@ export async function resolveWorktreeCreationIntent(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a change request's head into a remote-tracking ref, so a new branch can start from it
|
||||
* without checking the change request out. A same-repository head lands where `git fetch` puts
|
||||
* the branch; any other head lands under `paseo-pr-<number>`, the remote a checkout of the same
|
||||
* change request pushes to.
|
||||
*/
|
||||
async function fetchChangeRequestHead(params: {
|
||||
input: ResolveWorktreeCreationIntentInput;
|
||||
changeRequest: { number: number; forge?: string };
|
||||
repoRoot: string;
|
||||
deps: ResolveWorktreeCreationIntentDeps;
|
||||
}): Promise<string> {
|
||||
const { input, changeRequest, repoRoot, deps } = params;
|
||||
assertCheckoutSourceMatchesResolvedForge(changeRequest, deps);
|
||||
const checkout = await resolvePrCheckoutIntent({
|
||||
refName: input.refName,
|
||||
changeRequestNumber: changeRequest.number,
|
||||
repoRoot,
|
||||
deps,
|
||||
});
|
||||
const headBranch = checkout.headRef.startsWith("refs/") ? "head" : checkout.headRef;
|
||||
const destination = checkout.trackOriginHead
|
||||
? `refs/remotes/origin/${headBranch}`
|
||||
: `refs/remotes/paseo-pr-${changeRequest.number}/${headBranch}`;
|
||||
await deps.fetchRef({ repoRoot, sources: checkout.checkoutRefs, destination });
|
||||
return destination;
|
||||
}
|
||||
|
||||
interface PrCheckoutIntentParams {
|
||||
refName?: string;
|
||||
changeRequestNumber: number;
|
||||
@@ -163,9 +203,11 @@ function assertCheckoutSourceMatchesResolvedForge(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolvePrCheckoutIntent(
|
||||
params: PrCheckoutIntentParams,
|
||||
): Promise<Extract<WorktreeCreationIntent, { kind: "checkout-change-request" }>> {
|
||||
async function resolvePrCheckoutIntent(params: PrCheckoutIntentParams): Promise<
|
||||
Extract<WorktreeCreationIntent, { kind: "checkout-change-request" }> & {
|
||||
checkoutRefs: WorktreeCheckoutRef[];
|
||||
}
|
||||
> {
|
||||
const { deps } = params;
|
||||
const service = deps.forgeService;
|
||||
const checkoutTarget = await resolvePrCheckoutTarget(params);
|
||||
|
||||
@@ -3322,6 +3322,8 @@ export class Session {
|
||||
return this.checkoutSession.handleStatusRequest(msg);
|
||||
case "checkout.commits.list.request":
|
||||
return this.checkoutSession.handleCommitsListRequest(msg);
|
||||
case "checkout.worktrees.list.request":
|
||||
return this.checkoutSession.handleWorktreesListRequest(msg);
|
||||
case "checkout.commits.file_diff.request":
|
||||
return this.checkoutSession.handleCommitFileDiffRequest(msg, this.delivery.requestSignal);
|
||||
case "validate_branch_request":
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
CheckoutRefreshRequest,
|
||||
CheckoutRenameBranchRequest,
|
||||
CheckoutStatusRequest,
|
||||
CheckoutWorktreesListRequest,
|
||||
SessionInboundMessage,
|
||||
SessionOutboundMessage,
|
||||
SubscribeCheckoutDiffRequest,
|
||||
@@ -54,6 +55,7 @@ import {
|
||||
} from "../../../utils/checkout-git.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
import { expandTilde } from "../../../utils/path.js";
|
||||
import { listGitWorktrees } from "../../../utils/worktree.js";
|
||||
import type { GitMetadataGenerator } from "./git-metadata-generator.js";
|
||||
|
||||
/**
|
||||
@@ -290,6 +292,23 @@ export class CheckoutSession {
|
||||
}
|
||||
}
|
||||
|
||||
async handleWorktreesListRequest(msg: CheckoutWorktreesListRequest): Promise<void> {
|
||||
const { cwd, requestId } = msg;
|
||||
|
||||
try {
|
||||
const worktrees = await listGitWorktrees({ cwd: expandTilde(cwd) });
|
||||
this.host.emit({
|
||||
type: "checkout.worktrees.list.response",
|
||||
payload: { cwd, worktrees, error: null, requestId },
|
||||
});
|
||||
} catch (error) {
|
||||
this.host.emit({
|
||||
type: "checkout.worktrees.list.response",
|
||||
payload: { cwd, worktrees: [], error: toCheckoutError(error), requestId },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleCommitFileDiffRequest(
|
||||
msg: CheckoutCommitFileDiffRequest,
|
||||
signal: AbortSignal,
|
||||
|
||||
@@ -2057,6 +2057,10 @@ export class VoiceAssistantWebSocketServer {
|
||||
// COMPAT(backgroundAgents): added in v0.15.0; remove gate after 2027-05-03.
|
||||
backgroundAgents: true,
|
||||
workspaceBaseBranch: true,
|
||||
// COMPAT(checkoutWorktreeList): added after v0.16.2, remove gate after 2027-11-19.
|
||||
checkoutWorktreeList: true,
|
||||
// COMPAT(worktreeRefActions): added after v0.16.2, remove gate after 2027-11-19.
|
||||
worktreeRefActions: true,
|
||||
// COMPAT(directorySync): added in v0.3.x, remove gate after 2027-02-12.
|
||||
directorySync: true,
|
||||
// COMPAT(workspaceLabels): added in v0.5.0, remove after 2027-08-14.
|
||||
|
||||
@@ -73,6 +73,43 @@ test("workspace.create worktree source forwards action=checkout + refName into t
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test("checkout.worktrees.list returns git worktrees Paseo did not create", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
const manualPath = path.join(tempRoot, "manual");
|
||||
execFileSync("git", ["worktree", "add", "-b", "feature/manual", manualPath], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.1.82",
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, action: "branch-off", branchName: "feature/paseo" },
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
|
||||
const worktrees = await client.listCheckoutWorktrees(repoDir);
|
||||
|
||||
expect(worktrees.map(({ branchName, containsCwd }) => ({ branchName, containsCwd }))).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ branchName: "main", containsCwd: true },
|
||||
{ branchName: "feature/manual", containsCwd: false },
|
||||
{ branchName: "feature/paseo", containsCwd: false },
|
||||
]),
|
||||
);
|
||||
expect(worktrees).toHaveLength(3);
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test.each([false, true])(
|
||||
"workspace.create opens worktree.terminals (setup service: %s)",
|
||||
async (withSetupService) => {
|
||||
|
||||
@@ -379,6 +379,10 @@ function getBranchUpstream(cwd: string): string | null {
|
||||
return result.status === 0 ? result.stdout.trim() : null;
|
||||
}
|
||||
|
||||
function git(cwd: string, ...args: string[]): string {
|
||||
return execFileSync("git", args, { cwd, stdio: "pipe" }).toString().trim();
|
||||
}
|
||||
|
||||
function getGitConfigValue(cwd: string, key: string): string | null {
|
||||
const result = spawnSync("git", ["config", "--get", key], {
|
||||
cwd,
|
||||
@@ -1450,6 +1454,99 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
).rejects.toBeInstanceOf(UnknownBranchError);
|
||||
});
|
||||
|
||||
test("branches off a same-repo pull request's head without checking it out", async () => {
|
||||
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
// The head branch has never been fetched, so creation has to fetch it.
|
||||
execFileSync("git", ["update-ref", "-d", "refs/remotes/origin/daemon-shutdown-diagnostics"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const github = {
|
||||
...createGitHubServiceStub(),
|
||||
getPullRequestCheckoutTarget: async () => ({
|
||||
number: 1790,
|
||||
baseRefName: "main",
|
||||
headRefName: "daemon-shutdown-diagnostics",
|
||||
headOwnerLogin: "getpaseo",
|
||||
headRepositorySshUrl: remoteDir,
|
||||
headRepositoryUrl: remoteDir,
|
||||
isCrossRepository: false,
|
||||
}),
|
||||
};
|
||||
|
||||
const result = await createCoreWorktree(
|
||||
{
|
||||
cwd: repoDir,
|
||||
action: "branch-off",
|
||||
checkoutSource: { kind: "change_request", forge: "github", number: 1790 },
|
||||
branchName: "follow-up",
|
||||
paseoHome,
|
||||
},
|
||||
createCoreDeps({ github }),
|
||||
);
|
||||
|
||||
const prHead = execFileSync("git", [
|
||||
`--git-dir=${remoteDir}`,
|
||||
"rev-parse",
|
||||
"refs/pull/1790/head",
|
||||
])
|
||||
.toString()
|
||||
.trim();
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "refs/remotes/origin/daemon-shutdown-diagnostics",
|
||||
branchName: "follow-up",
|
||||
});
|
||||
expect(result.worktree.branchName).toBe("follow-up");
|
||||
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(prHead);
|
||||
expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull();
|
||||
expect(result.worktree.comparisonBaseRef).toBe(
|
||||
"refs/remotes/origin/daemon-shutdown-diagnostics",
|
||||
);
|
||||
expect(git(repoDir, "branch", "--list", "daemon-shutdown-diagnostics")).toBe("");
|
||||
});
|
||||
|
||||
test("branches off a fork pull request's head without checking it out", async () => {
|
||||
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
const github = {
|
||||
...createGitHubServiceStub(),
|
||||
getPullRequestCheckoutTarget: async () => ({
|
||||
number: 526,
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
headOwnerLogin: "therainisme",
|
||||
headRepositorySshUrl: headRemoteDir,
|
||||
headRepositoryUrl: headRemoteDir,
|
||||
isCrossRepository: true,
|
||||
}),
|
||||
};
|
||||
|
||||
const result = await createCoreWorktree(
|
||||
{
|
||||
cwd: repoDir,
|
||||
action: "branch-off",
|
||||
checkoutSource: { kind: "change_request", forge: "github", number: 526 },
|
||||
branchName: "follow-up",
|
||||
paseoHome,
|
||||
},
|
||||
createCoreDeps({ github }),
|
||||
);
|
||||
|
||||
const readme = readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8");
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "refs/remotes/paseo-pr-526/main",
|
||||
branchName: "follow-up",
|
||||
});
|
||||
expect(result.worktree.branchName).toBe("follow-up");
|
||||
expect(readme.replace(/\r\n/g, "\n")).toBe("fork pr main branch\n");
|
||||
expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull();
|
||||
expect(git(repoDir, "branch", "--list", "therainisme/main")).toBe("");
|
||||
expect(getGitConfigValue(repoDir, "remote.paseo-pr-526.url")).toBeNull();
|
||||
});
|
||||
|
||||
test("creates the agent-create worktree input shape", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createNameId } from "mnemonic-id";
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import {
|
||||
createWorktree,
|
||||
fetchFirstAvailableRef,
|
||||
resolveDefaultWorktreePath,
|
||||
slugify,
|
||||
validateBranchSlug,
|
||||
@@ -76,7 +77,11 @@ async function createWorktreeCoreWithPriority(
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
} else if (input.checkoutSource !== undefined || input.githubPrNumber !== undefined) {
|
||||
} else if (
|
||||
input.action !== "branch-off" &&
|
||||
(input.checkoutSource !== undefined || input.githubPrNumber !== undefined)
|
||||
) {
|
||||
// A change request with no action is checked out, as clients did before `action` existed.
|
||||
intentInput = {
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
@@ -88,6 +93,8 @@ async function createWorktreeCoreWithPriority(
|
||||
intentInput = {
|
||||
action: "branch-off",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
branchName: requestedBranchName,
|
||||
worktreeSlug,
|
||||
};
|
||||
@@ -98,6 +105,8 @@ async function createWorktreeCoreWithPriority(
|
||||
forge: forge.forge,
|
||||
forgeService: forge.service,
|
||||
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps),
|
||||
fetchRef: ({ repoRoot: cwd, sources, destination }) =>
|
||||
fetchFirstAvailableRef({ cwd, sources, destination }),
|
||||
});
|
||||
let normalizedSlug: string;
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
getWorktreeTeardownCommands,
|
||||
isServiceScript,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
listGitWorktrees,
|
||||
listPaseoWorktrees,
|
||||
readPaseoConfig,
|
||||
resolveWorktreeRuntimeEnv,
|
||||
@@ -1695,6 +1696,45 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
expect(remaining.map((worktree) => worktree.path)).toEqual([second.worktreePath]);
|
||||
});
|
||||
|
||||
it("lists every git worktree of the repository, not only Paseo's", async () => {
|
||||
const paseoWorktree = await createLegacyWorktreeForTest({
|
||||
branchName: "feature/paseo",
|
||||
cwd: repoDir,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "alpha",
|
||||
paseoHome,
|
||||
});
|
||||
const manualPath = join(tempDir, "manual");
|
||||
execFileSync("git", ["worktree", "add", "-b", "feature/manual", manualPath], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
const detachedPath = join(tempDir, "detached");
|
||||
execFileSync("git", ["worktree", "add", "--detach", detachedPath], { cwd: repoDir });
|
||||
const removedPath = join(tempDir, "removed");
|
||||
execFileSync("git", ["worktree", "add", "-b", "feature/removed", removedPath], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
rmSync(removedPath, { recursive: true, force: true });
|
||||
|
||||
const fromProject = await listGitWorktrees({ cwd: repoDir });
|
||||
const fromPaseoWorktree = await listGitWorktrees({ cwd: paseoWorktree.worktreePath });
|
||||
|
||||
const [mainWorktree, ...linkedWorktrees] = fromProject.map(
|
||||
({ path, branchName, containsCwd }) => ({ path, branchName, containsCwd }),
|
||||
);
|
||||
expect(mainWorktree).toEqual({ path: repoDir, branchName: "main", containsCwd: true });
|
||||
expect(linkedWorktrees.sort((a, b) => a.path.localeCompare(b.path))).toEqual(
|
||||
[
|
||||
{ path: paseoWorktree.worktreePath, branchName: "feature/paseo", containsCwd: false },
|
||||
{ path: manualPath, branchName: "feature/manual", containsCwd: false },
|
||||
{ path: detachedPath, branchName: null, containsCwd: false },
|
||||
].sort((a, b) => a.path.localeCompare(b.path)),
|
||||
);
|
||||
expect(
|
||||
fromPaseoWorktree.filter((worktree) => worktree.containsCwd).map(({ path }) => path),
|
||||
).toEqual([paseoWorktree.worktreePath]);
|
||||
});
|
||||
|
||||
it("deletes a paseo worktree even when given a subdirectory path", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "main",
|
||||
|
||||
@@ -1071,9 +1071,18 @@ async function resolveMetadataOwnedWorktree(
|
||||
|
||||
type ParsedPaseoWorktreeInfo = Omit<PaseoWorktreeInfo, "createdAt">;
|
||||
|
||||
interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo {
|
||||
/** A bare repository or a worktree whose directory is gone; nothing can work there. */
|
||||
unusable?: true;
|
||||
}
|
||||
|
||||
function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] {
|
||||
const entries: ParsedPaseoWorktreeInfo[] = [];
|
||||
let current: ParsedPaseoWorktreeInfo | null = null;
|
||||
return parseWorktreeEntries(output).map(({ unusable: _unusable, ...entry }) => entry);
|
||||
}
|
||||
|
||||
function parseWorktreeEntries(output: string): ParsedWorktreeEntry[] {
|
||||
const entries: ParsedWorktreeEntry[] = [];
|
||||
let current: ParsedWorktreeEntry | null = null;
|
||||
|
||||
for (const line of output.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
@@ -1093,6 +1102,8 @@ function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] {
|
||||
current.branchName = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
|
||||
} else if (line.startsWith("HEAD ")) {
|
||||
current.head = line.slice("HEAD ".length).trim();
|
||||
} else if (line === "bare" || line.startsWith("prunable")) {
|
||||
current.unusable = true;
|
||||
} else if (line.trim().length === 0) {
|
||||
if (current.path) {
|
||||
entries.push(current);
|
||||
@@ -1120,6 +1131,47 @@ async function resolveWorktreeCreatedAtIso(worktreePath: string): Promise<string
|
||||
}
|
||||
}
|
||||
|
||||
/** One git worktree of a repository, whoever created it. */
|
||||
export interface GitWorktree {
|
||||
path: string;
|
||||
/** Null when HEAD is detached. */
|
||||
branchName: string | null;
|
||||
head: string | null;
|
||||
createdAt: string;
|
||||
/** Whether the `cwd` the list was asked for is inside this worktree. */
|
||||
containsCwd: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every usable worktree of the repository `cwd` is in. The main worktree comes first; the rest
|
||||
* follow in no meaningful order.
|
||||
* Unlike `listPaseoWorktrees`, ownership plays no part.
|
||||
*/
|
||||
export async function listGitWorktrees({ cwd }: { cwd: string }): Promise<GitWorktree[]> {
|
||||
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], {
|
||||
cwd,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
const { stdout: toplevel } = await runGitCommand(["rev-parse", "--show-toplevel"], {
|
||||
cwd,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
const cwdWorktree = await normalizePathForOwnership(toplevel.trim());
|
||||
const worktrees: GitWorktree[] = [];
|
||||
for (const entry of parseWorktreeEntries(stdout)) {
|
||||
if (entry.unusable) continue;
|
||||
const path = await normalizePathForOwnership(entry.path);
|
||||
worktrees.push({
|
||||
path,
|
||||
branchName: entry.branchName ?? null,
|
||||
head: entry.head ?? null,
|
||||
createdAt: await resolveWorktreeCreatedAtIso(path),
|
||||
containsCwd: path === cwdWorktree,
|
||||
});
|
||||
}
|
||||
return worktrees;
|
||||
}
|
||||
|
||||
export async function listPaseoWorktrees({
|
||||
cwd,
|
||||
paseoHome,
|
||||
@@ -1675,10 +1727,10 @@ async function resolveWorktreeSourcePlan({
|
||||
const normalizedBaseRefName = normalizeRequiredBaseBranch(source.baseRefName);
|
||||
const changeRequestNumber =
|
||||
source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber;
|
||||
await fetchWorktreeCheckoutRefs({
|
||||
await fetchFirstAvailableRef({
|
||||
cwd,
|
||||
localBranchName,
|
||||
checkoutRefs: source.checkoutRefs ?? [
|
||||
destination: `refs/heads/${localBranchName}`,
|
||||
sources: source.checkoutRefs ?? [
|
||||
{ remoteName: "origin", remoteRef: `refs/pull/${changeRequestNumber}/head` },
|
||||
],
|
||||
});
|
||||
@@ -1777,21 +1829,22 @@ async function configureWorktreePushRemote(options: {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWorktreeCheckoutRefs(options: {
|
||||
/** Fetches the first of `sources` a remote serves into the local ref `destination`. */
|
||||
export async function fetchFirstAvailableRef(options: {
|
||||
cwd: string;
|
||||
localBranchName: string;
|
||||
checkoutRefs: WorktreeCheckoutRef[];
|
||||
sources: WorktreeCheckoutRef[];
|
||||
destination: string;
|
||||
}): Promise<void> {
|
||||
let lastResult:
|
||||
| Awaited<ReturnType<typeof runGitCommand>>
|
||||
| { stderr: string; stdout: string; exitCode: number | null }
|
||||
| null = null;
|
||||
for (const checkoutRef of options.checkoutRefs) {
|
||||
for (const checkoutRef of options.sources) {
|
||||
lastResult = await runGitCommand(
|
||||
[
|
||||
"fetch",
|
||||
checkoutRef.remoteName ?? "origin",
|
||||
`+${checkoutRef.remoteRef}:refs/heads/${options.localBranchName}`,
|
||||
`+${checkoutRef.remoteRef}:${options.destination}`,
|
||||
"--force",
|
||||
],
|
||||
{
|
||||
@@ -1804,11 +1857,11 @@ async function fetchWorktreeCheckoutRefs(options: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const attemptedRefs = options.checkoutRefs
|
||||
const attemptedRefs = options.sources
|
||||
.map((checkoutRef) => `${checkoutRef.remoteName ?? "origin"} ${checkoutRef.remoteRef}`)
|
||||
.join(", ");
|
||||
throw new Error(
|
||||
`Unable to fetch change request refs for worktree branch ${options.localBranchName}: ${attemptedRefs}${lastResult?.stderr ? `\n${lastResult.stderr}` : ""}`,
|
||||
`Unable to fetch change request refs into ${options.destination}: ${attemptedRefs}${lastResult?.stderr ? `\n${lastResult.stderr}` : ""}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user