@laoyuehanni/dsh-git-worktree 0.4.15 → 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 +2 -1
- package/README.zh.md +2 -1
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/lib/client.js +2032 -509
- package/lib/deferred-worktree.d.ts +2 -1
- package/lib/deferred-worktree.js +2 -1
- package/lib/git.d.ts +76 -0
- package/lib/git.js +303 -0
- package/lib/index.js +45 -3
- package/lib/pr.d.ts +177 -0
- package/lib/pr.js +672 -0
- package/lib/routes.d.ts +30 -3
- package/lib/routes.js +392 -4
- package/lib/wire.d.ts +136 -0
- package/lib/wire.js +6 -0
- package/package.json +1 -1
|
@@ -39,11 +39,12 @@ export interface DeferredCreateOutcome {
|
|
|
39
39
|
readonly fetchWarning?: string;
|
|
40
40
|
readonly excludeWarning?: string;
|
|
41
41
|
readonly copyWarning?: string;
|
|
42
|
+
readonly trackPrUrl?: string;
|
|
42
43
|
}
|
|
43
44
|
/** Host seams injected into {@link DeferredWorktreeCoordinator}. */
|
|
44
45
|
export interface DeferredCoordinatorDeps {
|
|
45
46
|
/** Execute the plugin's worktree creation pipeline and report phase changes. */
|
|
46
|
-
readonly createWorktree: (spec: DeferredWorktreeSpec, onPhase: (phase: Exclude<DeferredWorktreePhase, 'switch'>, resolvedBranch?: string) => void) => Promise<DeferredCreateOutcome>;
|
|
47
|
+
readonly createWorktree: (spec: DeferredWorktreeSpec, onPhase: (phase: Exclude<DeferredWorktreePhase, 'switch'>, resolvedBranch?: string) => void, signal?: AbortSignal) => Promise<DeferredCreateOutcome>;
|
|
47
48
|
/** Move the Agent's working directory via DSH `ctx.workingDirectory.set`. */
|
|
48
49
|
readonly setWorkingDirectory: (agent: DeferredAgentLike, path: string, signal?: AbortSignal) => Promise<string>;
|
|
49
50
|
}
|
package/lib/deferred-worktree.js
CHANGED
|
@@ -229,7 +229,7 @@ export class DeferredWorktreeCoordinator {
|
|
|
229
229
|
publishPhase('create', spec.cutout ? spec.name : spec.branch);
|
|
230
230
|
created = await this.deps.createWorktree(spec, (phase, branch) => {
|
|
231
231
|
publishPhase(phase, branch);
|
|
232
|
-
});
|
|
232
|
+
}, signal);
|
|
233
233
|
slot.created = created;
|
|
234
234
|
signal.throwIfAborted();
|
|
235
235
|
}
|
|
@@ -243,6 +243,7 @@ export class DeferredWorktreeCoordinator {
|
|
|
243
243
|
...(created.fetchWarning === undefined ? {} : { fetchWarning: created.fetchWarning }),
|
|
244
244
|
...(created.excludeWarning === undefined ? {} : { excludeWarning: created.excludeWarning }),
|
|
245
245
|
...(created.copyWarning === undefined ? {} : { copyWarning: created.copyWarning }),
|
|
246
|
+
...(created.trackPrUrl === undefined ? {} : { trackPrUrl: created.trackPrUrl }),
|
|
246
247
|
};
|
|
247
248
|
this.slots.delete(sessionId);
|
|
248
249
|
this.emit(sessionId, { state: null, completed });
|
package/lib/git.d.ts
CHANGED
|
@@ -348,6 +348,14 @@ export declare function probeWorkspaceGit(exec: Exec, path: string): Promise<Wor
|
|
|
348
348
|
export declare function writeWorktreeBaseBranch(worktreePath: string, baseBranch: string): Promise<void>;
|
|
349
349
|
/** Read the persisted base branch for a linked worktree, or undefined when absent. */
|
|
350
350
|
export declare function readWorktreeBaseBranch(worktreePath: string): Promise<string | undefined>;
|
|
351
|
+
/**
|
|
352
|
+
* Best-effort persistence of the last fetched PR/MR commit SHA inside
|
|
353
|
+
* `<worktreeGitDir>/dsh-worktree-pr-sha` so later updates can distinguish a
|
|
354
|
+
* remote force-push (clean, zero local commits) from diverged local commits.
|
|
355
|
+
*/
|
|
356
|
+
export declare function writeWorktreePrSha(worktreePath: string, sha: string): Promise<void>;
|
|
357
|
+
/** Read the last synced PR/MR head SHA for a linked worktree, or undefined when absent. */
|
|
358
|
+
export declare function readWorktreePrSha(worktreePath: string): Promise<string | undefined>;
|
|
351
359
|
/** The one local-ignore rule the project-internal worktree layout needs.
|
|
352
360
|
* Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
|
|
353
361
|
* may want to commit stay trackable. */
|
|
@@ -382,3 +390,71 @@ export declare const fsExcludeSeams: ExcludeSeams;
|
|
|
382
390
|
* failure text otherwise.
|
|
383
391
|
*/
|
|
384
392
|
export declare function appendWorktreeExclude(seams: ExcludeSeams, repoRoot: string): Promise<string | undefined>;
|
|
393
|
+
/**
|
|
394
|
+
* List repository remotes with their fetch URL, preserving git order and deduplicating names.
|
|
395
|
+
* @param exec - executor seam.
|
|
396
|
+
* @param repoRoot - main worktree directory.
|
|
397
|
+
*/
|
|
398
|
+
export declare function listRemotes(exec: Exec, repoRoot: string): Promise<Array<{
|
|
399
|
+
name: string;
|
|
400
|
+
url: string;
|
|
401
|
+
}>>;
|
|
402
|
+
/**
|
|
403
|
+
* Probe whether a specific ref (e.g. `refs/pull/42/head` or `refs/merge-requests/17/head`)
|
|
404
|
+
* exists on `remote` via `git ls-remote` without transferring any Git objects.
|
|
405
|
+
* Returns the tip commit SHA when present, or `undefined` when the remote is reachable
|
|
406
|
+
* and does not advertise the ref.
|
|
407
|
+
* @param exec - executor seam.
|
|
408
|
+
* @param repoRoot - main worktree directory.
|
|
409
|
+
* @param remote - target remote name.
|
|
410
|
+
* @param refSpec - exact remote ref name to check.
|
|
411
|
+
* @param signal - optional cancellation signal that kills the child process tree on abort.
|
|
412
|
+
*/
|
|
413
|
+
export declare function probeRemoteRef(exec: Exec, repoRoot: string, remote: string, refSpec: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
414
|
+
/**
|
|
415
|
+
* Fetch an explicit remote ref (e.g. `refs/pull/42/head`) into a unique temporary ref
|
|
416
|
+
* and return its commit SHA without touching `FETCH_HEAD`, any local branch, or the working tree.
|
|
417
|
+
* @param exec - executor seam.
|
|
418
|
+
* @param repoRoot - main worktree directory.
|
|
419
|
+
* @param remote - target remote name.
|
|
420
|
+
* @param refSpec - remote ref to fetch.
|
|
421
|
+
* @param live - optional streaming progress and cancellation.
|
|
422
|
+
*/
|
|
423
|
+
export declare function fetchRefToTip(exec: Exec, repoRoot: string, remote: string, refSpec: string, live?: LiveRun): Promise<string>;
|
|
424
|
+
/**
|
|
425
|
+
* Create (or reuse) a linked worktree for `branch` pointing at `commitSha`.
|
|
426
|
+
* - If a live worktree already holds `branch`, returns it unchanged (`created: false`).
|
|
427
|
+
* - If `branch` does not exist yet, creates it at `commitSha` via `git worktree add <path> -b <branch> <sha>`.
|
|
428
|
+
* - If `branch` already exists locally without a worktree: fast-forwards it when it is an ancestor of
|
|
429
|
+
* `commitSha`, or preserves the local branch untouched (`preservedLocalBranch: true`) when it has local-only commits.
|
|
430
|
+
*/
|
|
431
|
+
export declare function addWorktreeAtCommit(exec: Exec, repoRoot: string, branch: string, commitSha: string, targetPath: string, dirExists?: DirExists): Promise<{
|
|
432
|
+
path: string;
|
|
433
|
+
created: boolean;
|
|
434
|
+
preservedLocalBranch?: boolean;
|
|
435
|
+
}>;
|
|
436
|
+
/**
|
|
437
|
+
* Return whether a worktree contains tracked or staged uncommitted changes
|
|
438
|
+
* (`--untracked-files=no`), ignoring pure untracked files such as copied
|
|
439
|
+
* `.worktreeinclude` config files (e.g. `.env.local`).
|
|
440
|
+
*/
|
|
441
|
+
export declare function hasTrackedChanges(exec: Exec, worktreePath: string): Promise<boolean>;
|
|
442
|
+
/**
|
|
443
|
+
* Sync an existing clean linked PR/MR worktree to `commitSha`:
|
|
444
|
+
* - refuses immediately if tracked/staged uncommitted changes exist (pure untracked or ignored
|
|
445
|
+
* files such as `.worktreeinclude` copies do not block syncing unless they collide with `commitSha`);
|
|
446
|
+
* - returns `up-to-date` when HEAD already equals `commitSha`;
|
|
447
|
+
* - fast-forwards when HEAD is an ancestor of `commitSha`;
|
|
448
|
+
* - when histories diverged (e.g. PR author rebased & force-pushed): safely resets via
|
|
449
|
+
* `git reset --hard <sha>` if `HEAD === lastKnownPrSha` (proving zero local-only commits),
|
|
450
|
+
* or if `forceReset: true` (after explicit user confirmation);
|
|
451
|
+
* - refuses to overwrite colliding untracked or `.gitignore`-ignored local files on all update paths;
|
|
452
|
+
* - otherwise refuses with a clear GitError so local commits are never silently discarded.
|
|
453
|
+
*/
|
|
454
|
+
export declare function updateCleanWorktreeToCommit(exec: Exec, worktreePath: string, commitSha: string, options?: {
|
|
455
|
+
readonly forceReset?: boolean;
|
|
456
|
+
readonly lastKnownPrSha?: string | undefined;
|
|
457
|
+
}): Promise<{
|
|
458
|
+
updated: boolean;
|
|
459
|
+
mode: 'up-to-date' | 'ff' | 'force-updated' | 'reset';
|
|
460
|
+
}>;
|
package/lib/git.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* argument assembly plus porcelain parsing, no ambient state.
|
|
5
5
|
*/
|
|
6
6
|
import { execFile, spawn } from 'node:child_process';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
7
8
|
import { existsSync, readdirSync } from 'node:fs';
|
|
8
9
|
import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
9
10
|
import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:path';
|
|
@@ -858,6 +859,8 @@ export async function probeWorkspaceGit(exec, path) {
|
|
|
858
859
|
}
|
|
859
860
|
/** Filename inside a linked worktree's gitdir storing the base branch it was created from. */
|
|
860
861
|
const WORKTREE_BASE_FILE = 'dsh-worktree-base';
|
|
862
|
+
/** Filename inside a linked PR/MR worktree's gitdir storing the last synced PR head commit SHA. */
|
|
863
|
+
const WORKTREE_PR_SHA_FILE = 'dsh-worktree-pr-sha';
|
|
861
864
|
/** Resolve the linked worktree's private gitdir from its `.git` pointer file. */
|
|
862
865
|
async function resolveWorktreeGitDir(worktreePath) {
|
|
863
866
|
try {
|
|
@@ -906,6 +909,38 @@ export async function readWorktreeBaseBranch(worktreePath) {
|
|
|
906
909
|
return undefined;
|
|
907
910
|
}
|
|
908
911
|
}
|
|
912
|
+
/**
|
|
913
|
+
* Best-effort persistence of the last fetched PR/MR commit SHA inside
|
|
914
|
+
* `<worktreeGitDir>/dsh-worktree-pr-sha` so later updates can distinguish a
|
|
915
|
+
* remote force-push (clean, zero local commits) from diverged local commits.
|
|
916
|
+
*/
|
|
917
|
+
export async function writeWorktreePrSha(worktreePath, sha) {
|
|
918
|
+
const trimmed = sha.trim();
|
|
919
|
+
if (trimmed === '')
|
|
920
|
+
return;
|
|
921
|
+
const gitDir = await resolveWorktreeGitDir(worktreePath);
|
|
922
|
+
if (gitDir === undefined)
|
|
923
|
+
return;
|
|
924
|
+
try {
|
|
925
|
+
await writeFile(join(gitDir, WORKTREE_PR_SHA_FILE), `${trimmed}\n`, 'utf8');
|
|
926
|
+
}
|
|
927
|
+
catch {
|
|
928
|
+
// Metadata persistence must never fail worktree creation or update.
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
/** Read the last synced PR/MR head SHA for a linked worktree, or undefined when absent. */
|
|
932
|
+
export async function readWorktreePrSha(worktreePath) {
|
|
933
|
+
const gitDir = await resolveWorktreeGitDir(worktreePath);
|
|
934
|
+
if (gitDir === undefined)
|
|
935
|
+
return undefined;
|
|
936
|
+
try {
|
|
937
|
+
const text = (await readFile(join(gitDir, WORKTREE_PR_SHA_FILE), 'utf8')).trim();
|
|
938
|
+
return text === '' ? undefined : text;
|
|
939
|
+
}
|
|
940
|
+
catch {
|
|
941
|
+
return undefined;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
909
944
|
/** The one local-ignore rule the project-internal worktree layout needs.
|
|
910
945
|
* Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
|
|
911
946
|
* may want to commit stay trackable. */
|
|
@@ -961,3 +996,271 @@ export async function appendWorktreeExclude(seams, repoRoot) {
|
|
|
961
996
|
return error instanceof Error ? error.message : String(error);
|
|
962
997
|
}
|
|
963
998
|
}
|
|
999
|
+
/**
|
|
1000
|
+
* List repository remotes with their fetch URL, preserving git order and deduplicating names.
|
|
1001
|
+
* @param exec - executor seam.
|
|
1002
|
+
* @param repoRoot - main worktree directory.
|
|
1003
|
+
*/
|
|
1004
|
+
export async function listRemotes(exec, repoRoot) {
|
|
1005
|
+
const out = await gitMaybe(exec, repoRoot, ['remote', '-v']);
|
|
1006
|
+
if (out === undefined)
|
|
1007
|
+
return [];
|
|
1008
|
+
const byName = new Map();
|
|
1009
|
+
for (const line of out.split('\n')) {
|
|
1010
|
+
const trimmed = line.trim();
|
|
1011
|
+
if (trimmed === '')
|
|
1012
|
+
continue;
|
|
1013
|
+
const match = /^(\S+)\s+(\S+)(?:\s+\((fetch|push)\))?$/.exec(trimmed);
|
|
1014
|
+
if (match === null)
|
|
1015
|
+
continue;
|
|
1016
|
+
const name = match[1];
|
|
1017
|
+
const url = match[2];
|
|
1018
|
+
const kind = match[3];
|
|
1019
|
+
if (name === undefined || url === undefined)
|
|
1020
|
+
continue;
|
|
1021
|
+
if (kind === 'fetch' || !byName.has(name)) {
|
|
1022
|
+
byName.set(name, url);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
return [...byName.entries()].map(([name, url]) => ({ name, url }));
|
|
1026
|
+
}
|
|
1027
|
+
/** Timeout for lightweight `git ls-remote` PR/MR ref existence probes. */
|
|
1028
|
+
const REMOTE_REF_PROBE_TIMEOUT_MS = 12_000;
|
|
1029
|
+
/**
|
|
1030
|
+
* Probe whether a specific ref (e.g. `refs/pull/42/head` or `refs/merge-requests/17/head`)
|
|
1031
|
+
* exists on `remote` via `git ls-remote` without transferring any Git objects.
|
|
1032
|
+
* Returns the tip commit SHA when present, or `undefined` when the remote is reachable
|
|
1033
|
+
* and does not advertise the ref.
|
|
1034
|
+
* @param exec - executor seam.
|
|
1035
|
+
* @param repoRoot - main worktree directory.
|
|
1036
|
+
* @param remote - target remote name.
|
|
1037
|
+
* @param refSpec - exact remote ref name to check.
|
|
1038
|
+
* @param signal - optional cancellation signal that kills the child process tree on abort.
|
|
1039
|
+
*/
|
|
1040
|
+
export async function probeRemoteRef(exec, repoRoot, remote, refSpec, signal) {
|
|
1041
|
+
if (signal?.aborted)
|
|
1042
|
+
throw new CancelledError();
|
|
1043
|
+
const res = await exec('git', ['ls-remote', '--', remote, refSpec], {
|
|
1044
|
+
cwd: repoRoot,
|
|
1045
|
+
nonInteractive: true,
|
|
1046
|
+
timeoutMs: REMOTE_REF_PROBE_TIMEOUT_MS,
|
|
1047
|
+
...(signal === undefined ? {} : { signal }),
|
|
1048
|
+
});
|
|
1049
|
+
if (res.cancelled)
|
|
1050
|
+
throw new CancelledError();
|
|
1051
|
+
if (res.code !== 0)
|
|
1052
|
+
throw new GitError(['ls-remote', remote, refSpec], res.code, res.stderr);
|
|
1053
|
+
for (const line of res.stdout.split(/\r?\n/)) {
|
|
1054
|
+
const trimmed = line.trim();
|
|
1055
|
+
if (trimmed === '')
|
|
1056
|
+
continue;
|
|
1057
|
+
const [sha, name] = trimmed.split(/\s+/);
|
|
1058
|
+
if (sha !== undefined && sha !== '' && name === refSpec)
|
|
1059
|
+
return sha;
|
|
1060
|
+
}
|
|
1061
|
+
return undefined;
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Fetch an explicit remote ref (e.g. `refs/pull/42/head`) into a unique temporary ref
|
|
1065
|
+
* and return its commit SHA without touching `FETCH_HEAD`, any local branch, or the working tree.
|
|
1066
|
+
* @param exec - executor seam.
|
|
1067
|
+
* @param repoRoot - main worktree directory.
|
|
1068
|
+
* @param remote - target remote name.
|
|
1069
|
+
* @param refSpec - remote ref to fetch.
|
|
1070
|
+
* @param live - optional streaming progress and cancellation.
|
|
1071
|
+
*/
|
|
1072
|
+
export async function fetchRefToTip(exec, repoRoot, remote, refSpec, live) {
|
|
1073
|
+
const tmpRef = `refs/dsh-pr-tmp/${randomUUID()}`;
|
|
1074
|
+
const fetchSpec = `+${refSpec}:${tmpRef}`;
|
|
1075
|
+
try {
|
|
1076
|
+
if (live === undefined) {
|
|
1077
|
+
const res = await exec('git', ['fetch', '--no-tags', '--', remote, fetchSpec], { cwd: repoRoot, nonInteractive: true });
|
|
1078
|
+
if (res.code !== 0)
|
|
1079
|
+
throw new GitError(['fetch', remote, refSpec], res.code, res.stderr);
|
|
1080
|
+
}
|
|
1081
|
+
else {
|
|
1082
|
+
live.onRemote?.(remote);
|
|
1083
|
+
const res = await exec('git', ['fetch', '--no-tags', '--progress', '--', remote, fetchSpec], {
|
|
1084
|
+
cwd: repoRoot,
|
|
1085
|
+
nonInteractive: true,
|
|
1086
|
+
...liveExecOptions(live),
|
|
1087
|
+
});
|
|
1088
|
+
if (res.cancelled)
|
|
1089
|
+
throw new CancelledError();
|
|
1090
|
+
if (res.code !== 0)
|
|
1091
|
+
throw new GitError(['fetch', remote, refSpec], res.code, stripProgress(res.stderr));
|
|
1092
|
+
}
|
|
1093
|
+
const sha = (await git(exec, repoRoot, ['rev-parse', '--verify', tmpRef])).trim();
|
|
1094
|
+
if (sha === '')
|
|
1095
|
+
throw new GitError(['rev-parse', tmpRef], 1, 'fetched ref is empty');
|
|
1096
|
+
return sha;
|
|
1097
|
+
}
|
|
1098
|
+
finally {
|
|
1099
|
+
await exec('git', ['update-ref', '-d', tmpRef], { cwd: repoRoot, nonInteractive: true }).catch(() => undefined);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Create (or reuse) a linked worktree for `branch` pointing at `commitSha`.
|
|
1104
|
+
* - If a live worktree already holds `branch`, returns it unchanged (`created: false`).
|
|
1105
|
+
* - If `branch` does not exist yet, creates it at `commitSha` via `git worktree add <path> -b <branch> <sha>`.
|
|
1106
|
+
* - If `branch` already exists locally without a worktree: fast-forwards it when it is an ancestor of
|
|
1107
|
+
* `commitSha`, or preserves the local branch untouched (`preservedLocalBranch: true`) when it has local-only commits.
|
|
1108
|
+
*/
|
|
1109
|
+
export async function addWorktreeAtCommit(exec, repoRoot, branch, commitSha, targetPath, dirExists = fsDirExists) {
|
|
1110
|
+
let worktrees = await listWorktrees(exec, repoRoot);
|
|
1111
|
+
const mainHolder = worktrees.find(w => w.main && w.branch === branch);
|
|
1112
|
+
if (mainHolder !== undefined) {
|
|
1113
|
+
throw new GitError(['worktree', 'add', targetPath, branch], 1, `branch "${branch}" is already checked out in the main worktree`);
|
|
1114
|
+
}
|
|
1115
|
+
const existing = worktrees.find(w => !w.main && w.branch === branch);
|
|
1116
|
+
if (existing !== undefined && dirExists(existing.path)) {
|
|
1117
|
+
return { path: existing.path, created: false };
|
|
1118
|
+
}
|
|
1119
|
+
if (existing !== undefined) {
|
|
1120
|
+
await git(exec, repoRoot, ['worktree', 'prune']);
|
|
1121
|
+
worktrees = await listWorktrees(exec, repoRoot);
|
|
1122
|
+
const afterPrune = worktrees.find(w => !w.main && w.branch === branch);
|
|
1123
|
+
if (afterPrune !== undefined && dirExists(afterPrune.path)) {
|
|
1124
|
+
return { path: afterPrune.path, created: false };
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
const hasBranch = (await exec('git', ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], { cwd: repoRoot })).code === 0;
|
|
1128
|
+
if (!hasBranch) {
|
|
1129
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, '-b', branch, commitSha]);
|
|
1130
|
+
return { path: targetPath, created: true };
|
|
1131
|
+
}
|
|
1132
|
+
const canFastForward = (await exec('git', ['merge-base', '--is-ancestor', `refs/heads/${branch}`, commitSha], { cwd: repoRoot })).code === 0;
|
|
1133
|
+
if (canFastForward) {
|
|
1134
|
+
await git(exec, repoRoot, ['branch', '-f', branch, commitSha]);
|
|
1135
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, branch]);
|
|
1136
|
+
return { path: targetPath, created: true };
|
|
1137
|
+
}
|
|
1138
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, branch]);
|
|
1139
|
+
return { path: targetPath, created: true, preservedLocalBranch: true };
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Return whether a worktree contains tracked or staged uncommitted changes
|
|
1143
|
+
* (`--untracked-files=no`), ignoring pure untracked files such as copied
|
|
1144
|
+
* `.worktreeinclude` config files (e.g. `.env.local`).
|
|
1145
|
+
*/
|
|
1146
|
+
export async function hasTrackedChanges(exec, worktreePath) {
|
|
1147
|
+
const status = await git(exec, worktreePath, ['status', '--porcelain', '--untracked-files=no']);
|
|
1148
|
+
return status.split('\n').some(line => line.trim() !== '');
|
|
1149
|
+
}
|
|
1150
|
+
function normalizeGitPathForCollision(filePath) {
|
|
1151
|
+
const unified = filePath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
|
1152
|
+
return process.platform === 'win32' || process.platform === 'darwin'
|
|
1153
|
+
? unified.toLowerCase()
|
|
1154
|
+
: unified;
|
|
1155
|
+
}
|
|
1156
|
+
function addPathAncestors(target, normalizedPath) {
|
|
1157
|
+
let slash = normalizedPath.lastIndexOf('/');
|
|
1158
|
+
while (slash > 0) {
|
|
1159
|
+
target.add(normalizedPath.slice(0, slash));
|
|
1160
|
+
slash = normalizedPath.lastIndexOf('/', slash - 1);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
function checkFileCollision(file, targetFiles, targetDirs, commitSha) {
|
|
1164
|
+
const norm = normalizeGitPathForCollision(file);
|
|
1165
|
+
if (targetFiles.has(norm) || targetDirs.has(norm)) {
|
|
1166
|
+
throw new GitError(['update', commitSha], 1, `untracked working tree file "${file}" would be overwritten by update; move or remove it before updating`);
|
|
1167
|
+
}
|
|
1168
|
+
let slash = norm.lastIndexOf('/');
|
|
1169
|
+
while (slash > 0) {
|
|
1170
|
+
if (targetFiles.has(norm.slice(0, slash))) {
|
|
1171
|
+
throw new GitError(['update', commitSha], 1, `untracked working tree file "${file}" would be overwritten by update; move or remove it before updating`);
|
|
1172
|
+
}
|
|
1173
|
+
slash = norm.lastIndexOf('/', slash - 1);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Guard PR worktree updates (`merge --ff-only` and `reset --hard`) against silently
|
|
1178
|
+
* overwriting untracked or `.gitignore`-ignored local files (such as `.worktreeinclude`
|
|
1179
|
+
* copies like `.env.local`) when `commitSha` introduces a tracked file at the same path
|
|
1180
|
+
* or a colliding file/directory prefix.
|
|
1181
|
+
*/
|
|
1182
|
+
async function assertNoUntrackedOrIgnoredOverwriteCollision(exec, worktreePath, commitSha) {
|
|
1183
|
+
const untrackedRaw = await git(exec, worktreePath, ['ls-files', '--others', '--exclude-standard', '-z']);
|
|
1184
|
+
const untracked = untrackedRaw.split('\0').filter(Boolean);
|
|
1185
|
+
const ignoredRaw = await git(exec, worktreePath, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z']);
|
|
1186
|
+
const ignoredEntries = ignoredRaw.split('\0').filter(Boolean);
|
|
1187
|
+
if (untracked.length === 0 && ignoredEntries.length === 0)
|
|
1188
|
+
return;
|
|
1189
|
+
const treeRaw = await git(exec, worktreePath, ['ls-tree', '-r', '--name-only', '-z', commitSha]);
|
|
1190
|
+
const targetFiles = new Set();
|
|
1191
|
+
const targetDirs = new Set();
|
|
1192
|
+
for (const entry of treeRaw.split('\0')) {
|
|
1193
|
+
if (entry === '')
|
|
1194
|
+
continue;
|
|
1195
|
+
const norm = normalizeGitPathForCollision(entry);
|
|
1196
|
+
targetFiles.add(norm);
|
|
1197
|
+
addPathAncestors(targetDirs, norm);
|
|
1198
|
+
}
|
|
1199
|
+
for (const file of untracked) {
|
|
1200
|
+
checkFileCollision(file, targetFiles, targetDirs, commitSha);
|
|
1201
|
+
}
|
|
1202
|
+
for (const entry of ignoredEntries) {
|
|
1203
|
+
if (!entry.endsWith('/')) {
|
|
1204
|
+
checkFileCollision(entry, targetFiles, targetDirs, commitSha);
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
const dirPath = entry.slice(0, -1);
|
|
1208
|
+
const dirNorm = normalizeGitPathForCollision(dirPath);
|
|
1209
|
+
if (targetFiles.has(dirNorm)) {
|
|
1210
|
+
throw new GitError(['update', commitSha], 1, `untracked working tree file "${dirPath}" would be overwritten by update; move or remove it before updating`);
|
|
1211
|
+
}
|
|
1212
|
+
let slash = dirNorm.lastIndexOf('/');
|
|
1213
|
+
while (slash > 0) {
|
|
1214
|
+
if (targetFiles.has(dirNorm.slice(0, slash))) {
|
|
1215
|
+
throw new GitError(['update', commitSha], 1, `untracked working tree file "${dirPath}" would be overwritten by update; move or remove it before updating`);
|
|
1216
|
+
}
|
|
1217
|
+
slash = dirNorm.lastIndexOf('/', slash - 1);
|
|
1218
|
+
}
|
|
1219
|
+
if (targetDirs.has(dirNorm)) {
|
|
1220
|
+
// Only descend into ignored directories that overlap with paths in commitSha
|
|
1221
|
+
// (avoids scanning unrelated heavy directories like node_modules/).
|
|
1222
|
+
const nestedRaw = await git(exec, worktreePath, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', dirPath]);
|
|
1223
|
+
for (const nestedFile of nestedRaw.split('\0').filter(Boolean)) {
|
|
1224
|
+
checkFileCollision(nestedFile, targetFiles, targetDirs, commitSha);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Sync an existing clean linked PR/MR worktree to `commitSha`:
|
|
1231
|
+
* - refuses immediately if tracked/staged uncommitted changes exist (pure untracked or ignored
|
|
1232
|
+
* files such as `.worktreeinclude` copies do not block syncing unless they collide with `commitSha`);
|
|
1233
|
+
* - returns `up-to-date` when HEAD already equals `commitSha`;
|
|
1234
|
+
* - fast-forwards when HEAD is an ancestor of `commitSha`;
|
|
1235
|
+
* - when histories diverged (e.g. PR author rebased & force-pushed): safely resets via
|
|
1236
|
+
* `git reset --hard <sha>` if `HEAD === lastKnownPrSha` (proving zero local-only commits),
|
|
1237
|
+
* or if `forceReset: true` (after explicit user confirmation);
|
|
1238
|
+
* - refuses to overwrite colliding untracked or `.gitignore`-ignored local files on all update paths;
|
|
1239
|
+
* - otherwise refuses with a clear GitError so local commits are never silently discarded.
|
|
1240
|
+
*/
|
|
1241
|
+
export async function updateCleanWorktreeToCommit(exec, worktreePath, commitSha, options) {
|
|
1242
|
+
if (await hasTrackedChanges(exec, worktreePath)) {
|
|
1243
|
+
throw new GitError(['merge', '--ff-only'], 1, 'worktree has uncommitted changes; commit or stash them before updating');
|
|
1244
|
+
}
|
|
1245
|
+
const before = (await git(exec, worktreePath, ['rev-parse', 'HEAD'])).trim();
|
|
1246
|
+
if (before === commitSha)
|
|
1247
|
+
return { updated: false, mode: 'up-to-date' };
|
|
1248
|
+
if (options?.forceReset === true) {
|
|
1249
|
+
await assertNoUntrackedOrIgnoredOverwriteCollision(exec, worktreePath, commitSha);
|
|
1250
|
+
await git(exec, worktreePath, ['reset', '--hard', commitSha]);
|
|
1251
|
+
return { updated: true, mode: 'reset' };
|
|
1252
|
+
}
|
|
1253
|
+
const canFastForward = (await exec('git', ['merge-base', '--is-ancestor', before, commitSha], { cwd: worktreePath })).code === 0;
|
|
1254
|
+
if (canFastForward) {
|
|
1255
|
+
await assertNoUntrackedOrIgnoredOverwriteCollision(exec, worktreePath, commitSha);
|
|
1256
|
+
await git(exec, worktreePath, ['merge', '--ff-only', commitSha]);
|
|
1257
|
+
const after = (await git(exec, worktreePath, ['rev-parse', 'HEAD'])).trim();
|
|
1258
|
+
return { updated: before !== after, mode: before !== after ? 'ff' : 'up-to-date' };
|
|
1259
|
+
}
|
|
1260
|
+
if (options?.lastKnownPrSha !== undefined && before === options.lastKnownPrSha) {
|
|
1261
|
+
await assertNoUntrackedOrIgnoredOverwriteCollision(exec, worktreePath, commitSha);
|
|
1262
|
+
await git(exec, worktreePath, ['reset', '--hard', commitSha]);
|
|
1263
|
+
return { updated: true, mode: 'force-updated' };
|
|
1264
|
+
}
|
|
1265
|
+
throw new GitError(['merge', '--ff-only'], 1, 'PR worktree has diverged local commits');
|
|
1266
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -9,12 +9,13 @@ import { homedir } from 'node:os';
|
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
10
|
import { DeferredWorktreeCoordinator } from './deferred-worktree.js';
|
|
11
11
|
import { childProcessExec } from './git.js';
|
|
12
|
-
import {
|
|
12
|
+
import { isForgeServiceLike } from './pr.js';
|
|
13
|
+
import { executeCreateWorktree, handleArmDeferredWorktree, handleCreateBranch, handleCreateWorktree, handleDeferredWorktreeAction, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGetDeferredWorktree, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePrCheckout, handlePrContext, handlePrResolve, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleSetSessionDirectory, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
13
14
|
import { validateRootDir } from './settings.js';
|
|
14
15
|
import { handleAuthors, handleHistory, handleCommit } from './routes.js';
|
|
15
16
|
import { ROUTE_AUTHORS, ROUTE_HISTORY, ROUTE_COMMIT } from './wire.js';
|
|
16
17
|
import { streamRoute } from './stream.js';
|
|
17
|
-
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_DEFERRED, ROUTE_DEFERRED_ACTION, ROUTE_DEFERRED_ARM, ROUTE_DEFERRED_EVENTS, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_SESSION_CWD, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
18
|
+
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_DEFERRED, ROUTE_DEFERRED_ACTION, ROUTE_DEFERRED_ARM, ROUTE_DEFERRED_EVENTS, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PR_CHECKOUT, ROUTE_PR_CONTEXT, ROUTE_PR_RESOLVE, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_SESSION_CWD, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
18
19
|
export const name = 'dsh-git-worktree';
|
|
19
20
|
export const inject = [];
|
|
20
21
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
@@ -153,12 +154,14 @@ export function apply(ctx, config = {}) {
|
|
|
153
154
|
const currentConfig = () => ctx.fiber?.config ?? config;
|
|
154
155
|
let sessionDirectorySetter;
|
|
155
156
|
let deferredWorktrees;
|
|
157
|
+
let forgeService;
|
|
156
158
|
const baseDeps = () => ({
|
|
157
159
|
exec: childProcessExec,
|
|
158
160
|
sectionRootDir: () => readVolatile(currentConfig().rootDir),
|
|
159
161
|
sectionFetchBeforeCreate: () => readVolatile(currentConfig().fetchBeforeCreate),
|
|
160
162
|
sectionPostCreateCopyFiles: () => readVolatile(currentConfig().postCreateCopyFiles),
|
|
161
163
|
sectionManageOfficialWorktrees: () => readVolatile(currentConfig().manageOfficialWorktrees),
|
|
164
|
+
forge: () => forgeService,
|
|
162
165
|
...(sessionDirectorySetter === undefined ? {} : { setSessionDirectory: sessionDirectorySetter }),
|
|
163
166
|
...(deferredWorktrees === undefined ? {} : { deferredWorktrees }),
|
|
164
167
|
home: () => homedir(),
|
|
@@ -166,6 +169,16 @@ export function apply(ctx, config = {}) {
|
|
|
166
169
|
});
|
|
167
170
|
if (typeof ctx.inject === 'function') {
|
|
168
171
|
const injectOptional = ctx.inject.bind(ctx);
|
|
172
|
+
injectOptional(['forge'], (forgeCtx) => {
|
|
173
|
+
const candidate = forgeCtx.forge;
|
|
174
|
+
if (isForgeServiceLike(candidate)) {
|
|
175
|
+
forgeService = candidate;
|
|
176
|
+
forgeCtx.effect(() => () => {
|
|
177
|
+
if (forgeService === candidate)
|
|
178
|
+
forgeService = undefined;
|
|
179
|
+
}, 'git-worktree: optional forge bridge');
|
|
180
|
+
}
|
|
181
|
+
});
|
|
169
182
|
injectOptional(['agents', 'workingDirectory'], (hostCtx) => {
|
|
170
183
|
const agentsCandidate = hostCtx.agents;
|
|
171
184
|
const workingDirCandidate = hostCtx.workingDirectory;
|
|
@@ -188,7 +201,7 @@ export function apply(ctx, config = {}) {
|
|
|
188
201
|
throw withHttpStatus(`Session "${sessionId}" is not loaded`, 404);
|
|
189
202
|
};
|
|
190
203
|
const coordinator = new DeferredWorktreeCoordinator({
|
|
191
|
-
createWorktree: (spec, onPhase) => executeCreateWorktree(baseDeps(), spec, onPhase),
|
|
204
|
+
createWorktree: (spec, onPhase, signal) => executeCreateWorktree(baseDeps(), spec, onPhase, signal),
|
|
192
205
|
setWorkingDirectory: (agent, targetPath, signal) => workingDirCandidate.set(agent, targetPath, signal),
|
|
193
206
|
});
|
|
194
207
|
sessionDirectorySetter = setter;
|
|
@@ -389,5 +402,34 @@ export function apply(ctx, config = {}) {
|
|
|
389
402
|
} }), 'git-worktree: deferred-events route');
|
|
390
403
|
postRoute(ROUTE_DEFERRED_ARM, 'deferred-arm', handleArmDeferredWorktree);
|
|
391
404
|
postRoute(ROUTE_DEFERRED_ACTION, 'deferred-action', handleDeferredWorktreeAction);
|
|
405
|
+
const cancellablePostRoute = (path, label, handle) => {
|
|
406
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path, handler: async (req, res) => {
|
|
407
|
+
let body;
|
|
408
|
+
try {
|
|
409
|
+
body = await readJson(req);
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const controller = new AbortController();
|
|
416
|
+
res.on('close', () => {
|
|
417
|
+
if (!res.writableEnded)
|
|
418
|
+
controller.abort();
|
|
419
|
+
});
|
|
420
|
+
try {
|
|
421
|
+
const outcome = await handle(deps(), body, controller.signal);
|
|
422
|
+
if (!res.writableEnded)
|
|
423
|
+
send(res, outcome);
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
if (!res.writableEnded)
|
|
427
|
+
send(res, { status: 500, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
428
|
+
}
|
|
429
|
+
} }), `git-worktree: ${label} route`);
|
|
430
|
+
};
|
|
431
|
+
cancellablePostRoute(ROUTE_PR_CONTEXT, 'pr-context', handlePrContext);
|
|
432
|
+
cancellablePostRoute(ROUTE_PR_RESOLVE, 'pr-resolve', handlePrResolve);
|
|
433
|
+
streamPostRoute(ROUTE_PR_CHECKOUT, 'pr-checkout', handlePrCheckout);
|
|
392
434
|
});
|
|
393
435
|
}
|