vcs/jujutsu: Support colocated checkouts in the daemon
Use Git for checkout placement and forge integration, and route revision reads, diffs and mutations through Jujutsu. Compare at the fork point and attach the unintegrated operation to change rows. Create colocated workspaces from a selected checkout, preserve recovery snapshots, and remove owned checkouts at final archive. Use the source working-copy change when no default bookmark exists. Expose capabilities, change search and native actions to clients. Run the Jujutsu daemon cases in the integration job alongside the Jujutsu checkout and recovery unit coverage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
643ca85844
commit
2c927fe02d
35 files changed
+2966
-103
No files matched your search
@@ -241,6 +241,23 @@ jobs:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- &server_jj
|
||||
name: Install Jujutsu for checkout tests
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$RUNNER_OS" == Windows ]]; then
|
||||
asset=jj-v0.47.1-x86_64-pc-windows-msvc.zip
|
||||
checksum=72f9f80bc99d07a7f48d5f219cf5bab91f7e906e4b53f6c827948e646cd1152f
|
||||
else
|
||||
asset=jj-v0.47.1-x86_64-unknown-linux-musl.tar.gz
|
||||
checksum=d4b657f622ee50929c8916466dfa3d6a6c17a0a32b50e7b2c793707ec9ebcad7
|
||||
fi
|
||||
curl --fail --location --retry 3 "https://github.com/jj-vcs/jj/releases/download/v0.47.1/$asset" -o "$RUNNER_TEMP/$asset"
|
||||
echo "$checksum $RUNNER_TEMP/$asset" | sha256sum --check
|
||||
mkdir -p "$RUNNER_TEMP/jj"
|
||||
tar -xf "$RUNNER_TEMP/$asset" -C "$RUNNER_TEMP/jj"
|
||||
echo "$RUNNER_TEMP/jj" >> "$GITHUB_PATH"
|
||||
|
||||
- &server_fetch
|
||||
name: Fetch origin/main (worktree tests)
|
||||
if: ${{ needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false' }}
|
||||
@@ -286,6 +303,7 @@ jobs:
|
||||
- *server_capacity
|
||||
- *server_checkout
|
||||
- *server_node
|
||||
- *server_jj
|
||||
- *server_fetch
|
||||
- *server_install
|
||||
- *server_agent_clis
|
||||
@@ -309,6 +327,7 @@ jobs:
|
||||
- *server_capacity
|
||||
- *server_checkout
|
||||
- *server_node
|
||||
- *server_jj
|
||||
- *server_fetch
|
||||
- *server_install
|
||||
- *server_agent_clis
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
DiffStreamRouter,
|
||||
DiffSubscriptionError,
|
||||
@@ -5174,6 +5175,30 @@ export class DaemonClient {
|
||||
});
|
||||
}
|
||||
|
||||
async searchJujutsuChanges(cwd: string, query: string) {
|
||||
if (!this.getLastServerInfoMessage()?.features?.jujutsuCheckoutActions) {
|
||||
throw new Error("Update the host to use Jujutsu actions.");
|
||||
}
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"checkout.jujutsu.changes.response">({
|
||||
message: { type: "checkout.jujutsu.changes.request", cwd, query },
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async checkoutJujutsuAction(
|
||||
cwd: string,
|
||||
expectedChangeId: string,
|
||||
action: JujutsuCheckoutAction,
|
||||
) {
|
||||
if (!this.getLastServerInfoMessage()?.features?.jujutsuCheckoutActions) {
|
||||
throw new Error("Update the host to use Jujutsu actions.");
|
||||
}
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"checkout.jujutsu.action.response">({
|
||||
message: { type: "checkout.jujutsu.action.request", cwd, expectedChangeId, action },
|
||||
timeout: 180_000,
|
||||
});
|
||||
}
|
||||
|
||||
async checkoutRefresh(cwd: string, requestId?: string): Promise<CheckoutRefreshPayload> {
|
||||
return this.sendCorrelatedSessionRequest({
|
||||
requestId,
|
||||
@@ -5226,6 +5251,7 @@ export class DaemonClient {
|
||||
sha: string,
|
||||
path: string,
|
||||
requestId?: string,
|
||||
jujutsuOperationId?: string,
|
||||
): Promise<{ file: ParsedDiffFile | null }> {
|
||||
const payload =
|
||||
await this.sendNamespacedCorrelatedSessionRequest<"checkout.commits.file_diff.response">({
|
||||
@@ -5235,6 +5261,7 @@ export class DaemonClient {
|
||||
cwd,
|
||||
sha,
|
||||
path,
|
||||
...(jujutsuOperationId ? { jujutsuOperationId } : {}),
|
||||
},
|
||||
timeout: 60000,
|
||||
});
|
||||
|
||||
@@ -2598,6 +2598,47 @@ export const CheckoutPushRequestSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
const JujutsuBookmarkNameSchema = z.string().trim().min(1).max(255);
|
||||
export const JujutsuCheckoutActionSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("describe"), description: z.string().trim().min(1).max(65536) }),
|
||||
z.object({
|
||||
kind: z.literal("new"),
|
||||
description: z.string().trim().min(1).max(65536).optional(),
|
||||
// Start the new change on this bookmark instead of on the current change.
|
||||
parent: JujutsuBookmarkNameSchema.optional(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("publish"),
|
||||
bookmark: JujutsuBookmarkNameSchema,
|
||||
remote: z.string().trim().min(1).max(255).optional(),
|
||||
create: z.boolean().optional(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("create_pull_request"),
|
||||
bookmark: JujutsuBookmarkNameSchema,
|
||||
base: JujutsuBookmarkNameSchema,
|
||||
title: z.string().trim().min(1).max(512),
|
||||
body: z.string().max(65536).optional(),
|
||||
}),
|
||||
z.object({ kind: z.literal("fetch"), remote: z.string().min(1).optional() }),
|
||||
]);
|
||||
export type JujutsuCheckoutAction = z.infer<typeof JujutsuCheckoutActionSchema>;
|
||||
|
||||
export const JujutsuChangeSearchRequestSchema = z.object({
|
||||
type: z.literal("checkout.jujutsu.changes.request"),
|
||||
cwd: z.string(),
|
||||
query: z.string().max(200),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const JujutsuCheckoutActionRequestSchema = z.object({
|
||||
type: z.literal("checkout.jujutsu.action.request"),
|
||||
cwd: z.string(),
|
||||
expectedChangeId: z.string().min(1),
|
||||
action: JujutsuCheckoutActionSchema,
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const CheckoutRefreshRequestSchema = z.object({
|
||||
type: z.literal("checkout.refresh.request"),
|
||||
cwd: z.string(),
|
||||
@@ -2663,6 +2704,20 @@ const CheckoutCommitSchema = z.object({
|
||||
// COMPAT(commitBaseClassification): added in v0.2.0, remove optional after 2027-01-23.
|
||||
isOnBase: z.boolean().optional(),
|
||||
files: z.array(CheckoutCommitFileSchema),
|
||||
// Jujutsu checkouts list changes; shortSha then holds the short change ID.
|
||||
jujutsu: z
|
||||
.object({
|
||||
changeId: z.string(),
|
||||
bookmarks: z.array(z.string()),
|
||||
isWorkingCopy: z.boolean(),
|
||||
isEmpty: z.boolean(),
|
||||
hasConflicts: z.boolean(),
|
||||
operationId: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{12,128}$/)
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const CheckoutCommitsListRequestSchema = z.object({
|
||||
@@ -2682,6 +2737,10 @@ export const CheckoutCommitFileDiffRequestSchema = z.object({
|
||||
cwd: z.string(),
|
||||
sha: z.string(),
|
||||
path: z.string(),
|
||||
jujutsuOperationId: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{12,128}$/)
|
||||
.optional(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
@@ -3721,6 +3780,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
CheckoutPullRequestSchema,
|
||||
CheckoutPushRequestSchema,
|
||||
CheckoutRefreshRequestSchema,
|
||||
JujutsuCheckoutActionRequestSchema,
|
||||
JujutsuChangeSearchRequestSchema,
|
||||
CheckoutDiscardChangesRequestSchema,
|
||||
CheckoutPrCreateRequestSchema,
|
||||
CheckoutPrMergeRequestSchema,
|
||||
@@ -4226,6 +4287,7 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
// COMPAT(checkoutDiscardChanges): added in v0.3.0, remove gate after 2027-02-08.
|
||||
checkoutDiscardChanges: z.boolean().optional(),
|
||||
checkoutDiffAll: z.boolean().optional(),
|
||||
jujutsuCheckoutActions: z.boolean().optional(),
|
||||
// COMPAT(agentProfiles): added in v0.3.2, remove gate after 2027-02-11.
|
||||
// An older daemon parses its persisted config strictly, so writing
|
||||
// agentProfiles to one is silently dropped. The client hides the feature
|
||||
@@ -4470,6 +4532,13 @@ const WorkspaceGitRuntimePayloadSchema = z
|
||||
.optional(),
|
||||
aheadOfOrigin: z.number().nullable().optional(),
|
||||
behindOfOrigin: z.number().nullable().optional(),
|
||||
// Jujutsu checkouts have no current branch; clients label them by bookmark or change.
|
||||
jujutsu: z
|
||||
.object({
|
||||
changeId: z.string(),
|
||||
bookmarks: z.array(z.string()),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.optional()
|
||||
.nullable();
|
||||
@@ -5847,7 +5916,34 @@ const AheadBehindSchema = z.object({
|
||||
behind: z.number(),
|
||||
});
|
||||
|
||||
export const JujutsuStateSchema = z.object({
|
||||
changeId: z.string(),
|
||||
commitId: z.string(),
|
||||
description: z.string(),
|
||||
bookmarks: z.array(z.string()),
|
||||
hasConflicts: z.boolean(),
|
||||
// The closest local bookmark on @'s ancestry; the default base for a new workspace.
|
||||
nearestBookmark: z.string().nullable().optional(),
|
||||
baseBookmarkMissing: z.boolean().optional(),
|
||||
hasRemotes: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const CheckoutStatusCommonSchema = z.object({
|
||||
vcs: z
|
||||
.object({
|
||||
kind: z.enum(["git", "jujutsu", "none"]),
|
||||
capabilities: z.object({
|
||||
isolatedWorkspace: z.boolean(),
|
||||
gitMutations: z.boolean(),
|
||||
describe: z.boolean().optional(),
|
||||
newChange: z.boolean().optional(),
|
||||
publishBookmark: z.boolean().optional(),
|
||||
createPullRequest: z.boolean().optional(),
|
||||
fetch: z.boolean().optional(),
|
||||
}),
|
||||
})
|
||||
.optional(),
|
||||
jujutsu: JujutsuStateSchema.optional(),
|
||||
cwd: z.string(),
|
||||
error: CheckoutErrorSchema.nullable(),
|
||||
requestId: z.string(),
|
||||
@@ -6157,6 +6253,36 @@ export const CheckoutPushResponseSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const JujutsuChangeSummarySchema = z.object({
|
||||
changeId: z.string(),
|
||||
commitId: z.string(),
|
||||
description: z.string(),
|
||||
bookmarks: z.array(z.string()),
|
||||
workingCopies: z.array(z.string()),
|
||||
isEmpty: z.boolean(),
|
||||
authorDate: z.string(),
|
||||
});
|
||||
|
||||
export const JujutsuChangeSearchResponseSchema = z.object({
|
||||
type: z.literal("checkout.jujutsu.changes.response"),
|
||||
payload: z.object({
|
||||
cwd: z.string(),
|
||||
changes: z.array(JujutsuChangeSummarySchema),
|
||||
error: CheckoutErrorSchema.nullable(),
|
||||
requestId: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const JujutsuCheckoutActionResponseSchema = z.object({
|
||||
type: z.literal("checkout.jujutsu.action.response"),
|
||||
payload: z.object({
|
||||
cwd: z.string(),
|
||||
url: z.string().nullable(),
|
||||
error: CheckoutErrorSchema.nullable(),
|
||||
requestId: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const CheckoutRefreshResponseSchema = z.object({
|
||||
type: z.literal("checkout.refresh.response"),
|
||||
payload: z.object({
|
||||
@@ -7889,6 +8015,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
CheckoutPullResponseSchema,
|
||||
CheckoutPushResponseSchema,
|
||||
CheckoutRefreshResponseSchema,
|
||||
JujutsuCheckoutActionResponseSchema,
|
||||
JujutsuChangeSearchResponseSchema,
|
||||
CheckoutDiscardChangesResponseSchema,
|
||||
CheckoutPrCreateResponseSchema,
|
||||
CheckoutPrMergeResponseSchema,
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|Jujutsu|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -59,6 +59,8 @@ const INBOUND_PERMISSION = {
|
||||
"checkout.forge.set_auto_merge.request": "workspace.write",
|
||||
"checkout.github.get_check_details.request": "workspace.read",
|
||||
"checkout.github.set_auto_merge.request": "workspace.write",
|
||||
"checkout.jujutsu.action.request": "workspace.write",
|
||||
"checkout.jujutsu.changes.request": "workspace.read",
|
||||
"checkout.refresh.request": "workspace.read",
|
||||
"checkout.rename_branch.request": "workspace.write",
|
||||
checkout_commit_request: "workspace.write",
|
||||
@@ -316,6 +318,8 @@ const OUTBOUND_PERMISSION = {
|
||||
"checkout.forge.set_auto_merge.response": "workspace.write",
|
||||
"checkout.github.get_check_details.response": "workspace.read",
|
||||
"checkout.github.set_auto_merge.response": "workspace.write",
|
||||
"checkout.jujutsu.action.response": "workspace.write",
|
||||
"checkout.jujutsu.changes.response": "workspace.read",
|
||||
"checkout.refresh.response": "workspace.read",
|
||||
"checkout.rename_branch.response": "workspace.write",
|
||||
checkout_commit_response: "workspace.write",
|
||||
|
||||
@@ -13,6 +13,13 @@ describe("checkout status projection", () => {
|
||||
const snapshot: WorkspaceGitRuntimeSnapshot = {
|
||||
cwd: "/repo",
|
||||
git: {
|
||||
jujutsu: {
|
||||
changeId: "abcdefghijkl",
|
||||
commitId: "a".repeat(40),
|
||||
description: "Task\n",
|
||||
bookmarks: [],
|
||||
hasConflicts: true,
|
||||
},
|
||||
isGit: true,
|
||||
repoRoot: "/repo",
|
||||
mainRepoRoot: null,
|
||||
@@ -38,6 +45,23 @@ describe("checkout status projection", () => {
|
||||
snapshot,
|
||||
});
|
||||
|
||||
expect(payload.jujutsu).toEqual(snapshot.git.jujutsu);
|
||||
expect(payload.vcs).toEqual({
|
||||
kind: "jujutsu",
|
||||
capabilities: {
|
||||
isolatedWorkspace: true,
|
||||
gitMutations: false,
|
||||
describe: true,
|
||||
newChange: true,
|
||||
publishBookmark: true,
|
||||
createPullRequest: true,
|
||||
fetch: true,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload
|
||||
.jujutsu,
|
||||
).toEqual(snapshot.git.jujutsu);
|
||||
expect(payload.forgeWeb).toEqual({
|
||||
host: "github.com",
|
||||
referenceRepository: "main-owner/repo",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { describeCheckoutVcs } from "../../utils/checkout-vcs.js";
|
||||
import type {
|
||||
CheckoutPrStatusResponse,
|
||||
CheckoutStatusResponse,
|
||||
@@ -15,6 +16,15 @@ type CheckoutPrStatusWireStatus = Omit<CheckoutPrStatusPayloadStatus, "forge"> &
|
||||
forge?: string;
|
||||
};
|
||||
|
||||
function checkoutVcsFromSnapshot(snapshot: WorkspaceGitRuntimeSnapshot) {
|
||||
if (!snapshot.git.isGit) return describeCheckoutVcs("none");
|
||||
return describeCheckoutVcs(snapshot.git.jujutsu ? "jujutsu" : "git", {
|
||||
hasRemote: snapshot.git.hasRemote,
|
||||
hasFetchRemote: snapshot.git.jujutsu?.hasRemotes,
|
||||
hasForge: Boolean(snapshot.forge.forge ?? snapshot.forgeWeb) || snapshot.forge.featuresEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
cwd,
|
||||
requestId,
|
||||
@@ -24,10 +34,12 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
requestId: string;
|
||||
snapshot: WorkspaceGitRuntimeSnapshot;
|
||||
}): CheckoutStatusResponse["payload"] {
|
||||
const vcs = checkoutVcsFromSnapshot(snapshot);
|
||||
if (!snapshot.git.isGit) {
|
||||
return {
|
||||
cwd,
|
||||
isGit: false,
|
||||
vcs,
|
||||
repoRoot: null,
|
||||
currentBranch: null,
|
||||
isDirty: null,
|
||||
@@ -55,6 +67,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
|
||||
return {
|
||||
cwd,
|
||||
jujutsu: snapshot.git.jujutsu,
|
||||
vcs,
|
||||
isGit: true,
|
||||
repoRoot: snapshot.git.repoRoot,
|
||||
mainRepoRoot: snapshot.git.mainRepoRoot,
|
||||
@@ -82,6 +96,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
|
||||
return {
|
||||
cwd,
|
||||
jujutsu: snapshot.git.jujutsu,
|
||||
vcs,
|
||||
isGit: true,
|
||||
repoRoot: snapshot.git.repoRoot,
|
||||
mainRepoRoot: snapshot.git.mainRepoRoot,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect, beforeEach, afterEach } from "vitest";
|
||||
import { test, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import {
|
||||
mkdtempSync,
|
||||
writeFileSync,
|
||||
@@ -726,3 +726,174 @@ async function waitForWorkspaceSetup(workspaceId: string, status: "completed" |
|
||||
if (!snapshot) throw new Error("Expected workspace setup snapshot");
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
test("runs a Jujutsu describe and new through the daemon protocol", async () => {
|
||||
const directory = tmpCwd();
|
||||
const repo = path.join(directory, "repo");
|
||||
const configuration = path.join(directory, "jj.toml");
|
||||
writeFileSync(configuration, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
|
||||
vi.stubEnv("JJ_CONFIG", configuration);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
|
||||
try {
|
||||
execFileSync("jj", ["git", "init", "--colocate", repo]);
|
||||
writeFileSync(path.join(repo, "task.txt"), "working copy edit\n");
|
||||
const first = await ctx.client.getCheckoutStatus(repo);
|
||||
const changeId = first.jujutsu?.changeId ?? "";
|
||||
expect(first.vcs).toMatchObject({
|
||||
kind: "jujutsu",
|
||||
capabilities: { describe: true, newChange: true },
|
||||
});
|
||||
|
||||
const described = await ctx.client.checkoutJujutsuAction(repo, changeId, {
|
||||
kind: "describe",
|
||||
description: "Review this task",
|
||||
});
|
||||
expect(described.error).toBeNull();
|
||||
const created = await ctx.client.checkoutJujutsuAction(repo, changeId, {
|
||||
kind: "new",
|
||||
description: "Follow-up",
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
|
||||
const stale = await ctx.client.checkoutJujutsuAction(repo, changeId, {
|
||||
kind: "describe",
|
||||
description: "Wrong change",
|
||||
});
|
||||
expect(stale.error?.message).toContain("working-copy change has moved");
|
||||
expect(readFileSync(path.join(repo, "task.txt"), "utf8")).toBe("working copy edit\n");
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("creates a Jujutsu workspace from the working copy when there is no default bookmark", async () => {
|
||||
const directory = tmpCwd();
|
||||
const repo = path.join(directory, "repo");
|
||||
const config = path.join(directory, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
|
||||
try {
|
||||
execFileSync("jj", ["git", "init", "--colocate", repo]);
|
||||
writeFileSync(path.join(repo, "task.txt"), "unrecorded working-copy edit\n");
|
||||
|
||||
const created = await ctx.client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repo, action: "branch-off" },
|
||||
});
|
||||
if (!created.workspace) throw new Error(created.error ?? "Workspace creation failed");
|
||||
const { workspaceDirectory } = created.workspace;
|
||||
expect(readFileSync(path.join(workspaceDirectory, "task.txt"), "utf8")).toBe(
|
||||
"unrecorded working-copy edit\n",
|
||||
);
|
||||
|
||||
const readChangeId = (cwd: string, revision: string) =>
|
||||
execFileSync(
|
||||
"jj",
|
||||
["--ignore-working-copy", "log", "--no-graph", "-r", revision, "-T", "change_id"],
|
||||
{ cwd, encoding: "utf8" },
|
||||
);
|
||||
const sourceChange = readChangeId(repo, "@");
|
||||
expect(readChangeId(workspaceDirectory, "@-")).toBe(sourceChange);
|
||||
expect(readChangeId(workspaceDirectory, "@")).not.toBe(sourceChange);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("opens a file in the unintegrated working-copy merge shown in Jujutsu Changes", async () => {
|
||||
const directory = tmpCwd();
|
||||
const repo = path.join(directory, "repo");
|
||||
const config = path.join(directory, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
|
||||
try {
|
||||
execFileSync("jj", ["git", "init", "--colocate", repo]);
|
||||
const jj = (...args: string[]) => execFileSync("jj", args, { cwd: repo }).toString();
|
||||
writeFileSync(path.join(repo, "base.txt"), "base\n");
|
||||
jj("commit", "-m", "Base");
|
||||
jj("bookmark", "create", "-r", "@-", "main");
|
||||
writeFileSync(path.join(repo, "left.txt"), "from first parent\n");
|
||||
jj("bookmark", "create", "left");
|
||||
jj("new", "main");
|
||||
writeFileSync(path.join(repo, "project [right].txt"), "from second parent\n");
|
||||
jj("bookmark", "create", "right");
|
||||
jj("new", "left", "right");
|
||||
rmSync(path.join(repo, "project [right].txt"));
|
||||
|
||||
const { commits } = await ctx.client.listCheckoutCommits(repo);
|
||||
const merge = commits.find((commit) => commit.jujutsu?.isWorkingCopy);
|
||||
expect(merge?.files).toContainEqual({
|
||||
path: "project [right].txt",
|
||||
status: "deleted",
|
||||
additions: 0,
|
||||
deletions: 1,
|
||||
});
|
||||
if (!merge?.jujutsu?.operationId) throw new Error("Missing Jujutsu snapshot operation");
|
||||
|
||||
writeFileSync(path.join(repo, "project [right].txt"), "later edit\n");
|
||||
const { file } = await ctx.client.getCommitFileDiff(
|
||||
repo,
|
||||
merge.sha,
|
||||
"project [right].txt",
|
||||
undefined,
|
||||
merge.jujutsu.operationId,
|
||||
);
|
||||
expect(file).toMatchObject({ isDeleted: true, deletions: 1 });
|
||||
expect(JSON.stringify(file?.hunks)).toContain("from second parent");
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("archives and restores a Jujutsu worktree through the daemon", async () => {
|
||||
const directory = tmpCwd();
|
||||
const repo = path.join(directory, "repo");
|
||||
const config = path.join(directory, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
|
||||
try {
|
||||
execFileSync("jj", ["git", "init", "--colocate", repo]);
|
||||
writeFileSync(path.join(repo, ".gitignore"), "scratch.log\n");
|
||||
writeFileSync(path.join(repo, "task.txt"), "base\n");
|
||||
execFileSync("jj", ["commit", "-m", "Base"], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "create", "-r", "@-", "main"], { cwd: repo });
|
||||
|
||||
const added = await ctx.client.addProject(repo);
|
||||
if (!added.project) throw new Error(added.error ?? "Project creation failed");
|
||||
const created = await ctx.client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
projectId: added.project.projectId,
|
||||
action: "branch-off",
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "jj-archive",
|
||||
},
|
||||
});
|
||||
if (!created.workspace) throw new Error(created.error ?? "Workspace creation failed");
|
||||
const { id, workspaceDirectory: cwd } = created.workspace;
|
||||
const original = await ctx.client.getCheckoutStatus(cwd);
|
||||
expect(original.jujutsu?.changeId).toBeTruthy();
|
||||
|
||||
writeFileSync(path.join(cwd, "task.txt"), "working-copy edit\n");
|
||||
writeFileSync(path.join(cwd, "scratch.log"), "ignored file\n");
|
||||
|
||||
const archived = await ctx.client.archiveWorkspace(id);
|
||||
expect(archived.error).toBeNull();
|
||||
expect(archived.archivedAt).toBeTruthy();
|
||||
expect(existsSync(cwd)).toBe(false);
|
||||
|
||||
await ctx.client.restoreWorkspace(id);
|
||||
const restored = await ctx.client.getCheckoutStatus(cwd);
|
||||
expect(restored.jujutsu?.changeId).toBe(original.jujutsu?.changeId);
|
||||
expect(readFileSync(path.join(cwd, "task.txt"), "utf8")).toBe("working-copy edit\n");
|
||||
expect(existsSync(path.join(cwd, "scratch.log"))).toBe(false);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getJujutsuOperationHeads } from "../../utils/checkout-jj.js";
|
||||
import { resolve, relative } from "node:path";
|
||||
import type { Logger } from "pino";
|
||||
import { runGitCommand } from "../../utils/run-git-command.js";
|
||||
@@ -100,6 +101,10 @@ export class DiffDependencyObserver {
|
||||
),
|
||||
);
|
||||
}
|
||||
const jujutsuHeads = await getJujutsuOperationHeads(input.cwd);
|
||||
if (jujutsuHeads) {
|
||||
metadata.push(await this.observeMetadata(jujutsuHeads, null, () => changed("endpoints")));
|
||||
}
|
||||
const workingTree = await this.workspaceGit.requestWorkingTreeWatch(input.cwd, () =>
|
||||
changed(input.worktree ? "endpoints" : "interpretation"),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { resolveCheckoutProvider } from "../../utils/checkout-vcs.js";
|
||||
import { listJujutsuComparison } from "./jj.js";
|
||||
import { parseGitRevParsePath } from "../../utils/git-rev-parse-path.js";
|
||||
import { readGitInputs } from "./inputs.js";
|
||||
import { Patches } from "./patches.js";
|
||||
@@ -158,6 +160,14 @@ export async function listComparison(
|
||||
compare: Compare,
|
||||
revisions?: ComparisonRevisions,
|
||||
): Promise<Comparison> {
|
||||
if (compare.head.kind === "worktree" || compare.checkoutBase) {
|
||||
const provider = await resolveCheckoutProvider(compare.cwd);
|
||||
if (provider.kind === "jujutsu") {
|
||||
validateCompare(compare);
|
||||
return listJujutsuComparison({ ...compare, cwd: provider.root });
|
||||
}
|
||||
}
|
||||
|
||||
if (compare.checkoutBase) {
|
||||
if (revisions) revisions.checkoutBase = null;
|
||||
const selected = await resolveCheckoutDiffBase(compare.cwd, compare.checkoutBase.compare, {
|
||||
|
||||
@@ -2,6 +2,8 @@ import type { Logger } from "pino";
|
||||
import { TOTAL_DIFF_MAX_BYTES } from "../../utils/checkout-git.js";
|
||||
import { DEFAULT_MAX_OUTPUT_BYTES, runGitCommand } from "../../utils/run-git-command.js";
|
||||
import { expandTilde, createRealpathAwarePathMatcher } from "../../utils/path.js";
|
||||
import { findJujutsuRoot } from "../../utils/checkout-jj.js";
|
||||
import { readJujutsuCommitFile } from "./jj.js";
|
||||
import { packBodies } from "./batches.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import {
|
||||
@@ -64,7 +66,7 @@ interface Target {
|
||||
}
|
||||
export interface CommitFileRead extends Pick<
|
||||
CheckoutCommitFileDiffRequest,
|
||||
"cwd" | "sha" | "path"
|
||||
"cwd" | "sha" | "path" | "jujutsuOperationId"
|
||||
> {
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -96,6 +98,9 @@ export class DiffSubscriptions {
|
||||
}
|
||||
async readCommitFile(input: CommitFileRead): Promise<ParsedDiffFile | null> {
|
||||
input.signal?.throwIfAborted();
|
||||
const jujutsuRoot = await findJujutsuRoot(expandTilde(input.cwd));
|
||||
if (jujutsuRoot) return readJujutsuCommitFile({ ...input, cwd: jujutsuRoot });
|
||||
|
||||
const cwd = await worktreeRoot(expandTilde(input.cwd));
|
||||
const result = await runGitCommand(
|
||||
["rev-list", "--parents", "--max-count=1", "--end-of-options", input.sha],
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { materializeDiffFile, type DiffEntry } from "@getpaseo/protocol/binary-frames/index";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { Comparison, Compare, ListedFile } from "./git.js";
|
||||
import { getCheckoutDiff, PER_FILE_DIFF_MAX_BYTES } from "../../utils/checkout-git.js";
|
||||
import {
|
||||
getJujutsuDiff,
|
||||
getJujutsuState,
|
||||
parseJujutsuDiff,
|
||||
runJujutsu,
|
||||
} from "../../utils/checkout-jj.js";
|
||||
|
||||
export async function listJujutsuComparison(compare: Compare): Promise<Comparison> {
|
||||
if (compare.base.kind === "index") {
|
||||
throw new Error("Jujutsu does not use Git's staging area. Compare the current change instead.");
|
||||
}
|
||||
const state = await getJujutsuState(compare.cwd);
|
||||
let baseRef: string | undefined;
|
||||
if (compare.base.kind === "empty") baseRef = "root()";
|
||||
else if (compare.base.kind === "rev" && compare.base.rev !== "HEAD") baseRef = compare.base.rev;
|
||||
let diff: string;
|
||||
if (compare.checkoutBase) {
|
||||
const result = await getCheckoutDiff(compare.cwd, {
|
||||
...compare.checkoutBase.compare,
|
||||
includeStructured: false,
|
||||
});
|
||||
if (result.diffTooLarge) throw new Error("Jujutsu diff exceeds the supported size");
|
||||
diff = result.diff;
|
||||
} else {
|
||||
diff = await getJujutsuDiff(compare.cwd, {
|
||||
baseRef,
|
||||
ignoreWhitespace: compare.ignoreWhitespace,
|
||||
});
|
||||
}
|
||||
const parsed = new Map(parseJujutsuDiff(diff).map((file) => [file.path, file]));
|
||||
const files: ListedFile[] = [...parsed.values()].map((file) => ({
|
||||
entry: jujutsuDiffEntry(file),
|
||||
identity: createHash("sha256").update(JSON.stringify(file)).digest("hex"),
|
||||
source: { kind: "tracked" },
|
||||
}));
|
||||
files.sort((a, b) => a.entry.path.localeCompare(b.entry.path));
|
||||
|
||||
return {
|
||||
baseSha: "",
|
||||
headSha: state.commitId,
|
||||
mergeBaseSha: "",
|
||||
files,
|
||||
metrics: { highlightCalls: 0 },
|
||||
close: async () => {},
|
||||
selectBodies: () => {},
|
||||
hasInterpretationChanged: async () => false,
|
||||
async read(file, budget = {}) {
|
||||
const contents = parsed.get(file.entry.path);
|
||||
if (!contents) throw new Error(`Missing Jujutsu diff for ${file.entry.path}`);
|
||||
const body = { path: file.entry.path, hunks: contents.hunks };
|
||||
const bytes = Buffer.byteLength(JSON.stringify(body));
|
||||
if (
|
||||
bytes > (budget.maxPatchBytes ?? PER_FILE_DIFF_MAX_BYTES) ||
|
||||
bytes > (budget.remainingBytes ?? Infinity)
|
||||
) {
|
||||
return { kind: "too_large" };
|
||||
}
|
||||
return { kind: "ready", body, bytes };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type JujutsuDiffFile = ReturnType<typeof parseJujutsuDiff>[number];
|
||||
|
||||
function jujutsuDiffEntry(file: JujutsuDiffFile): DiffEntry {
|
||||
let change: DiffEntry["change"] = "modified";
|
||||
if (file.isNew) change = "added";
|
||||
else if (file.isDeleted) change = "deleted";
|
||||
else if (file.oldPath) change = "renamed";
|
||||
|
||||
const binary = file.status === "binary";
|
||||
return {
|
||||
path: file.path,
|
||||
oldPath: file.oldPath,
|
||||
change,
|
||||
content: binary ? "binary" : "text",
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
body: !binary,
|
||||
};
|
||||
}
|
||||
|
||||
export async function readJujutsuCommitFile(input: {
|
||||
cwd: string;
|
||||
sha: string;
|
||||
path: string;
|
||||
jujutsuOperationId?: string;
|
||||
signal?: AbortSignal;
|
||||
}) {
|
||||
const { cwd, sha, path, jujutsuOperationId, signal } = input;
|
||||
if (!/^[a-f0-9]{40}$/.test(sha)) throw new Error(`Invalid Jujutsu commit ID: ${sha}`);
|
||||
const diff = await runJujutsu(
|
||||
cwd,
|
||||
["diff", "--git", "-r", sha, "--", `root-file:${JSON.stringify(path)}`],
|
||||
{ atOperation: jujutsuOperationId, signal },
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
const file = parseJujutsuDiff(diff).find((candidate) => candidate.path === path);
|
||||
if (!file || file.status === "binary") return null;
|
||||
|
||||
const tooLarge = Buffer.byteLength(diff) > PER_FILE_DIFF_MAX_BYTES;
|
||||
const body = tooLarge ? null : { path, hunks: file.hunks };
|
||||
return materializeDiffFile(jujutsuDiffEntry(file), body, tooLarge);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { findJujutsuRoot } from "../utils/checkout-jj.js";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
@@ -191,6 +192,10 @@ export async function attemptFirstAgentBranchAutoName(options: {
|
||||
renameCurrentBranch?: typeof renameCurrentBranch;
|
||||
localBranchExists?: typeof localBranchExists;
|
||||
}): Promise<AttemptFirstAgentBranchAutoNameResult> {
|
||||
if (await findJujutsuRoot(options.cwd)) {
|
||||
return { attempted: false, renamed: false, branchName: null };
|
||||
}
|
||||
|
||||
const firstAgentContext = options.firstAgentContext;
|
||||
if (!firstAgentContext || !buildAgentBranchNameSeed(firstAgentContext)) {
|
||||
return { attempted: false, renamed: false, branchName: null };
|
||||
@@ -282,6 +287,8 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
|
||||
createdWorktree: Awaited<ReturnType<typeof createWorktreeCore>>;
|
||||
input: Pick<CreatePaseoWorktreeInput, "branchName">;
|
||||
}): Promise<void> {
|
||||
if (await findJujutsuRoot(options.createdWorktree.worktree.worktreePath)) return;
|
||||
|
||||
const { createdWorktree, input } = options;
|
||||
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
|
||||
return;
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
|
||||
export type WorktreeCreationIntent = Exclude<
|
||||
WorktreeSource,
|
||||
{ kind: "restore" | "restore-from-base" | "restore-commit" }
|
||||
{ kind: "restore" | "restore-from-base" | "restore-commit" | "restore-jujutsu" }
|
||||
> & { untrustedSource?: UntrustedWorkspaceSource };
|
||||
|
||||
export function worktreeUntrustedSource(
|
||||
|
||||
@@ -3465,6 +3465,10 @@ export class Session {
|
||||
return this.checkoutSession.handleCheckoutPullRequest(msg);
|
||||
case "checkout_push_request":
|
||||
return this.checkoutSession.handleCheckoutPushRequest(msg);
|
||||
case "checkout.jujutsu.action.request":
|
||||
return this.checkoutSession.handleJujutsuActionRequest(msg);
|
||||
case "checkout.jujutsu.changes.request":
|
||||
return this.checkoutSession.handleJujutsuChangesRequest(msg);
|
||||
case "checkout.refresh.request":
|
||||
return this.checkoutSession.handleRefreshRequest(msg);
|
||||
case "checkout.discard_changes.request":
|
||||
@@ -6342,6 +6346,14 @@ export class Session {
|
||||
aheadBehind: snapshot.git.aheadBehind,
|
||||
aheadOfOrigin: snapshot.git.aheadOfOrigin,
|
||||
behindOfOrigin: snapshot.git.behindOfOrigin,
|
||||
...(snapshot.git.jujutsu
|
||||
? {
|
||||
jujutsu: {
|
||||
changeId: snapshot.git.jujutsu.changeId,
|
||||
bookmarks: snapshot.git.jujutsu.bookmarks,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import { runJujutsuCheckoutAction } from "../../../utils/jujutsu-actions.js";
|
||||
import {
|
||||
assertGitMutationAllowed,
|
||||
findJujutsuRoot,
|
||||
searchJujutsuChanges,
|
||||
} from "../../../utils/checkout-jj.js";
|
||||
import type pino from "pino";
|
||||
import type { SessionDelivery } from "../owned-subscriptions/index.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
@@ -313,7 +319,7 @@ export class CheckoutSession {
|
||||
msg: CheckoutCommitFileDiffRequest,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
const { cwd, sha, path, requestId } = msg;
|
||||
const { cwd, sha, path, requestId, jujutsuOperationId } = msg;
|
||||
|
||||
try {
|
||||
assertSafeGitRef(sha, "commit");
|
||||
@@ -324,6 +330,7 @@ export class CheckoutSession {
|
||||
cwd: expandTilde(cwd),
|
||||
sha,
|
||||
path,
|
||||
...(jujutsuOperationId ? { jujutsuOperationId } : {}),
|
||||
signal,
|
||||
});
|
||||
this.host.emit({
|
||||
@@ -507,6 +514,52 @@ export class CheckoutSession {
|
||||
await ownership.release(msg.subscriptionId);
|
||||
}
|
||||
|
||||
async handleJujutsuActionRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "checkout.jujutsu.action.request" }>,
|
||||
): Promise<void> {
|
||||
const { cwd, requestId, expectedChangeId, action } = msg;
|
||||
try {
|
||||
const resolvedCwd = expandTilde(cwd);
|
||||
const url = await runJujutsuCheckoutAction({
|
||||
cwd: resolvedCwd,
|
||||
expectedChangeId,
|
||||
action,
|
||||
resolveForge: async () => (await this.requireForgeService(resolvedCwd)).service,
|
||||
});
|
||||
this.workspaceGitService.onWorkspaceStateMayHaveChanged(resolvedCwd);
|
||||
await this.scheduleDiffRefresh(resolvedCwd);
|
||||
this.host.emit({
|
||||
type: "checkout.jujutsu.action.response",
|
||||
payload: { cwd, requestId, url, error: null },
|
||||
});
|
||||
} catch (error) {
|
||||
this.host.emit({
|
||||
type: "checkout.jujutsu.action.response",
|
||||
payload: { cwd, requestId, url: null, error: toCheckoutError(error) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleJujutsuChangesRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "checkout.jujutsu.changes.request" }>,
|
||||
): Promise<void> {
|
||||
const { cwd, requestId, query } = msg;
|
||||
try {
|
||||
const root = await findJujutsuRoot(expandTilde(cwd));
|
||||
if (!root) throw new Error("This checkout does not use Jujutsu.");
|
||||
const changes = await searchJujutsuChanges(root, query);
|
||||
this.host.emit({
|
||||
type: "checkout.jujutsu.changes.response",
|
||||
payload: { cwd, requestId, changes, error: null },
|
||||
});
|
||||
} catch (error) {
|
||||
this.host.emit({
|
||||
type: "checkout.jujutsu.changes.response",
|
||||
payload: { cwd, requestId, changes: [], error: toCheckoutError(error) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleRefreshRequest(msg: CheckoutRefreshRequest): Promise<void> {
|
||||
const { cwd, requestId } = msg;
|
||||
const resolvedCwd = expandTilde(cwd);
|
||||
@@ -703,6 +756,7 @@ export class CheckoutSession {
|
||||
): Promise<void> {
|
||||
const { cwd, requestId } = msg;
|
||||
try {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
const branchLabel = msg.branch?.trim() ?? "";
|
||||
const message = branchLabel
|
||||
? `${CheckoutSession.PASEO_STASH_PREFIX} ${branchLabel}`
|
||||
@@ -730,6 +784,7 @@ export class CheckoutSession {
|
||||
): Promise<void> {
|
||||
const { cwd, stashIndex, requestId } = msg;
|
||||
try {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
await runGitCommand(["stash", "pop", `stash@{${stashIndex}}`], {
|
||||
cwd,
|
||||
timeout: 120_000,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertGitMutationAllowed } from "../../../utils/checkout-jj.js";
|
||||
import type pino from "pino";
|
||||
import { getErrorMessage } from "@getpaseo/protocol/error-utils";
|
||||
import {
|
||||
@@ -64,6 +65,7 @@ export function createGitMutationService(deps: {
|
||||
}
|
||||
|
||||
async function ensureCleanWorkingTree(cwd: string): Promise<void> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
const dirty = await isWorkingTreeDirty(cwd);
|
||||
if (dirty) {
|
||||
throw new Error(
|
||||
|
||||
@@ -76,6 +76,7 @@ export function createWorkspaceBaseBranchService(deps: Dependencies) {
|
||||
await setPaseoWorktreeBaseRef({
|
||||
worktreeRoot: root,
|
||||
baseRef: metadata.baseRef ?? metadata.baseRefName,
|
||||
jujutsuBaseCommit: metadata.jujutsuBaseCommit,
|
||||
});
|
||||
for (const record of matching) {
|
||||
await deps.workspaceRegistry.update(record.workspaceId, (latest) => ({
|
||||
|
||||
+115
-2
@@ -12,7 +12,7 @@ import {
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import pino from "pino";
|
||||
import { archivePersistedWorkspaceRecord } from "../../workspace-archive-service.js";
|
||||
@@ -21,7 +21,12 @@ import {
|
||||
readPaseoWorktreeMetadata,
|
||||
writePaseoWorktreeMetadata,
|
||||
} from "../../../utils/worktree-metadata.js";
|
||||
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
|
||||
import { getJujutsuState, getJujutsuWorkspaceName } from "../../../utils/checkout-jj.js";
|
||||
import {
|
||||
createWorktree,
|
||||
deletePaseoWorktree,
|
||||
rollbackCreatedPaseoWorktree,
|
||||
} from "../../../utils/worktree.js";
|
||||
import {
|
||||
FileBackedProjectRegistry,
|
||||
FileBackedWorkspaceRegistry,
|
||||
@@ -852,3 +857,111 @@ describe("recovery approval ownership for shared archived history", () => {
|
||||
expect(restored?.untrustedSource).toEqual(untrustedSource);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Jujutsu workspace recovery", () => {
|
||||
async function createFixture() {
|
||||
const { tempDir, repoDir } = createGitRepository();
|
||||
const config = join(tempDir, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@example.com"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", join(tempDir, "config"));
|
||||
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
|
||||
const paseoHome = join(tempDir, "paseo");
|
||||
const created = await createWorktree({
|
||||
cwd: repoDir,
|
||||
paseoHome,
|
||||
worktreeSlug: "recovery",
|
||||
source: { kind: "branch-off", branchName: "recovery", baseBranch: "main" },
|
||||
});
|
||||
const workspace = createWorkspace({
|
||||
cwd: created.worktreePath,
|
||||
worktreeRoot: created.worktreePath,
|
||||
mainRepoRoot: repoDir,
|
||||
branch: null,
|
||||
baseBranch: created.comparisonBaseRef,
|
||||
archivedAt: null,
|
||||
});
|
||||
const registry = new FileBackedWorkspaceRegistry(
|
||||
join(tempDir, "workspaces.json"),
|
||||
pino({ level: "silent" }),
|
||||
);
|
||||
await registry.upsert(workspace);
|
||||
const service = createWorkspaceRecoveryService({
|
||||
paseoHome,
|
||||
getWorkspace: (id) => registry.get(id),
|
||||
getProject: async () => createProject({ rootPath: repoDir }),
|
||||
isDirectory: async (path) => existsSync(path) && statSync(path).isDirectory(),
|
||||
unarchiveWorkspace: async (record) => {
|
||||
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
|
||||
},
|
||||
});
|
||||
return { repoDir, workspace, registry, service };
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
test.each([
|
||||
["an empty change", null],
|
||||
["a change with disk edits", "unsnapshotted work\n"],
|
||||
])("recreates the removed checkout for %s", async (_case, editedContent) => {
|
||||
const { repoDir, workspace, registry, service } = await createFixture();
|
||||
const file = join(workspace.cwd, "README.md");
|
||||
const before = await getJujutsuState(workspace.cwd);
|
||||
const metadata = await readPaseoWorktreeMetadata(workspace.cwd);
|
||||
expect(metadata?.jujutsuBaseCommit).toMatch(/^[a-f0-9]{40}$/);
|
||||
if (editedContent) writeFileSync(file, editedContent);
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId: workspace.workspaceId,
|
||||
workspaceRegistry: registry,
|
||||
});
|
||||
const saved = await registry.get(workspace.workspaceId);
|
||||
const recoveryCommit = saved?.jujutsuRecoveryCommit;
|
||||
if (!recoveryCommit) throw new Error("Missing Jujutsu recovery snapshot");
|
||||
if (editedContent) expect(recoveryCommit).not.toBe(before.commitId);
|
||||
else expect(recoveryCommit).toBe(before.commitId);
|
||||
expect(saved?.jujutsuBaseCommit).toBe(metadata?.jujutsuBaseCommit);
|
||||
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: workspace.cwd,
|
||||
registryProven: true,
|
||||
teardownCwds: [],
|
||||
jujutsuRecoveryCommit: recoveryCommit,
|
||||
});
|
||||
expect(existsSync(workspace.cwd)).toBe(false);
|
||||
await expect(service.restore(workspace.workspaceId)).resolves.toEqual({
|
||||
workspaceId: workspace.workspaceId,
|
||||
action: "restore",
|
||||
});
|
||||
expect(readFileSync(file, "utf8")).toBe(editedContent ?? "initial\n");
|
||||
expect(await readPaseoWorktreeMetadata(workspace.cwd)).toMatchObject({
|
||||
jujutsuBaseCommit: saved?.jujutsuBaseCommit,
|
||||
});
|
||||
expect(await getJujutsuState(workspace.cwd)).toMatchObject({
|
||||
changeId: before.changeId,
|
||||
commitId: saved?.jujutsuRecoveryCommit,
|
||||
});
|
||||
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
|
||||
expect(readFileSync(join(repoDir, "README.md"), "utf8")).toBe("initial\n");
|
||||
});
|
||||
|
||||
test("rolls back both registrations after provisioning fails", async () => {
|
||||
const { repoDir, workspace } = await createFixture();
|
||||
const cause = new Error("provisioning failed");
|
||||
await expect(
|
||||
rollbackCreatedPaseoWorktree(
|
||||
{
|
||||
cwd: repoDir,
|
||||
worktreePath: workspace.cwd,
|
||||
teardownCwds: [],
|
||||
},
|
||||
cause,
|
||||
),
|
||||
).rejects.toBe(cause);
|
||||
expect(existsSync(workspace.cwd)).toBe(false);
|
||||
expect(await getJujutsuWorkspaceName(repoDir, workspace.cwd)).toBeNull();
|
||||
expect(
|
||||
execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repoDir, encoding: "utf8" }),
|
||||
).not.toContain(workspace.cwd);
|
||||
});
|
||||
});
|
||||
+21
-4
@@ -186,7 +186,14 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
): Promise<{ worktreePath: string; pluginId: string | null }> {
|
||||
let source: WorktreeSource;
|
||||
const checkout = parseWorkspaceHead(workspace);
|
||||
if (checkout.kind === "branch") {
|
||||
if (workspace.jujutsuRecoveryCommit) {
|
||||
source = {
|
||||
kind: "restore-jujutsu",
|
||||
commit: workspace.jujutsuRecoveryCommit,
|
||||
baseRef: workspace.baseBranch,
|
||||
baseCommit: workspace.jujutsuBaseCommit,
|
||||
};
|
||||
} else if (checkout.kind === "branch") {
|
||||
source = {
|
||||
kind: "restore",
|
||||
branchName: checkout.branch,
|
||||
@@ -207,7 +214,9 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
}
|
||||
|
||||
try {
|
||||
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
|
||||
if (source.kind !== "restore-jujutsu") {
|
||||
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
|
||||
}
|
||||
} catch {
|
||||
// A stale worktree registration is not guaranteed; creation reports any real conflict.
|
||||
}
|
||||
@@ -290,7 +299,10 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
async function recreateWorktreeCheckout(options: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
sourceRepoRoot: string;
|
||||
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
|
||||
source: Extract<
|
||||
WorktreeSource,
|
||||
{ kind: "restore" | "restore-commit" | "restore-from-base" | "restore-jujutsu" }
|
||||
>;
|
||||
previousWorktreePath: string;
|
||||
hasRecordedWorktreePath: boolean;
|
||||
untrusted: boolean;
|
||||
@@ -304,7 +316,12 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
untrusted,
|
||||
} = options;
|
||||
const managerPluginId = workspace.worktreeManagerPluginId;
|
||||
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
|
||||
if (
|
||||
source.kind !== "restore-jujutsu" &&
|
||||
managerPluginId &&
|
||||
hasRecordedWorktreePath &&
|
||||
deps.worktreeManagers
|
||||
) {
|
||||
const adopted = await runPluginWorktreeManagerCheckout({
|
||||
cwd: sourceRepoRoot,
|
||||
source,
|
||||
|
||||
@@ -2292,6 +2292,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
fsEntryDuplicate: true,
|
||||
// COMPAT(checkoutDiscardChanges): added in v0.3.0, remove gate after 2027-02-08.
|
||||
checkoutDiscardChanges: true,
|
||||
jujutsuCheckoutActions: true,
|
||||
checkoutDiffAll: true,
|
||||
// COMPAT(agentProfiles): added in v0.3.2, remove gate after 2027-02-11.
|
||||
agentProfiles: true,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { getJujutsuWorkspaceName } from "../utils/checkout-jj.js";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
readPaseoWorktreeMetadata,
|
||||
@@ -20,6 +21,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
archivePersistedWorkspaceRecord,
|
||||
unarchiveWorkspaceAgents,
|
||||
type ActiveWorkspaceRef,
|
||||
type ArchiveDependencies,
|
||||
@@ -1750,3 +1752,127 @@ test.each(["outer", "inner"])(
|
||||
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
|
||||
},
|
||||
);
|
||||
|
||||
describe("Jujutsu workspace archive", () => {
|
||||
async function createFixture(workspaceIds: string[]) {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const config = path.join(tempDir, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(tempDir, "config"));
|
||||
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
|
||||
|
||||
const paseoHome = path.join(tempDir, "paseo");
|
||||
const { worktreePath: cwd } = await createPaseoOwnedWorktree(repoDir, paseoHome, "jj-archive");
|
||||
const registry = new FileBackedWorkspaceRegistry(
|
||||
path.join(tempDir, "workspaces.json"),
|
||||
createLogger(),
|
||||
);
|
||||
const now = new Date().toISOString();
|
||||
const workspaces = workspaceIds.map((workspaceId) =>
|
||||
createPersistedWorkspaceRecord({
|
||||
workspaceId,
|
||||
projectId: repoDir,
|
||||
cwd,
|
||||
kind: "worktree",
|
||||
worktreeRoot: cwd,
|
||||
mainRepoRoot: repoDir,
|
||||
isPaseoOwnedWorktree: true,
|
||||
displayName: workspaceId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
);
|
||||
for (const record of workspaces) await registry.upsert(record);
|
||||
|
||||
const dependencies = createArchiveDeps({ paseoHome, activeWorkspaces: workspaces });
|
||||
dependencies.getWorkspace = (id) => registry.get(id);
|
||||
dependencies.listActiveWorkspaces = () => registry.listActive();
|
||||
dependencies.archiveWorkspaceRecord = async (workspaceId, archivedAt) => {
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId,
|
||||
archivedAt,
|
||||
workspaceRegistry: registry,
|
||||
});
|
||||
};
|
||||
return { repoDir, cwd, registry, dependencies };
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
test("removes both registrations and the checkout after the last workspace is archived", async () => {
|
||||
const { repoDir, cwd, dependencies, registry } = await createFixture(["first", "second"]);
|
||||
writeFileSync(path.join(cwd, ".gitignore"), "scratch.log\n");
|
||||
writeFileSync(path.join(cwd, "scratch.log"), "ignored file\n");
|
||||
|
||||
const first = await archiveByScope(dependencies, {
|
||||
scope: { kind: "workspace", workspaceId: "first" },
|
||||
requestId: "archive-first",
|
||||
});
|
||||
assertArchiveResult(first, { archivedWorkspaceIds: ["first"], removedDirectory: false });
|
||||
expect(existsSync(path.join(cwd, "scratch.log"))).toBe(true);
|
||||
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeTruthy();
|
||||
|
||||
const second = await archiveByScope(dependencies, {
|
||||
scope: { kind: "workspace", workspaceId: "second" },
|
||||
requestId: "archive-second",
|
||||
});
|
||||
assertArchiveResult(second, { archivedWorkspaceIds: ["second"], removedDirectory: true });
|
||||
expect(existsSync(cwd)).toBe(false);
|
||||
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeNull();
|
||||
expect(
|
||||
execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repoDir }).toString(),
|
||||
).not.toContain("jj-archive");
|
||||
for (const id of ["first", "second"]) {
|
||||
expect((await registry.get(id))?.jujutsuRecoveryCommit).toMatch(/^[a-f0-9]{40}$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a nested linked Git worktree from another repository on archive", async () => {
|
||||
const { repoDir, cwd, dependencies, registry } = await createFixture(["jj-workspace"]);
|
||||
const { repoDir: nestedRepo } = createGitRepo();
|
||||
const nestedPath = path.join(cwd, "nested");
|
||||
const dirtyFile = path.join(nestedPath, "uncommitted.txt");
|
||||
writeFileSync(path.join(cwd, ".gitignore"), "nested/\n");
|
||||
execFileSync("git", ["worktree", "add", "-b", "nested-task", nestedPath], {
|
||||
cwd: nestedRepo,
|
||||
stdio: "pipe",
|
||||
});
|
||||
writeFileSync(dirtyFile, "keep-inner");
|
||||
|
||||
const result = await archiveByScope(dependencies, {
|
||||
scope: { kind: "workspace", workspaceId: "jj-workspace" },
|
||||
requestId: "archive-nested-jj",
|
||||
});
|
||||
|
||||
assertArchiveResult(result, {
|
||||
archivedWorkspaceIds: ["jj-workspace"],
|
||||
removedDirectory: false,
|
||||
});
|
||||
expect((await registry.get("jj-workspace"))?.jujutsuRecoveryCommit).toMatch(/^[a-f0-9]{40}$/);
|
||||
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeTruthy();
|
||||
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
|
||||
const worktrees = execFileSync("git", ["worktree", "list", "--porcelain"], {
|
||||
cwd: nestedRepo,
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(worktrees).toContain("refs/heads/nested-task");
|
||||
expect(worktrees).not.toContain("prunable");
|
||||
});
|
||||
|
||||
test("retains the checkout if no Jujutsu recovery snapshot was recorded", async () => {
|
||||
const { cwd, dependencies, registry } = await createFixture(["jj-workspace"]);
|
||||
dependencies.archiveWorkspaceRecord = async (id, archivedAt) => {
|
||||
await registry.archive(id, archivedAt);
|
||||
};
|
||||
const result = await archiveByScope(dependencies, {
|
||||
scope: { kind: "workspace", workspaceId: "jj-workspace" },
|
||||
requestId: "skip-jj-removal",
|
||||
});
|
||||
assertArchiveResult(result, {
|
||||
archivedWorkspaceIds: ["jj-workspace"],
|
||||
removedDirectory: false,
|
||||
});
|
||||
expect(existsSync(path.join(cwd, ".jj"))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { commandRunHook } from "./command-run-hook.js";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import { findJujutsuRoot, saveJujutsuRecoveryCommit } from "../utils/checkout-jj.js";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import type { Logger } from "pino";
|
||||
@@ -629,8 +630,13 @@ async function maybeRemoveDirectory(
|
||||
|
||||
// Last chance to keep the directory. Teardown commands already ran, so a cancel here restores
|
||||
// a workspace whose teardown hooks fired; that beats deleting what the user asked to keep.
|
||||
request.checkpoint();
|
||||
try {
|
||||
const jujutsuRecoveryCommit =
|
||||
(await findJujutsuRoot(backing.path)) === resolve(backing.path)
|
||||
? await getArchivedJujutsuRecoveryCommit(dependencies, backing.path, archivedWorkspaceIds)
|
||||
: undefined;
|
||||
request.checkpoint();
|
||||
|
||||
await deletePaseoWorktree({
|
||||
cwd: backing.mainRepoRoot,
|
||||
worktreePath: backing.path,
|
||||
@@ -643,11 +649,13 @@ async function maybeRemoveDirectory(
|
||||
worktreeManagerPluginId: backing.worktreeManagerPluginId,
|
||||
removeReason: "archive",
|
||||
untrusted: untrustedBacking,
|
||||
jujutsuRecoveryCommit,
|
||||
});
|
||||
dependencies.workspaceGitService.invalidateWorktrees();
|
||||
dependencies.github.invalidate({ cwd: backing.path });
|
||||
return { removedDirectory: true };
|
||||
} catch (error) {
|
||||
if (error instanceof WorkspaceArchiveCanceledError) throw error;
|
||||
dependencies.sessionLogger?.warn(
|
||||
{ err: error, targetPath: backing.path, requestId: request.requestId },
|
||||
"Worktree disk removal failed during archive; workspace already archived",
|
||||
@@ -688,6 +696,23 @@ async function resolveCheckoutTeardownPlan(
|
||||
};
|
||||
}
|
||||
|
||||
async function getArchivedJujutsuRecoveryCommit(
|
||||
dependencies: Pick<ArchiveDependencies, "getWorkspace">,
|
||||
path: string,
|
||||
archivedWorkspaceIds: string[],
|
||||
): Promise<string | undefined> {
|
||||
const matches = createRealpathAwarePathMatcher(path);
|
||||
const records = await Promise.all(
|
||||
archivedWorkspaceIds.map((id) => dependencies.getWorkspace?.(id)),
|
||||
);
|
||||
return records.find(
|
||||
(record) =>
|
||||
record?.archivedAt &&
|
||||
record.jujutsuRecoveryCommit &&
|
||||
matches(record.worktreeRoot ?? record.cwd),
|
||||
)?.jujutsuRecoveryCommit;
|
||||
}
|
||||
|
||||
async function filterAllowedTeardownTargets(
|
||||
dependencies: ArchiveDependencies,
|
||||
targets: Array<{ workspaceId: string; cwd: string }>,
|
||||
@@ -899,13 +924,22 @@ export async function archivePersistedWorkspaceRecord(input: {
|
||||
|
||||
const archivedAt = input.archivedAt ?? new Date().toISOString();
|
||||
let head: string | null = null;
|
||||
let jujutsuRecoveryCommit: string | undefined;
|
||||
let jujutsuBaseCommit: string | undefined;
|
||||
if (existingWorkspace.kind === "worktree") {
|
||||
const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
|
||||
head = await readWorktreeHeadReference(cwd);
|
||||
if (existingWorkspace.isPaseoOwnedWorktree && (await findJujutsuRoot(cwd)) === resolve(cwd)) {
|
||||
jujutsuRecoveryCommit = await saveJujutsuRecoveryCommit(cwd);
|
||||
jujutsuBaseCommit = (await readPaseoWorktreeMetadata(cwd))?.jujutsuBaseCommit;
|
||||
} else {
|
||||
head = await readWorktreeHeadReference(cwd);
|
||||
}
|
||||
}
|
||||
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
|
||||
...input.context,
|
||||
...(head ? { head } : {}),
|
||||
jujutsuRecoveryCommit,
|
||||
jujutsuBaseCommit,
|
||||
});
|
||||
|
||||
return existingWorkspace;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { findJujutsuRoot } from "../utils/checkout-jj.js";
|
||||
import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js";
|
||||
|
||||
export interface WorkspaceGitFetchResult {
|
||||
@@ -21,6 +22,8 @@ export async function fetchWorkspaceGitRemote(
|
||||
observer: WorkspaceGitFetchObserver,
|
||||
run: RunGitCommand = runGitCommand,
|
||||
): Promise<WorkspaceGitFetchResult> {
|
||||
if (await findJujutsuRoot(cwd)) return { changes: [], error: null };
|
||||
|
||||
let before: Map<string, string> | null = null;
|
||||
let after: Map<string, string> | null = null;
|
||||
let error: unknown | null = null;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { getJujutsuOperationHeads } from "../utils/checkout-jj.js";
|
||||
import type { JujutsuState } from "../utils/checkout-jj.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
@@ -174,6 +176,7 @@ export const getWorkspaceGitSelfHealPhaseMs = getWorkspaceGitObservationReensure
|
||||
export interface WorkspaceGitRuntimeSnapshot {
|
||||
cwd: string;
|
||||
git: {
|
||||
jujutsu?: JujutsuState;
|
||||
isGit: boolean;
|
||||
repoRoot: string | null;
|
||||
mainRepoRoot: string | null;
|
||||
@@ -482,6 +485,7 @@ class WorkspaceGitWatcherSubscriptionTimeoutError extends Error {
|
||||
}
|
||||
|
||||
interface WorkspaceGitTarget {
|
||||
jujutsuSubscription?: FileObserverSubscription;
|
||||
gitDirPaths: GitObservationPaths | null;
|
||||
cwd: string;
|
||||
listeners: Set<WorkspaceGitListener>;
|
||||
@@ -1476,12 +1480,54 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
target.repoGitRoot = repoGitRoot;
|
||||
await this.ensureRepoTarget(target);
|
||||
if (facts.jujutsu) await this.setupJujutsuObservation(target);
|
||||
|
||||
if (this.isActiveObservedWorkspaceTarget(target)) {
|
||||
target.observationSetupComplete = true;
|
||||
this.refreshAfterWorkingTreeCoverage(target);
|
||||
}
|
||||
}
|
||||
|
||||
private releaseJujutsuObservation(target: WorkspaceGitTarget): void {
|
||||
const subscription = target.jujutsuSubscription;
|
||||
target.jujutsuSubscription = undefined;
|
||||
if (!subscription) return;
|
||||
void subscription.unsubscribe().catch((error) => {
|
||||
this.logger.warn(
|
||||
{ err: error, cwd: target.cwd },
|
||||
"Failed to release Jujutsu metadata observation",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async setupJujutsuObservation(target: WorkspaceGitTarget): Promise<void> {
|
||||
if (target.jujutsuSubscription) return;
|
||||
const heads = await getJujutsuOperationHeads(target.cwd);
|
||||
if (!heads) return;
|
||||
const subscription = await this.subscribeWithDeadline(
|
||||
heads,
|
||||
(error) => {
|
||||
if (!this.isActiveObservedWorkspaceTarget(target)) return;
|
||||
if (error) {
|
||||
this.logger.warn({ err: error, cwd: target.cwd }, "Jujutsu metadata observation failed");
|
||||
target.observationSetupComplete = false;
|
||||
this.releaseJujutsuObservation(target);
|
||||
}
|
||||
this.scheduleWorkspaceRefresh(target, {
|
||||
origin: "observation",
|
||||
reason: "jujutsu-operation",
|
||||
});
|
||||
},
|
||||
{},
|
||||
() => {},
|
||||
);
|
||||
if (!this.isActiveObservedWorkspaceTarget(target)) {
|
||||
await subscription.unsubscribe();
|
||||
return;
|
||||
}
|
||||
target.jujutsuSubscription = subscription;
|
||||
}
|
||||
|
||||
// Watchers report only changes made after they subscribe, and the initial
|
||||
// snapshot is read in parallel with observation setup, so an edit or branch
|
||||
// switch in between reaches no watcher. Read the checkout once more now that
|
||||
@@ -3363,6 +3409,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
target: WorkspaceGitTarget,
|
||||
): WorkspaceForgePrStatusPollTarget | null {
|
||||
const git = target.latestGit;
|
||||
if (git?.jujutsu && target.latestFacts?.isGit) {
|
||||
return target.latestFacts.pullRequestLookupTarget;
|
||||
}
|
||||
if (!git?.currentBranch) {
|
||||
return null;
|
||||
}
|
||||
@@ -3835,6 +3884,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
: (target.latestGit?.diffStat ?? null);
|
||||
|
||||
target.latestGit = {
|
||||
...(checkoutStatus.jujutsu ? { jujutsu: checkoutStatus.jujutsu } : {}),
|
||||
isGit: true,
|
||||
repoRoot: checkoutStatus.repoRoot,
|
||||
mainRepoRoot: checkoutStatus.mainRepoRoot,
|
||||
@@ -3947,7 +3997,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
|
||||
private getForgePrStatusPollKey(target: WorkspaceGitTarget): string | null {
|
||||
const git = target.latestGit;
|
||||
if (!git?.currentBranch || !git.remoteUrl) {
|
||||
if (!git?.remoteUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -4320,6 +4370,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
|
||||
private stopWorkspaceObservation(target: WorkspaceGitTarget): void {
|
||||
this.releaseJujutsuObservation(target);
|
||||
if (target.workingTreeWatchTarget) {
|
||||
this.removeWorkspaceWorkingTreeLink(target.workingTreeWatchTarget, target.cwd);
|
||||
target.workingTreeWatchTarget = null;
|
||||
|
||||
@@ -73,6 +73,14 @@ const PersistedWorkspaceRecordSchema = z.object({
|
||||
.optional()
|
||||
.transform((value) => value ?? null),
|
||||
head: z.string().optional(),
|
||||
jujutsuRecoveryCommit: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{40}$/)
|
||||
.optional(),
|
||||
jujutsuBaseCommit: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{40}$/)
|
||||
.optional(),
|
||||
// Exact checkout/worktree root backing cwd. This differs from cwd when the
|
||||
// selected project is a subdirectory inside a repository. Persist it so
|
||||
// archive and recovery do not need the directory to still exist in order to
|
||||
@@ -129,6 +137,8 @@ export interface WorkspaceMutationContext {
|
||||
export interface WorkspaceArchiveContext {
|
||||
autoArchivedChangeRequestUrl?: string;
|
||||
head?: string;
|
||||
jujutsuRecoveryCommit?: string;
|
||||
jujutsuBaseCommit?: string;
|
||||
}
|
||||
|
||||
export interface ProjectMutation {
|
||||
@@ -590,6 +600,8 @@ export class FileBackedWorkspaceRegistry
|
||||
updatedAt: archivedAt,
|
||||
archivedAt,
|
||||
head: context?.head,
|
||||
jujutsuRecoveryCommit: context?.jujutsuRecoveryCommit ?? existing.jujutsuRecoveryCommit,
|
||||
jujutsuBaseCommit: context?.jujutsuBaseCommit ?? existing.jujutsuBaseCommit,
|
||||
...(context?.autoArchivedChangeRequestUrl
|
||||
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
|
||||
: {}),
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test, afterEach } from "vitest";
|
||||
import { describe, expect, test, afterEach, vi } from "vitest";
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import { createGitLabService } from "../services/gitlab-service.js";
|
||||
import {
|
||||
@@ -435,6 +435,46 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
expect(existsSync(result.worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("creates a Jujutsu workspace from @ with a Git worktree manager installed", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
const config = path.join(tempDir, "jj.toml");
|
||||
writeFileSync(config, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
|
||||
vi.stubEnv("JJ_CONFIG", config);
|
||||
vi.stubEnv("XDG_CONFIG_HOME", path.join(tempDir, "config"));
|
||||
|
||||
try {
|
||||
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
|
||||
writeFileSync(path.join(repoDir, "uncommitted.txt"), "from source @");
|
||||
const managerCreateWorktree = vi.fn(async () => null);
|
||||
const result = await createCoreWorktree(
|
||||
{
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "jj-with-manager",
|
||||
action: "branch-off",
|
||||
refName: "@",
|
||||
paseoHome,
|
||||
},
|
||||
{
|
||||
...createCoreDeps(),
|
||||
worktreeManagers: {
|
||||
hasWorktreeManager: () => true,
|
||||
createWorktree: managerCreateWorktree,
|
||||
removeWorktree: async () => null,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(managerCreateWorktree).not.toHaveBeenCalled();
|
||||
expect(existsSync(path.join(result.worktree.worktreePath, ".jj"))).toBe(true);
|
||||
expect(
|
||||
readFileSync(path.join(result.worktree.worktreePath, "uncommitted.txt"), "utf8"),
|
||||
).toBe("from source @");
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps default placement suffixes when the default destination already exists", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
|
||||
@@ -2,6 +2,9 @@ import type {
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateRequest,
|
||||
} from "@getpaseo/plugin/server";
|
||||
|
||||
import { resolveRepositoryDefaultBranch } from "../utils/checkout-git.js";
|
||||
import { resolveCheckoutProvider } from "../utils/checkout-vcs.js";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
import { createNameId } from "mnemonic-id";
|
||||
@@ -75,6 +78,21 @@ export async function createWorktreeCore(
|
||||
return runWithGitCommandPriority("high", () => createWorktreeCoreWithPriority(input, deps));
|
||||
}
|
||||
|
||||
async function resolveJujutsuSource(input: CreateWorktreeCoreInput): Promise<string | null> {
|
||||
const provider = await resolveCheckoutProvider(input.cwd);
|
||||
const jujutsuRoot = provider.kind === "jujutsu" ? provider.root : null;
|
||||
if (
|
||||
jujutsuRoot &&
|
||||
(input.action === "checkout" || input.checkoutSource || input.githubPrNumber !== undefined)
|
||||
) {
|
||||
throw new Error(
|
||||
"Jujutsu workspaces support branching from a base revision; open existing changes as local workspaces.",
|
||||
);
|
||||
}
|
||||
|
||||
return jujutsuRoot;
|
||||
}
|
||||
|
||||
async function createWorktreeCoreWithPriority(
|
||||
input: CreateWorktreeCoreInput,
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
@@ -90,48 +108,17 @@ async function createWorktreeAtRepositoryRoot(
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
repoRoot: string,
|
||||
): Promise<CreateWorktreeCoreResult> {
|
||||
const jujutsuRoot = await resolveJujutsuSource(input);
|
||||
|
||||
const requestedWorktreeSlug = input.worktreeSlug
|
||||
? normalizeWorktreeSlug(input.worktreeSlug)
|
||||
: undefined;
|
||||
const requestedBranchName = input.branchName?.trim();
|
||||
|
||||
let intentInput: ResolveWorktreeCreationIntentInput;
|
||||
if (input.action === "checkout") {
|
||||
intentInput = {
|
||||
action: "checkout",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
} 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,
|
||||
refName: input.refName,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
} else {
|
||||
const worktreeSlug = requestedWorktreeSlug ?? normalizeWorktreeSlug(createNameId());
|
||||
intentInput = {
|
||||
action: "branch-off",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
branchName: requestedBranchName,
|
||||
worktreeSlug,
|
||||
};
|
||||
}
|
||||
|
||||
const intentInput = describeCreationIntentInput(input, requestedWorktreeSlug);
|
||||
const forge = await resolveForge(repoRoot, deps, intentInput);
|
||||
let intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, {
|
||||
forge: forge.forge,
|
||||
forgeService: forge.service,
|
||||
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps),
|
||||
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps, jujutsuRoot !== null),
|
||||
fetchRef: ({ repoRoot: cwd, sources, destination }) =>
|
||||
fetchFirstAvailableRef({ cwd, sources, destination }),
|
||||
});
|
||||
@@ -178,18 +165,23 @@ async function createWorktreeAtRepositoryRoot(
|
||||
intent = creationIntentFromRequest(transformed, intent);
|
||||
const untrustedSource = originalUntrustedSource ?? worktreeUntrustedSource(intent);
|
||||
|
||||
const { worktree: managedWorktree, preparedBranchOff } = await tryCreateWithWorktreeManager({
|
||||
repoRoot,
|
||||
transformed,
|
||||
intent,
|
||||
untrusted: Boolean(untrustedSource),
|
||||
input,
|
||||
deps,
|
||||
});
|
||||
// Worktree managers prepare and verify a Git branch, including before their callback.
|
||||
const { worktree: managedWorktree, preparedBranchOff } = jujutsuRoot
|
||||
? { worktree: null, preparedBranchOff: undefined }
|
||||
: await tryCreateWithWorktreeManager({
|
||||
repoRoot,
|
||||
transformed,
|
||||
intent,
|
||||
untrusted: Boolean(untrustedSource),
|
||||
input,
|
||||
deps,
|
||||
});
|
||||
const createdWorktree =
|
||||
managedWorktree ??
|
||||
(await createWorktree({
|
||||
cwd: repoRoot,
|
||||
cwd: jujutsuRoot ?? sourceCheckout,
|
||||
// Git worktrees have historically inherited root-level Paseo config from repoRoot.
|
||||
configSourceCwd: jujutsuRoot ?? repoRoot,
|
||||
worktreeSlug: normalizedSlug,
|
||||
worktreePath: transformed.path,
|
||||
source: intent,
|
||||
@@ -209,6 +201,31 @@ async function createWorktreeAtRepositoryRoot(
|
||||
};
|
||||
}
|
||||
|
||||
function describeCreationIntentInput(
|
||||
input: CreateWorktreeCoreInput,
|
||||
worktreeSlug: string | undefined,
|
||||
): ResolveWorktreeCreationIntentInput {
|
||||
const { checkoutSource, githubPrNumber, refName } = input;
|
||||
if (input.action === "checkout") {
|
||||
return { action: "checkout", refName, checkoutSource, githubPrNumber, worktreeSlug };
|
||||
}
|
||||
if (
|
||||
input.action !== "branch-off" &&
|
||||
(checkoutSource !== undefined || githubPrNumber !== undefined)
|
||||
) {
|
||||
// A change request with no action is checked out, as clients did before `action` existed.
|
||||
return { checkoutSource, githubPrNumber, refName, worktreeSlug };
|
||||
}
|
||||
return {
|
||||
action: "branch-off",
|
||||
refName,
|
||||
checkoutSource,
|
||||
githubPrNumber,
|
||||
branchName: input.branchName?.trim(),
|
||||
worktreeSlug: worktreeSlug ?? normalizeWorktreeSlug(createNameId()),
|
||||
};
|
||||
}
|
||||
|
||||
async function tryCreateWithWorktreeManager(options: {
|
||||
repoRoot: string;
|
||||
transformed: PluginWorktreeCreateRequest;
|
||||
@@ -325,7 +342,12 @@ async function resolveForge(
|
||||
async function resolveDefaultBranch(
|
||||
repoRoot: string,
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
isJujutsu: boolean,
|
||||
): Promise<string> {
|
||||
if (isJujutsu && !deps.resolveDefaultBranch) {
|
||||
return (await resolveRepositoryDefaultBranch(repoRoot)) ?? "@";
|
||||
}
|
||||
|
||||
const baseBranch = deps.resolveDefaultBranch
|
||||
? await deps.resolveDefaultBranch(repoRoot)
|
||||
: await deps.workspaceGitService?.resolveDefaultBranch(repoRoot);
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
import { runJujutsuCheckoutAction } from "./jujutsu-actions.js";
|
||||
import { createWorktreeCore } from "../server/worktree-core.js";
|
||||
import { createGitHubService } from "../services/github-service.js";
|
||||
import {
|
||||
WorkspaceGitServiceImpl,
|
||||
type WorkspaceGitRuntimeSnapshot,
|
||||
} from "../server/workspace-git-service.js";
|
||||
import { listComparison } from "../server/diff/git.js";
|
||||
import { deletePaseoWorktree } from "./worktree.js";
|
||||
import {
|
||||
findJujutsuRoot,
|
||||
getJujutsuState,
|
||||
getJujutsuDiff,
|
||||
listJujutsuCommits,
|
||||
saveJujutsuRecoveryCommit,
|
||||
resolveJujutsuRevision,
|
||||
searchJujutsuChanges,
|
||||
} from "./checkout-jj.js";
|
||||
import { describe, it, expect, beforeEach, afterEach, afterAll } from "vitest";
|
||||
import { execFileSync, execSync, spawnSync } from "child_process";
|
||||
import {
|
||||
@@ -49,6 +67,7 @@ import {
|
||||
isPaseoWorktreePath,
|
||||
isDescendantPath,
|
||||
warmCheckoutShortstatInBackground,
|
||||
listCheckoutCommits,
|
||||
} from "./checkout-git.js";
|
||||
import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js";
|
||||
import { createForgeResolver } from "../services/forge-resolver.js";
|
||||
@@ -4836,3 +4855,690 @@ describe("discardChanges", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Jujutsu checkout inspection", () => {
|
||||
let root: string;
|
||||
let repo: string;
|
||||
let config: string | undefined;
|
||||
let cache: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), "paseo-jj-"));
|
||||
repo = join(root, "repo");
|
||||
config = process.env.JJ_CONFIG;
|
||||
cache = process.env.XDG_CONFIG_HOME;
|
||||
process.env.JJ_CONFIG = join(root, "jj.toml");
|
||||
process.env.XDG_CONFIG_HOME = join(root, "config");
|
||||
writeFileSync(process.env.JJ_CONFIG, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
|
||||
execFileSync("jj", ["git", "init", "--colocate", repo]);
|
||||
writeFileSync(join(repo, "file.txt"), "base\n");
|
||||
execFileSync("jj", ["commit", "-m", "Base"], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "create", "main", "-r", "@-"], { cwd: repo });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (config === undefined) delete process.env.JJ_CONFIG;
|
||||
else process.env.JJ_CONFIG = config;
|
||||
if (cache === undefined) delete process.env.XDG_CONFIG_HOME;
|
||||
else process.env.XDG_CONFIG_HOME = cache;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("detects a colocated checkout from subdirectories and respects nested Git roots", async () => {
|
||||
const nested = join(repo, "nested");
|
||||
mkdirSync(nested);
|
||||
expect(await findJujutsuRoot(nested)).toBe(repo);
|
||||
execFileSync("git", ["init", nested]);
|
||||
expect(await findJujutsuRoot(nested)).toBeNull();
|
||||
});
|
||||
|
||||
it("reads live changes without moving the operation head, @, or Git HEAD", async () => {
|
||||
const before = await getJujutsuState(repo);
|
||||
const operation = execFileSync(
|
||||
"jj",
|
||||
["--ignore-working-copy", "op", "log", "--no-graph", "--limit", "1", "-T", "id"],
|
||||
{ cwd: repo },
|
||||
).toString();
|
||||
const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repo }).toString();
|
||||
writeFileSync(join(repo, "file.txt"), "base\nlive edit\n");
|
||||
writeFileSync(join(repo, "new file.txt"), "new content\n");
|
||||
|
||||
const diff = await getJujutsuDiff(repo, {});
|
||||
|
||||
expect(diff).toContain("+live edit");
|
||||
expect(diff).toContain("+new content");
|
||||
expect(await getJujutsuState(repo)).toEqual(before);
|
||||
expect(
|
||||
execFileSync(
|
||||
"jj",
|
||||
["--ignore-working-copy", "op", "log", "--no-graph", "--limit", "1", "-T", "id"],
|
||||
{ cwd: repo },
|
||||
).toString(),
|
||||
).toBe(operation);
|
||||
expect(execFileSync("git", ["rev-parse", "HEAD"], { cwd: repo }).toString()).toBe(head);
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\nlive edit\n");
|
||||
});
|
||||
it("reports jj identity, bookmarks and changes through checkout status", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "base\nstatus edit\n");
|
||||
execFileSync("jj", ["describe", "-m", "Current task"], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "create", "task"], { cwd: repo });
|
||||
|
||||
const status = await getCheckoutStatus(repo);
|
||||
|
||||
expect(status.isGit).toBe(true);
|
||||
expect(status).toMatchObject({
|
||||
isDirty: true,
|
||||
jujutsu: { description: "Current task\n", bookmarks: ["task"], hasConflicts: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("streams the current change including disk edits through the shared diff engine", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "base\nrecorded edit\n");
|
||||
execFileSync("jj", ["describe", "-m", "Task"], { cwd: repo });
|
||||
writeFileSync(join(repo, "file.txt"), "base\nrecorded edit\nlive edit\n");
|
||||
const comparison = await listComparison({
|
||||
cwd: repo,
|
||||
base: { kind: "rev", rev: "HEAD" },
|
||||
head: { kind: "worktree" },
|
||||
highlight: false,
|
||||
});
|
||||
try {
|
||||
expect(comparison.files.map((file) => file.entry)).toEqual([
|
||||
{
|
||||
path: "file.txt",
|
||||
oldPath: null,
|
||||
change: "modified",
|
||||
content: "text",
|
||||
additions: 2,
|
||||
deletions: 0,
|
||||
body: true,
|
||||
},
|
||||
]);
|
||||
const read = await comparison.read(comparison.files[0]);
|
||||
expect(read.kind).toBe("ready");
|
||||
expect(JSON.stringify(read)).toContain("recorded edit");
|
||||
expect(JSON.stringify(read)).toContain("live edit");
|
||||
} finally {
|
||||
await comparison.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves Git remote-tracking names for any remote and leaves revsets alone", async () => {
|
||||
const upstream = join(root, "upstream.git");
|
||||
execFileSync("git", ["init", "--bare", upstream]);
|
||||
execFileSync("git", ["remote", "add", "upstream", upstream], { cwd: repo });
|
||||
execFileSync("jj", ["git", "push", "--remote", "upstream", "--bookmark", "main"], {
|
||||
cwd: repo,
|
||||
});
|
||||
execFileSync("jj", ["bookmark", "create", "feature/x", "-r", "main"], { cwd: repo });
|
||||
const main = execFileSync("git", ["rev-parse", "main"], { cwd: repo }).toString().trim();
|
||||
|
||||
expect(await resolveJujutsuRevision(repo, "upstream/main")).toBe(main);
|
||||
expect(await resolveJujutsuRevision(repo, "refs/remotes/upstream/main")).toBe(main);
|
||||
expect(await resolveJujutsuRevision(repo, "feature/x")).toBe("feature/x");
|
||||
expect(await resolveJujutsuRevision(repo, "main@upstream")).toBe("main@upstream");
|
||||
});
|
||||
|
||||
it("rejects Git mutations without altering a jj checkout", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "keep this edit\n");
|
||||
await expect(commitAll(repo, "Wrong VCS")).rejects.toThrow("uses Jujutsu");
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("keep this edit\n");
|
||||
});
|
||||
|
||||
it("discards working-copy changes to the given paths with jj restore", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "discard this\n");
|
||||
writeFileSync(join(repo, "new file.txt"), "and this\n");
|
||||
writeFileSync(join(repo, "other.txt"), "keep this\n");
|
||||
|
||||
await discardChanges(repo, ["file.txt", "new file.txt"]);
|
||||
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
|
||||
expect(existsSync(join(repo, "new file.txt"))).toBe(false);
|
||||
expect(readFileSync(join(repo, "other.txt"), "utf8")).toBe("keep this\n");
|
||||
});
|
||||
|
||||
it("keeps a Jujutsu checkout when it has changed since the recovery snapshot", async () => {
|
||||
const result = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "parallel",
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: "parallel" },
|
||||
});
|
||||
expect(existsSync(join(result.worktreePath, ".jj"))).toBe(true);
|
||||
expect(existsSync(join(result.worktreePath, ".git"))).toBe(true);
|
||||
expect(await findJujutsuRoot(result.worktreePath)).toBe(result.worktreePath);
|
||||
const jujutsuRecoveryCommit = await saveJujutsuRecoveryCommit(result.worktreePath);
|
||||
writeFileSync(join(result.worktreePath, "file.txt"), "agent edit\n");
|
||||
writeFileSync(join(result.worktreePath, "scratch.log"), "keep scratch\n");
|
||||
await expect(
|
||||
deletePaseoWorktree({
|
||||
cwd: repo,
|
||||
worktreePath: result.worktreePath,
|
||||
paseoHome: join(root, "paseo"),
|
||||
jujutsuRecoveryCommit,
|
||||
}),
|
||||
).rejects.toThrow("changed after the archive snapshot");
|
||||
expect(readFileSync(join(result.worktreePath, "file.txt"), "utf8")).toBe("agent edit\n");
|
||||
expect(readFileSync(join(result.worktreePath, "scratch.log"), "utf8")).toBe("keep scratch\n");
|
||||
expect((await getJujutsuState(repo)).bookmarks).toEqual([]);
|
||||
});
|
||||
|
||||
it("branches from current work explicitly and keeps parallel edits isolated", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "base\ncurrent work\n");
|
||||
const first = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "parallel",
|
||||
source: { kind: "branch-off", baseBranch: "@", branchName: "parallel" },
|
||||
});
|
||||
const second = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "parallel",
|
||||
source: { kind: "branch-off", baseBranch: "@", branchName: "parallel" },
|
||||
});
|
||||
expect(readFileSync(join(first.worktreePath, "file.txt"), "utf8")).toBe("base\ncurrent work\n");
|
||||
expect(readFileSync(join(second.worktreePath, "file.txt"), "utf8")).toBe(
|
||||
"base\ncurrent work\n",
|
||||
);
|
||||
writeFileSync(join(first.worktreePath, "file.txt"), "first agent\n");
|
||||
expect(readFileSync(join(second.worktreePath, "file.txt"), "utf8")).toBe(
|
||||
"base\ncurrent work\n",
|
||||
);
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\ncurrent work\n");
|
||||
});
|
||||
|
||||
it("records the base by name and diffs from its fork point after it moves", async () => {
|
||||
const named = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "named",
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: "named" },
|
||||
});
|
||||
expect(await readPaseoWorktreeMetadata(named.worktreePath)).toMatchObject({
|
||||
baseRefName: "main",
|
||||
baseRef: "main",
|
||||
});
|
||||
|
||||
const current = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "current",
|
||||
source: { kind: "branch-off", baseBranch: "@", branchName: "current" },
|
||||
});
|
||||
const sourceChange = (await getJujutsuState(repo)).changeId;
|
||||
const recorded = (await readPaseoWorktreeMetadata(current.worktreePath))?.baseRef;
|
||||
expect(recorded && sourceChange.startsWith(recorded)).toBe(true);
|
||||
|
||||
// Move `main` on in the source workspace; the task diff must not show that as a revert.
|
||||
writeFileSync(join(named.worktreePath, "task.txt"), "task\n");
|
||||
writeFileSync(join(repo, "file.txt"), "base\nupstream\n");
|
||||
execFileSync("jj", ["commit", "-m", "Upstream"], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "set", "main", "-r", "@-"], { cwd: repo });
|
||||
const diff = await getJujutsuDiff(named.worktreePath, { baseRef: "main" });
|
||||
expect(diff).toContain("+task");
|
||||
expect(diff).not.toContain("upstream");
|
||||
});
|
||||
|
||||
it("records an operation that includes commits imported from Git", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "working copy edit\n");
|
||||
const git = (args: string[]) =>
|
||||
execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
|
||||
const tree = git(["rev-parse", "HEAD^{tree}"]);
|
||||
const imported = git([
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.invalid",
|
||||
"commit-tree",
|
||||
"-m",
|
||||
"Imported",
|
||||
tree,
|
||||
]);
|
||||
git(["branch", "imported", imported]);
|
||||
|
||||
const commits = await listJujutsuCommits(repo, "main", 5);
|
||||
const operationId = commits.find((commit) => commit.jujutsu.isWorkingCopy)?.jujutsu.operationId;
|
||||
expect(operationId).toMatch(/^[0-9a-f]+$/);
|
||||
|
||||
const output = execFileSync(
|
||||
"jj",
|
||||
["--at-operation", operationId!, "log", "--no-graph", "-r", imported, "-T", "commit_id"],
|
||||
{ cwd: repo, encoding: "utf8" },
|
||||
);
|
||||
expect(output).toBe(imported);
|
||||
});
|
||||
|
||||
it("keeps the selected comparison when the bookmark is deleted", async () => {
|
||||
const paseoHome = join(root, "paseo");
|
||||
const workspace = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome,
|
||||
worktreeSlug: "missing-bookmark",
|
||||
source: { kind: "branch-off", baseBranch: "refs/heads/main", branchName: "missing-bookmark" },
|
||||
});
|
||||
const cwd = workspace.worktreePath;
|
||||
const context = { paseoHome };
|
||||
writeFileSync(join(cwd, "file.txt"), "edit after base\n");
|
||||
const compare = { mode: "base", baseRef: "refs/heads/main" } as const;
|
||||
const before = await getCheckoutDiff(cwd, compare, context);
|
||||
expect(before.diff).toContain("+edit after base");
|
||||
|
||||
execFileSync("jj", ["bookmark", "delete", "main"], { cwd: repo });
|
||||
|
||||
expect(await getCheckoutStatus(cwd, context)).toMatchObject({
|
||||
jujutsu: { baseBookmarkMissing: true },
|
||||
});
|
||||
expect(await getCheckoutDiff(cwd, compare, context)).toEqual(before);
|
||||
const { commits } = await listCheckoutCommits({ cwd, context });
|
||||
expect(commits.find((commit) => commit.isOnBase)?.subject).toBe("Base");
|
||||
expect(commits.find((commit) => commit.jujutsu?.isWorkingCopy)?.files).toEqual([
|
||||
{ path: "file.txt", additions: 1, deletions: 1, status: "modified" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("starts a change on an exact local ref even when its name starts with a remote", async () => {
|
||||
execFileSync("jj", ["git", "remote", "add", "origin", join(root, "unused")], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "create", "-r", "main", "origin/topic"], { cwd: repo });
|
||||
|
||||
await runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: (await getJujutsuState(repo)).changeId,
|
||||
action: { kind: "new", parent: "refs/heads/origin/topic" },
|
||||
resolveForge: async () => {
|
||||
throw new Error("No forge configured");
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
execFileSync("jj", ["log", "--no-graph", "-r", "@-", "-T", "commit_id"], {
|
||||
cwd: repo,
|
||||
}).toString(),
|
||||
).toBe(
|
||||
execFileSync("git", ["rev-parse", "refs/heads/origin/topic"], { cwd: repo })
|
||||
.toString()
|
||||
.trim(),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the nearest bookmark and starts a new change on a chosen bookmark", async () => {
|
||||
// `main` is on @-, so it is the closest bookmark under the working copy.
|
||||
expect((await getJujutsuState(repo)).nearestBookmark).toBe("main");
|
||||
|
||||
writeFileSync(join(repo, "file.txt"), "work in progress\n");
|
||||
execFileSync("jj", ["describe", "-m", "WIP"], { cwd: repo });
|
||||
const before = await getJujutsuState(repo);
|
||||
await runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: before.changeId,
|
||||
action: { kind: "new", parent: "main" },
|
||||
resolveForge: async () => {
|
||||
throw new Error("No forge configured");
|
||||
},
|
||||
});
|
||||
|
||||
const parent = execFileSync("jj", ["log", "--no-graph", "-r", "@-", "-T", "commit_id"], {
|
||||
cwd: repo,
|
||||
}).toString();
|
||||
const main = execFileSync("jj", ["log", "--no-graph", "-r", "main", "-T", "commit_id"], {
|
||||
cwd: repo,
|
||||
}).toString();
|
||||
expect(parent).toBe(main);
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
|
||||
// The previous change keeps its work.
|
||||
expect(
|
||||
execFileSync("jj", ["file", "show", "-r", before.changeId, "file.txt"], {
|
||||
cwd: repo,
|
||||
}).toString(),
|
||||
).toBe("work in progress\n");
|
||||
});
|
||||
|
||||
it("lists a workspace's jj changes since its base, then the base's history", async () => {
|
||||
const workspace = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "changes",
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: "changes" },
|
||||
});
|
||||
const cwd = workspace.worktreePath;
|
||||
writeFileSync(join(cwd, "first.txt"), "one\ntwo\n");
|
||||
execFileSync("jj", ["commit", "-m", "First change"], { cwd });
|
||||
writeFileSync(join(cwd, "file.txt"), "edited\n");
|
||||
|
||||
const { baseRef, commits } = await listCheckoutCommits({
|
||||
cwd,
|
||||
context: { paseoHome: join(root, "paseo") },
|
||||
});
|
||||
expect(baseRef).toBe("main");
|
||||
const ahead = commits.filter((commit) => !commit.isOnBase);
|
||||
// Newest first: the working copy (described or not), then the committed change.
|
||||
expect(ahead.map((commit) => [commit.subject, commit.jujutsu?.isWorkingCopy])).toEqual([
|
||||
["", true],
|
||||
["First change", false],
|
||||
]);
|
||||
// The working copy's live edit is listed although nothing has snapshotted it.
|
||||
expect(ahead[0].files).toEqual([
|
||||
{ path: "file.txt", additions: 1, deletions: 1, status: "modified" },
|
||||
]);
|
||||
expect(ahead[1].files).toEqual([
|
||||
{ path: "first.txt", additions: 2, deletions: 0, status: "added" },
|
||||
]);
|
||||
expect(ahead[1].shortSha).toBe(ahead[1].jujutsu?.changeId.slice(0, ahead[1].shortSha.length));
|
||||
expect(commits.find((commit) => commit.isOnBase)?.subject).toBe("Base");
|
||||
});
|
||||
|
||||
it("searches changes across the repository, not just the current line", async () => {
|
||||
// A side branch off `main`, away from the working copy's line.
|
||||
execFileSync("jj", ["new", "main", "-m", "Side experiment"], { cwd: repo });
|
||||
writeFileSync(join(repo, "side.txt"), "side\n");
|
||||
execFileSync("jj", ["new", "main"], { cwd: repo });
|
||||
const side = execFileSync(
|
||||
"jj",
|
||||
["log", "--no-graph", "-r", 'description(exact:"Side experiment\n")', "-T", "change_id"],
|
||||
{ cwd: repo },
|
||||
).toString();
|
||||
|
||||
const all = await searchJujutsuChanges(repo, "");
|
||||
expect(all.map((change) => change.changeId)).toContain(side);
|
||||
expect((await searchJujutsuChanges(repo, "side EXPERIMENT")).map((c) => c.changeId)).toEqual([
|
||||
side,
|
||||
]);
|
||||
expect((await searchJujutsuChanges(repo, side.slice(0, 6))).map((c) => c.changeId)).toEqual([
|
||||
side,
|
||||
]);
|
||||
expect(
|
||||
(await searchJujutsuChanges(repo, "main")).some((c) => c.bookmarks.includes("main")),
|
||||
).toBe(true);
|
||||
// Revset syntax in a query is only ever text to match.
|
||||
await expect(searchJujutsuChanges(repo, '") | all() | ("')).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("fetches the selected upstream base even with an origin and a stale change ID", async () => {
|
||||
const remote = join(root, "remote.git");
|
||||
execFileSync("git", ["init", "--bare", remote]);
|
||||
const origin = join(root, "origin.git");
|
||||
execFileSync("git", ["init", "--bare", origin]);
|
||||
execFileSync("jj", ["git", "remote", "add", "origin", origin], { cwd: repo });
|
||||
execFileSync("jj", ["git", "remote", "add", "upstream", remote], { cwd: repo });
|
||||
execFileSync("git", ["push", "upstream", "refs/heads/main:refs/heads/main"], { cwd: repo });
|
||||
execFileSync("jj", ["git", "fetch", "--remote", "upstream"], { cwd: repo });
|
||||
const workspace = await createWorktreePrimitive({
|
||||
cwd: repo,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "upstream-base",
|
||||
source: {
|
||||
kind: "branch-off",
|
||||
baseBranch: "refs/remotes/upstream/main",
|
||||
branchName: "upstream-base",
|
||||
},
|
||||
});
|
||||
const other = join(root, "other");
|
||||
execFileSync("git", ["clone", "-q", "-b", "main", remote, other]);
|
||||
writeFileSync(join(other, "file.txt"), "from elsewhere\n");
|
||||
execFileSync("git", ["-c", "user.name=T", "-c", "user.email=t@t", "commit", "-qam", "Remote"], {
|
||||
cwd: other,
|
||||
});
|
||||
execFileSync("git", ["push", "-q", "origin", "HEAD:main"], { cwd: other });
|
||||
const remoteHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: other }).toString().trim();
|
||||
|
||||
await runJujutsuCheckoutAction({
|
||||
cwd: workspace.worktreePath,
|
||||
expectedChangeId: "stale-change-id",
|
||||
action: { kind: "fetch" },
|
||||
resolveForge: async () => {
|
||||
throw new Error("No forge configured");
|
||||
},
|
||||
});
|
||||
expect(
|
||||
execFileSync("jj", ["log", "--no-graph", "-r", "main@upstream", "-T", "commit_id"], {
|
||||
cwd: repo,
|
||||
}).toString(),
|
||||
).toBe(remoteHead);
|
||||
});
|
||||
|
||||
it("updates subscribed status when a jj operation changes the description", async () => {
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: pino({ level: "silent" }),
|
||||
paseoHome: join(root, "paseo"),
|
||||
});
|
||||
let latest: WorkspaceGitRuntimeSnapshot | undefined;
|
||||
const subscription = service.registerWorkspace({ cwd: repo }, (snapshot) => {
|
||||
latest = snapshot;
|
||||
});
|
||||
try {
|
||||
await expect
|
||||
.poll(() => service.getMetrics().fileObserver.activeObservationCount, { timeout: 10_000 })
|
||||
.toBeGreaterThanOrEqual(3);
|
||||
execFileSync("jj", ["describe", "-m", "Updated from terminal"], { cwd: repo });
|
||||
await expect
|
||||
.poll(() => latest?.git.jujutsu?.description, { timeout: 10_000 })
|
||||
.toBe("Updated from terminal\n");
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
}, 15_000);
|
||||
it("identifies binary files in the shared diff stream", async () => {
|
||||
writeFileSync(join(repo, "binary.dat"), Buffer.from([0, 1, 2, 3]));
|
||||
const comparison = await listComparison({
|
||||
cwd: repo,
|
||||
base: { kind: "rev", rev: "HEAD" },
|
||||
head: { kind: "worktree" },
|
||||
});
|
||||
try {
|
||||
expect(comparison.files.map((file) => file.entry)).toEqual([
|
||||
{
|
||||
path: "binary.dat",
|
||||
oldPath: null,
|
||||
change: "added",
|
||||
content: "binary",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
body: false,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await comparison.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports conflicts and renders a task diff against an explicit base", async () => {
|
||||
writeFileSync(join(repo, "file.txt"), "left\n");
|
||||
execFileSync("jj", ["describe", "-m", "Left"], { cwd: repo });
|
||||
execFileSync("jj", ["bookmark", "create", "left"], { cwd: repo });
|
||||
execFileSync("jj", ["new", "main"], { cwd: repo });
|
||||
writeFileSync(join(repo, "file.txt"), "right\n");
|
||||
execFileSync("jj", ["describe", "-m", "Right"], { cwd: repo });
|
||||
execFileSync("jj", ["new", "left", "@"], { cwd: repo });
|
||||
expect((await getJujutsuState(repo)).hasConflicts).toBe(true);
|
||||
const comparison = await listComparison({
|
||||
cwd: repo,
|
||||
base: { kind: "rev", rev: "main" },
|
||||
head: { kind: "rev", rev: "HEAD" },
|
||||
checkoutBase: { compare: { mode: "base", baseRef: "main" }, paseoHome: join(root, "paseo") },
|
||||
});
|
||||
try {
|
||||
expect(comparison.files.map((file) => file.entry.path)).toEqual(["file.txt"]);
|
||||
const contents = await comparison.read(comparison.files[0]);
|
||||
expect(JSON.stringify(contents)).toContain("left");
|
||||
expect(JSON.stringify(contents)).toContain("right");
|
||||
} finally {
|
||||
await comparison.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the selected Jujutsu workspace for @ and config seeding", async () => {
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: pino({ level: "silent" }),
|
||||
paseoHome: join(root, "paseo"),
|
||||
});
|
||||
try {
|
||||
const first = await createWorktreeCore(
|
||||
{ cwd: repo, paseoHome: join(root, "paseo"), worktreeSlug: "first", refName: "main" },
|
||||
{
|
||||
github: createGitHubService(),
|
||||
workspaceGitService: service,
|
||||
},
|
||||
);
|
||||
const source = first.worktree.worktreePath;
|
||||
const sourceConfig = '{"worktree":{"setup":["echo selected workspace"]}}';
|
||||
writeFileSync(join(source, "file.txt"), "selected source\n");
|
||||
writeFileSync(join(source, ".gitignore"), "paseo.json\n");
|
||||
writeFileSync(join(source, "paseo.json"), sourceConfig);
|
||||
writeFileSync(join(repo, "paseo.json"), '{"worktree":{"setup":["echo main checkout"]}}');
|
||||
const second = await createWorktreeCore(
|
||||
{
|
||||
cwd: source,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "second",
|
||||
refName: "@",
|
||||
},
|
||||
{
|
||||
github: createGitHubService(),
|
||||
workspaceGitService: service,
|
||||
},
|
||||
);
|
||||
expect(readFileSync(join(second.worktree.worktreePath, "file.txt"), "utf8")).toBe(
|
||||
"selected source\n",
|
||||
);
|
||||
expect(readFileSync(join(second.worktree.worktreePath, "paseo.json"), "utf8")).toBe(
|
||||
sourceConfig,
|
||||
);
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
|
||||
} finally {
|
||||
await service.dispose();
|
||||
}
|
||||
});
|
||||
it("describes the current change, starts a child, and rejects requests for a stale change", async () => {
|
||||
const initial = await getJujutsuState(repo);
|
||||
const run = (action: import("@getpaseo/protocol/messages").JujutsuCheckoutAction) =>
|
||||
runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: initial.changeId,
|
||||
action,
|
||||
resolveForge: async () => {
|
||||
throw new Error("No forge configured");
|
||||
},
|
||||
});
|
||||
|
||||
writeFileSync(join(repo, "file.txt"), "local edit\n");
|
||||
await run({ kind: "describe", description: "Describe the patch" });
|
||||
expect(await getJujutsuState(repo)).toMatchObject({
|
||||
changeId: initial.changeId,
|
||||
description: "Describe the patch\n",
|
||||
});
|
||||
await run({ kind: "new", description: "Follow-up" });
|
||||
const current = await getJujutsuState(repo);
|
||||
expect(current.changeId).not.toBe(initial.changeId);
|
||||
expect(current.description).toBe("Follow-up\n");
|
||||
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("local edit\n");
|
||||
await expect(run({ kind: "describe", description: "Stale request" })).rejects.toThrow(
|
||||
"has moved",
|
||||
);
|
||||
expect(await getJujutsuState(repo)).toEqual(current);
|
||||
});
|
||||
|
||||
it("publishes an exact bookmark and creates a pull request from that bookmark", async () => {
|
||||
const remote = join(root, "remote.git");
|
||||
execFileSync("git", ["init", "--bare", remote]);
|
||||
execFileSync("jj", ["git", "remote", "add", "origin", remote], { cwd: repo });
|
||||
writeFileSync(join(repo, "file.txt"), "published work\n");
|
||||
execFileSync("jj", ["describe", "-m", "Publish task"], { cwd: repo });
|
||||
const current = await getJujutsuState(repo);
|
||||
let pullRequest: import("../services/forge-service.js").CreatePullRequestOptions | undefined;
|
||||
const resolveForge = async () => ({
|
||||
createPullRequest: async (
|
||||
input: import("../services/forge-service.js").CreatePullRequestOptions,
|
||||
) => {
|
||||
pullRequest = input;
|
||||
return { url: "https://example.invalid/pull/1", number: 1 };
|
||||
},
|
||||
invalidate: () => {},
|
||||
});
|
||||
|
||||
await runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: current.changeId,
|
||||
resolveForge,
|
||||
action: { kind: "publish", bookmark: "task", create: true },
|
||||
});
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "refs/heads/task"], {
|
||||
cwd: remote,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe(current.commitId);
|
||||
expect(
|
||||
execFileSync("git", ["for-each-ref", "--format=%(refname)", "refs/heads"], {
|
||||
cwd: remote,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("refs/heads/task");
|
||||
expect(await getCheckoutSnapshotFacts(repo)).toMatchObject({
|
||||
pullRequestLookupTarget: { headRef: "task", headSha: current.commitId },
|
||||
});
|
||||
|
||||
await expect(
|
||||
runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: current.changeId,
|
||||
resolveForge,
|
||||
action: {
|
||||
kind: "create_pull_request",
|
||||
bookmark: "task",
|
||||
base: "main",
|
||||
title: "Publish task",
|
||||
},
|
||||
}),
|
||||
).resolves.toBe("https://example.invalid/pull/1");
|
||||
expect(pullRequest).toMatchObject({ head: "task", base: "main", title: "Publish task" });
|
||||
execFileSync("jj", ["bookmark", "delete", "task"], { cwd: repo });
|
||||
await expect(
|
||||
runJujutsuCheckoutAction({
|
||||
cwd: repo,
|
||||
expectedChangeId: current.changeId,
|
||||
resolveForge,
|
||||
action: { kind: "publish", bookmark: "task" },
|
||||
}),
|
||||
).rejects.toThrow("existing, unambiguous local bookmark");
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "refs/heads/task"], {
|
||||
cwd: remote,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe(current.commitId);
|
||||
});
|
||||
it("uses Git for the selected Git worktree and seeds config from the main checkout", async () => {
|
||||
const gitOnly = join(root, "git-only");
|
||||
execFileSync("git", ["worktree", "add", "--detach", gitOnly, "main"], { cwd: repo });
|
||||
await writePaseoWorktreeMetadata(gitOnly, { baseRefName: "main" });
|
||||
const mainConfig = '{"worktree":{"setup":["echo main checkout"]}}';
|
||||
writeFileSync(join(repo, "paseo.json"), mainConfig);
|
||||
writeFileSync(join(gitOnly, "paseo.json"), '{"worktree":{"setup":["echo linked checkout"]}}');
|
||||
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: pino({ level: "silent" }),
|
||||
paseoHome: join(root, "paseo"),
|
||||
});
|
||||
try {
|
||||
const result = await createWorktreeCore(
|
||||
{
|
||||
cwd: gitOnly,
|
||||
paseoHome: join(root, "paseo"),
|
||||
worktreeSlug: "git-only-child",
|
||||
refName: "main",
|
||||
branchName: "git-child",
|
||||
},
|
||||
{ github: createGitHubService(), workspaceGitService: service },
|
||||
);
|
||||
expect(result.repoRoot).toBe(repo);
|
||||
expect(result.worktree.branchName).toBe("git-child");
|
||||
expect(await findJujutsuRoot(result.worktree.worktreePath)).toBeNull();
|
||||
expect(readFileSync(join(result.worktree.worktreePath, "paseo.json"), "utf8")).toBe(
|
||||
mainConfig,
|
||||
);
|
||||
} finally {
|
||||
await service.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,16 @@
|
||||
import { resolveCheckoutProvider } from "./checkout-vcs.js";
|
||||
import {
|
||||
findJujutsuRoot,
|
||||
findJujutsuCommit,
|
||||
resolveJujutsuComparisonBase,
|
||||
resolveJujutsuRevision,
|
||||
getJujutsuDiff,
|
||||
listJujutsuCommits,
|
||||
assertGitMutationAllowed,
|
||||
restoreJujutsuPaths,
|
||||
type JujutsuState,
|
||||
parseJujutsuDiff,
|
||||
} from "./checkout-jj.js";
|
||||
import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
|
||||
import { resolve, dirname, basename } from "path";
|
||||
import {
|
||||
@@ -523,6 +536,7 @@ export async function checkoutResolvedBranch(
|
||||
input: CheckoutResolvedBranchInput,
|
||||
): Promise<CheckoutExistingBranchResult> {
|
||||
const { cwd, resolution } = input;
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
switch (resolution.kind) {
|
||||
case "local": {
|
||||
@@ -899,6 +913,7 @@ export interface CheckoutStatus {
|
||||
}
|
||||
|
||||
export interface CheckoutStatusGitNonPaseo {
|
||||
jujutsu?: JujutsuState;
|
||||
isGit: true;
|
||||
repoRoot: string;
|
||||
mainRepoRoot: string | null;
|
||||
@@ -929,6 +944,7 @@ export interface CheckoutStatusGitNonPaseo {
|
||||
}
|
||||
|
||||
export interface CheckoutStatusGitPaseo {
|
||||
jujutsu?: JujutsuState;
|
||||
isGit: true;
|
||||
repoRoot: string;
|
||||
mainRepoRoot: string;
|
||||
@@ -995,6 +1011,8 @@ export type CheckoutSnapshotFacts =
|
||||
| {
|
||||
isGit: true;
|
||||
worktreeRoot: string;
|
||||
jujutsu?: JujutsuState;
|
||||
jujutsuBaseRevision?: string;
|
||||
currentBranch: string | null;
|
||||
remoteUrl: string | null;
|
||||
absoluteGitDir: string | null;
|
||||
@@ -1300,6 +1318,8 @@ export async function renameCurrentBranch(
|
||||
cwd: string,
|
||||
newName: string,
|
||||
): Promise<{ previousBranch: string | null; currentBranch: string | null }> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
const worktreeRoot = await requireGitWorktreeRoot(cwd);
|
||||
|
||||
const previousBranch = await getCurrentBranch(cwd);
|
||||
@@ -1398,7 +1418,14 @@ export async function setCheckoutBaseBranch(input: {
|
||||
if (valid.exitCode !== 0 || !(await doesGitRefExist(input.cwd, candidate))) continue;
|
||||
const worktreeRoot = await getWorktreeRoot(input.cwd);
|
||||
if (!worktreeRoot) throw new NotGitRepoError(input.cwd);
|
||||
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate });
|
||||
let jujutsuBaseCommit: string | undefined;
|
||||
if (await findJujutsuRoot(worktreeRoot)) {
|
||||
const revision = await resolveJujutsuRevision(worktreeRoot, candidate);
|
||||
const commit = await findJujutsuCommit(worktreeRoot, revision);
|
||||
if (!commit) throw new Error(`Jujutsu base not found: ${candidate}`);
|
||||
jujutsuBaseCommit = commit;
|
||||
}
|
||||
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate, jujutsuBaseCommit });
|
||||
return candidate;
|
||||
}
|
||||
throw new Error(`Base branch not found: ${requested}`);
|
||||
@@ -1420,6 +1447,33 @@ interface BaseRefResolution {
|
||||
resolvedBaseRef: string | null;
|
||||
}
|
||||
|
||||
// The same base the checkout facts compare a jj workspace against, without the rest of the
|
||||
// facts (upstream status, pull request lookup).
|
||||
async function resolveJujutsuBaseForCwd(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<{ resolvedBaseRef: string | null; revision: string }> {
|
||||
if (context?.facts?.isGit && context.facts.jujutsuBaseRevision) {
|
||||
return {
|
||||
resolvedBaseRef: context.facts.resolvedBaseRef,
|
||||
revision: context.facts.jujutsuBaseRevision,
|
||||
};
|
||||
}
|
||||
|
||||
const ownership = await getPaseoWorktreeForCwd(cwd, { context });
|
||||
const metadata = ownership.isPaseoOwnedWorktree
|
||||
? await readPaseoWorktreeMetadata(ownership.worktreeRoot)
|
||||
: null;
|
||||
const resolvedBaseRef =
|
||||
storedBaseRefFromMetadata(metadata) ?? (await resolveBaseRef(cwd, context));
|
||||
const { revision } = await resolveJujutsuComparisonBase(
|
||||
cwd,
|
||||
resolvedBaseRef,
|
||||
metadata?.jujutsuBaseCommit,
|
||||
);
|
||||
return { resolvedBaseRef, revision };
|
||||
}
|
||||
|
||||
async function resolveBaseRefForCwd(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
@@ -1471,6 +1525,9 @@ function resolveOperationBaseRef(input: {
|
||||
// Untracked files count whatever `status.showUntrackedFiles` says: archive warns from this before
|
||||
// it removes a worktree, and a file nobody added yet is still work to lose.
|
||||
async function isWorkingTreeDirty(cwd: string, context?: CheckoutContext): Promise<boolean> {
|
||||
const jjRoot = await findJujutsuRoot(cwd);
|
||||
if (jjRoot) return (await getJujutsuDiff(jjRoot, {})).length > 0;
|
||||
|
||||
const { stdout } = await getRunGitCommand(context)(
|
||||
["status", "--porcelain", "--untracked-files=normal"],
|
||||
{
|
||||
@@ -2335,6 +2392,26 @@ async function resolveFactsPullRequestLookupTarget(input: {
|
||||
return target;
|
||||
}
|
||||
|
||||
async function resolveJujutsuPullRequestTarget(
|
||||
cwd: string,
|
||||
change: JujutsuState,
|
||||
context?: CheckoutContext,
|
||||
): Promise<PullRequestStatusLookupTarget | null> {
|
||||
const { stdout } = await getRunGitCommand(context)(
|
||||
["for-each-ref", "--format=%(refname)%00%(objectname)", "refs/remotes/origin/"],
|
||||
{ cwd, envOverlay: READ_ONLY_GIT_ENV },
|
||||
);
|
||||
const candidates = stdout
|
||||
.trim()
|
||||
.split("\n")
|
||||
.flatMap((line) => {
|
||||
const [ref, headSha] = line.split("\0");
|
||||
const headRef = ref.slice("refs/remotes/origin/".length);
|
||||
return headSha && change.bookmarks.includes(headRef) ? [{ headRef, headSha }] : [];
|
||||
});
|
||||
return candidates.length === 1 ? candidates[0] : null;
|
||||
}
|
||||
|
||||
export async function getCheckoutSnapshotFacts(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
@@ -2349,7 +2426,15 @@ async function collectCheckoutSnapshotFacts(
|
||||
cwd: string,
|
||||
context: CheckoutContext,
|
||||
): Promise<CheckoutSnapshotFacts> {
|
||||
const provider = await resolveCheckoutProvider(cwd);
|
||||
let jujutsu = await provider.readChange();
|
||||
|
||||
const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: true });
|
||||
if (provider.kind === "jujutsu" && !inspected) {
|
||||
throw new Error(
|
||||
"Paseo requires a colocated Jujutsu checkout. Enable colocation with jj git colocation enable.",
|
||||
);
|
||||
}
|
||||
if (!inspected) {
|
||||
return { isGit: false };
|
||||
}
|
||||
@@ -2402,27 +2487,41 @@ async function collectCheckoutSnapshotFacts(
|
||||
context,
|
||||
})
|
||||
: null;
|
||||
let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
|
||||
cwd,
|
||||
inspected,
|
||||
metadata: paseoWorktreeMetadata,
|
||||
branchRemoteName,
|
||||
branchMergeRef,
|
||||
branchRemoteUrl,
|
||||
resolvedBaseRef,
|
||||
context,
|
||||
});
|
||||
pullRequestLookupTarget = await addHeadShaToPullRequestLookupTarget(
|
||||
cwd,
|
||||
pullRequestLookupTarget,
|
||||
context,
|
||||
);
|
||||
let pullRequestLookupTarget: PullRequestStatusLookupTarget | null;
|
||||
let jujutsuBaseRevision: string | undefined;
|
||||
if (jujutsu) {
|
||||
const base = await resolveJujutsuComparisonBase(
|
||||
cwd,
|
||||
resolvedBaseRef,
|
||||
paseoWorktreeMetadata?.jujutsuBaseCommit,
|
||||
);
|
||||
jujutsuBaseRevision = base.revision;
|
||||
jujutsu = { ...jujutsu, baseBookmarkMissing: base.bookmarkMissing };
|
||||
pullRequestLookupTarget = await resolveJujutsuPullRequestTarget(cwd, jujutsu, context);
|
||||
} else {
|
||||
pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
|
||||
cwd,
|
||||
inspected,
|
||||
metadata: paseoWorktreeMetadata,
|
||||
branchRemoteName,
|
||||
branchMergeRef,
|
||||
branchRemoteUrl,
|
||||
resolvedBaseRef,
|
||||
context,
|
||||
});
|
||||
pullRequestLookupTarget = await addHeadShaToPullRequestLookupTarget(
|
||||
cwd,
|
||||
pullRequestLookupTarget,
|
||||
context,
|
||||
);
|
||||
}
|
||||
const upstreamStatus = resolveUpstreamStatus(
|
||||
await upstreamTrackingPromise,
|
||||
branchRemoteName !== null && branchMergeRef !== null,
|
||||
);
|
||||
|
||||
return {
|
||||
...(jujutsu ? { jujutsu, jujutsuBaseRevision } : {}),
|
||||
isGit: true,
|
||||
worktreeRoot: inspected.worktreeRoot,
|
||||
currentBranch: inspected.currentBranch,
|
||||
@@ -2682,6 +2781,7 @@ export async function getCheckoutStatus(
|
||||
|
||||
if (paseoWorktree.isPaseoOwnedWorktree && baseRef) {
|
||||
return {
|
||||
jujutsu: facts.jujutsu,
|
||||
isGit: true,
|
||||
repoRoot: worktreeRoot,
|
||||
mainRepoRoot: mainRepoRoot ?? worktreeRoot,
|
||||
@@ -2699,6 +2799,7 @@ export async function getCheckoutStatus(
|
||||
}
|
||||
|
||||
return {
|
||||
jujutsu: facts.jujutsu,
|
||||
isGit: true,
|
||||
repoRoot: worktreeRoot,
|
||||
mainRepoRoot:
|
||||
@@ -2943,6 +3044,14 @@ export async function listCheckoutCommits({
|
||||
cwd: string;
|
||||
context?: CheckoutContext;
|
||||
}): Promise<CheckoutCommitsResult> {
|
||||
// jj checkouts have no current branch; list their changes instead.
|
||||
const jujutsuRoot = await findJujutsuRoot(cwd);
|
||||
if (jujutsuRoot) {
|
||||
const { resolvedBaseRef, revision } = await resolveJujutsuBaseForCwd(jujutsuRoot, context);
|
||||
const commits = await listJujutsuCommits(jujutsuRoot, revision, CHECKOUT_BASE_COMMIT_LIMIT);
|
||||
return { baseRef: resolvedBaseRef ? branchNameFromRef(resolvedBaseRef) : null, commits };
|
||||
}
|
||||
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
if (!currentBranch) {
|
||||
return { baseRef: null, commits: [] };
|
||||
@@ -3336,6 +3445,18 @@ export async function getCheckoutShortstat(
|
||||
context?: CheckoutContext,
|
||||
options?: CheckoutReadCacheOptions,
|
||||
): Promise<CheckoutShortstat | null> {
|
||||
const jjRoot = await findJujutsuRoot(cwd);
|
||||
if (jjRoot) {
|
||||
const files = parseJujutsuDiff(await getJujutsuDiff(jjRoot, {}));
|
||||
return files.reduce(
|
||||
(total, file) => ({
|
||||
additions: total.additions + file.additions,
|
||||
deletions: total.deletions + file.deletions,
|
||||
}),
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
}
|
||||
|
||||
return getOrLoadCheckoutShortstat(cwd, context, options);
|
||||
}
|
||||
|
||||
@@ -3946,6 +4067,16 @@ export async function getCheckoutDiff(
|
||||
compare: CheckoutDiffCompare,
|
||||
context?: CheckoutContext,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CheckoutDiffResult> {
|
||||
const provider = await resolveCheckoutProvider(cwd);
|
||||
return provider.readDiff(compare, context, signal);
|
||||
}
|
||||
|
||||
export async function getGitCheckoutDiff(
|
||||
cwd: string,
|
||||
compare: CheckoutDiffCompare,
|
||||
context?: CheckoutContext,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CheckoutDiffResult> {
|
||||
cwd = await requireGitWorktreeRoot(cwd);
|
||||
|
||||
@@ -4087,6 +4218,8 @@ export async function commitChanges(
|
||||
cwd: string,
|
||||
options: { message: string; addAll?: boolean },
|
||||
): Promise<void> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
if (options.addAll ?? true) {
|
||||
await runGitCommand(["add", "-A"], { cwd, timeout: 120_000 });
|
||||
@@ -4102,6 +4235,12 @@ export async function commitAll(cwd: string, message: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function discardChanges(cwd: string, pathspecs: string[]): Promise<void> {
|
||||
const jujutsuRoot = await findJujutsuRoot(cwd);
|
||||
if (jujutsuRoot) {
|
||||
await restoreJujutsuPaths(jujutsuRoot, pathspecs);
|
||||
return;
|
||||
}
|
||||
|
||||
const worktreeRoot = await requireGitWorktreeRoot(cwd);
|
||||
if (pathspecs.length === 0) {
|
||||
return;
|
||||
@@ -4232,6 +4371,8 @@ export async function mergeToBase(
|
||||
options: MergeToBaseOptions = {},
|
||||
context?: CheckoutContext,
|
||||
): Promise<string> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
const { storedBaseRef, resolvedBaseRef } = await resolveBaseRefForCwd(cwd, context);
|
||||
@@ -4304,6 +4445,8 @@ export async function mergeFromBase(
|
||||
options: MergeFromBaseOptions = {},
|
||||
context?: CheckoutContext,
|
||||
): Promise<void> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
if (!currentBranch || currentBranch === "HEAD") {
|
||||
@@ -4411,6 +4554,8 @@ async function detectAndThrowMergeFromBaseConflict(
|
||||
}
|
||||
|
||||
export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService): Promise<void> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
if (!currentBranch || currentBranch === "HEAD") {
|
||||
@@ -4442,6 +4587,8 @@ export async function pushCurrentBranch(
|
||||
forgeService?: ForgeService,
|
||||
context?: CheckoutContext,
|
||||
): Promise<void> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
if (!currentBranch || currentBranch === "HEAD") {
|
||||
@@ -4809,6 +4956,8 @@ export async function createPullRequest(
|
||||
forgeService: ForgeService = createGitHubService(),
|
||||
context?: CheckoutContext,
|
||||
): Promise<{ url: string; number: number }> {
|
||||
await assertGitMutationAllowed(cwd);
|
||||
|
||||
await requireGitRepo(cwd);
|
||||
|
||||
const head = options.head ?? (await getCurrentBranch(cwd));
|
||||
@@ -4851,10 +5000,17 @@ export async function getPullRequestStatus(
|
||||
options?: CheckoutReadCacheOptions,
|
||||
context?: CheckoutContext,
|
||||
): Promise<PullRequestStatusResult> {
|
||||
const [headSha, head] = await Promise.all([
|
||||
getCurrentHeadSha(cwd, context),
|
||||
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
|
||||
]);
|
||||
const facts = context?.facts;
|
||||
const jujutsu = facts?.isGit && facts.jujutsu;
|
||||
const [headSha, head] = jujutsu
|
||||
? [
|
||||
facts.pullRequestLookupTarget?.headSha ?? null,
|
||||
facts.pullRequestLookupTarget?.headRef ?? null,
|
||||
]
|
||||
: await Promise.all([
|
||||
getCurrentHeadSha(cwd, context),
|
||||
facts?.isGit ? facts.currentBranch : getCurrentBranch(cwd, context),
|
||||
]);
|
||||
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
|
||||
if (!options?.force) {
|
||||
const cached = pullRequestStatusCache.get(cacheKey);
|
||||
@@ -4950,7 +5106,7 @@ function getUnavailablePullRequestStatus(
|
||||
}
|
||||
if (
|
||||
facts?.isGit === true &&
|
||||
facts.paseoWorktree.isPaseoOwnedWorktree &&
|
||||
(facts.paseoWorktree.isPaseoOwnedWorktree || facts.jujutsu) &&
|
||||
facts.pullRequestLookupTarget === null
|
||||
) {
|
||||
return buildPullRequestStatusResult(null, "authenticated");
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
import { parseDiff, type ParsedDiffFile } from "../server/utils/diff-highlighter.js";
|
||||
import { unquoteGitPath } from "./git-quoted-path.js";
|
||||
import { stat, readFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import pLimit from "p-limit";
|
||||
import { z } from "zod";
|
||||
import { execCommand } from "./spawn.js";
|
||||
|
||||
const commands = pLimit(2);
|
||||
|
||||
export interface JujutsuState {
|
||||
changeId: string;
|
||||
commitId: string;
|
||||
description: string;
|
||||
bookmarks: string[];
|
||||
hasConflicts: boolean;
|
||||
nearestBookmark: string | null;
|
||||
baseBookmarkMissing?: boolean;
|
||||
hasRemotes: boolean;
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await stat(path);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Stop at the nearest checkout boundary, including a nested Git repository.
|
||||
export async function findJujutsuRoot(cwd: string): Promise<string | null> {
|
||||
let current = resolve(cwd);
|
||||
while (true) {
|
||||
if (await exists(join(current, ".jj"))) return current;
|
||||
if (await exists(join(current, ".git"))) return null;
|
||||
|
||||
const parent = dirname(current);
|
||||
if (parent === current) return null;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
interface JujutsuCommandOptions {
|
||||
snapshot?: boolean;
|
||||
atOperation?: string;
|
||||
write?: boolean;
|
||||
signal?: AbortSignal;
|
||||
timeout?: number;
|
||||
nonInteractive?: boolean;
|
||||
}
|
||||
|
||||
export async function runJujutsu(
|
||||
cwd: string,
|
||||
args: string[],
|
||||
options?: JujutsuCommandOptions,
|
||||
): Promise<string> {
|
||||
return (await runJujutsuCommand(cwd, args, options)).stdout;
|
||||
}
|
||||
|
||||
function runJujutsuCommand(cwd: string, args: string[], options?: JujutsuCommandOptions) {
|
||||
let mode: string[] = [];
|
||||
if (options?.atOperation) mode = ["--at-operation", options.atOperation];
|
||||
else if (options?.snapshot) mode = ["--no-integrate-operation"];
|
||||
else if (!options?.write) mode = ["--ignore-working-copy"];
|
||||
|
||||
return commands(() =>
|
||||
execCommand("jj", ["--no-pager", "--color=never", ...mode, ...args], {
|
||||
cwd,
|
||||
signal: options?.signal,
|
||||
timeout: options?.timeout ?? 30_000,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
...(options?.nonInteractive ? { envOverlay: { GIT_TERMINAL_PROMPT: "0" } } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getJujutsuState(cwd: string): Promise<JujutsuState> {
|
||||
const [output, nearest, remotes] = await Promise.all([
|
||||
readJujutsuChange(cwd),
|
||||
runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"heads(::@ & bookmarks())",
|
||||
"-T",
|
||||
'json(local_bookmarks.map(|b| b.name())) ++ "\\n"',
|
||||
]),
|
||||
exists(join(cwd, ".git")).then((colocated) => (colocated ? listJujutsuGitRemotes(cwd) : [])),
|
||||
]);
|
||||
const nearestBookmark =
|
||||
nearest
|
||||
.trimEnd()
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.flatMap((line) => z.array(z.string()).parse(JSON.parse(line)))[0] ?? null;
|
||||
|
||||
const [changeId, commitId, description, bookmarks, hasConflicts] = output;
|
||||
return {
|
||||
changeId,
|
||||
commitId,
|
||||
description,
|
||||
bookmarks,
|
||||
hasConflicts,
|
||||
nearestBookmark,
|
||||
hasRemotes: remotes.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJujutsuChange(cwd: string) {
|
||||
const output = await runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@",
|
||||
"-T",
|
||||
'json(change_id) ++ "\\n" ++ json(commit_id) ++ "\\n" ++ json(description) ++ "\\n" ++ json(local_bookmarks.map(|b| b.name())) ++ "\\n" ++ json(conflict)',
|
||||
]);
|
||||
return z
|
||||
.tuple([z.string().min(1), z.string().min(1), z.string(), z.array(z.string()), z.boolean()])
|
||||
.parse(
|
||||
output
|
||||
.trimEnd()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getJujutsuDiff(
|
||||
cwd: string,
|
||||
options: { baseRef?: string; ignoreWhitespace?: boolean; signal?: AbortSignal },
|
||||
): Promise<string> {
|
||||
const baseRef = options.baseRef ? await resolveJujutsuRevision(cwd, options.baseRef) : undefined;
|
||||
// Snapshot into an unintegrated operation: include disk edits without moving @,
|
||||
// importing/exporting Git refs, or updating another agent's working copy. Comparing
|
||||
// from the fork point keeps a base that has moved on (e.g. after a fetch) from
|
||||
// showing its newer changes as reverted here.
|
||||
return runJujutsu(
|
||||
cwd,
|
||||
[
|
||||
"diff",
|
||||
"--git",
|
||||
...(baseRef ? ["--from", `fork_point((${baseRef}) | @)`, "--to", "@"] : ["-r", "@"]),
|
||||
...(options.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
],
|
||||
{ snapshot: true, signal: options.signal },
|
||||
);
|
||||
}
|
||||
|
||||
// Discard puts files back as they are in the working-copy change's parent, as Git's discard
|
||||
// restores them from HEAD.
|
||||
export async function restoreJujutsuPaths(cwd: string, paths: string[]): Promise<void> {
|
||||
if (paths.length === 0) return;
|
||||
const filesets = paths.map((path) => `root-file:${JSON.stringify(path)}`);
|
||||
await runJujutsu(cwd, ["restore", "--", ...filesets], { write: true, timeout: 60_000 });
|
||||
}
|
||||
|
||||
export async function assertGitMutationAllowed(cwd: string): Promise<void> {
|
||||
if (await findJujutsuRoot(cwd)) {
|
||||
throw new Error(
|
||||
"This checkout uses Jujutsu. Use jj to change revisions, describe changes, or publish bookmarks.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createJujutsuWorkspace(options: {
|
||||
cwd: string;
|
||||
path: string;
|
||||
name: string;
|
||||
base: string;
|
||||
}): Promise<void> {
|
||||
await runJujutsu(
|
||||
options.cwd,
|
||||
[
|
||||
"workspace",
|
||||
"add",
|
||||
"--colocate",
|
||||
"--name",
|
||||
options.name,
|
||||
"-r",
|
||||
options.base,
|
||||
"--",
|
||||
options.path,
|
||||
],
|
||||
{ write: true, timeout: 120_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function getJujutsuWorkspaceName(cwd: string, path: string): Promise<string | null> {
|
||||
const output = await runJujutsu(cwd, [
|
||||
"workspace",
|
||||
"list",
|
||||
"-T",
|
||||
'json(name) ++ "\\n" ++ json(root) ++ "\\n"',
|
||||
]);
|
||||
const fields = output.trimEnd().split("\n");
|
||||
for (let i = 0; i + 1 < fields.length; i += 2) {
|
||||
const name = z.string().parse(JSON.parse(fields[i]));
|
||||
const root = z
|
||||
.string()
|
||||
.nullable()
|
||||
.parse(JSON.parse(fields[i + 1]));
|
||||
if (root && resolve(root) === resolve(path)) return name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function removeJujutsuWorkspace(cwd: string, path: string): Promise<boolean> {
|
||||
const name = await getJujutsuWorkspaceName(cwd, path);
|
||||
if (!name || resolve(cwd) === resolve(path)) return false;
|
||||
await runJujutsu(dirname(path), ["-R", path, "workspace", "remove", "--", name], {
|
||||
write: true,
|
||||
timeout: 120_000,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function clearMissingJujutsuWorkspace(cwd: string, path: string): Promise<void> {
|
||||
if (await exists(path)) throw new Error(`Cannot restore over an existing directory: ${path}`);
|
||||
const name = await getJujutsuWorkspaceName(cwd, path);
|
||||
if (name) await runJujutsu(cwd, ["workspace", "forget", "--", name]);
|
||||
|
||||
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain", "-z"], { cwd });
|
||||
if (
|
||||
stdout
|
||||
.split("\0")
|
||||
.some((field) => field.startsWith("worktree ") && resolve(field.slice(9)) === resolve(path))
|
||||
) {
|
||||
if (await exists(path)) throw new Error(`Cannot restore over an existing directory: ${path}`);
|
||||
await runGitCommand(["worktree", "remove", "--force", "--", path], { cwd });
|
||||
}
|
||||
}
|
||||
|
||||
export async function snapshotJujutsuWorkingCopy(cwd: string): Promise<string> {
|
||||
const commit = (
|
||||
await runJujutsu(cwd, ["log", "--no-graph", "-r", "@", "-T", "commit_id"], { write: true })
|
||||
).trim();
|
||||
if (!/^[a-f0-9]{40}$/.test(commit))
|
||||
throw new Error("Jujutsu returned an invalid recovery commit");
|
||||
return commit;
|
||||
}
|
||||
|
||||
export async function saveJujutsuRecoveryCommit(cwd: string): Promise<string> {
|
||||
// Archive integrates the snapshot so other workspaces can resolve it for restore.
|
||||
const commit = await snapshotJujutsuWorkingCopy(cwd);
|
||||
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], { cwd });
|
||||
return commit;
|
||||
}
|
||||
|
||||
export async function getJujutsuOperationHeads(cwd: string): Promise<string | null> {
|
||||
const root = await findJujutsuRoot(cwd);
|
||||
if (!root) return null;
|
||||
const repository = join(root, ".jj", "repo");
|
||||
const info = await stat(repository);
|
||||
if (info.isDirectory()) return join(repository, "op_heads", "heads");
|
||||
if (info.size > 64 * 1024) throw new Error("Jujutsu repository pointer is too large");
|
||||
const pointer = (await readFile(repository, "utf8")).trim();
|
||||
return join(resolve(root, ".jj", pointer), "op_heads", "heads");
|
||||
}
|
||||
|
||||
async function listJujutsuGitRemotes(cwd: string): Promise<string[]> {
|
||||
const { stdout } = await runGitCommand(["remote"], { cwd });
|
||||
return stdout.split("\n").filter(Boolean);
|
||||
}
|
||||
|
||||
function findTrackingRemote(remotes: string[], trackingRef: string): string | null {
|
||||
return (
|
||||
remotes
|
||||
.filter((remote) => trackingRef.startsWith(`${remote}/`))
|
||||
.sort((a, b) => b.length - a.length)[0] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export async function findJujutsuRemoteForBase(cwd: string, base: string): Promise<string | null> {
|
||||
const remotePrefix = "refs/remotes/";
|
||||
if (base.startsWith("refs/") && !base.startsWith(remotePrefix)) return null;
|
||||
|
||||
const remotes = await listJujutsuGitRemotes(cwd);
|
||||
if (base.startsWith(remotePrefix))
|
||||
return findTrackingRemote(remotes, base.slice(remotePrefix.length));
|
||||
|
||||
const separator = base.lastIndexOf("@");
|
||||
const nativeRemote = separator > 0 ? base.slice(separator + 1) : null;
|
||||
if (nativeRemote && remotes.includes(nativeRemote)) return nativeRemote;
|
||||
|
||||
return findTrackingRemote(remotes, base);
|
||||
}
|
||||
|
||||
// Convert Git-style remote refs at the boundary. Native jj revsets pass through unchanged.
|
||||
export async function resolveJujutsuRevision(cwd: string, revision: string): Promise<string> {
|
||||
const resolved = await findJujutsuRevision(cwd, revision);
|
||||
if (!resolved) throw new Error(`Jujutsu revision not found: ${revision}`);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
async function findJujutsuRevision(cwd: string, revision: string): Promise<string | null> {
|
||||
let ref = revision.startsWith("refs/") ? revision : null;
|
||||
if (
|
||||
!ref &&
|
||||
revision.includes("/") &&
|
||||
findTrackingRemote(await listJujutsuGitRemotes(cwd), revision)
|
||||
) {
|
||||
ref = `refs/remotes/${revision}`;
|
||||
}
|
||||
if (!ref) return revision;
|
||||
|
||||
const result = await runGitCommand(
|
||||
["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`],
|
||||
{ cwd, acceptExitCodes: [0, 1] },
|
||||
);
|
||||
return result.exitCode === 0 ? result.stdout.trim() : null;
|
||||
}
|
||||
|
||||
export async function findJujutsuCommit(cwd: string, revision: string): Promise<string | null> {
|
||||
const output = await runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
`present(${revision})`,
|
||||
"--limit",
|
||||
"2",
|
||||
"-T",
|
||||
'commit_id ++ "\\n"',
|
||||
]);
|
||||
const commits = output.trim().split("\n").filter(Boolean);
|
||||
return commits.length === 1 ? commits[0] : null;
|
||||
}
|
||||
|
||||
export async function resolveJujutsuComparisonBase(
|
||||
cwd: string,
|
||||
baseRef: string | null,
|
||||
savedCommit?: string,
|
||||
): Promise<{ revision: string; bookmarkMissing: boolean }> {
|
||||
if (!baseRef) return { revision: "trunk()", bookmarkMissing: false };
|
||||
|
||||
const revision = await findJujutsuRevision(cwd, baseRef);
|
||||
const commit = revision ? await findJujutsuCommit(cwd, revision) : null;
|
||||
if (commit) return { revision: commit, bookmarkMissing: false };
|
||||
|
||||
const fallback = savedCommit ? await findJujutsuCommit(cwd, savedCommit) : null;
|
||||
return { revision: fallback ?? "trunk()", bookmarkMissing: true };
|
||||
}
|
||||
|
||||
export function parseJujutsuDiff(diff: string): Array<ParsedDiffFile & { oldPath: string | null }> {
|
||||
const files: Array<ParsedDiffFile & { oldPath: string | null }> = [];
|
||||
for (const section of diff.split(/(?=^diff --git )/m)) {
|
||||
const rename = section.match(/^rename from (.*)$/m);
|
||||
for (const file of parseDiff(section)) {
|
||||
files.push({
|
||||
...file,
|
||||
oldPath: rename ? unquoteGitPath(rename[1]) : null,
|
||||
...(/^Binary files .* differ$/m.test(section) ? { status: "binary" as const } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
export interface JujutsuCommitRecord {
|
||||
sha: string;
|
||||
shortSha: string;
|
||||
subject: string;
|
||||
authorName: string;
|
||||
authorDate: string;
|
||||
isOnRemote: boolean;
|
||||
isOnBase: boolean;
|
||||
files: Array<{
|
||||
path: string;
|
||||
additions: number;
|
||||
deletions: number;
|
||||
status: "added" | "modified" | "deleted" | "renamed";
|
||||
}>;
|
||||
jujutsu: {
|
||||
changeId: string;
|
||||
bookmarks: string[];
|
||||
isWorkingCopy: boolean;
|
||||
isEmpty: boolean;
|
||||
hasConflicts: boolean;
|
||||
operationId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
// One JSON array per change, so descriptions and paths need no further escaping.
|
||||
const COMMIT_FIELDS = [
|
||||
"json(commit_id)",
|
||||
"json(change_id.short())",
|
||||
"json(change_id)",
|
||||
"json(description.first_line())",
|
||||
"json(author.name())",
|
||||
"json(author.timestamp())",
|
||||
"json(local_bookmarks.map(|b| b.name()))",
|
||||
"current_working_copy",
|
||||
"empty",
|
||||
"conflict",
|
||||
'"[" ++ diff.stat().files().map(|e| "[" ++ json(e.path().display()) ++ "," ++ json(e.status()) ++ "," ++ e.lines_added() ++ "," ++ e.lines_removed() ++ "]").join(",") ++ "]"',
|
||||
];
|
||||
const COMMIT_TEMPLATE = `"[" ++ ${COMMIT_FIELDS.join(' ++ "," ++ ')} ++ "]\\n"`;
|
||||
|
||||
const CommitRowSchema = z.tuple([
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.array(z.string()),
|
||||
z.boolean(),
|
||||
z.boolean(),
|
||||
z.boolean(),
|
||||
z.array(z.tuple([z.string(), z.string(), z.number(), z.number()])),
|
||||
]);
|
||||
|
||||
function fileStatus(status: string): JujutsuCommitRecord["files"][number]["status"] {
|
||||
if (status === "removed") return "deleted";
|
||||
if (status === "renamed") return "renamed";
|
||||
if (status === "added" || status === "copied") return "added";
|
||||
return "modified";
|
||||
}
|
||||
|
||||
async function readCommits(cwd: string, revset: string, limit?: number) {
|
||||
const { stdout, stderr } = await runJujutsuCommand(
|
||||
cwd,
|
||||
[
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
revset,
|
||||
...(limit ? ["--limit", String(limit)] : []),
|
||||
"-T",
|
||||
COMMIT_TEMPLATE,
|
||||
],
|
||||
{ snapshot: true },
|
||||
);
|
||||
const rows = stdout
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => CommitRowSchema.parse(JSON.parse(line)));
|
||||
return { rows, operationId: parseUncommittedOperationId(stderr) };
|
||||
}
|
||||
|
||||
// A snapshot and a Git import each leave an unintegrated operation, the import on top of the
|
||||
// snapshot. The last one printed is the one that can see every commit the command read.
|
||||
function parseUncommittedOperationId(stderr: string): string | undefined {
|
||||
const matches = stderr.matchAll(
|
||||
/^(?:Snapshot o|O)peration left uncommitted because --no-integrate-operation was requested: ([0-9a-f]+)\r?$/gm,
|
||||
);
|
||||
return [...matches].at(-1)?.[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* The jj counterpart of the Changes pane's commit list: this workspace's changes since the
|
||||
* base (newest first, including the working copy), then the base's recent history.
|
||||
*/
|
||||
export async function listJujutsuCommits(
|
||||
cwd: string,
|
||||
baseRevision: string,
|
||||
baseLimit: number,
|
||||
): Promise<JujutsuCommitRecord[]> {
|
||||
const forkPoint = `fork_point(${baseRevision} | @)`;
|
||||
const task = `${forkPoint}..@`;
|
||||
const history = `ancestors(${forkPoint}, ${baseLimit})`;
|
||||
|
||||
const [taskRows, historyRows, pushed] = await Promise.all([
|
||||
readCommits(cwd, task),
|
||||
readCommits(cwd, history, baseLimit),
|
||||
runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
`(${task} | ${history}) & ::remote_bookmarks()`,
|
||||
"-T",
|
||||
'commit_id ++ "\\n"',
|
||||
]),
|
||||
]);
|
||||
const onRemote = new Set(pushed.split("\n").filter(Boolean));
|
||||
|
||||
const toRecord = (
|
||||
row: z.infer<typeof CommitRowSchema>,
|
||||
isOnBase: boolean,
|
||||
operationId?: string,
|
||||
) => {
|
||||
const [sha, shortChange, changeId, subject, authorName, authorDate, bookmarks] = row;
|
||||
const [, , , , , , , isWorkingCopy, isEmpty, hasConflicts, files] = row;
|
||||
return {
|
||||
sha,
|
||||
shortSha: shortChange,
|
||||
subject,
|
||||
authorName,
|
||||
authorDate,
|
||||
isOnRemote: onRemote.has(sha),
|
||||
isOnBase,
|
||||
files: files.map(([path, status, additions, deletions]) => ({
|
||||
path,
|
||||
additions,
|
||||
deletions,
|
||||
status: fileStatus(status),
|
||||
})),
|
||||
jujutsu: { changeId, bookmarks, isWorkingCopy, isEmpty, hasConflicts, operationId },
|
||||
};
|
||||
};
|
||||
return [
|
||||
...taskRows.rows.map((row) => toRecord(row, false, taskRows.operationId)),
|
||||
...historyRows.rows.map((row) => toRecord(row, true, historyRows.operationId)),
|
||||
];
|
||||
}
|
||||
|
||||
export interface JujutsuChangeSummary {
|
||||
changeId: string;
|
||||
commitId: string;
|
||||
description: string;
|
||||
bookmarks: string[];
|
||||
workingCopies: string[];
|
||||
isEmpty: boolean;
|
||||
authorDate: string;
|
||||
}
|
||||
|
||||
const SEARCH_TEMPLATE = `"[" ++ ${[
|
||||
"json(change_id)",
|
||||
"json(commit_id)",
|
||||
"json(description.first_line())",
|
||||
"json(local_bookmarks.map(|b| b.name()))",
|
||||
"json(self.working_copies().map(|w| w.name()))",
|
||||
"empty",
|
||||
"json(author.timestamp())",
|
||||
].join(' ++ "," ++ ')} ++ "]\\n"`;
|
||||
|
||||
const SearchRowSchema = z.tuple([
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.array(z.string()),
|
||||
z.array(z.string()),
|
||||
z.boolean(),
|
||||
z.string(),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Changes to start new work on, across the repository rather than this workspace's line:
|
||||
* everything still mutable (every workspace's work and side branches), bookmarks, and recent
|
||||
* trunk history. A query matches descriptions, bookmark names, and change or commit ID prefixes.
|
||||
*/
|
||||
export async function searchJujutsuChanges(
|
||||
cwd: string,
|
||||
query: string,
|
||||
limit = 50,
|
||||
): Promise<JujutsuChangeSummary[]> {
|
||||
const scope = "(mutable() | bookmarks() | remote_bookmarks() | ancestors(trunk(), 20)) ~ root()";
|
||||
|
||||
// Build the filter from string literals only; the query never becomes revset syntax.
|
||||
const text = [...query]
|
||||
.filter((char) => char >= " " && char !== "\u007f")
|
||||
.join("")
|
||||
.trim();
|
||||
let revset = scope;
|
||||
if (text) {
|
||||
const literal = JSON.stringify(text);
|
||||
const terms = [`description(substring-i:${literal})`, `bookmarks(substring:${literal})`];
|
||||
if (/^[k-z]+$/.test(text)) terms.push(`change_id(${text})`);
|
||||
if (/^[0-9a-f]+$/.test(text)) terms.push(`commit_id(${text})`);
|
||||
revset = `(${scope}) & (${terms.join(" | ")})`;
|
||||
}
|
||||
|
||||
const output = await runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
revset,
|
||||
"--limit",
|
||||
String(limit),
|
||||
"-T",
|
||||
SEARCH_TEMPLATE,
|
||||
]);
|
||||
return output
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const [changeId, commitId, description, bookmarks, workingCopies, isEmpty, authorDate] =
|
||||
SearchRowSchema.parse(JSON.parse(line));
|
||||
return { changeId, commitId, description, bookmarks, workingCopies, isEmpty, authorDate };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { CheckoutStatusResponse } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
getCheckoutSnapshotFacts,
|
||||
getGitCheckoutDiff,
|
||||
TOTAL_DIFF_MAX_BYTES,
|
||||
type CheckoutContext,
|
||||
type CheckoutDiffCompare,
|
||||
type CheckoutDiffResult,
|
||||
} from "./checkout-git.js";
|
||||
import {
|
||||
findJujutsuRoot,
|
||||
getJujutsuDiff,
|
||||
getJujutsuState,
|
||||
parseJujutsuDiff,
|
||||
type JujutsuState,
|
||||
} from "./checkout-jj.js";
|
||||
|
||||
type CheckoutVcs = NonNullable<CheckoutStatusResponse["payload"]["vcs"]>;
|
||||
type ReadDiff = (
|
||||
compare: CheckoutDiffCompare,
|
||||
context?: CheckoutContext,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<CheckoutDiffResult>;
|
||||
|
||||
interface CheckoutProvider {
|
||||
kind: "git" | "jujutsu";
|
||||
root: string;
|
||||
readDiff: ReadDiff;
|
||||
readChange(): Promise<JujutsuState | undefined>;
|
||||
}
|
||||
|
||||
export function describeCheckoutVcs(
|
||||
kind: CheckoutVcs["kind"],
|
||||
options?: { hasRemote: boolean; hasForge: boolean; hasFetchRemote?: boolean },
|
||||
): CheckoutVcs {
|
||||
return {
|
||||
kind,
|
||||
capabilities: {
|
||||
isolatedWorkspace: kind !== "none",
|
||||
gitMutations: kind === "git",
|
||||
...(kind === "jujutsu"
|
||||
? {
|
||||
describe: true,
|
||||
newChange: true,
|
||||
publishBookmark: options?.hasRemote ?? false,
|
||||
fetch: options?.hasFetchRemote ?? options?.hasRemote ?? false,
|
||||
createPullRequest: options?.hasForge ?? false,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolveCheckoutProvider(cwd: string): Promise<CheckoutProvider> {
|
||||
const root = await findJujutsuRoot(cwd);
|
||||
if (root) {
|
||||
return {
|
||||
kind: "jujutsu",
|
||||
root,
|
||||
readDiff: (compare, context, signal) => readJujutsuDiff(root, compare, context, signal),
|
||||
readChange: () => getJujutsuState(root),
|
||||
};
|
||||
}
|
||||
|
||||
// The Git implementation also probes whether this is an ordinary directory.
|
||||
return {
|
||||
kind: "git",
|
||||
root: cwd,
|
||||
readDiff: (compare, context, signal) => getGitCheckoutDiff(cwd, compare, context, signal),
|
||||
readChange: async () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJujutsuDiff(
|
||||
root: string,
|
||||
compare: CheckoutDiffCompare,
|
||||
context?: CheckoutContext,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CheckoutDiffResult> {
|
||||
let baseRef: string | undefined;
|
||||
if (compare.mode !== "uncommitted") {
|
||||
const facts = await getCheckoutSnapshotFacts(root, context);
|
||||
if (facts.isGit) {
|
||||
baseRef =
|
||||
!compare.baseRef || compare.baseRef === facts.resolvedBaseRef
|
||||
? facts.jujutsuBaseRevision
|
||||
: compare.baseRef;
|
||||
}
|
||||
}
|
||||
|
||||
const diff = await getJujutsuDiff(root, {
|
||||
baseRef,
|
||||
ignoreWhitespace: compare.ignoreWhitespace,
|
||||
signal,
|
||||
});
|
||||
if (Buffer.byteLength(diff, "utf8") > TOTAL_DIFF_MAX_BYTES) {
|
||||
return { diff: "", structured: [], diffTooLarge: true };
|
||||
}
|
||||
return { diff, ...(compare.includeStructured ? { structured: parseJujutsuDiff(diff) } : {}) };
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import { getCheckoutSnapshotFacts } from "./checkout-git.js";
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
import {
|
||||
findJujutsuCommit,
|
||||
findJujutsuRemoteForBase,
|
||||
getJujutsuOperationHeads,
|
||||
getJujutsuState,
|
||||
resolveJujutsuRevision,
|
||||
runJujutsu,
|
||||
} from "./checkout-jj.js";
|
||||
|
||||
const pendingActions = new Map<string, Promise<unknown>>();
|
||||
|
||||
export async function runJujutsuCheckoutAction(options: {
|
||||
cwd: string;
|
||||
expectedChangeId: string;
|
||||
action: JujutsuCheckoutAction;
|
||||
resolveForge: () => Promise<Pick<ForgeService, "createPullRequest" | "invalidate">>;
|
||||
}): Promise<string | null> {
|
||||
const { cwd, expectedChangeId, action } = options;
|
||||
const repository = await getJujutsuOperationHeads(cwd);
|
||||
if (!repository) throw new Error("This checkout does not use Jujutsu.");
|
||||
|
||||
const operation = (pendingActions.get(repository) ?? Promise.resolve())
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
if (action.kind === "fetch") {
|
||||
const remote = action.remote ?? (await resolveFetchRemote(cwd));
|
||||
await runJujutsu(
|
||||
cwd,
|
||||
["git", "fetch", ...(remote ? ["--remote", `exact:${remote}`] : [])],
|
||||
{
|
||||
write: true,
|
||||
timeout: 120_000,
|
||||
nonInteractive: true,
|
||||
},
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const current = await getJujutsuState(cwd);
|
||||
if (current.changeId !== expectedChangeId) {
|
||||
throw new Error("The working-copy change has moved. Refresh and try again.");
|
||||
}
|
||||
switch (action.kind) {
|
||||
case "describe":
|
||||
await runJujutsu(cwd, ["describe", "-r", expectedChangeId, "-m", action.description], {
|
||||
write: true,
|
||||
});
|
||||
return null;
|
||||
case "new": {
|
||||
const parent = action.parent ? await resolveSingleRevision(cwd, action.parent) : "@";
|
||||
await runJujutsu(
|
||||
cwd,
|
||||
["new", parent, ...(action.description ? ["-m", action.description] : [])],
|
||||
{ write: true },
|
||||
);
|
||||
return null;
|
||||
}
|
||||
case "publish":
|
||||
await publishBookmark(
|
||||
cwd,
|
||||
action.bookmark,
|
||||
action.remote ?? "origin",
|
||||
action.create ?? false,
|
||||
);
|
||||
return null;
|
||||
case "create_pull_request":
|
||||
return createJujutsuPullRequest(cwd, action, await options.resolveForge());
|
||||
default:
|
||||
throw new Error("Unsupported Jujutsu checkout action");
|
||||
}
|
||||
});
|
||||
pendingActions.set(repository, operation);
|
||||
try {
|
||||
return await operation;
|
||||
} finally {
|
||||
if (pendingActions.get(repository) === operation) pendingActions.delete(repository);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveFetchRemote(cwd: string): Promise<string | null> {
|
||||
const facts = await getCheckoutSnapshotFacts(cwd);
|
||||
if (!facts.isGit || !facts.resolvedBaseRef) return null;
|
||||
|
||||
return findJujutsuRemoteForBase(cwd, facts.resolvedBaseRef);
|
||||
}
|
||||
|
||||
async function resolveSingleRevision(cwd: string, name: string): Promise<string> {
|
||||
const revision = await resolveJujutsuRevision(cwd, name);
|
||||
const commit = await findJujutsuCommit(cwd, revision);
|
||||
if (!commit) throw new Error(`Choose one Jujutsu change: ${name}`);
|
||||
return commit;
|
||||
}
|
||||
|
||||
async function verifyBranchName(cwd: string, name: string): Promise<void> {
|
||||
await runGitCommand(["check-ref-format", `refs/heads/${name}`], { cwd });
|
||||
}
|
||||
|
||||
async function publishBookmark(
|
||||
cwd: string,
|
||||
bookmark: string,
|
||||
remote: string,
|
||||
create: boolean,
|
||||
): Promise<void> {
|
||||
await verifyBranchName(cwd, bookmark);
|
||||
if (create) {
|
||||
const current = await getJujutsuState(cwd);
|
||||
if (!current.bookmarks.includes(bookmark)) {
|
||||
// Create refuses to move a bookmark that already points to another change.
|
||||
await runJujutsu(cwd, ["bookmark", "create", "-r", "@", "--", bookmark], { write: true });
|
||||
}
|
||||
}
|
||||
const localCommit = await runJujutsu(cwd, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
`bookmarks(exact:${JSON.stringify(bookmark)})`,
|
||||
"-T",
|
||||
'commit_id ++ "\\n"',
|
||||
]);
|
||||
if (localCommit.trim().split("\n").length !== 1 || !localCommit.trim()) {
|
||||
throw new Error(`Choose an existing, unambiguous local bookmark: ${bookmark}`);
|
||||
}
|
||||
|
||||
await runJujutsu(cwd, ["git", "push", "--remote", remote, "--bookmark", `exact:${bookmark}`], {
|
||||
write: true,
|
||||
timeout: 120_000,
|
||||
nonInteractive: true,
|
||||
});
|
||||
}
|
||||
|
||||
async function createJujutsuPullRequest(
|
||||
cwd: string,
|
||||
action: Extract<JujutsuCheckoutAction, { kind: "create_pull_request" }>,
|
||||
forge: Pick<ForgeService, "createPullRequest" | "invalidate">,
|
||||
): Promise<string> {
|
||||
if (action.bookmark === action.base) {
|
||||
throw new Error("Choose different bookmarks for the head and base.");
|
||||
}
|
||||
await verifyBranchName(cwd, action.base);
|
||||
await publishBookmark(cwd, action.bookmark, "origin", false);
|
||||
try {
|
||||
const result = await forge.createPullRequest({
|
||||
cwd,
|
||||
head: action.bookmark,
|
||||
base: action.base,
|
||||
title: action.title,
|
||||
body: action.body,
|
||||
});
|
||||
return result.url;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Bookmark published to origin. Could not create the pull request: ${message}`, {
|
||||
cause: error,
|
||||
});
|
||||
} finally {
|
||||
forge.invalidate({ cwd });
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@ const PaseoWorktreeMetadataV1Schema = z.object({
|
||||
version: z.literal(1),
|
||||
baseRefName: z.string().min(1),
|
||||
baseRef: z.string().min(1).optional(),
|
||||
jujutsuBaseCommit: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{40}$/)
|
||||
.optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
@@ -37,6 +41,10 @@ const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
version: z.literal(2),
|
||||
baseRefName: z.string().min(1),
|
||||
baseRef: z.string().min(1).optional(),
|
||||
jujutsuBaseCommit: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{40}$/)
|
||||
.optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
@@ -254,6 +262,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
options: {
|
||||
baseRefName: string;
|
||||
baseRef?: string;
|
||||
jujutsuBaseCommit?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
worktreeManagerPluginId?: string;
|
||||
untrustedSource?: PaseoWorktreeUntrustedSource;
|
||||
@@ -271,6 +280,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
version: 1,
|
||||
baseRefName,
|
||||
...(baseRef ? { baseRef } : {}),
|
||||
jujutsuBaseCommit: options.jujutsuBaseCommit,
|
||||
...(options.changeRequestLookupTarget
|
||||
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
|
||||
: {}),
|
||||
@@ -315,6 +325,7 @@ export async function setPaseoWorktreeUntrustedSource(
|
||||
export async function setPaseoWorktreeBaseRef(input: {
|
||||
worktreeRoot: string;
|
||||
baseRef: string;
|
||||
jujutsuBaseCommit?: string;
|
||||
}): Promise<void> {
|
||||
return mutateMetadata(input.worktreeRoot, async (root) => {
|
||||
const current = await readMetadataFile(root);
|
||||
@@ -323,6 +334,7 @@ export async function setPaseoWorktreeBaseRef(input: {
|
||||
...current,
|
||||
baseRefName: branchNameFromRef(input.baseRef),
|
||||
baseRef: input.baseRef,
|
||||
jujutsuBaseCommit: input.jujutsuBaseCommit,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
import {
|
||||
findJujutsuRoot,
|
||||
createJujutsuWorkspace,
|
||||
runJujutsu,
|
||||
resolveJujutsuRevision,
|
||||
clearMissingJujutsuWorkspace,
|
||||
removeJujutsuWorkspace,
|
||||
snapshotJujutsuWorkingCopy,
|
||||
} from "./checkout-jj.js";
|
||||
import { promisify } from "util";
|
||||
import { constants as fsConstants, type Dirent, realpath } from "fs";
|
||||
import { copyFile, mkdir, readdir, rm, stat } from "fs/promises";
|
||||
@@ -273,6 +282,7 @@ export type WorktreeSource =
|
||||
| { kind: "checkout-branch"; branchName: string }
|
||||
| { kind: "restore"; branchName: string; baseRef: string | null }
|
||||
| { kind: "restore-commit"; commit: string; baseRef: string }
|
||||
| { kind: "restore-jujutsu"; commit: string; baseRef: string | null; baseCommit?: string }
|
||||
| { kind: "restore-from-base"; baseRef: string; branchName: string }
|
||||
| {
|
||||
kind: "checkout-change-request";
|
||||
@@ -307,6 +317,7 @@ export interface PreparedWorktreeBranchOff {
|
||||
|
||||
export interface CreateWorktreeOptions {
|
||||
cwd: string;
|
||||
configSourceCwd?: string;
|
||||
worktreeSlug: string;
|
||||
source: WorktreeSource;
|
||||
preparedBranchOff?: PreparedWorktreeBranchOff;
|
||||
@@ -1475,6 +1486,7 @@ export interface DeletePaseoWorktreeOptions {
|
||||
removeReason?: "archive" | "rollback";
|
||||
untrusted?: boolean;
|
||||
signal?: AbortSignal;
|
||||
jujutsuRecoveryCommit?: string;
|
||||
}
|
||||
|
||||
// Project scoping for delete: a proof for some other repo's worktree must
|
||||
@@ -1540,6 +1552,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({
|
||||
removeReason = "archive",
|
||||
untrusted = false,
|
||||
signal,
|
||||
jujutsuRecoveryCommit,
|
||||
}: DeletePaseoWorktreeOptions): Promise<void> {
|
||||
if (!worktreePath && !worktreeSlug) {
|
||||
throw new Error("worktreePath or worktreeSlug is required");
|
||||
@@ -1580,10 +1593,20 @@ async function deletePaseoWorktreeAtRepositoryRoot({
|
||||
}
|
||||
|
||||
if (await pathExists(resolvedWorktree)) {
|
||||
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: resolvedWorktree,
|
||||
teardownCwd,
|
||||
});
|
||||
}
|
||||
if ((await findJujutsuRoot(resolvedWorktree)) === resolvedWorktree) {
|
||||
await removeArchivedJujutsuWorktree(cwd, resolvedWorktree, jujutsuRecoveryCommit);
|
||||
return;
|
||||
}
|
||||
|
||||
const removedByPlugin = await prepareAndTryPluginWorktreeRemove({
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
@@ -1664,7 +1687,6 @@ async function pruneWorktreesBestEffort(cwd: string | null): Promise<void> {
|
||||
async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
cwd: string | null;
|
||||
resolvedWorktree: string;
|
||||
teardownCwds?: string[];
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
removeReason: "archive" | "rollback";
|
||||
@@ -1674,19 +1696,12 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
const {
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
untrusted,
|
||||
signal,
|
||||
} = options;
|
||||
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: resolvedWorktree,
|
||||
teardownCwd,
|
||||
});
|
||||
}
|
||||
const effectiveManagerPluginId =
|
||||
worktreeManagerPluginId !== undefined
|
||||
? worktreeManagerPluginId
|
||||
@@ -1729,13 +1744,48 @@ async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
return true;
|
||||
}
|
||||
|
||||
async function removeArchivedJujutsuWorktree(
|
||||
cwd: string | null,
|
||||
worktreePath: string,
|
||||
recoveryCommit?: string,
|
||||
): Promise<void> {
|
||||
if (!cwd || !recoveryCommit || !/^[a-f0-9]{40}$/.test(recoveryCommit)) {
|
||||
throw new Error("Missing Jujutsu workspace recovery snapshot");
|
||||
}
|
||||
|
||||
const { stdout } = await runGitCommand(
|
||||
["rev-parse", "--verify", `refs/paseo/kept-commits/${recoveryCommit}^{commit}`],
|
||||
{ cwd: worktreePath },
|
||||
);
|
||||
if (stdout.trim() !== recoveryCommit) throw new Error("Jujutsu recovery ref has changed");
|
||||
// A teardown hook or editor may have changed files since the archive record was saved.
|
||||
if ((await snapshotJujutsuWorkingCopy(worktreePath)) !== recoveryCommit) {
|
||||
throw new Error("Jujutsu working copy changed after the archive snapshot");
|
||||
}
|
||||
|
||||
await removeRegisteredJujutsuWorktree(cwd, worktreePath);
|
||||
}
|
||||
|
||||
async function removeRegisteredJujutsuWorktree(cwd: string, worktreePath: string): Promise<void> {
|
||||
await assertNoNestedLinkedWorktrees(worktreePath);
|
||||
if (!(await removeJujutsuWorkspace(cwd, worktreePath))) {
|
||||
throw new Error("Jujutsu workspace registration was not found");
|
||||
}
|
||||
}
|
||||
|
||||
export async function rollbackCreatedPaseoWorktree(
|
||||
options: DeletePaseoWorktreeOptions,
|
||||
cause: unknown,
|
||||
): Promise<never> {
|
||||
let cleanupError: unknown;
|
||||
try {
|
||||
await deletePaseoWorktree(options);
|
||||
const path = options.worktreePath;
|
||||
if (options.cwd && path && (await findJujutsuRoot(path)) === resolve(path)) {
|
||||
await assertWorktreeBelongsToRepo(options.cwd, path);
|
||||
await removeRegisteredJujutsuWorktree(options.cwd, path);
|
||||
} else {
|
||||
await deletePaseoWorktree(options);
|
||||
}
|
||||
} catch (error) {
|
||||
cleanupError = error;
|
||||
}
|
||||
@@ -1811,7 +1861,7 @@ async function listLocalBranchNames(cwd: string): Promise<Set<string>> {
|
||||
// ref may be rolled back when creation fails — never any other
|
||||
// branch that appeared in the meantime; other creators own those.
|
||||
function planCreatedLocalBranch(
|
||||
source: WorktreeSource,
|
||||
source: GitWorktreeSource,
|
||||
sourcePlan: WorktreeSourcePlan,
|
||||
): string | null {
|
||||
switch (source.kind) {
|
||||
@@ -1852,8 +1902,74 @@ export async function resolveDefaultWorktreePath(
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function createJujutsuWorktree({
|
||||
cwd,
|
||||
configSourceCwd = cwd,
|
||||
source,
|
||||
worktreeSlug,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
worktreePath: explicitWorktreePath,
|
||||
}: CreateWorktreeOptions): Promise<CreatedWorktree> {
|
||||
if (source.kind !== "branch-off" && source.kind !== "restore-jujutsu") {
|
||||
throw new Error(
|
||||
"Jujutsu workspaces support branching from a base revision. Open existing changes as local workspaces.",
|
||||
);
|
||||
}
|
||||
const worktreePath =
|
||||
explicitWorktreePath ??
|
||||
(await resolveDefaultWorktreePath({ cwd, paseoHome, worktreesRoot, worktreeSlug }));
|
||||
await mkdir(dirname(worktreePath), { recursive: true });
|
||||
|
||||
const restoring = source.kind === "restore-jujutsu";
|
||||
const revision = restoring ? source.commit : await resolveJujutsuRevision(cwd, source.baseBranch);
|
||||
if (restoring) {
|
||||
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error("Invalid Jujutsu recovery commit");
|
||||
await runJujutsu(cwd, ["log", "--no-graph", "-r", revision, "-T", "commit_id"]);
|
||||
await clearMissingJujutsuWorkspace(cwd, worktreePath);
|
||||
}
|
||||
|
||||
const suffix = createHash("sha256").update(worktreePath).digest("hex").slice(0, 8);
|
||||
await createJujutsuWorkspace({
|
||||
cwd,
|
||||
path: worktreePath,
|
||||
name: `paseo-${worktreeSlug}-${suffix}`,
|
||||
base: revision,
|
||||
});
|
||||
|
||||
try {
|
||||
if (restoring) await runJujutsu(worktreePath, ["edit", "-r", revision], { write: true });
|
||||
let base = restoring ? source.baseRef : source.baseBranch;
|
||||
let baseCommit = restoring ? source.baseCommit : undefined;
|
||||
if (!restoring) {
|
||||
const output = await runJujutsu(worktreePath, [
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
'commit_id ++ " " ++ change_id ++ "\\n"',
|
||||
]);
|
||||
const parents = output.trim().split("\n");
|
||||
if (parents.length !== 1) throw new Error("Choose one Jujutsu change as the workspace base");
|
||||
const [commit, changeId] = parents[0].split(" ");
|
||||
baseCommit = commit;
|
||||
if (base === "@") base = changeId;
|
||||
}
|
||||
await writePaseoWorktreeMetadata(worktreePath, {
|
||||
baseRefName: restoring ? (base ?? "Jujutsu") : source.baseBranch,
|
||||
...(base ? { baseRef: base } : {}),
|
||||
jujutsuBaseCommit: baseCommit,
|
||||
});
|
||||
await seedPaseoConfigFile({ sourceCwd: configSourceCwd, targetCwd: worktreePath });
|
||||
return { branchName: "", worktreePath, comparisonBaseRef: base };
|
||||
} catch (error) {
|
||||
return rollbackCreatedPaseoWorktree({ cwd, worktreePath, teardownCwds: [] }, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a git worktree with proper naming conventions
|
||||
* Create a worktree using the selected checkout's version control.
|
||||
*/
|
||||
export function createWorktree(
|
||||
options: CreateWorktreeOptions & { source: Exclude<WorktreeSource, { kind: "restore-commit" }> },
|
||||
@@ -1867,17 +1983,32 @@ export function createWorktree(
|
||||
return runWithRepositoryRoot(options.cwd, () => createWorktreeAtRepositoryRoot(options));
|
||||
}
|
||||
|
||||
async function createWorktreeAtRepositoryRoot({
|
||||
async function createWorktreeAtRepositoryRoot(
|
||||
options: CreateWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
|
||||
const { source } = options;
|
||||
if (source.kind === "restore-jujutsu" || source.kind === "branch-off") {
|
||||
if (await findJujutsuRoot(options.cwd)) return createJujutsuWorktree(options);
|
||||
if (source.kind === "restore-jujutsu") {
|
||||
throw new Error("The source repository is no longer a Jujutsu checkout");
|
||||
}
|
||||
}
|
||||
|
||||
return createGitWorktree({ ...options, source });
|
||||
}
|
||||
|
||||
type GitWorktreeSource = Exclude<WorktreeSource, { kind: "restore-jujutsu" }>;
|
||||
|
||||
async function createGitWorktree({
|
||||
cwd,
|
||||
configSourceCwd = cwd,
|
||||
source,
|
||||
preparedBranchOff,
|
||||
worktreeSlug,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
worktreePath: explicitWorktreePath,
|
||||
}: CreateWorktreeOptions): Promise<
|
||||
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
|
||||
> {
|
||||
}: CreateWorktreeOptions & { source: GitWorktreeSource }) {
|
||||
const branchesBefore =
|
||||
source.kind === "checkout-branch" ||
|
||||
source.kind === "checkout-change-request" ||
|
||||
@@ -1920,7 +2051,7 @@ async function createWorktreeAtRepositoryRoot({
|
||||
: {}),
|
||||
});
|
||||
|
||||
await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath });
|
||||
await seedPaseoConfigFile({ sourceCwd: configSourceCwd, targetCwd: worktreePath });
|
||||
|
||||
return {
|
||||
branchName: sourcePlan.branchName,
|
||||
@@ -1941,7 +2072,7 @@ async function createWorktreeAtRepositoryRoot({
|
||||
|
||||
interface AdoptPluginWorktreeOptions {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
source: GitWorktreeSource;
|
||||
worktreePath: string;
|
||||
worktreeManagerPluginId: string;
|
||||
/** Worktree paths that existed before creation; an overlap fails instead of hijacking user worktrees. */
|
||||
@@ -1951,7 +2082,7 @@ interface AdoptPluginWorktreeOptions {
|
||||
}
|
||||
|
||||
export interface RunPluginWorktreeManagerCheckoutOptions<
|
||||
Source extends WorktreeSource = WorktreeSource,
|
||||
Source extends GitWorktreeSource = GitWorktreeSource,
|
||||
> {
|
||||
cwd: string;
|
||||
source: Source;
|
||||
@@ -1976,7 +2107,7 @@ export interface RunPluginWorktreeManagerCheckoutOptions<
|
||||
*/
|
||||
export function runPluginWorktreeManagerCheckout(
|
||||
options: RunPluginWorktreeManagerCheckoutOptions<
|
||||
Exclude<WorktreeSource, { kind: "restore-commit" }>
|
||||
Exclude<GitWorktreeSource, { kind: "restore-commit" }>
|
||||
>,
|
||||
): Promise<CreatedWorktree | null>;
|
||||
export function runPluginWorktreeManagerCheckout(
|
||||
@@ -2311,7 +2442,7 @@ async function verifyPluginChangeRequestHead(options: {
|
||||
|
||||
async function verifyPluginCheckoutTarget(options: {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
source: GitWorktreeSource;
|
||||
worktreePath: string;
|
||||
branchName: string | null;
|
||||
worktreeManagerPluginId: string;
|
||||
@@ -2411,7 +2542,7 @@ function resolveChangeRequestMetadata(
|
||||
*/
|
||||
async function resolveWorktreeMetadata(options: {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
source: GitWorktreeSource;
|
||||
branchName: string | null;
|
||||
resolvedBaseRef?: string;
|
||||
}): Promise<ResolvedWorktreeMetadata> {
|
||||
@@ -2461,7 +2592,7 @@ async function resolveWorktreeMetadata(options: {
|
||||
|
||||
interface ResolveWorktreeSourcePlanOptions {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
source: GitWorktreeSource;
|
||||
desiredSlug: string;
|
||||
preparedBranchOff?: PreparedWorktreeBranchOff;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user