@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/git.js
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
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
|
-
import { appendFile, mkdir, readFile, rm } from 'node:fs/promises';
|
|
9
|
+
import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
9
10
|
import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:path';
|
|
10
|
-
import { localBranchName } from './normalize.js';
|
|
11
|
+
import { generateRandomBranchName, localBranchName } from './normalize.js';
|
|
11
12
|
import { stripProgress } from './progress.js';
|
|
12
13
|
/** Failure of one git invocation: non-zero exit with the stderr text. */
|
|
13
14
|
export class GitError extends Error {
|
|
@@ -463,6 +464,28 @@ export async function cutoutBranchName(exec, repoRoot, base, folderTaken) {
|
|
|
463
464
|
return candidate;
|
|
464
465
|
}
|
|
465
466
|
}
|
|
467
|
+
/**
|
|
468
|
+
* Plan a random branch name (`<stem>-<4hex>`) to cut out of `base`, avoiding
|
|
469
|
+
* collisions with existing local branches and storage folders. Remote display
|
|
470
|
+
* names (`origin/feat/x`) strip their remote prefix before generating the stem.
|
|
471
|
+
* @param exec - executor seam.
|
|
472
|
+
* @param repoRoot - main worktree directory.
|
|
473
|
+
* @param base - base branch display name (local, `<remote>/<name>`, or `HEAD`).
|
|
474
|
+
* @param folderTaken - storage-folder occupancy probe (branch name → taken).
|
|
475
|
+
* @param randomHex - optional 4-hex generator seam for deterministic tests.
|
|
476
|
+
*/
|
|
477
|
+
export async function randomCutoutBranchName(exec, repoRoot, base, folderTaken, randomHex) {
|
|
478
|
+
const out = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
479
|
+
const locals = new Set(out.split('\n').map(l => l.trim()).filter(l => l !== ''));
|
|
480
|
+
let stem = base;
|
|
481
|
+
if (base !== 'HEAD' && !locals.has(base) && base.includes('/')) {
|
|
482
|
+
const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', `refs/remotes/${base}`, '--format=%(refname:short)']);
|
|
483
|
+
if (remoteOut !== undefined && remoteOut.trim() !== '') {
|
|
484
|
+
stem = localBranchName(base);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return generateRandomBranchName(stem, candidate => locals.has(candidate) || (folderTaken?.(candidate) ?? false), randomHex);
|
|
488
|
+
}
|
|
466
489
|
/**
|
|
467
490
|
* Create a worktree on a brand-new branch cut out of `base`: the base is
|
|
468
491
|
* checked out by the main worktree (git forbids a second worktree on it),
|
|
@@ -822,13 +845,102 @@ export async function probeWorkspaceGit(exec, path) {
|
|
|
822
845
|
// Git outputs carry forward slashes on Windows — normalize every derived
|
|
823
846
|
// path so consumers can compare against join()-built ones.
|
|
824
847
|
const gitDir = normalize(resolve(path, commonDir));
|
|
848
|
+
const main = isMainWorktree(toplevel, gitDir);
|
|
849
|
+
const branch = branchName === '' || branchName === 'HEAD' ? null : branchName;
|
|
850
|
+
const rawBaseBranch = main ? undefined : await readWorktreeBaseBranch(toplevel);
|
|
851
|
+
const baseBranch = rawBaseBranch !== undefined && rawBaseBranch !== branch ? rawBaseBranch : undefined;
|
|
825
852
|
return {
|
|
826
853
|
repoRoot: dirname(gitDir),
|
|
827
854
|
repoName: basename(dirname(gitDir)),
|
|
828
|
-
branch
|
|
829
|
-
main
|
|
855
|
+
branch,
|
|
856
|
+
main,
|
|
857
|
+
...(baseBranch === undefined ? {} : { baseBranch }),
|
|
830
858
|
};
|
|
831
859
|
}
|
|
860
|
+
/** Filename inside a linked worktree's gitdir storing the base branch it was created from. */
|
|
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';
|
|
864
|
+
/** Resolve the linked worktree's private gitdir from its `.git` pointer file. */
|
|
865
|
+
async function resolveWorktreeGitDir(worktreePath) {
|
|
866
|
+
try {
|
|
867
|
+
const raw = await readFile(join(worktreePath, '.git'), 'utf8');
|
|
868
|
+
const match = /^gitdir:\s*(.+)$/m.exec(raw);
|
|
869
|
+
if (match === null)
|
|
870
|
+
return undefined;
|
|
871
|
+
const target = match[1]?.trim();
|
|
872
|
+
if (target === undefined || target === '')
|
|
873
|
+
return undefined;
|
|
874
|
+
return isAbsolute(target) ? normalize(target) : normalize(resolve(worktreePath, target));
|
|
875
|
+
}
|
|
876
|
+
catch {
|
|
877
|
+
return undefined;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Best-effort persistence of the base branch a linked worktree was created
|
|
882
|
+
* from, stored inside `<worktreeGitDir>/dsh-worktree-base` so it never dirties
|
|
883
|
+
* the working tree and is removed automatically by `git worktree remove`.
|
|
884
|
+
*/
|
|
885
|
+
export async function writeWorktreeBaseBranch(worktreePath, baseBranch) {
|
|
886
|
+
const trimmed = baseBranch.trim();
|
|
887
|
+
if (trimmed === '')
|
|
888
|
+
return;
|
|
889
|
+
const gitDir = await resolveWorktreeGitDir(worktreePath);
|
|
890
|
+
if (gitDir === undefined)
|
|
891
|
+
return;
|
|
892
|
+
try {
|
|
893
|
+
await writeFile(join(gitDir, WORKTREE_BASE_FILE), `${trimmed}\n`, 'utf8');
|
|
894
|
+
}
|
|
895
|
+
catch {
|
|
896
|
+
// Metadata persistence must never fail worktree creation.
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
/** Read the persisted base branch for a linked worktree, or undefined when absent. */
|
|
900
|
+
export async function readWorktreeBaseBranch(worktreePath) {
|
|
901
|
+
const gitDir = await resolveWorktreeGitDir(worktreePath);
|
|
902
|
+
if (gitDir === undefined)
|
|
903
|
+
return undefined;
|
|
904
|
+
try {
|
|
905
|
+
const text = (await readFile(join(gitDir, WORKTREE_BASE_FILE), 'utf8')).trim();
|
|
906
|
+
return text === '' ? undefined : text;
|
|
907
|
+
}
|
|
908
|
+
catch {
|
|
909
|
+
return undefined;
|
|
910
|
+
}
|
|
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
|
+
}
|
|
832
944
|
/** The one local-ignore rule the project-internal worktree layout needs.
|
|
833
945
|
* Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
|
|
834
946
|
* may want to commit stay trackable. */
|
|
@@ -884,3 +996,271 @@ export async function appendWorktreeExclude(seams, repoRoot) {
|
|
|
884
996
|
return error instanceof Error ? error.message : String(error);
|
|
885
997
|
}
|
|
886
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.d.ts
CHANGED
|
@@ -27,6 +27,13 @@ export interface Config {
|
|
|
27
27
|
/** Post-create configuration files to copy when .worktreeinclude is absent;
|
|
28
28
|
* absent = none. */
|
|
29
29
|
postCreateCopyFiles?: Volatile<string[]> | string[];
|
|
30
|
+
/** Hide the official top-right new-worktree control in blank sessions; absent = on. */
|
|
31
|
+
hideOfficialWorktreeEntry?: Volatile<boolean> | boolean;
|
|
32
|
+
/** Open worktrees by switching the session working directory under the parent
|
|
33
|
+
* repository workspace instead of creating a standalone workspace; absent = off. */
|
|
34
|
+
switchSessionDirectory?: Volatile<boolean> | boolean;
|
|
35
|
+
/** Include official `<repo>/.agents/worktrees` worktrees in the worktree manager; absent = off. */
|
|
36
|
+
manageOfficialWorktrees?: Volatile<boolean> | boolean;
|
|
30
37
|
}
|
|
31
38
|
/** The shipped prune cap (whole storage root, valid git worktrees only). */
|
|
32
39
|
export declare const KEEP_WORKTREES_DEFAULT = 30;
|
|
@@ -64,6 +71,12 @@ export interface SectionConfig {
|
|
|
64
71
|
keepWorktrees?: number;
|
|
65
72
|
/** Post-create configuration files to copy when .worktreeinclude is absent. */
|
|
66
73
|
postCreateCopyFiles?: string[];
|
|
74
|
+
/** Hide the official top-right new-worktree control in blank sessions; absent = on. */
|
|
75
|
+
hideOfficialWorktreeEntry?: boolean;
|
|
76
|
+
/** Switch session working directory under parent repository workspace instead of creating standalone workspaces; absent = off. */
|
|
77
|
+
switchSessionDirectory?: boolean;
|
|
78
|
+
/** Include official `<repo>/.agents/worktrees` worktrees in the worktree manager; absent = off. */
|
|
79
|
+
manageOfficialWorktrees?: boolean;
|
|
67
80
|
}
|
|
68
81
|
/** The section-shaped view of a config: absent keys stay absent
|
|
69
82
|
* (`exactOptionalPropertyTypes`) except the switches, which spell their
|