@laoyuehanni/dsh-git-worktree 0.4.14 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -3
- package/README.zh.md +9 -3
- package/docs/DETAIL.md +5 -2
- package/docs/DETAIL.zh.md +5 -2
- package/lib/client.js +4253 -620
- package/lib/deferred-worktree.d.ts +105 -0
- package/lib/deferred-worktree.js +293 -0
- package/lib/git.d.ts +95 -0
- package/lib/git.js +384 -4
- package/lib/index.d.ts +13 -0
- package/lib/index.js +204 -4
- package/lib/normalize.d.ts +13 -0
- package/lib/normalize.js +51 -0
- package/lib/pr.d.ts +177 -0
- package/lib/pr.js +672 -0
- package/lib/routes.d.ts +61 -3
- package/lib/routes.js +639 -80
- package/lib/wire.d.ts +235 -3
- package/lib/wire.js +17 -0
- package/package.json +1 -1
package/lib/routes.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
6
6
|
import { mkdir, readdir, rm, stat } from 'node:fs/promises';
|
|
7
7
|
import { runPostCreateCopy } from './copy-files.js';
|
|
8
|
-
import {
|
|
8
|
+
import { addWorktree, addWorktreeAtCommit, addWorktreeCutout, appendWorktreeExclude, CancelledError, createBranch, cutoutBranchName, deleteBranch, fetchAll, fetchRefToTip, fsDirExists, fsExcludeSeams, GitError, inspectWorktree, isAbsoluteDir, listRemotes, probeRemoteRef, probeRepo, probeWorkspaceGit, randomCutoutBranchName, readWorktreePrSha, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch, updateCleanWorktreeToCommit, writeWorktreeBaseBranch, writeWorktreePrSha } from './git.js';
|
|
9
9
|
import { readCheckedOutBranch } from './head.js';
|
|
10
10
|
import { invalidateAuthorCache, readAuthors, readHistory, readCommit } from './history.js';
|
|
11
|
+
import { classifyRemotes, fetchPrMeta, formatPrBaseLabel, loadPrContext, PrResolutionError, resolvePrTarget } from './pr.js';
|
|
11
12
|
import { openPush, previewPush, pushBranch } from './push.js';
|
|
12
13
|
import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
|
|
13
14
|
import { createProgressReader } from './progress.js';
|
|
@@ -102,6 +103,8 @@ export async function handleGroupWorktrees(deps, body) {
|
|
|
102
103
|
}
|
|
103
104
|
/** The project-internal layout directory name every repository uses. */
|
|
104
105
|
const PROJECT_LAYOUT_DIR = join('.dsh', 'gitworktree');
|
|
106
|
+
/** The official DSH worktree layout directory inside a repository. */
|
|
107
|
+
const OFFICIAL_LAYOUT_DIR = join('.agents', 'worktrees');
|
|
105
108
|
/**
|
|
106
109
|
* Whether `canonical` sits DIRECTLY inside a `<repo>/.dsh/gitworktree`
|
|
107
110
|
* layout root whose repository actually exists on disk. The layout names its
|
|
@@ -117,6 +120,16 @@ function insideProjectLayout(canonical, dirExists) {
|
|
|
117
120
|
return false;
|
|
118
121
|
return dirExists(join(dirname(dsh), '.git'));
|
|
119
122
|
}
|
|
123
|
+
/** Whether `canonical` sits DIRECTLY inside a `<repo>/.agents/worktrees` directory. */
|
|
124
|
+
function insideOfficialLayout(canonical, dirExists) {
|
|
125
|
+
const layout = dirname(canonical);
|
|
126
|
+
if (basename(layout) !== 'worktrees')
|
|
127
|
+
return false;
|
|
128
|
+
const agents = dirname(layout);
|
|
129
|
+
if (basename(agents) !== '.agents')
|
|
130
|
+
return false;
|
|
131
|
+
return dirExists(join(dirname(agents), '.git'));
|
|
132
|
+
}
|
|
120
133
|
/**
|
|
121
134
|
* POST /worktrees-all — git facts for every DIRECT child directory of the two
|
|
122
135
|
* storage locations the plugin has ever used, merged:
|
|
@@ -175,7 +188,7 @@ export async function handleWorktreesAll(deps, body) {
|
|
|
175
188
|
const gitFacts = await probeWorkspaceGit(deps.exec, path);
|
|
176
189
|
return gitFacts === undefined
|
|
177
190
|
? { path, repoName: null, branch: null, source }
|
|
178
|
-
: { path, repoName: gitFacts.repoName, branch: gitFacts.branch, source };
|
|
191
|
+
: { path, repoRoot: gitFacts.repoRoot, repoName: gitFacts.repoName, branch: gitFacts.branch, source };
|
|
179
192
|
}
|
|
180
193
|
catch {
|
|
181
194
|
return { path, repoName: null, branch: null, source };
|
|
@@ -206,8 +219,12 @@ export async function handleWorktreesAll(deps, body) {
|
|
|
206
219
|
repoRoots.add(workspaceFacts.repoRoot);
|
|
207
220
|
}
|
|
208
221
|
}
|
|
222
|
+
const includeOfficial = deps.sectionManageOfficialWorktrees?.() === true;
|
|
209
223
|
for (const repoRoot of repoRoots) {
|
|
210
224
|
await scanLocation(join(repoRoot, PROJECT_LAYOUT_DIR), 'project');
|
|
225
|
+
if (includeOfficial) {
|
|
226
|
+
await scanLocation(join(repoRoot, OFFICIAL_LAYOUT_DIR), 'official');
|
|
227
|
+
}
|
|
211
228
|
}
|
|
212
229
|
return { status: 200, body: { worktrees: facts, legacyRoot, legacyRootExists, ...truncated ? { truncated } : {} } };
|
|
213
230
|
}
|
|
@@ -246,7 +263,11 @@ export async function handlePurgeDirectory(deps, body) {
|
|
|
246
263
|
}
|
|
247
264
|
const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
|
|
248
265
|
const canonical = resolve(path);
|
|
249
|
-
|
|
266
|
+
const allowOfficialPurge = deps.sectionManageOfficialWorktrees?.() === true;
|
|
267
|
+
const dirExists = deps.dirExists ?? fsDirExists;
|
|
268
|
+
if (dirname(canonical) !== resolve(rootDir)
|
|
269
|
+
&& !insideProjectLayout(canonical, dirExists)
|
|
270
|
+
&& !(allowOfficialPurge && insideOfficialLayout(canonical, dirExists))) {
|
|
250
271
|
return fail(400, `"${canonical}" is outside the plugin's worktree storage locations`);
|
|
251
272
|
}
|
|
252
273
|
const statDirectory = deps.statDirectory ?? fsStatDirectory;
|
|
@@ -301,7 +322,9 @@ function gitFailure(error) {
|
|
|
301
322
|
// before ever spawning git) and a path the repository never registered
|
|
302
323
|
// (a stale sidebar row racing a terminal-side removal).
|
|
303
324
|
|| error.stderr.includes('cannot remove the main worktree')
|
|
304
|
-
|| error.stderr.includes('is not a registered worktree')
|
|
325
|
+
|| error.stderr.includes('is not a registered worktree')
|
|
326
|
+
|| error.stderr.includes('worktree has uncommitted changes')
|
|
327
|
+
|| error.stderr.includes("couldn't find remote ref");
|
|
305
328
|
return fail(usage ? 400 : 500, error.message);
|
|
306
329
|
}
|
|
307
330
|
/**
|
|
@@ -434,94 +457,179 @@ export async function handleCommit(deps, body) {
|
|
|
434
457
|
* @param deps - host dependencies.
|
|
435
458
|
* @param body - parsed request body.
|
|
436
459
|
*/
|
|
460
|
+
/**
|
|
461
|
+
* Shared worktree creation execution pipeline used by both immediate
|
|
462
|
+
* `POST /worktree` and deferred first-turn creation.
|
|
463
|
+
*/
|
|
464
|
+
export async function executeCreateWorktree(deps, spec, onPhase, signal) {
|
|
465
|
+
if (spec.pr !== undefined) {
|
|
466
|
+
const pr = spec.pr;
|
|
467
|
+
const controller = new AbortController();
|
|
468
|
+
const abortSignal = signal ?? controller.signal;
|
|
469
|
+
const outcome = await handlePrCheckout(deps, {
|
|
470
|
+
repoPath: spec.repoPath,
|
|
471
|
+
input: pr.input,
|
|
472
|
+
...(pr.remote === undefined ? {} : { remote: pr.remote }),
|
|
473
|
+
...(pr.provider === undefined ? {} : { provider: pr.provider }),
|
|
474
|
+
...(pr.ifExists === undefined ? {} : { ifExists: pr.ifExists }),
|
|
475
|
+
}, {
|
|
476
|
+
signal: abortSignal,
|
|
477
|
+
emit: (event) => {
|
|
478
|
+
if (event.type !== 'stage')
|
|
479
|
+
return;
|
|
480
|
+
if (event.stage === 'fetch')
|
|
481
|
+
onPhase?.('fetch', spec.branch);
|
|
482
|
+
else if (event.stage === 'worktree')
|
|
483
|
+
onPhase?.('create', spec.branch);
|
|
484
|
+
else if (event.stage === 'copy')
|
|
485
|
+
onPhase?.('copy', spec.branch);
|
|
486
|
+
},
|
|
487
|
+
});
|
|
488
|
+
if (outcome.status !== 200) {
|
|
489
|
+
const errBody = outcome.body;
|
|
490
|
+
throw Object.assign(new Error(errBody.error), { httpStatus: outcome.status });
|
|
491
|
+
}
|
|
492
|
+
const res = outcome.body;
|
|
493
|
+
onPhase?.('create', res.branch);
|
|
494
|
+
const trackPrUrl = pr.canonicalUrl === null ? undefined : (pr.canonicalUrl ?? res.canonicalUrl ?? undefined);
|
|
495
|
+
return {
|
|
496
|
+
path: res.path,
|
|
497
|
+
branch: res.branch,
|
|
498
|
+
created: res.created,
|
|
499
|
+
...(res.fetchWarning === undefined ? {} : { fetchWarning: res.fetchWarning }),
|
|
500
|
+
...(res.excludeWarning === undefined ? {} : { excludeWarning: res.excludeWarning }),
|
|
501
|
+
...(res.copyWarning === undefined ? {} : { copyWarning: res.copyWarning }),
|
|
502
|
+
...(trackPrUrl === undefined ? {} : { trackPrUrl }),
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
const { repoPath, branch, cutout, random, name } = spec;
|
|
506
|
+
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
507
|
+
if (facts === undefined) {
|
|
508
|
+
throw Object.assign(new Error(`"${repoPath}" is not inside a git repository`), { httpStatus: 400 });
|
|
509
|
+
}
|
|
510
|
+
const excludeWarning = await appendWorktreeExclude(deps.excludeSeams ?? fsExcludeSeams, facts.repoRoot);
|
|
511
|
+
const layoutRoot = join(facts.repoRoot, PROJECT_LAYOUT_DIR);
|
|
512
|
+
let fetchWarning;
|
|
513
|
+
let resolvedBranch;
|
|
514
|
+
let branchResolved = false;
|
|
515
|
+
if (deps.sectionFetchBeforeCreate() === true) {
|
|
516
|
+
resolvedBranch = await resolveBranch(deps.exec, facts.repoRoot, branch);
|
|
517
|
+
branchResolved = true;
|
|
518
|
+
if (resolvedBranch?.remote !== undefined) {
|
|
519
|
+
onPhase?.('fetch');
|
|
520
|
+
try {
|
|
521
|
+
await fetchAll(deps.exec, facts.repoRoot);
|
|
522
|
+
}
|
|
523
|
+
catch (error) {
|
|
524
|
+
fetchWarning = error instanceof GitError ? error.stderr.trim() : error instanceof Error ? error.message : String(error);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
const warnings = {
|
|
529
|
+
...(fetchWarning === undefined ? {} : { fetchWarning }),
|
|
530
|
+
...(excludeWarning === undefined ? {} : { excludeWarning }),
|
|
531
|
+
};
|
|
532
|
+
if (cutout) {
|
|
533
|
+
const custom = name?.trim();
|
|
534
|
+
if (custom !== undefined && custom !== '') {
|
|
535
|
+
if (custom.startsWith('-')) {
|
|
536
|
+
throw Object.assign(new Error('"name" must not start with "-"'), { httpStatus: 400 });
|
|
537
|
+
}
|
|
538
|
+
onPhase?.('create', custom);
|
|
539
|
+
const target = join(layoutRoot, sanitizeBranchDir(custom));
|
|
540
|
+
await mkdirSlot(deps, layoutRoot);
|
|
541
|
+
await addWorktreeCutout(deps.exec, facts.repoRoot, branch, custom, target);
|
|
542
|
+
await writeWorktreeBaseBranch(target, branch);
|
|
543
|
+
onPhase?.('copy', custom);
|
|
544
|
+
const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
|
|
545
|
+
return {
|
|
546
|
+
path: target,
|
|
547
|
+
branch: custom,
|
|
548
|
+
created: true,
|
|
549
|
+
...warnings,
|
|
550
|
+
...(copyWarning === undefined ? {} : { copyWarning }),
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
const dirExists = deps.dirExists ?? fsDirExists;
|
|
554
|
+
const folderTaken = (candidate) => dirExists(join(layoutRoot, sanitizeBranchDir(candidate)));
|
|
555
|
+
const newBranch = random === true
|
|
556
|
+
? await randomCutoutBranchName(deps.exec, facts.repoRoot, branch, folderTaken, deps.randomHex)
|
|
557
|
+
: await cutoutBranchName(deps.exec, facts.repoRoot, branch, folderTaken);
|
|
558
|
+
onPhase?.('create', newBranch);
|
|
559
|
+
const target = join(layoutRoot, sanitizeBranchDir(newBranch));
|
|
560
|
+
await mkdirSlot(deps, layoutRoot);
|
|
561
|
+
await addWorktreeCutout(deps.exec, facts.repoRoot, branch, newBranch, target);
|
|
562
|
+
await writeWorktreeBaseBranch(target, branch);
|
|
563
|
+
onPhase?.('copy', newBranch);
|
|
564
|
+
const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
|
|
565
|
+
return {
|
|
566
|
+
path: target,
|
|
567
|
+
branch: newBranch,
|
|
568
|
+
created: true,
|
|
569
|
+
...warnings,
|
|
570
|
+
...(copyWarning === undefined ? {} : { copyWarning }),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
if (!branchResolved) {
|
|
574
|
+
resolvedBranch = await resolveBranch(deps.exec, facts.repoRoot, branch);
|
|
575
|
+
}
|
|
576
|
+
const isRemote = resolvedBranch?.remote !== undefined;
|
|
577
|
+
const localName = resolvedBranch?.local ?? branch;
|
|
578
|
+
onPhase?.('create', localName);
|
|
579
|
+
const target = join(layoutRoot, sanitizeBranchDir(branch));
|
|
580
|
+
await mkdirSlot(deps, layoutRoot);
|
|
581
|
+
const result = await addWorktree(deps.exec, facts.repoRoot, branch, target, deps.dirExists);
|
|
582
|
+
let copyWarning;
|
|
583
|
+
if (result.created) {
|
|
584
|
+
if (isRemote)
|
|
585
|
+
await writeWorktreeBaseBranch(result.path, branch);
|
|
586
|
+
onPhase?.('copy', localName);
|
|
587
|
+
copyWarning = await runPostCreateCopy(deps, facts.repoRoot, result.path);
|
|
588
|
+
}
|
|
589
|
+
return {
|
|
590
|
+
path: result.path,
|
|
591
|
+
branch: localName,
|
|
592
|
+
created: result.created,
|
|
593
|
+
...warnings,
|
|
594
|
+
...(copyWarning === undefined ? {} : { copyWarning }),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
437
597
|
export async function handleCreateWorktree(deps, body) {
|
|
438
|
-
const parsed = readBody(body, ['repoPath', 'branch'], ['cutout'], ['name']);
|
|
598
|
+
const parsed = readBody(body, ['repoPath', 'branch'], ['cutout', 'random'], ['name']);
|
|
439
599
|
if (isOutcome(parsed))
|
|
440
600
|
return parsed;
|
|
441
|
-
const { repoPath, branch, cutout, name } = parsed;
|
|
601
|
+
const { repoPath, branch, cutout, random, name } = parsed;
|
|
442
602
|
if (!isAbsoluteDir(repoPath))
|
|
443
603
|
return fail(400, '"repoPath" must be an absolute directory');
|
|
444
604
|
if (branch.trim() === '')
|
|
445
605
|
return fail(400, '"branch" must be non-empty');
|
|
446
606
|
try {
|
|
447
|
-
const
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
// rides the successful response as `fetchWarning` for the client to
|
|
465
|
-
// toast.
|
|
466
|
-
let fetchWarning;
|
|
467
|
-
if (deps.sectionFetchBeforeCreate() === true) {
|
|
468
|
-
const resolved = await resolveBranch(deps.exec, facts.repoRoot, branch);
|
|
469
|
-
if (resolved?.remote !== undefined) {
|
|
470
|
-
try {
|
|
471
|
-
await fetchAll(deps.exec, facts.repoRoot);
|
|
472
|
-
}
|
|
473
|
-
catch (error) {
|
|
474
|
-
fetchWarning = error instanceof GitError ? error.stderr.trim() : error instanceof Error ? error.message : String(error);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
const warnings = { ...fetchWarning === undefined ? {} : { fetchWarning }, ...excludeWarning === undefined ? {} : { excludeWarning } };
|
|
479
|
-
if (cutout === true) {
|
|
480
|
-
// An explicit name skips the `-wt` suffix walk and is used verbatim —
|
|
481
|
-
// both for the branch and the storage folder. A leading dash would
|
|
482
|
-
// ride `worktree add -b` as a flag; any other git-invalid name
|
|
483
|
-
// surfaces through the error envelope (the client pre-flights).
|
|
484
|
-
const custom = name?.trim();
|
|
485
|
-
if (custom !== undefined && custom !== '') {
|
|
486
|
-
if (custom.startsWith('-'))
|
|
487
|
-
return fail(400, '"name" must not start with "-"');
|
|
488
|
-
const target = join(layoutRoot, sanitizeBranchDir(custom));
|
|
489
|
-
await mkdirSlot(deps, layoutRoot);
|
|
490
|
-
await addWorktreeCutout(deps.exec, facts.repoRoot, branch, custom, target);
|
|
491
|
-
const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
|
|
492
|
-
const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
|
|
493
|
-
return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
|
|
494
|
-
}
|
|
495
|
-
// The new branch name must be known before the folder name can be
|
|
496
|
-
// computed: the folder carries the NEW branch's directory name. The
|
|
497
|
-
// name must be free in BOTH namespaces — the branch table and the
|
|
498
|
-
// storage folder: a leftover folder of a since-deleted branch would
|
|
499
|
-
// otherwise fail `worktree add` with a bare "already exists", so the
|
|
500
|
-
// suffix walk probes the folder too.
|
|
501
|
-
const dirExists = deps.dirExists ?? fsDirExists;
|
|
502
|
-
const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(layoutRoot, sanitizeBranchDir(candidate))));
|
|
503
|
-
const target = join(layoutRoot, sanitizeBranchDir(newBranch));
|
|
504
|
-
await mkdirSlot(deps, layoutRoot);
|
|
505
|
-
await addWorktreeCutout(deps.exec, facts.repoRoot, branch, newBranch, target);
|
|
506
|
-
const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
|
|
507
|
-
const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
|
|
508
|
-
return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
|
|
509
|
-
}
|
|
510
|
-
// The folder name carries the branch: `<repo>/.dsh/gitworktree/<branch>`.
|
|
511
|
-
const target = join(layoutRoot, sanitizeBranchDir(branch));
|
|
512
|
-
await mkdirSlot(deps, layoutRoot);
|
|
513
|
-
const result = await addWorktree(deps.exec, facts.repoRoot, branch, target, deps.dirExists);
|
|
514
|
-
let copyWarning;
|
|
515
|
-
if (result.created) {
|
|
516
|
-
copyWarning = await runPostCreateCopy(deps, facts.repoRoot, result.path);
|
|
517
|
-
}
|
|
518
|
-
const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
|
|
519
|
-
return { status: 200, body: { ...result, ...warnings, ...copyWarnObj } };
|
|
607
|
+
const outcome = await executeCreateWorktree(deps, {
|
|
608
|
+
repoPath,
|
|
609
|
+
branch,
|
|
610
|
+
cutout: cutout === true,
|
|
611
|
+
...(name === undefined ? {} : { name }),
|
|
612
|
+
...(random === undefined ? {} : { random }),
|
|
613
|
+
});
|
|
614
|
+
return {
|
|
615
|
+
status: 200,
|
|
616
|
+
body: {
|
|
617
|
+
path: outcome.path,
|
|
618
|
+
created: outcome.created,
|
|
619
|
+
...(outcome.fetchWarning === undefined ? {} : { fetchWarning: outcome.fetchWarning }),
|
|
620
|
+
...(outcome.excludeWarning === undefined ? {} : { excludeWarning: outcome.excludeWarning }),
|
|
621
|
+
...(outcome.copyWarning === undefined ? {} : { copyWarning: outcome.copyWarning }),
|
|
622
|
+
},
|
|
623
|
+
};
|
|
520
624
|
}
|
|
521
625
|
catch (error) {
|
|
522
626
|
if (error instanceof GitError)
|
|
523
627
|
return gitFailure(error);
|
|
524
|
-
|
|
628
|
+
const status = typeof error === 'object' && error !== null && 'httpStatus' in error
|
|
629
|
+
&& typeof error.httpStatus === 'number'
|
|
630
|
+
? error.httpStatus
|
|
631
|
+
: 500;
|
|
632
|
+
return fail(status, error instanceof Error ? error.message : String(error));
|
|
525
633
|
}
|
|
526
634
|
}
|
|
527
635
|
/**
|
|
@@ -1005,3 +1113,454 @@ export async function handleEnsureDirectory(deps, body) {
|
|
|
1005
1113
|
return fail(500, error instanceof Error ? error.message : String(error));
|
|
1006
1114
|
}
|
|
1007
1115
|
}
|
|
1116
|
+
/**
|
|
1117
|
+
* POST /session-cwd — move a session's working directory to an existing
|
|
1118
|
+
* directory via the host `workingDirectory` service. Used by the shared
|
|
1119
|
+
* workspace mode (`switchSessionDirectory`) so a blank session stays under
|
|
1120
|
+
* its parent repository workspace while working inside a linked worktree.
|
|
1121
|
+
* @param deps - host dependencies.
|
|
1122
|
+
* @param body - parsed request body: `{ sessionId, path }`.
|
|
1123
|
+
*/
|
|
1124
|
+
export async function handleSetSessionDirectory(deps, body) {
|
|
1125
|
+
const parsed = readBody(body, ['sessionId', 'path']);
|
|
1126
|
+
if (isOutcome(parsed))
|
|
1127
|
+
return parsed;
|
|
1128
|
+
const sessionId = parsed.sessionId.trim();
|
|
1129
|
+
const { path } = parsed;
|
|
1130
|
+
if (sessionId === '')
|
|
1131
|
+
return fail(400, '"sessionId" must be non-empty');
|
|
1132
|
+
if (!isAbsoluteDir(path))
|
|
1133
|
+
return fail(400, '"path" must be an absolute directory');
|
|
1134
|
+
if (deps.setSessionDirectory === undefined) {
|
|
1135
|
+
return fail(501, 'Session working directory switching is not supported by this host');
|
|
1136
|
+
}
|
|
1137
|
+
const canonical = resolve(path);
|
|
1138
|
+
const statDirectory = deps.statDirectory ?? fsStatDirectory;
|
|
1139
|
+
if (!(await statDirectory(canonical))) {
|
|
1140
|
+
return fail(400, `"${canonical}" is not an existing directory`);
|
|
1141
|
+
}
|
|
1142
|
+
try {
|
|
1143
|
+
const committed = await deps.setSessionDirectory(sessionId, canonical);
|
|
1144
|
+
return { status: 200, body: { sessionId, path: committed } };
|
|
1145
|
+
}
|
|
1146
|
+
catch (error) {
|
|
1147
|
+
const status = typeof error === 'object' && error !== null && 'httpStatus' in error
|
|
1148
|
+
&& typeof error.httpStatus === 'number'
|
|
1149
|
+
? error.httpStatus
|
|
1150
|
+
: 500;
|
|
1151
|
+
return fail(status, error instanceof Error ? error.message : String(error));
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/** GET /deferred?sessionId=<id> — read a session's current deferred worktree state. */
|
|
1155
|
+
export async function handleGetDeferredWorktree(deps, sessionId) {
|
|
1156
|
+
if (sessionId === undefined || sessionId.trim() === '') {
|
|
1157
|
+
return fail(400, 'query parameter "sessionId" must be non-empty');
|
|
1158
|
+
}
|
|
1159
|
+
const state = deps.deferredWorktrees?.get(sessionId.trim()) ?? null;
|
|
1160
|
+
return { status: 200, body: { state } };
|
|
1161
|
+
}
|
|
1162
|
+
function parseDeferredPr(raw) {
|
|
1163
|
+
if (raw === undefined)
|
|
1164
|
+
return undefined;
|
|
1165
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
1166
|
+
return fail(400, 'body key "pr" must be a JSON object');
|
|
1167
|
+
}
|
|
1168
|
+
const rec = raw;
|
|
1169
|
+
const unknown = Object.keys(rec).filter(k => !['input', 'remote', 'provider', 'ifExists', 'canonicalUrl'].includes(k));
|
|
1170
|
+
if (unknown.length > 0)
|
|
1171
|
+
return fail(400, `unknown "pr" key "${unknown[0]}"`);
|
|
1172
|
+
if (typeof rec.input !== 'string' || rec.input.trim() === '') {
|
|
1173
|
+
return fail(400, '"pr.input" must be a non-empty string');
|
|
1174
|
+
}
|
|
1175
|
+
if (rec.remote !== undefined && (typeof rec.remote !== 'string' || rec.remote.trim() === '')) {
|
|
1176
|
+
return fail(400, '"pr.remote" must be a non-empty string when present');
|
|
1177
|
+
}
|
|
1178
|
+
if (rec.provider !== undefined && rec.provider !== 'github' && rec.provider !== 'gitlab') {
|
|
1179
|
+
return fail(400, '"pr.provider" must be "github" or "gitlab"');
|
|
1180
|
+
}
|
|
1181
|
+
if (rec.ifExists !== undefined && rec.ifExists !== 'reuse' && rec.ifExists !== 'update' && rec.ifExists !== 'reset') {
|
|
1182
|
+
return fail(400, '"pr.ifExists" must be "reuse", "update", or "reset"');
|
|
1183
|
+
}
|
|
1184
|
+
if (rec.canonicalUrl !== undefined && rec.canonicalUrl !== null && typeof rec.canonicalUrl !== 'string') {
|
|
1185
|
+
return fail(400, '"pr.canonicalUrl" must be a string or null when present');
|
|
1186
|
+
}
|
|
1187
|
+
return {
|
|
1188
|
+
input: rec.input.trim(),
|
|
1189
|
+
...(typeof rec.remote === 'string' ? { remote: rec.remote } : {}),
|
|
1190
|
+
...(rec.provider === 'github' || rec.provider === 'gitlab' ? { provider: rec.provider } : {}),
|
|
1191
|
+
...(rec.ifExists === 'reuse' || rec.ifExists === 'update' || rec.ifExists === 'reset' ? { ifExists: rec.ifExists } : {}),
|
|
1192
|
+
...(rec.canonicalUrl === null || typeof rec.canonicalUrl === 'string' ? { canonicalUrl: rec.canonicalUrl } : {}),
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
/** POST /deferred/arm — arm a deferred worktree creation for a blank session. */
|
|
1196
|
+
export async function handleArmDeferredWorktree(deps, body) {
|
|
1197
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
1198
|
+
return fail(400, 'request body must be a JSON object');
|
|
1199
|
+
}
|
|
1200
|
+
const { pr: rawPr, ...scalarBody } = body;
|
|
1201
|
+
const parsed = readBody(scalarBody, ['sessionId', 'repoPath', 'branch'], ['cutout', 'random'], ['name']);
|
|
1202
|
+
if (isOutcome(parsed))
|
|
1203
|
+
return parsed;
|
|
1204
|
+
const parsedPr = parseDeferredPr(rawPr);
|
|
1205
|
+
if (parsedPr !== undefined && isOutcome(parsedPr))
|
|
1206
|
+
return parsedPr;
|
|
1207
|
+
const sessionId = parsed.sessionId.trim();
|
|
1208
|
+
if (sessionId === '')
|
|
1209
|
+
return fail(400, '"sessionId" must be non-empty');
|
|
1210
|
+
if (!isAbsoluteDir(parsed.repoPath))
|
|
1211
|
+
return fail(400, '"repoPath" must be an absolute directory');
|
|
1212
|
+
if (parsed.branch.trim() === '')
|
|
1213
|
+
return fail(400, '"branch" must be non-empty');
|
|
1214
|
+
const custom = parsed.name?.trim();
|
|
1215
|
+
if (custom !== undefined && custom !== '' && custom.startsWith('-')) {
|
|
1216
|
+
return fail(400, '"name" must not start with "-"');
|
|
1217
|
+
}
|
|
1218
|
+
if (deps.deferredWorktrees === undefined) {
|
|
1219
|
+
return fail(501, 'Deferred worktree creation is not supported by this host');
|
|
1220
|
+
}
|
|
1221
|
+
try {
|
|
1222
|
+
const state = deps.deferredWorktrees.arm(sessionId, {
|
|
1223
|
+
repoPath: parsed.repoPath,
|
|
1224
|
+
branch: parsed.branch,
|
|
1225
|
+
cutout: parsed.cutout === true,
|
|
1226
|
+
...(custom !== undefined && custom !== '' ? { name: custom } : {}),
|
|
1227
|
+
...(parsed.random === true ? { random: true } : {}),
|
|
1228
|
+
...(parsedPr === undefined ? {} : { pr: parsedPr }),
|
|
1229
|
+
});
|
|
1230
|
+
return { status: 200, body: { state } };
|
|
1231
|
+
}
|
|
1232
|
+
catch (error) {
|
|
1233
|
+
const status = typeof error === 'object' && error !== null && 'httpStatus' in error
|
|
1234
|
+
&& typeof error.httpStatus === 'number'
|
|
1235
|
+
? error.httpStatus
|
|
1236
|
+
: 500;
|
|
1237
|
+
return fail(status, error instanceof Error ? error.message : String(error));
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
/** POST /deferred/action — cancel, retry, or withdraw a deferred worktree. */
|
|
1241
|
+
export async function handleDeferredWorktreeAction(deps, body) {
|
|
1242
|
+
const parsed = readBody(body, ['sessionId', 'action']);
|
|
1243
|
+
if (isOutcome(parsed))
|
|
1244
|
+
return parsed;
|
|
1245
|
+
const sessionId = parsed.sessionId.trim();
|
|
1246
|
+
if (sessionId === '')
|
|
1247
|
+
return fail(400, '"sessionId" must be non-empty');
|
|
1248
|
+
const action = parsed.action;
|
|
1249
|
+
if (action !== 'cancel' && action !== 'retry' && action !== 'withdraw') {
|
|
1250
|
+
return fail(400, '"action" must be "cancel", "retry", or "withdraw"');
|
|
1251
|
+
}
|
|
1252
|
+
if (deps.deferredWorktrees === undefined) {
|
|
1253
|
+
return fail(501, 'Deferred worktree creation is not supported by this host');
|
|
1254
|
+
}
|
|
1255
|
+
if (action === 'cancel')
|
|
1256
|
+
deps.deferredWorktrees.cancel(sessionId);
|
|
1257
|
+
else if (action === 'retry')
|
|
1258
|
+
deps.deferredWorktrees.retry(sessionId);
|
|
1259
|
+
else
|
|
1260
|
+
deps.deferredWorktrees.withdraw(sessionId);
|
|
1261
|
+
return { status: 200, body: { state: deps.deferredWorktrees.get(sessionId) } };
|
|
1262
|
+
}
|
|
1263
|
+
function failCode(status, error, code, params) {
|
|
1264
|
+
return {
|
|
1265
|
+
status,
|
|
1266
|
+
body: {
|
|
1267
|
+
error,
|
|
1268
|
+
code,
|
|
1269
|
+
...(params === undefined ? {} : { params }),
|
|
1270
|
+
},
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
function prGitFailure(error, context) {
|
|
1274
|
+
const stderr = error.stderr;
|
|
1275
|
+
if (stderr.includes('worktree has uncommitted changes')) {
|
|
1276
|
+
return failCode(400, error.message, 'worktree_dirty');
|
|
1277
|
+
}
|
|
1278
|
+
const lowerStderr = stderr.toLowerCase();
|
|
1279
|
+
if (lowerStderr.includes('untracked working tree file') && lowerStderr.includes('would be overwritten')) {
|
|
1280
|
+
return fail(400, error.message);
|
|
1281
|
+
}
|
|
1282
|
+
if (stderr.includes('PR worktree has diverged local commits')) {
|
|
1283
|
+
return failCode(409, error.message, 'worktree_diverged', { branch: context.branch });
|
|
1284
|
+
}
|
|
1285
|
+
if (stderr.includes('already checked out in the main worktree')) {
|
|
1286
|
+
return failCode(400, error.message, 'occupied_by_main', { branch: context.branch });
|
|
1287
|
+
}
|
|
1288
|
+
if (stderr.includes("couldn't find remote ref")) {
|
|
1289
|
+
return failCode(400, error.message, 'pr_ref_not_found', { ref: context.refSpec, remote: context.remote });
|
|
1290
|
+
}
|
|
1291
|
+
if (stderr.includes('Authentication failed')
|
|
1292
|
+
|| stderr.includes('HTTP Basic: Access denied')
|
|
1293
|
+
|| stderr.includes('Invalid username or token')
|
|
1294
|
+
|| stderr.includes('returned error: 403')
|
|
1295
|
+
|| stderr.includes('could not read Username')
|
|
1296
|
+
|| stderr.includes('terminal prompts disabled')
|
|
1297
|
+
|| stderr.includes('Permission denied (publickey)')
|
|
1298
|
+
|| stderr.includes('Permission denied, please try again')
|
|
1299
|
+
|| stderr.includes('Host key verification failed')) {
|
|
1300
|
+
return failCode(400, error.message, 'pr_auth_failed', { remote: context.remote });
|
|
1301
|
+
}
|
|
1302
|
+
if (stderr.includes('Git command timed out')
|
|
1303
|
+
|| lowerStderr.includes('connection timed out')
|
|
1304
|
+
|| lowerStderr.includes('operation timed out')) {
|
|
1305
|
+
return failCode(504, error.message, 'pr_timeout', { remote: context.remote });
|
|
1306
|
+
}
|
|
1307
|
+
if (lowerStderr.includes('could not resolve host')
|
|
1308
|
+
|| lowerStderr.includes('failed to connect')
|
|
1309
|
+
|| lowerStderr.includes('network is unreachable')
|
|
1310
|
+
|| lowerStderr.includes('connection refused')
|
|
1311
|
+
|| lowerStderr.includes('could not read from remote repository')) {
|
|
1312
|
+
return failCode(502, error.message, 'pr_network_failed', { remote: context.remote });
|
|
1313
|
+
}
|
|
1314
|
+
return gitFailure(error);
|
|
1315
|
+
}
|
|
1316
|
+
function validatePrOptionalFields(remote, provider) {
|
|
1317
|
+
if (remote !== undefined && remote.trim() === '')
|
|
1318
|
+
return fail(400, '"remote" must be non-empty when present');
|
|
1319
|
+
if (provider !== undefined && provider !== 'github' && provider !== 'gitlab') {
|
|
1320
|
+
return fail(400, '"provider" must be "github" or "gitlab"');
|
|
1321
|
+
}
|
|
1322
|
+
return undefined;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* POST /pr-context — remotes, optional `ctx.forge` readiness, and open PR/MR candidates.
|
|
1326
|
+
* @param deps - host dependencies.
|
|
1327
|
+
* @param body - parsed request body: `{ repoPath, remote? }`.
|
|
1328
|
+
* @param signal - optional cancellation signal aborted when the HTTP client disconnects.
|
|
1329
|
+
*/
|
|
1330
|
+
export async function handlePrContext(deps, body, signal) {
|
|
1331
|
+
const parsed = readBody(body, ['repoPath'], [], ['remote']);
|
|
1332
|
+
if (isOutcome(parsed))
|
|
1333
|
+
return parsed;
|
|
1334
|
+
const { repoPath, remote } = parsed;
|
|
1335
|
+
if (!isAbsoluteDir(repoPath))
|
|
1336
|
+
return fail(400, '"repoPath" must be an absolute directory');
|
|
1337
|
+
if (remote !== undefined && remote.trim() === '')
|
|
1338
|
+
return fail(400, '"remote" must be non-empty when present');
|
|
1339
|
+
const isAborted = () => signal?.aborted === true;
|
|
1340
|
+
try {
|
|
1341
|
+
if (isAborted())
|
|
1342
|
+
return fail(499, 'Cancelled');
|
|
1343
|
+
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
1344
|
+
if (facts === undefined)
|
|
1345
|
+
return fail(400, `"${repoPath}" is not inside a git repository`);
|
|
1346
|
+
const rawRemotes = await listRemotes(deps.exec, facts.repoRoot);
|
|
1347
|
+
const forge = deps.forge?.();
|
|
1348
|
+
const result = await loadPrContext({
|
|
1349
|
+
repoRoot: facts.repoRoot,
|
|
1350
|
+
repoName: facts.repoName,
|
|
1351
|
+
rawRemotes,
|
|
1352
|
+
worktrees: facts.worktrees,
|
|
1353
|
+
...(remote === undefined ? {} : { requestedRemote: remote }),
|
|
1354
|
+
...(forge === undefined ? {} : { forge }),
|
|
1355
|
+
...(signal === undefined ? {} : { signal }),
|
|
1356
|
+
});
|
|
1357
|
+
if (isAborted())
|
|
1358
|
+
return fail(499, 'Cancelled');
|
|
1359
|
+
return { status: 200, body: result };
|
|
1360
|
+
}
|
|
1361
|
+
catch (error) {
|
|
1362
|
+
if (error instanceof CancelledError)
|
|
1363
|
+
return fail(499, error.message);
|
|
1364
|
+
if (error instanceof GitError)
|
|
1365
|
+
return gitFailure(error);
|
|
1366
|
+
return fail(500, error instanceof Error ? error.message : String(error));
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* POST /pr-resolve — parse and validate a PR/MR ID or URL against repository remotes,
|
|
1371
|
+
* verifying remote ref existence via lightweight `git ls-remote` unless skipped for live
|
|
1372
|
+
* candidates or an already-existing local worktree.
|
|
1373
|
+
* @param deps - host dependencies.
|
|
1374
|
+
* @param body - parsed request body.
|
|
1375
|
+
* @param signal - optional cancellation signal aborted when the HTTP client disconnects.
|
|
1376
|
+
*/
|
|
1377
|
+
export async function handlePrResolve(deps, body, signal) {
|
|
1378
|
+
const parsed = readBody(body, ['repoPath', 'input'], ['verifyRemote'], ['remote', 'provider']);
|
|
1379
|
+
if (isOutcome(parsed))
|
|
1380
|
+
return parsed;
|
|
1381
|
+
const { repoPath, input, remote, provider, verifyRemote } = parsed;
|
|
1382
|
+
if (!isAbsoluteDir(repoPath))
|
|
1383
|
+
return fail(400, '"repoPath" must be an absolute directory');
|
|
1384
|
+
const fieldErr = validatePrOptionalFields(remote, provider);
|
|
1385
|
+
if (fieldErr !== undefined)
|
|
1386
|
+
return fieldErr;
|
|
1387
|
+
let resolvedContext;
|
|
1388
|
+
const metaController = new AbortController();
|
|
1389
|
+
const onAbort = () => { metaController.abort(); };
|
|
1390
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1391
|
+
try {
|
|
1392
|
+
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
1393
|
+
if (facts === undefined)
|
|
1394
|
+
return fail(400, `"${repoPath}" is not inside a git repository`);
|
|
1395
|
+
const rawRemotes = await listRemotes(deps.exec, facts.repoRoot);
|
|
1396
|
+
const forge = deps.forge?.();
|
|
1397
|
+
const remotes = classifyRemotes(rawRemotes, forge);
|
|
1398
|
+
const localBranches = facts.branches.filter(b => b.kind === 'local').map(b => b.name);
|
|
1399
|
+
const resolved = resolvePrTarget({
|
|
1400
|
+
repoRoot: facts.repoRoot,
|
|
1401
|
+
input,
|
|
1402
|
+
remotes,
|
|
1403
|
+
worktrees: facts.worktrees,
|
|
1404
|
+
localBranches,
|
|
1405
|
+
...(remote === undefined ? {} : { requestedRemote: remote }),
|
|
1406
|
+
...(provider === undefined ? {} : { requestedProvider: provider }),
|
|
1407
|
+
...(forge === undefined ? {} : { forge }),
|
|
1408
|
+
});
|
|
1409
|
+
resolvedContext = { remote: resolved.remote, refSpec: resolved.refSpec, branch: resolved.localBranch };
|
|
1410
|
+
if (verifyRemote !== false && resolved.occupiedByMain !== true && resolved.existingWorktreePath === undefined) {
|
|
1411
|
+
const matchedRemote = remotes.find(r => r.name === resolved.remote);
|
|
1412
|
+
const metaPromise = resolved.meta === undefined
|
|
1413
|
+
? fetchPrMeta(forge, matchedRemote, resolved.provider, resolved.number, metaController.signal).catch(() => undefined)
|
|
1414
|
+
: Promise.resolve(undefined);
|
|
1415
|
+
const remoteSha = await probeRemoteRef(deps.exec, facts.repoRoot, resolved.remote, resolved.refSpec, signal);
|
|
1416
|
+
if (remoteSha === undefined) {
|
|
1417
|
+
metaController.abort();
|
|
1418
|
+
return failCode(400, `Could not find ref "${resolved.refSpec}" on remote "${resolved.remote}".`, 'pr_ref_not_found', { ref: resolved.refSpec, remote: resolved.remote });
|
|
1419
|
+
}
|
|
1420
|
+
const fetchedMeta = await metaPromise;
|
|
1421
|
+
if (fetchedMeta !== undefined) {
|
|
1422
|
+
return { status: 200, body: { ...resolved, meta: fetchedMeta } };
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
return { status: 200, body: resolved };
|
|
1426
|
+
}
|
|
1427
|
+
catch (error) {
|
|
1428
|
+
metaController.abort();
|
|
1429
|
+
if (error instanceof CancelledError)
|
|
1430
|
+
return fail(499, error.message);
|
|
1431
|
+
if (error instanceof PrResolutionError)
|
|
1432
|
+
return failCode(400, error.message, error.code, error.params);
|
|
1433
|
+
if (error instanceof GitError) {
|
|
1434
|
+
return resolvedContext === undefined ? gitFailure(error) : prGitFailure(error, resolvedContext);
|
|
1435
|
+
}
|
|
1436
|
+
return fail(500, error instanceof Error ? error.message : String(error));
|
|
1437
|
+
}
|
|
1438
|
+
finally {
|
|
1439
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* POST /pr-checkout — stream native `git fetch refs/pull|merge-requests` + isolated worktree
|
|
1444
|
+
* creation (or safe reuse/update/reset when the worktree already exists).
|
|
1445
|
+
* @param deps - host dependencies.
|
|
1446
|
+
* @param body - parsed request body.
|
|
1447
|
+
* @param live - optional streaming channel for NDJSON progress events.
|
|
1448
|
+
*/
|
|
1449
|
+
export async function handlePrCheckout(deps, body, live) {
|
|
1450
|
+
const parsed = readBody(body, ['repoPath', 'input'], [], ['remote', 'provider', 'ifExists']);
|
|
1451
|
+
if (isOutcome(parsed))
|
|
1452
|
+
return parsed;
|
|
1453
|
+
const { repoPath, input, remote, provider, ifExists } = parsed;
|
|
1454
|
+
if (!isAbsoluteDir(repoPath))
|
|
1455
|
+
return fail(400, '"repoPath" must be an absolute directory');
|
|
1456
|
+
const fieldErr = validatePrOptionalFields(remote, provider);
|
|
1457
|
+
if (fieldErr !== undefined)
|
|
1458
|
+
return fieldErr;
|
|
1459
|
+
if (ifExists !== undefined && ifExists !== 'reuse' && ifExists !== 'update' && ifExists !== 'reset') {
|
|
1460
|
+
return fail(400, '"ifExists" must be "reuse", "update", or "reset"');
|
|
1461
|
+
}
|
|
1462
|
+
const { run, end } = startLive(live);
|
|
1463
|
+
let resolvedContext;
|
|
1464
|
+
try {
|
|
1465
|
+
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
1466
|
+
if (facts === undefined)
|
|
1467
|
+
return fail(400, `"${repoPath}" is not inside a git repository`);
|
|
1468
|
+
const rawRemotes = await listRemotes(deps.exec, facts.repoRoot);
|
|
1469
|
+
const forge = deps.forge?.();
|
|
1470
|
+
const remotes = classifyRemotes(rawRemotes, forge);
|
|
1471
|
+
const localBranches = facts.branches.filter(b => b.kind === 'local').map(b => b.name);
|
|
1472
|
+
const resolved = resolvePrTarget({
|
|
1473
|
+
repoRoot: facts.repoRoot,
|
|
1474
|
+
input,
|
|
1475
|
+
remotes,
|
|
1476
|
+
worktrees: facts.worktrees,
|
|
1477
|
+
localBranches,
|
|
1478
|
+
...(remote === undefined ? {} : { requestedRemote: remote }),
|
|
1479
|
+
...(provider === undefined ? {} : { requestedProvider: provider }),
|
|
1480
|
+
...(forge === undefined ? {} : { forge }),
|
|
1481
|
+
});
|
|
1482
|
+
resolvedContext = { remote: resolved.remote, refSpec: resolved.refSpec, branch: resolved.localBranch };
|
|
1483
|
+
if (resolved.occupiedByMain === true) {
|
|
1484
|
+
return failCode(400, `Branch "${resolved.localBranch}" is already checked out in the main worktree.`, 'occupied_by_main', { branch: resolved.localBranch });
|
|
1485
|
+
}
|
|
1486
|
+
if (resolved.existingWorktreePath !== undefined && ifExists !== 'update' && ifExists !== 'reset') {
|
|
1487
|
+
return {
|
|
1488
|
+
status: 200,
|
|
1489
|
+
body: {
|
|
1490
|
+
path: resolved.existingWorktreePath,
|
|
1491
|
+
created: false,
|
|
1492
|
+
branch: resolved.localBranch,
|
|
1493
|
+
provider: resolved.provider,
|
|
1494
|
+
number: resolved.number,
|
|
1495
|
+
canonicalUrl: resolved.canonicalUrl,
|
|
1496
|
+
},
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
live?.emit({ type: 'stage', stage: 'fetch' });
|
|
1500
|
+
const commitSha = await fetchRefToTip(deps.exec, facts.repoRoot, resolved.remote, resolved.refSpec, run);
|
|
1501
|
+
if (live?.signal.aborted)
|
|
1502
|
+
throw new CancelledError();
|
|
1503
|
+
if (resolved.existingWorktreePath !== undefined) {
|
|
1504
|
+
live?.emit({ type: 'stage', stage: 'worktree' });
|
|
1505
|
+
const lastKnownPrSha = await readWorktreePrSha(resolved.existingWorktreePath);
|
|
1506
|
+
const updated = await updateCleanWorktreeToCommit(deps.exec, resolved.existingWorktreePath, commitSha, { forceReset: ifExists === 'reset', lastKnownPrSha });
|
|
1507
|
+
await writeWorktreePrSha(resolved.existingWorktreePath, commitSha);
|
|
1508
|
+
await writeWorktreeBaseBranch(resolved.existingWorktreePath, formatPrBaseLabel(resolved.provider, resolved.number, resolved.meta?.baseBranch));
|
|
1509
|
+
return {
|
|
1510
|
+
status: 200,
|
|
1511
|
+
body: {
|
|
1512
|
+
path: resolved.existingWorktreePath,
|
|
1513
|
+
created: false,
|
|
1514
|
+
updated: updated.updated,
|
|
1515
|
+
...(updated.mode === 'force-updated' ? { forceUpdated: true } : {}),
|
|
1516
|
+
...(updated.mode === 'reset' ? { reset: true } : {}),
|
|
1517
|
+
branch: resolved.localBranch,
|
|
1518
|
+
provider: resolved.provider,
|
|
1519
|
+
number: resolved.number,
|
|
1520
|
+
canonicalUrl: resolved.canonicalUrl,
|
|
1521
|
+
},
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
const excludeWarning = await appendWorktreeExclude(deps.excludeSeams ?? fsExcludeSeams, facts.repoRoot);
|
|
1525
|
+
const layoutRoot = join(facts.repoRoot, PROJECT_LAYOUT_DIR);
|
|
1526
|
+
live?.emit({ type: 'stage', stage: 'worktree' });
|
|
1527
|
+
await mkdirSlot(deps, layoutRoot);
|
|
1528
|
+
const added = await addWorktreeAtCommit(deps.exec, facts.repoRoot, resolved.localBranch, commitSha, resolved.targetPath, deps.dirExists);
|
|
1529
|
+
let copyWarning;
|
|
1530
|
+
if (added.created) {
|
|
1531
|
+
if (added.preservedLocalBranch !== true) {
|
|
1532
|
+
await writeWorktreePrSha(added.path, commitSha);
|
|
1533
|
+
}
|
|
1534
|
+
await writeWorktreeBaseBranch(added.path, formatPrBaseLabel(resolved.provider, resolved.number, resolved.meta?.baseBranch));
|
|
1535
|
+
live?.emit({ type: 'stage', stage: 'copy' });
|
|
1536
|
+
copyWarning = await runPostCreateCopy(deps, facts.repoRoot, added.path);
|
|
1537
|
+
}
|
|
1538
|
+
return {
|
|
1539
|
+
status: 200,
|
|
1540
|
+
body: {
|
|
1541
|
+
path: added.path,
|
|
1542
|
+
created: added.created,
|
|
1543
|
+
branch: resolved.localBranch,
|
|
1544
|
+
provider: resolved.provider,
|
|
1545
|
+
number: resolved.number,
|
|
1546
|
+
canonicalUrl: resolved.canonicalUrl,
|
|
1547
|
+
...(added.preservedLocalBranch === true ? { preservedLocalBranch: true } : {}),
|
|
1548
|
+
...(excludeWarning === undefined ? {} : { excludeWarning }),
|
|
1549
|
+
...(copyWarning === undefined ? {} : { copyWarning }),
|
|
1550
|
+
},
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
catch (error) {
|
|
1554
|
+
if (error instanceof CancelledError)
|
|
1555
|
+
return fail(499, error.message);
|
|
1556
|
+
if (error instanceof PrResolutionError)
|
|
1557
|
+
return failCode(400, error.message, error.code, error.params);
|
|
1558
|
+
if (error instanceof GitError) {
|
|
1559
|
+
return resolvedContext === undefined ? gitFailure(error) : prGitFailure(error, resolvedContext);
|
|
1560
|
+
}
|
|
1561
|
+
return fail(500, error instanceof Error ? error.message : String(error));
|
|
1562
|
+
}
|
|
1563
|
+
finally {
|
|
1564
|
+
end();
|
|
1565
|
+
}
|
|
1566
|
+
}
|