dsh-git-desk 0.20.0 → 0.22.0

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.
@@ -323,6 +323,141 @@ export async function findRepository(runtime, directory) {
323
323
  const root = result.stdout.trim();
324
324
  return root === '' ? null : root;
325
325
  }
326
+ /**
327
+ * Read the absolute Git directory and common Git directory of a checkout.
328
+ * @param runtime the runtime helpers.
329
+ * @param root the checkout root.
330
+ * @returns the directories, or null when Git cannot report them.
331
+ */
332
+ async function gitDirs(runtime, root) {
333
+ const result = await runtime.run(root, ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir']);
334
+ if (result.code !== 0)
335
+ return null;
336
+ const lines = result.stdout
337
+ .split('\n')
338
+ .map((line) => line.trim())
339
+ .filter((line) => line !== '');
340
+ const gitDir = lines[0];
341
+ const commonDir = lines[1];
342
+ if (gitDir === undefined || commonDir === undefined)
343
+ return null;
344
+ return { gitDir, commonDir };
345
+ }
346
+ /**
347
+ * Resolve one path, falling back to the input when it is gone.
348
+ * @param runtime the runtime helpers.
349
+ * @param target the path.
350
+ * @returns the resolved path.
351
+ */
352
+ async function realOrSelf(runtime, target) {
353
+ try {
354
+ return await runtime.realpath(target);
355
+ }
356
+ catch {
357
+ return target;
358
+ }
359
+ }
360
+ /**
361
+ * Tell whether one path still resolves.
362
+ * @param runtime the runtime helpers.
363
+ * @param target the path.
364
+ * @returns whether the path exists.
365
+ */
366
+ async function resolves(runtime, target) {
367
+ try {
368
+ await runtime.realpath(target);
369
+ return true;
370
+ }
371
+ catch {
372
+ return false;
373
+ }
374
+ }
375
+ /**
376
+ * Tell whether one path names a directory or sits inside it.
377
+ * @param parent the directory.
378
+ * @param child the path.
379
+ * @returns whether the child is the directory or is inside it.
380
+ */
381
+ function containsPath(parent, child) {
382
+ return child === parent || child.startsWith(`${parent}${path.sep}`);
383
+ }
384
+ /**
385
+ * Parse one `git worktree list --porcelain -z` record.
386
+ * @param fields the record fields.
387
+ * @returns the worktree.
388
+ */
389
+ function parseWorktree(fields) {
390
+ const record = { path: '', branch: null, prunable: false, bare: false };
391
+ for (const field of fields) {
392
+ if (field.startsWith('worktree '))
393
+ record.path = field.slice('worktree '.length);
394
+ else if (field.startsWith('branch '))
395
+ record.branch = field.slice('branch '.length).replace(/^refs\/heads\//, '');
396
+ else if (field === 'bare')
397
+ record.bare = true;
398
+ else if (field.startsWith('prunable'))
399
+ record.prunable = true;
400
+ }
401
+ return record;
402
+ }
403
+ /**
404
+ * List every checkout of one repository, main first.
405
+ * @param runtime the runtime helpers.
406
+ * @param root the repository root.
407
+ * @returns the worktrees, empty when Git cannot report them.
408
+ */
409
+ async function listWorktrees(runtime, root) {
410
+ const result = await runtime.run(root, ['worktree', 'list', '--porcelain', '-z']);
411
+ if (result.code !== 0)
412
+ return [];
413
+ const list = [];
414
+ let fields = [];
415
+ for (const field of result.stdout.split('\x00')) {
416
+ if (field !== '') {
417
+ fields.push(field);
418
+ continue;
419
+ }
420
+ if (fields.length > 0)
421
+ list.push(parseWorktree(fields));
422
+ fields = [];
423
+ }
424
+ if (fields.length > 0)
425
+ list.push(parseWorktree(fields));
426
+ return list;
427
+ }
428
+ /**
429
+ * Tell whether a checkout is a linked worktree. A linked worktree keeps its
430
+ * own Git directory inside the common one.
431
+ * @param runtime the runtime helpers.
432
+ * @param root the checkout root.
433
+ * @returns whether it is a linked worktree.
434
+ */
435
+ async function isLinkedWorktree(runtime, root) {
436
+ const dirs = await gitDirs(runtime, root);
437
+ if (dirs === null)
438
+ return false;
439
+ return (await realOrSelf(runtime, dirs.gitDir)) !== (await realOrSelf(runtime, dirs.commonDir));
440
+ }
441
+ /**
442
+ * Tell whether a checkout belongs to one workspace. A linked worktree can sit
443
+ * outside the workspace folder while its common Git directory stays inside it.
444
+ * @param runtime the runtime helpers.
445
+ * @param workspacePath the workspace root.
446
+ * @param root the checkout root.
447
+ * @returns whether the checkout belongs to the workspace.
448
+ */
449
+ async function checkoutInWorkspace(runtime, workspacePath, root) {
450
+ const workspace = await realOrSelf(runtime, workspacePath);
451
+ const target = await realOrSelf(runtime, root);
452
+ if (containsPath(workspace, target))
453
+ return true;
454
+ if ((await findRepository(runtime, workspace)) === target)
455
+ return true;
456
+ const dirs = await gitDirs(runtime, target);
457
+ if (dirs === null)
458
+ return false;
459
+ return containsPath(workspace, await realOrSelf(runtime, dirs.commonDir));
460
+ }
326
461
  /**
327
462
  * Initialize a repository in one directory.
328
463
  * @param runtime the runtime helpers.
@@ -351,20 +486,15 @@ async function isRepoRoot(runtime, directory) {
351
486
  return (await runtime.lstatPath(path.join(directory, '.git'))) !== null;
352
487
  }
353
488
  /**
354
- * List the repositories inside one workspace.
489
+ * List the checkouts inside one workspace, each repository followed by its
490
+ * linked worktrees.
355
491
  * @param runtime the runtime helpers.
356
492
  * @param workspacePath the workspace root.
357
- * @returns the repositories, workspace first.
493
+ * @returns the checkouts, workspace repository first.
358
494
  */
359
495
  export async function discoverRepositories(runtime, workspacePath) {
360
496
  const found = new Map();
361
- let workspace = workspacePath;
362
- try {
363
- workspace = await runtime.realpath(workspacePath);
364
- }
365
- catch {
366
- workspace = workspacePath;
367
- }
497
+ const workspace = await realOrSelf(runtime, workspacePath);
368
498
  const root = await findRepository(runtime, workspace);
369
499
  if (root !== null)
370
500
  found.set(root, root);
@@ -389,13 +519,63 @@ export async function discoverRepositories(runtime, workspacePath) {
389
519
  }
390
520
  }
391
521
  await scan(workspace, 1);
392
- return [...found.values()]
393
- .map((repoRoot) => ({
394
- root: repoRoot,
395
- name: path.relative(workspace, repoRoot) || '.',
396
- label: path.basename(repoRoot),
397
- }))
398
- .sort((a, b) => (a.name === '.' ? -1 : b.name === '.' ? 1 : a.name.localeCompare(b.name)));
522
+ const candidates = [...found.values()].sort((a, b) => {
523
+ const left = path.relative(workspace, a) || '.';
524
+ const right = path.relative(workspace, b) || '.';
525
+ return left === '.' ? -1 : right === '.' ? 1 : left.localeCompare(right);
526
+ });
527
+ // The scan finds a worktree that sits in a non-dot folder as its own
528
+ // repository, and that worktree lists the whole family. Group by common Git
529
+ // directory so each family is listed once.
530
+ const families = new Map();
531
+ for (const candidate of candidates) {
532
+ const dirs = await gitDirs(runtime, candidate);
533
+ const family = dirs === null ? await realOrSelf(runtime, candidate) : await realOrSelf(runtime, dirs.commonDir);
534
+ if (families.has(family))
535
+ continue;
536
+ const records = [];
537
+ for (const record of await listWorktrees(runtime, candidate)) {
538
+ records.push({ record, real: await realOrSelf(runtime, record.path) });
539
+ }
540
+ const inWorkspace = containsPath(workspace, family);
541
+ // A family whose common Git directory is inside the workspace is one of its
542
+ // repositories, and its main checkout is the row. Otherwise the candidate is
543
+ // a worktree of a repository outside, and it stands for itself.
544
+ const main = records[0];
545
+ const primaryPath = inWorkspace && main !== undefined ? main.real : await realOrSelf(runtime, candidate);
546
+ const primaryRecord = records.find((entry) => entry.real === primaryPath);
547
+ const primary = {
548
+ root: primaryPath,
549
+ name: path.relative(workspace, primaryPath) || '.',
550
+ label: path.basename(primaryPath),
551
+ worktree: primaryRecord !== undefined && primaryRecord !== main,
552
+ branch: primaryRecord?.record.branch ?? null,
553
+ };
554
+ const worktrees = [];
555
+ for (const entry of records) {
556
+ if (entry.real === primaryPath)
557
+ continue;
558
+ if (entry.record.bare || entry.record.prunable)
559
+ continue;
560
+ if (!inWorkspace && !containsPath(workspace, entry.real))
561
+ continue;
562
+ // A locked worktree whose folder was deleted is not prunable, and opening
563
+ // it would fail. Leave it out.
564
+ if (!(await resolves(runtime, entry.record.path)))
565
+ continue;
566
+ worktrees.push({
567
+ root: entry.record.path,
568
+ name: path.relative(workspace, entry.record.path) || path.basename(entry.record.path),
569
+ label: path.basename(entry.record.path),
570
+ worktree: true,
571
+ branch: entry.record.branch,
572
+ });
573
+ }
574
+ families.set(family, { primary, worktrees });
575
+ }
576
+ return [...families.values()]
577
+ .sort((a, b) => (a.primary.name === '.' ? -1 : b.primary.name === '.' ? 1 : a.primary.name.localeCompare(b.primary.name)))
578
+ .flatMap((family) => [family.primary, ...family.worktrees]);
399
579
  }
400
580
  /**
401
581
  * Resolve a requested repository inside one workspace.
@@ -411,13 +591,6 @@ export async function resolveRepository(runtime, workspacePath, requested) {
411
591
  if (!path.isAbsolute(requested.trim())) {
412
592
  throw new GitError('git/repo-invalid', 'Choose the repository root.');
413
593
  }
414
- let workspace;
415
- try {
416
- workspace = await runtime.realpath(workspacePath);
417
- }
418
- catch {
419
- workspace = workspacePath;
420
- }
421
594
  let target;
422
595
  try {
423
596
  target = await runtime.realpath(requested.trim());
@@ -430,15 +603,29 @@ export async function resolveRepository(runtime, workspacePath, requested) {
430
603
  throw new GitError('git/not-repo', 'That folder is not a Git repository.');
431
604
  if (root !== target)
432
605
  throw new GitError('git/repo-invalid', 'Choose the repository root.');
433
- const inside = target === workspace || target.startsWith(`${workspace}${path.sep}`);
434
- if (!inside) {
435
- const workspaceRepo = await findRepository(runtime, workspace);
436
- if (workspaceRepo !== target) {
437
- throw new GitError('git/repo-invalid', 'That repository is outside this workspace.');
438
- }
606
+ if (!(await checkoutInWorkspace(runtime, workspacePath, target))) {
607
+ throw new GitError('git/repo-invalid', 'That repository is outside this workspace.');
439
608
  }
440
609
  return root;
441
610
  }
611
+ /**
612
+ * Resolve the checkout a Session works in.
613
+ * @param runtime the runtime helpers.
614
+ * @param workspacePath the workspace root.
615
+ * @param sessionDir the Session's working directory, or null.
616
+ * @returns the checkout root and whether it is a linked worktree.
617
+ */
618
+ export async function sessionCheckout(runtime, workspacePath, sessionDir) {
619
+ const directory = sessionDir === null ? '' : sessionDir.trim();
620
+ if (directory === '')
621
+ return { root: null, worktree: false };
622
+ const root = await findRepository(runtime, directory);
623
+ if (root === null)
624
+ return { root: null, worktree: false };
625
+ if (!(await checkoutInWorkspace(runtime, workspacePath, root)))
626
+ return { root: null, worktree: false };
627
+ return { root, worktree: await isLinkedWorktree(runtime, root) };
628
+ }
442
629
  /**
443
630
  * Read the repository status.
444
631
  * @param runtime the runtime helpers.
@@ -710,6 +897,86 @@ export async function unstagePaths(runtime, root, paths) {
710
897
  throw failure(result, 'Git could not unstage the selected files.');
711
898
  return readStatus(runtime, root);
712
899
  }
900
+ /**
901
+ * Discard every local change to the named files.
902
+ *
903
+ * The named entries are restored to HEAD in the index and the working tree. An
904
+ * untracked file is deleted. A rename is expanded to its recorded old path, so
905
+ * the old path returns and the new one leaves. The caller must confirm first.
906
+ * @param runtime the runtime helpers.
907
+ * @param root the repository root.
908
+ * @param paths the caller paths.
909
+ * @param confirm whether the caller confirmed the loss.
910
+ * @returns the fresh snapshot.
911
+ */
912
+ export async function discardPaths(runtime, root, paths, confirm) {
913
+ if (confirm !== true)
914
+ throw new GitError('git/confirm-required', 'Discarding changes needs confirmation.');
915
+ const safe = [...new Set(paths.map((value) => repoPath(root, value).path))];
916
+ if (safe.length === 0)
917
+ return readStatus(runtime, root);
918
+ const snapshot = await readStatus(runtime, root);
919
+ if (snapshot.merging || snapshot.rebasing || snapshot.reverting || snapshot.cherryPicking) {
920
+ throw new GitError('git/operation', 'Finish the current operation before discarding changes.');
921
+ }
922
+ const wanted = new Set(safe);
923
+ const entries = snapshot.entries.filter((entry) => wanted.has(entry.path));
924
+ if (entries.length === 0) {
925
+ throw new GitError('git/stale', 'The file changed after the list was read. Refresh and try again.');
926
+ }
927
+ if (entries.some((entry) => entry.conflicted)) {
928
+ throw new GitError('git/conflict', 'Resolve the conflict instead of discarding it.');
929
+ }
930
+ const selected = new Set(entries);
931
+ for (const entry of entries) {
932
+ if (entry.from === null || entry.from === undefined)
933
+ continue;
934
+ const occupant = snapshot.entries.find((other) => other.path === entry.from && !selected.has(other));
935
+ if (occupant !== undefined) {
936
+ throw new GitError('git/discard-blocked', 'The old path of this rename holds another file. Remove or discard that file first.');
937
+ }
938
+ }
939
+ const untracked = new Set();
940
+ const tracked = new Set();
941
+ for (const entry of entries) {
942
+ if (entry.untracked) {
943
+ untracked.add(entry.path);
944
+ continue;
945
+ }
946
+ tracked.add(entry.path);
947
+ if (entry.from !== null && entry.from !== undefined)
948
+ tracked.add(entry.from);
949
+ }
950
+ const literal = (values) => [...values].map((value) => `:(literal)${value}`);
951
+ if (untracked.size > 0) {
952
+ const cleaned = await runtime.run(root, ['clean', '-f', '--', ...literal(untracked)]);
953
+ if (cleaned.code !== 0)
954
+ throw failure(cleaned, 'Git could not delete the untracked files.');
955
+ }
956
+ if (tracked.size > 0) {
957
+ const specs = literal(tracked);
958
+ const head = await runtime.run(root, ['rev-parse', '--verify', 'HEAD']);
959
+ if (head.code === 0) {
960
+ const restored = await runtime.run(root, ['restore', '--source=HEAD', '--staged', '--worktree', '--', ...specs]);
961
+ if (restored.code !== 0)
962
+ throw failure(restored, 'Git could not discard the selected files.');
963
+ }
964
+ else {
965
+ const removed = await runtime.run(root, ['rm', '--cached', '-f', '--', ...specs]);
966
+ if (removed.code !== 0)
967
+ throw failure(removed, 'Git could not remove the staged files.');
968
+ const cleaned = await runtime.run(root, ['clean', '-f', '--', ...specs]);
969
+ if (cleaned.code !== 0)
970
+ throw failure(cleaned, 'Git could not delete the selected files.');
971
+ }
972
+ }
973
+ const status = await readStatus(runtime, root);
974
+ const remaining = [...untracked].filter((path) => status.entries.some((entry) => entry.path === path));
975
+ if (remaining.length > 0) {
976
+ throw new GitError('git/discard-incomplete', `An untracked path could not be deleted: ${remaining.join(', ')}. A nested repository must be removed outside the panel.`, { paths: remaining });
977
+ }
978
+ return status;
979
+ }
713
980
  /**
714
981
  * Commit the staged changes.
715
982
  * @param runtime the runtime helpers.
@@ -728,9 +995,12 @@ export async function commit(runtime, root, options) {
728
995
  if (!snapshot.entries.some((entry) => entry.staged)) {
729
996
  throw new GitError('git/nothing-staged', 'Stage at least one file before committing.');
730
997
  }
731
- const args = ['commit', '-F', '-'];
998
+ const args = ['commit'];
999
+ if (options.noVerify === true)
1000
+ args.push('--no-verify');
732
1001
  if (options.amend === true)
733
1002
  args.push('--amend');
1003
+ args.push('-F', '-');
734
1004
  const result = await runtime.run(root, args, {
735
1005
  input: message.endsWith('\n') ? message : `${message}\n`,
736
1006
  });
@@ -796,7 +1066,11 @@ export async function createBranchAndCommit(runtime, root, options) {
796
1066
  throw new GitError('git/branch-failed', created.stderr.trim() || 'Git could not create the branch.');
797
1067
  }
798
1068
  try {
799
- return await commit(runtime, root, { message: options.message, amend: false });
1069
+ return await commit(runtime, root, {
1070
+ message: options.message,
1071
+ amend: false,
1072
+ noVerify: options.noVerify === true,
1073
+ });
800
1074
  }
801
1075
  catch (error) {
802
1076
  if (error instanceof GitError) {
@@ -850,26 +1124,94 @@ export async function push(runtime, root) {
850
1124
  status: await readStatus(runtime, root),
851
1125
  };
852
1126
  }
1127
+ /** The stash message used when a pull has to carry local changes. */
1128
+ const PULL_STASH_MESSAGE = 'dsh-git: changes before pull';
853
1129
  /**
854
- * Pull fast-forward only.
1130
+ * Tell whether Git refused a pull because local changes are in the way.
1131
+ * @param text the combined command output.
1132
+ * @returns whether stashing the changes may let the pull continue.
1133
+ */
1134
+ function blockedByLocalChanges(text) {
1135
+ return /would be overwritten|cannot pull with rebase|Please commit your changes or stash them|Please commit or stash them|Please move or remove them/i.test(text);
1136
+ }
1137
+ /**
1138
+ * Build the failure for a pull that did not succeed.
1139
+ * @param result the command result.
1140
+ * @returns the error.
1141
+ */
1142
+ function pullFailure(result) {
1143
+ return new GitError('git/pull-failed', result.stderr.trim() || result.stdout.trim() || 'Pull failed.', {
1144
+ stdout: result.stdout,
1145
+ stderr: result.stderr,
1146
+ });
1147
+ }
1148
+ /**
1149
+ * Pull fast-forward only, carrying local changes through a stash.
1150
+ *
1151
+ * Git refuses a fast-forward when the update touches a file with local changes,
1152
+ * and when an untracked file would be overwritten. The working tree is stashed,
1153
+ * the pull is retried, and the stash is popped with the index intact. A pop
1154
+ * conflict keeps the stash and reports it, because the pull itself succeeded.
855
1155
  * @param runtime the runtime helpers.
856
1156
  * @param root the repository root.
857
- * @returns the command output and status.
1157
+ * @returns the command output, status, and whether local changes were carried.
858
1158
  */
859
1159
  export async function pull(runtime, root) {
860
1160
  const remote = await remoteStatus(runtime, root);
861
1161
  if (remote.upstream === null)
862
1162
  throw new GitError('git/no-upstream', 'This branch has no upstream branch.');
863
- const result = await runtime.run(root, ['pull', '--ff-only'], { network: true });
1163
+ const args = ['pull', '--ff-only', '--no-rebase'];
1164
+ let result = await runtime.run(root, args, { network: true });
1165
+ let autoStash;
864
1166
  if (result.code !== 0) {
865
- throw new GitError('git/pull-failed', result.stderr.trim() || result.stdout.trim() || 'Pull failed.', {
866
- stdout: result.stdout,
867
- stderr: result.stderr,
868
- });
1167
+ const text = `${result.stderr}\n${result.stdout}`;
1168
+ const status = blockedByLocalChanges(text) ? await readStatus(runtime, root) : null;
1169
+ if (status === null ||
1170
+ status.entries.length === 0 ||
1171
+ status.conflicts.length > 0 ||
1172
+ status.merging ||
1173
+ status.rebasing ||
1174
+ status.reverting ||
1175
+ status.cherryPicking) {
1176
+ throw pullFailure(result);
1177
+ }
1178
+ const includeUntracked = /untracked working tree files would be overwritten/i.test(text);
1179
+ const before = await runtime.run(root, ['rev-parse', '-q', '--verify', 'refs/stash']);
1180
+ const stashed = await runtime.run(root, [
1181
+ 'stash',
1182
+ 'push',
1183
+ ...(includeUntracked ? ['--include-untracked'] : []),
1184
+ '-m',
1185
+ PULL_STASH_MESSAGE,
1186
+ ]);
1187
+ const after = await runtime.run(root, ['rev-parse', '-q', '--verify', 'refs/stash']);
1188
+ if (stashed.code !== 0 || after.stdout.trim() === before.stdout.trim())
1189
+ throw pullFailure(result);
1190
+ result = await runtime.run(root, args, { network: true });
1191
+ const current = await runtime.run(root, ['rev-parse', '-q', '--verify', 'refs/stash']);
1192
+ const otherStash = current.stdout.trim() !== after.stdout.trim();
1193
+ if (result.code !== 0) {
1194
+ if (otherStash) {
1195
+ throw new GitError('git/pull-stash-failed', `${pullFailure(result).message} Another stash was created while the pull ran, so the local changes stay in the stash.`, { stdout: result.stdout, stderr: result.stderr });
1196
+ }
1197
+ const restored = await runtime.run(root, ['stash', 'pop', '--index', 'stash@{0}']);
1198
+ if (restored.code !== 0) {
1199
+ throw new GitError('git/pull-stash-failed', `${pullFailure(result).message} The local changes could not be restored and remain in the stash.`, { stdout: result.stdout, stderr: result.stderr });
1200
+ }
1201
+ throw pullFailure(result);
1202
+ }
1203
+ if (otherStash) {
1204
+ autoStash = 'conflict';
1205
+ }
1206
+ else {
1207
+ const restored = await runtime.run(root, ['stash', 'pop', '--index', 'stash@{0}']);
1208
+ autoStash = restored.code === 0 ? 'restored' : 'conflict';
1209
+ }
869
1210
  }
870
1211
  return {
871
1212
  output: `${result.stdout}${result.stderr}`.trim(),
872
1213
  status: await readStatus(runtime, root),
1214
+ ...(autoStash === undefined ? {} : { autoStash }),
873
1215
  };
874
1216
  }
875
1217
  /**
@@ -1161,14 +1503,28 @@ export async function resetToCommit(runtime, root, options) {
1161
1503
  * @returns the branches.
1162
1504
  */
1163
1505
  export async function branches(runtime, root) {
1164
- const result = await runtime.run(root, [
1165
- 'for-each-ref',
1166
- '--format=%(refname:short)%00%(HEAD)%00%(upstream:short)%00%(refname)',
1167
- 'refs/heads',
1168
- 'refs/remotes',
1506
+ const [result, worktrees] = await Promise.all([
1507
+ runtime.run(root, [
1508
+ 'for-each-ref',
1509
+ '--format=%(refname:short)%00%(HEAD)%00%(upstream:short)%00%(refname)',
1510
+ 'refs/heads',
1511
+ 'refs/remotes',
1512
+ ]),
1513
+ listWorktrees(runtime, root),
1169
1514
  ]);
1170
1515
  if (result.code !== 0)
1171
1516
  throw failure(result, 'Git could not list branches.');
1517
+ const here = await realOrSelf(runtime, root);
1518
+ const checkedOut = new Map();
1519
+ // A prunable or locked worktree still holds its branch: Git refuses the
1520
+ // checkout, so the branch has to stay marked.
1521
+ for (const worktree of worktrees) {
1522
+ if (worktree.bare || worktree.branch === null)
1523
+ continue;
1524
+ if ((await realOrSelf(runtime, worktree.path)) === here)
1525
+ continue;
1526
+ checkedOut.set(worktree.branch, worktree.path);
1527
+ }
1172
1528
  const list = [];
1173
1529
  for (const record of result.stdout.split('\n')) {
1174
1530
  if (record.trim() === '')
@@ -1184,6 +1540,7 @@ export async function branches(runtime, root) {
1184
1540
  current: head === '*',
1185
1541
  upstream: upstream !== undefined && upstream !== '' ? upstream : null,
1186
1542
  remote,
1543
+ worktree: remote ? null : checkedOut.get(name) ?? null,
1187
1544
  });
1188
1545
  }
1189
1546
  return { branches: list };
@@ -1200,6 +1557,16 @@ export async function checkout(runtime, root, options) {
1200
1557
  if (name === '' || name.startsWith('-') || name.includes('\0')) {
1201
1558
  throw new GitError('git/branch-invalid', 'Choose a branch.');
1202
1559
  }
1560
+ const here = await realOrSelf(runtime, root);
1561
+ for (const worktree of await listWorktrees(runtime, root)) {
1562
+ if (worktree.bare || worktree.branch !== name)
1563
+ continue;
1564
+ if ((await realOrSelf(runtime, worktree.path)) === here)
1565
+ continue;
1566
+ throw new GitError('git/branch-in-worktree', 'That branch is checked out in another worktree.', {
1567
+ path: worktree.path,
1568
+ });
1569
+ }
1203
1570
  const result = await runtime.run(root, options.remote === true ? ['checkout', '--track', name] : ['checkout', name]);
1204
1571
  if (result.code !== 0) {
1205
1572
  throw new GitError('git/checkout-failed', result.stderr.trim() || result.stdout.trim() || 'Checkout failed.');
@@ -1,6 +1,6 @@
1
1
  import { preferences, writeCommitMessage } from './ai.js';
2
2
  import { GitError } from './exec.js';
3
- import { applyBlocks, branches, checkout, cherryPickCommit, commit, commitDetail, createBranch, createBranchAndCommit, discoverRepositories, diff, fetch, findRepository, initRepository, log, pull, push, recentSubjects, resetToCommit, resolveConflict, resolveRepository, revertCommit, stagePaths, stagedPatch, stashApply, stashDrop, stashList, stashPush, status, undoCommit, unstagePaths, } from './git.js';
3
+ import { applyBlocks, branches, checkout, cherryPickCommit, commit, commitDetail, createBranch, createBranchAndCommit, discardPaths, discoverRepositories, diff, fetch, findRepository, initRepository, log, pull, push, recentSubjects, resetToCommit, resolveConflict, resolveRepository, revertCommit, sessionCheckout, stagePaths, stagedPatch, stashApply, stashDrop, stashList, stashPush, status, undoCommit, unstagePaths, } from './git.js';
4
4
  /**
5
5
  * Read one field from a client payload.
6
6
  * @param payload the payload.
@@ -102,6 +102,16 @@ async function repoOf(runtime, workspace, payload) {
102
102
  function workspaceInfo(workspace) {
103
103
  return { id: workspace.id, title: workspace.title, path: workspace.path };
104
104
  }
105
+ /**
106
+ * Read the checkout a Session works in from one status request.
107
+ * @param runtime the runtime helpers.
108
+ * @param workspace the workspace.
109
+ * @param payload the client payload.
110
+ * @returns the checkout root and whether it is a linked worktree.
111
+ */
112
+ function checkoutOf(runtime, workspace, payload) {
113
+ return sessionCheckout(runtime, workspace.path, optionalString(payload, 'sessionDir') ?? null);
114
+ }
105
115
  /**
106
116
  * Read the status for one workspace, including the repository list.
107
117
  * @param runtime the runtime helpers.
@@ -110,17 +120,21 @@ function workspaceInfo(workspace) {
110
120
  * @returns the snapshot.
111
121
  */
112
122
  async function statusFor(runtime, workspace, payload) {
123
+ const session = await checkoutOf(runtime, workspace, payload);
124
+ const sessionRoot = session.root;
125
+ const worktree = session.worktree;
113
126
  const requested = valueOf(payload, 'repo');
114
127
  if (typeof requested === 'string' && requested !== '') {
115
128
  const root = await resolveRepository(runtime, workspace.path, requested);
116
129
  const snapshot = await status(runtime, root);
117
- return { ...snapshot, selected: root, workspace: workspaceInfo(workspace) };
130
+ return { ...snapshot, sessionRoot, worktree, selected: root, workspace: workspaceInfo(workspace) };
118
131
  }
119
132
  const repos = await discoverRepositories(runtime, workspace.path);
120
133
  const workspaceRepo = await findRepository(runtime, workspace.path);
121
- if (workspaceRepo !== null) {
122
- const snapshot = await status(runtime, workspaceRepo);
123
- return { ...snapshot, repos, selected: workspaceRepo, workspace: workspaceInfo(workspace) };
134
+ const target = worktree && sessionRoot !== null ? sessionRoot : workspaceRepo;
135
+ if (target !== null) {
136
+ const snapshot = await status(runtime, target);
137
+ return { ...snapshot, repos, sessionRoot, worktree, selected: target, workspace: workspaceInfo(workspace) };
124
138
  }
125
139
  return {
126
140
  repo: false,
@@ -141,6 +155,8 @@ async function statusFor(runtime, workspace, payload) {
141
155
  cherryPicking: false,
142
156
  conflicts: [],
143
157
  repos,
158
+ sessionRoot,
159
+ worktree,
144
160
  selected: null,
145
161
  workspace: workspaceInfo(workspace),
146
162
  };
@@ -181,6 +197,8 @@ async function dispatch(ctx, runtime, endpoint, payload) {
181
197
  return stagePaths(runtime, root, pathsField(payload, 'paths'));
182
198
  case 'unstage':
183
199
  return unstagePaths(runtime, root, pathsField(payload, 'paths'));
200
+ case 'discard':
201
+ return discardPaths(runtime, root, pathsField(payload, 'paths'), valueOf(payload, 'confirm') === true);
184
202
  case 'applyBlocks':
185
203
  return applyBlocks(runtime, root, {
186
204
  path: stringField(payload, 'path'),
@@ -194,11 +212,13 @@ async function dispatch(ctx, runtime, endpoint, payload) {
194
212
  return commit(runtime, root, {
195
213
  message: optionalString(payload, 'message') ?? '',
196
214
  amend: valueOf(payload, 'amend') === true,
215
+ noVerify: valueOf(payload, 'noVerify') === true,
197
216
  });
198
217
  case 'createBranchAndCommit':
199
218
  return createBranchAndCommit(runtime, root, {
200
219
  name: stringField(payload, 'name'),
201
220
  message: stringField(payload, 'message'),
221
+ noVerify: valueOf(payload, 'noVerify') === true,
202
222
  });
203
223
  case 'push':
204
224
  return push(runtime, root);
package/icon.png ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-desk",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "type": "module",
5
5
  "description": "Git desk for DeepSeek Harness: a right-sidebar Git workbench with full-file side-by-side diffs, block staging, commits, history, branches, stash, and sync.",
6
6
  "keywords": [
@@ -29,14 +29,14 @@
29
29
  ".": "./dist/host/index.js",
30
30
  "./client": "./client.js",
31
31
  "./locale/*.json": "./locale/*.json",
32
- "./icon": "./icon.svg"
32
+ "./icon": "./icon.png"
33
33
  },
34
34
  "files": [
35
35
  "dist",
36
36
  "client.js",
37
37
  "cordis.patch.yml",
38
38
  "locale/*.json",
39
- "icon.svg",
39
+ "icon.png",
40
40
  "LICENSE",
41
41
  "README.md"
42
42
  ],
package/icon.svg DELETED
@@ -1,9 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
2
- <rect width="64" height="64" rx="14" fill="#0F172A"/>
3
- <path d="M32 15v34" stroke="#94A3B8" stroke-width="3" stroke-linecap="round"/>
4
- <path d="M32 31c0-7 5-12 12-12h4" stroke="#94A3B8" stroke-width="3" stroke-linecap="round"/>
5
- <circle cx="32" cy="14" r="6" fill="#F8FAFC"/>
6
- <circle cx="32" cy="32" r="6" fill="#38BDF8"/>
7
- <circle cx="32" cy="50" r="6" fill="#F8FAFC"/>
8
- <circle cx="50" cy="19" r="5" fill="#F8FAFC"/>
9
- </svg>