@statewalker/vcs-commands 0.4.0 → 0.5.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.
Files changed (99) hide show
  1. package/dist/commands/add-command.d.ts.map +1 -1
  2. package/dist/commands/checkout-command.d.ts +7 -24
  3. package/dist/commands/checkout-command.d.ts.map +1 -1
  4. package/dist/commands/clean-command.d.ts +34 -4
  5. package/dist/commands/clean-command.d.ts.map +1 -1
  6. package/dist/commands/clone-command.d.ts +62 -7
  7. package/dist/commands/clone-command.d.ts.map +1 -1
  8. package/dist/commands/core-config.d.ts +16 -0
  9. package/dist/commands/core-config.d.ts.map +1 -0
  10. package/dist/commands/fetch-command.d.ts +96 -14
  11. package/dist/commands/fetch-command.d.ts.map +1 -1
  12. package/dist/commands/index.d.ts +1 -0
  13. package/dist/commands/index.d.ts.map +1 -1
  14. package/dist/commands/index.js +2 -2
  15. package/dist/commands/init-command.d.ts.map +1 -1
  16. package/dist/commands/remote-command.d.ts +115 -6
  17. package/dist/commands/remote-command.d.ts.map +1 -1
  18. package/dist/commands/reset-command.d.ts.map +1 -1
  19. package/dist/commands/stash-apply-command.d.ts +35 -13
  20. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  21. package/dist/commands/stash-create-command.d.ts +59 -25
  22. package/dist/commands/stash-create-command.d.ts.map +1 -1
  23. package/dist/commands/stash-drop-command.d.ts +8 -2
  24. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  25. package/dist/commands/stash-list-command.d.ts +2 -4
  26. package/dist/commands/stash-list-command.d.ts.map +1 -1
  27. package/dist/commands/stash-working-tree.d.ts +72 -0
  28. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  29. package/dist/commands/status-command.d.ts +29 -22
  30. package/dist/commands/status-command.d.ts.map +1 -1
  31. package/dist/commands/tree-restore.d.ts +52 -5
  32. package/dist/commands/tree-restore.d.ts.map +1 -1
  33. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  34. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  35. package/dist/{commands-BpeXZTC3.js → commands-CsLNyvZ1.js} +2940 -631
  36. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  37. package/dist/core-commands/index.d.ts +0 -3
  38. package/dist/core-commands/index.d.ts.map +1 -1
  39. package/dist/errors/checkout-errors.d.ts +13 -0
  40. package/dist/errors/checkout-errors.d.ts.map +1 -1
  41. package/dist/errors/index.js +18 -1
  42. package/dist/git-command.d.ts +10 -1
  43. package/dist/git-command.d.ts.map +1 -1
  44. package/dist/git.d.ts +21 -3
  45. package/dist/git.d.ts.map +1 -1
  46. package/dist/index.js +4 -4
  47. package/dist/remote-config/index.d.ts +1 -0
  48. package/dist/remote-config/index.d.ts.map +1 -1
  49. package/dist/remote-config/remote-config-store.d.ts +18 -0
  50. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  51. package/dist/remote-config/remote-refs.d.ts +37 -0
  52. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  53. package/dist/results/clone-result.d.ts +6 -0
  54. package/dist/results/clone-result.d.ts.map +1 -1
  55. package/dist/results/fetch-result.d.ts +9 -1
  56. package/dist/results/fetch-result.d.ts.map +1 -1
  57. package/dist/results/index.js +2 -2
  58. package/dist/results/status-result.d.ts +91 -20
  59. package/dist/results/status-result.d.ts.map +1 -1
  60. package/dist/{status-result-BapZoQaR.js → status-result-BpyUK1Sg.js} +113 -5
  61. package/dist/transport-command.d.ts +12 -0
  62. package/dist/transport-command.d.ts.map +1 -1
  63. package/package.json +11 -10
  64. package/src/commands/add-command.ts +9 -7
  65. package/src/commands/checkout-command.ts +200 -118
  66. package/src/commands/clean-command.ts +187 -88
  67. package/src/commands/clone-command.ts +244 -40
  68. package/src/commands/core-config.ts +41 -0
  69. package/src/commands/fetch-command.ts +476 -57
  70. package/src/commands/index.ts +1 -0
  71. package/src/commands/init-command.ts +32 -7
  72. package/src/commands/remote-command.ts +429 -19
  73. package/src/commands/reset-command.ts +18 -5
  74. package/src/commands/stash-apply-command.ts +632 -97
  75. package/src/commands/stash-create-command.ts +142 -62
  76. package/src/commands/stash-drop-command.ts +53 -5
  77. package/src/commands/stash-list-command.ts +10 -4
  78. package/src/commands/stash-working-tree.ts +243 -0
  79. package/src/commands/status-command.ts +197 -91
  80. package/src/commands/tree-restore.ts +142 -13
  81. package/src/commands/worktree-overwrite-checks.ts +215 -0
  82. package/src/core-commands/add.command.impl.ts +2 -4
  83. package/src/core-commands/index.ts +0 -8
  84. package/src/errors/checkout-errors.ts +20 -0
  85. package/src/git-command.ts +42 -1
  86. package/src/git.ts +30 -2
  87. package/src/remote-config/index.ts +1 -0
  88. package/src/remote-config/remote-config-store.ts +84 -8
  89. package/src/remote-config/remote-refs.ts +103 -0
  90. package/src/results/clone-result.ts +6 -0
  91. package/src/results/fetch-result.ts +9 -1
  92. package/src/results/status-result.ts +212 -29
  93. package/src/transport-command.ts +18 -0
  94. package/dist/core-commands/checkout.command.d.ts +0 -103
  95. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  96. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  97. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  98. package/src/core-commands/checkout.command.impl.ts +0 -564
  99. package/src/core-commands/checkout.command.ts +0 -125
@@ -387,25 +387,133 @@ let StashApplyStatus = /* @__PURE__ */ function(StashApplyStatus) {
387
387
  //#endregion
388
388
  //#region src/results/status-result.ts
389
389
  /**
390
- * Implementation of Status interface.
390
+ * Implementation of the Status interface.
391
391
  */
392
392
  var StatusImpl = class {
393
393
  added;
394
394
  changed;
395
395
  removed;
396
396
  conflicting;
397
- constructor(added, changed, removed, conflicting) {
397
+ modified;
398
+ missing;
399
+ untracked;
400
+ ignored;
401
+ conflictingStageState;
402
+ files;
403
+ constructor(added, changed, removed, conflicting, worktree = {}) {
398
404
  this.added = added;
399
405
  this.changed = changed;
400
406
  this.removed = removed;
401
407
  this.conflicting = conflicting;
408
+ this.modified = worktree.modified ?? /* @__PURE__ */ new Set();
409
+ this.missing = worktree.missing ?? /* @__PURE__ */ new Set();
410
+ this.untracked = worktree.untracked ?? /* @__PURE__ */ new Set();
411
+ this.ignored = worktree.ignored ?? /* @__PURE__ */ new Set();
412
+ this.conflictingStageState = worktree.conflictingStageState ?? /* @__PURE__ */ new Map();
413
+ this.files = worktree.files ?? [];
402
414
  }
403
415
  isClean() {
404
- return this.added.size === 0 && this.changed.size === 0 && this.removed.size === 0 && this.conflicting.size === 0;
416
+ return !this.hasUncommittedChanges() && this.untracked.size === 0;
405
417
  }
406
418
  hasUncommittedChanges() {
407
- return !this.isClean();
419
+ return this.added.size > 0 || this.changed.size > 0 || this.removed.size > 0 || this.conflicting.size > 0 || this.modified.size > 0 || this.missing.size > 0;
408
420
  }
409
421
  };
422
+ /** git's byte order of paths (UTF-8 code units, as `strcmp`). */
423
+ function comparePaths(a, b) {
424
+ const ea = new TextEncoder().encode(a);
425
+ const eb = new TextEncoder().encode(b);
426
+ const n = Math.min(ea.length, eb.length);
427
+ for (let i = 0; i < n; i++) if (ea[i] !== eb[i]) return ea[i] - eb[i];
428
+ return ea.length - eb.length;
429
+ }
430
+ const ZERO_ID = "0".repeat(40);
431
+ const octal = (mode) => (mode ?? 0).toString(8).padStart(6, "0");
432
+ /**
433
+ * git's quoting of a path in status output (`core.quotePath`, on by default); porcelain v1
434
+ * quotes a path with a space too (`QUOTE_PATH_QUOTE_SP`), v2 does not.
435
+ */
436
+ function quotePath(path, quoteSpace = false) {
437
+ const bytes = new TextEncoder().encode(path);
438
+ let needs = false;
439
+ let out = "";
440
+ for (const b of bytes) if (b === 34 || b === 92) {
441
+ needs = true;
442
+ out += `\\${String.fromCharCode(b)}`;
443
+ } else if (b === 9) {
444
+ needs = true;
445
+ out += "\\t";
446
+ } else if (b === 10) {
447
+ needs = true;
448
+ out += "\\n";
449
+ } else if (b === 32 && quoteSpace) {
450
+ needs = true;
451
+ out += " ";
452
+ } else if (b < 32 || b >= 127) {
453
+ needs = true;
454
+ out += `\\${b.toString(8).padStart(3, "0")}`;
455
+ } else out += String.fromCharCode(b);
456
+ return needs ? `"${out}"` : path;
457
+ }
458
+ /**
459
+ * The status as `git status --porcelain` (v1) or `--porcelain=v2` prints it, with
460
+ * `--untracked-files=all` (and the ignored files when the status has them): the changed
461
+ * tracked paths first, then the untracked, then the ignored ones, each in git's path order.
462
+ * Renames are not detected (as `-c status.renames=false`).
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * formatStatusPorcelain(await git.status().call());
467
+ * // " M a.txt\nA b.txt\n?? new.txt\n"
468
+ * ```
469
+ */
470
+ function formatStatusPorcelain(status, version = 1) {
471
+ const entries = status.files;
472
+ const tracked = entries.filter((e) => e.index !== "?" && e.index !== "!").sort((a, b) => comparePaths(a.path, b.path));
473
+ const untracked = entries.filter((e) => e.index === "?").sort((a, b) => comparePaths(a.path, b.path));
474
+ const ignored = entries.filter((e) => e.index === "!").sort((a, b) => comparePaths(a.path, b.path));
475
+ const lines = [];
476
+ for (const e of tracked) {
477
+ const path = quotePath(e.path, version === 1);
478
+ if (version === 1) {
479
+ lines.push(`${e.index}${e.worktree} ${path}`);
480
+ continue;
481
+ }
482
+ const xy = `${e.index === " " ? "." : e.index}${e.worktree === " " ? "." : e.worktree}`;
483
+ const sub = e.staged?.mode === 57344 || e.head?.mode === 57344 ? `S${e.submoduleCommitChanged ? "C" : "."}..` : "N...";
484
+ if (e.stages) {
485
+ const [s1, s2, s3] = e.stages;
486
+ lines.push([
487
+ "u",
488
+ xy,
489
+ sub,
490
+ octal(s1?.mode),
491
+ octal(s2?.mode),
492
+ octal(s3?.mode),
493
+ octal(e.worktreeMode),
494
+ s1?.id ?? ZERO_ID,
495
+ s2?.id ?? ZERO_ID,
496
+ s3?.id ?? ZERO_ID,
497
+ path
498
+ ].join(" "));
499
+ continue;
500
+ }
501
+ lines.push([
502
+ "1",
503
+ xy,
504
+ sub,
505
+ octal(e.head?.mode),
506
+ octal(e.staged?.mode),
507
+ octal(e.worktreeMode),
508
+ e.head?.id ?? ZERO_ID,
509
+ e.staged?.id ?? ZERO_ID,
510
+ path
511
+ ].join(" "));
512
+ }
513
+ const mark = version === 1 ? ["??", "!!"] : ["?", "!"];
514
+ for (const e of untracked) lines.push(`${mark[0]} ${quotePath(e.path, version === 1)}`);
515
+ for (const e of ignored) lines.push(`${mark[1]} ${quotePath(e.path, version === 1)}`);
516
+ return lines.map((l) => `${l}\n`).join("");
517
+ }
410
518
  //#endregion
411
- export { isMergeSuccessful as C, MergeStrategy as S, getSuccessfulUpdates as _, RebaseStatus as a, FastForwardMode as b, getFailedUpdates as c, createAddEntry as d, createCopyEntry as f, RefUpdateStatus as g, createRenameEntry as h, RebaseAction as i, isPushSuccessful as l, createModifyEntry as m, StashApplyStatus as n, isRebaseSuccessful as o, createDeleteEntry as p, RevertStatus as r, PushStatus as s, StatusImpl as t, ChangeType as u, hasUpdates as v, CherryPickStatus as w, MergeStatus as x, ContentMergeStrategy as y };
519
+ export { MergeStrategy as C, MergeStatus as S, CherryPickStatus as T, RefUpdateStatus as _, RebaseAction as a, ContentMergeStrategy as b, PushStatus as c, ChangeType as d, createAddEntry as f, createRenameEntry as g, createModifyEntry as h, RevertStatus as i, getFailedUpdates as l, createDeleteEntry as m, formatStatusPorcelain as n, RebaseStatus as o, createCopyEntry as p, StashApplyStatus as r, isRebaseSuccessful as s, StatusImpl as t, isPushSuccessful as u, getSuccessfulUpdates as v, isMergeSuccessful as w, FastForwardMode as x, hasUpdates as y };
@@ -14,6 +14,8 @@ export interface TransportOptions {
14
14
  headers?: Record<string, string>;
15
15
  /** Request timeout in milliseconds */
16
16
  timeout?: number;
17
+ /** Gzip large fetch request bodies (default true, as git; see `setGzipRequests`) */
18
+ gzipRequests?: boolean;
17
19
  /** Progress callback */
18
20
  onProgress?: ProgressCallback;
19
21
  /** Raw progress message callback */
@@ -34,6 +36,8 @@ export declare abstract class TransportCommand<T> extends GitCommand<T> {
34
36
  protected timeout?: number;
35
37
  /** Custom HTTP headers */
36
38
  protected headers?: Record<string, string>;
39
+ /** Gzip large fetch request bodies (undefined: the transport's default, true) */
40
+ protected gzipRequests?: boolean;
37
41
  /** Progress callback */
38
42
  protected progressCallback?: ProgressCallback;
39
43
  /** Progress message callback */
@@ -57,6 +61,14 @@ export declare abstract class TransportCommand<T> extends GitCommand<T> {
57
61
  * @param timeout Timeout in milliseconds
58
62
  */
59
63
  setTimeout(timeout: number): this;
64
+ /**
65
+ * Send large upload-pack request bodies (a fetch's have-batches over 1024 bytes) gzipped,
66
+ * with `Content-Encoding: gzip`, as git does (default true). Pass false for a browser behind
67
+ * a CORS proxy that does not allow that header (it is not CORS-safelisted).
68
+ *
69
+ * @param gzip Whether to gzip large request bodies
70
+ */
71
+ setGzipRequests(gzip: boolean): this;
60
72
  /**
61
73
  * Set custom HTTP headers.
62
74
  *
@@ -1 +1 @@
1
- {"version":3,"file":"transport-command.d.ts","sourceRoot":"","sources":["../src/transport-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE5E,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,YAAY,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,iCAAiC;IACjC,IAAI,CAAC,EAAE,WAAW,CAAC;IACnB,0BAA0B;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,sCAAsC;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wBAAwB;IACxB,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,oCAAoC;IACpC,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/C;AAED;;;;;;;GAOG;AACH,8BAAsB,gBAAgB,CAAC,CAAC,CAA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I,CAIhC;IAED;;;;;;OAMG;IACH,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAInC;IAED;;;;OAIG;IACH,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAIhD;IAED;;;;OAIG;IACH,kBAAkB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAInD;IAED;;;;OAIG;IACH,0BAA0B,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAIpE;IAED;;OAEG;IACH,SAAS,CAAC,mBAAmB,IAAI,gBAAgB,CAShD;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/vcs-commands",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Git-like VCS commands (commit, checkout, merge, diff, log)",
5
5
  "bugs": {
6
6
  "url": "https://github.com/statewalker/webrun-vcs/issues"
@@ -46,21 +46,22 @@
46
46
  "src"
47
47
  ],
48
48
  "dependencies": {
49
- "@statewalker/vcs-store-mem": "^0.4.0",
50
- "@statewalker/vcs-transport": "^0.4.0",
51
- "@statewalker/vcs-store-files": "^0.4.0",
52
- "@statewalker/vcs-utils": "^0.4.0",
53
- "@statewalker/vcs-working-tree": "^0.4.0",
54
- "@statewalker/vcs-core": "^0.4.0"
49
+ "@statewalker/vcs-core": "^0.5.0",
50
+ "@statewalker/vcs-store-mem": "^0.5.0",
51
+ "@statewalker/vcs-transport": "^0.5.0",
52
+ "@statewalker/vcs-utils": "^0.5.0",
53
+ "@statewalker/vcs-working-tree": "^0.5.0",
54
+ "@statewalker/vcs-store-files": "^0.5.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/node": "^26.6.4",
58
58
  "rolldown": "^1.2.12",
59
59
  "typescript": "^7.0.2",
60
60
  "vitest": "^5.1.0",
61
- "@statewalker/vcs-transport-adapters": "^0.4.0",
62
- "@statewalker/vcs-utils-node": "^0.4.0",
63
- "@statewalker/vcs-store-sql": "^0.4.0"
61
+ "@statewalker/vcs-store-kv": "^0.5.0",
62
+ "@statewalker/vcs-store-sql": "^0.5.0",
63
+ "@statewalker/vcs-transport-adapters": "^0.5.0",
64
+ "@statewalker/vcs-utils-node": "^0.5.0"
64
65
  },
65
66
  "scripts": {
66
67
  "build": "rm -rf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
@@ -34,6 +34,8 @@
34
34
  import { EMPTY_BLOB_ID, FileMode } from "@statewalker/vcs-core";
35
35
  import {
36
36
  DeleteStagingEntry,
37
+ entryStatOf,
38
+ modeFromWorktree,
37
39
  UpdateStagingEntry,
38
40
  type Worktree,
39
41
  } from "@statewalker/vcs-working-tree";
@@ -45,6 +47,7 @@ import {
45
47
  StoreNotAvailableError,
46
48
  } from "../errors/index.js";
47
49
  import { GitCommand } from "../git-command.js";
50
+ import { worktreeModeTrust } from "./core-config.js";
48
51
 
49
52
  /**
50
53
  * Result of AddCommand execution.
@@ -420,6 +423,8 @@ export class AddCommand extends GitCommand<AddResult> {
420
423
 
421
424
  // Process files
422
425
  const editor = this.staging.createEditor();
426
+ // what the worktree's modes can be trusted for (git's core.filemode / core.symlinks)
427
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
423
428
 
424
429
  for (const file of filesToProcess) {
425
430
  if (!file.exists) {
@@ -459,13 +464,10 @@ export class AddCommand extends GitCommand<AddResult> {
459
464
  // the stat that matched the stored content (a fresh one after a retry)
460
465
  const stored = await storeWorktreeFile(this.blobs, worktree, file.path, worktreeEntry);
461
466
 
462
- // Add to staging
463
- editor.add(
464
- new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, {
465
- size: stored.entry.size,
466
- mtime: stored.entry.mtime,
467
- }),
468
- );
467
+ // Add to staging, with the mode git's ce_mode_from_stat would record
468
+ const indexMode = (await this.staging.getEntry(file.path))?.mode;
469
+ const mode = modeFromWorktree(stored.entry.mode, indexMode, trust);
470
+ editor.add(new UpdateStagingEntry(file.path, stored.id, mode, entryStatOf(stored.entry)));
469
471
  added.push(file.path);
470
472
  }
471
473
 
@@ -34,7 +34,7 @@
34
34
  */
35
35
 
36
36
  import { FileMode, isValidBranchName, type ObjectId, type Ref } from "@statewalker/vcs-core";
37
- import { UpdateStagingEntry } from "@statewalker/vcs-working-tree";
37
+ import { entryStatOf, UpdateStagingEntry, type Worktree } from "@statewalker/vcs-working-tree";
38
38
 
39
39
  import {
40
40
  InvalidRefNameError,
@@ -45,6 +45,17 @@ import {
45
45
  RefNotFoundError,
46
46
  } from "../errors/index.js";
47
47
  import { GitCommand } from "../git-command.js";
48
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
49
+ import { planTreeRestore, writeTreeRestorePlan } from "./tree-restore.js";
50
+ import {
51
+ findInTheWay,
52
+ overwriteMessage,
53
+ pruneEmptyParents,
54
+ worktreeDiffers,
55
+ } from "./worktree-overwrite-checks.js";
56
+
57
+ /** Names a branch checkout in failure messages. */
58
+ const CHECKOUT = "checkout";
48
59
 
49
60
  /**
50
61
  * Stage to check out for conflicting files.
@@ -92,8 +103,26 @@ export interface CheckoutResult {
92
103
 
93
104
  /** The ref that was checked out (null for path checkout) */
94
105
  readonly ref: Ref | null;
106
+
107
+ /**
108
+ * Why a checkout was refused, in git's words (`status` CONFLICTS): local changes or
109
+ * untracked files the switch would overwrite, or an index with unmerged entries.
110
+ */
111
+ readonly message?: string;
95
112
  }
96
113
 
114
+ /** A tree or index entry, as the two-way merge compares them (index entries with stat). */
115
+ interface Side {
116
+ objectId: ObjectId;
117
+ mode: number;
118
+ size?: number;
119
+ mtime?: number;
120
+ ctime?: number;
121
+ }
122
+
123
+ const sameSide = (a: Side | undefined, b: Side | undefined) =>
124
+ a === undefined || b === undefined ? a === b : a.objectId === b.objectId && a.mode === b.mode;
125
+
97
126
  /**
98
127
  * Command to checkout branches, commits, or paths.
99
128
  *
@@ -262,13 +291,12 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
262
291
  this.checkCallable();
263
292
  this.setCallable(false);
264
293
 
265
- // Path checkout mode
266
- if (this.allPaths || this.paths.length > 0) {
267
- return this.checkoutPaths();
268
- }
269
-
270
- // Branch checkout mode
271
- return this.checkoutBranch();
294
+ // path checkout, or branch checkout; one worktree batch, so the checks and the writes
295
+ // share one reading of the ignore rules
296
+ const run = () =>
297
+ this.allPaths || this.paths.length > 0 ? this.checkoutPaths() : this.checkoutBranch();
298
+ const worktree = this.worktreeAccess;
299
+ return worktree?.batch ? worktree.batch(run) : run();
272
300
  }
273
301
 
274
302
  /**
@@ -315,50 +343,10 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
315
343
  };
316
344
  }
317
345
 
318
- /**
319
- * Detect conflicts between staged changes and checkout target.
320
- *
321
- * Returns list of paths that have uncommitted staged changes.
322
- * Git prevents checkout when staged changes differ from HEAD,
323
- * as they would be lost during checkout.
324
- *
325
- * @param _targetTreeId Target tree to checkout (unused for now, checks HEAD vs staging)
326
- * @returns Array of conflicting paths
327
- */
328
- private async detectCheckoutConflicts(_targetTreeId?: ObjectId): Promise<string[]> {
329
- const conflicts: string[] = [];
330
-
331
- // Get current HEAD tree for comparison
332
- const headId = await this.resolveCommitId("HEAD");
333
- if (!headId) {
334
- // No HEAD commit yet (empty repository) - no conflicts possible
335
- return conflicts;
336
- }
337
-
338
- const headTreeId = await this.commits.getTree(headId);
339
- if (!headTreeId) {
340
- return conflicts;
341
- }
342
-
343
- // Collect HEAD tree entries
344
- const headEntries = new Map<string, { objectId: ObjectId; mode: number }>();
345
- await this.collectTreeEntries(headTreeId, "", headEntries);
346
-
347
- // Compare staging with HEAD
348
- for await (const entry of this.staging.entries()) {
349
- // Skip conflict stages (1-3) - only check stage 0
350
- if (entry.stage !== 0) continue;
351
-
352
- const headEntry = headEntries.get(entry.path);
353
-
354
- // Check if staged content differs from HEAD
355
- if (!headEntry || headEntry.objectId !== entry.objectId) {
356
- // Staged change differs from HEAD - this is an uncommitted change
357
- conflicts.push(entry.path);
358
- }
359
- }
360
-
361
- return conflicts;
346
+ /** Whether an untracked (not ignored) file or link is at `path`. */
347
+ private async untrackedFileAt(worktree: Worktree, path: string): Promise<boolean> {
348
+ const entry = await worktree.getEntry(path);
349
+ return !!entry && !entry.isDirectory && !(await worktree.isIgnored(path));
362
350
  }
363
351
 
364
352
  /**
@@ -394,18 +382,147 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
394
382
  // Get target tree for conflict detection and checkout
395
383
  const targetTreeId = targetId ? await this.commits.getTree(targetId) : undefined;
396
384
 
397
- // Detect conflicts with staged changes before checkout
398
- if (!this.force && !this.orphan) {
399
- const conflicts = await this.detectCheckoutConflicts(targetTreeId);
400
- if (conflicts.length > 0) {
401
- return {
402
- status: CheckoutStatus.CONFLICTS,
403
- updated: [],
404
- removed: [],
405
- conflicts,
406
- ref: null,
407
- };
385
+ // git's two-way merge (unpack-trees `twoway_merge`, checkout without -f): a path HEAD
386
+ // and the target agree on keeps its index entry and worktree file as they are (local
387
+ // edits survive the switch); a path they differ on is switched only when the index and
388
+ // the worktree still hold HEAD's version, else the checkout is refused, as are
389
+ // untracked files in the way and an index with unmerged entries. With `setForce`, as
390
+ // `git checkout -f`, the target's tree replaces index and worktree whatever they hold.
391
+ const worktree = this.worktreeAccess;
392
+ const headId = await this.resolveCommitId("HEAD");
393
+ const headTreeId = headId ? await this.commits.getTree(headId) : undefined;
394
+ const head = new Map<string, Side>();
395
+ const target = new Map<string, Side>();
396
+ if (headTreeId) await this.collectTreeEntries(headTreeId, "", head);
397
+ if (targetTreeId) await this.collectTreeEntries(targetTreeId, "", target);
398
+ const index = new Map<string, Side>();
399
+ const unmerged = new Set<string>();
400
+ for await (const entry of this.staging.entries()) {
401
+ if (entry.stage === 0) index.set(entry.path, entry);
402
+ else unmerged.add(entry.path);
403
+ }
404
+
405
+ if (!this.force && !this.orphan && unmerged.size > 0) {
406
+ return {
407
+ status: CheckoutStatus.CONFLICTS,
408
+ updated: [],
409
+ removed: [],
410
+ conflicts: [...unmerged].sort(),
411
+ ref: null,
412
+ message: "error: you need to resolve your current index first",
413
+ };
414
+ }
415
+
416
+ // the paths the switch changes, and those it must refuse to touch
417
+ const switched: string[] = [];
418
+ const local: string[] = [];
419
+ const untracked: string[] = [];
420
+ const untrackedRemoved: string[] = [];
421
+ const lostDirs: string[] = [];
422
+ const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : undefined;
423
+ const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
424
+ const paths = [...new Set([...head.keys(), ...target.keys()])].sort();
425
+ // (an orphan branch keeps index and worktree as they are, as git's --orphan)
426
+ for (const path of this.orphan ? [] : paths) {
427
+ const h = head.get(path);
428
+ const t = target.get(path);
429
+ if (!this.force && sameSide(h, t)) continue;
430
+ const i = index.get(path);
431
+ if (this.force) {
432
+ if (!sameSide(i, t) || t) switched.push(path);
433
+ continue;
408
434
  }
435
+ if (sameSide(i, t)) {
436
+ // kept; but a staged deletion the target also makes leaves the file untracked in
437
+ // the worktree, and the switch would remove it (git refuses)
438
+ if (h && !i && !t && worktree && (await this.untrackedFileAt(worktree, path))) {
439
+ untrackedRemoved.push(path);
440
+ }
441
+ continue;
442
+ }
443
+ if (!sameSide(i, h)) {
444
+ // staged changes (or a staged deletion) the switch would lose
445
+ if (i !== undefined || t !== undefined) local.push(path);
446
+ continue;
447
+ }
448
+ if (i !== undefined && worktree && (await worktreeDiffers(worktree, path, i, trust))) {
449
+ local.push(path);
450
+ continue;
451
+ }
452
+ switched.push(path);
453
+ }
454
+
455
+ // what stands where the switch writes (git's verify_absent, check_leading_path and
456
+ // verify_clean_subdirectory): untracked files or links on the path or a leading
457
+ // component, untracked files in a directory a file replaces
458
+ if (worktree && !this.force) {
459
+ const found = await findInTheWay(worktree, {
460
+ writes: switched.filter((p) => target.has(p)),
461
+ removes: new Set(switched.filter((p) => !target.has(p))),
462
+ index,
463
+ ignoreCase,
464
+ });
465
+ untracked.push(...found.untracked);
466
+ lostDirs.push(...found.lostDirs);
467
+ }
468
+ if (local.length + untracked.length + untrackedRemoved.length + lostDirs.length > 0) {
469
+ const message = overwriteMessage("checkout", {
470
+ local,
471
+ lostDirs,
472
+ untracked,
473
+ untrackedRemoved,
474
+ });
475
+ return {
476
+ status: CheckoutStatus.CONFLICTS,
477
+ updated: [],
478
+ removed: [],
479
+ conflicts: [...local, ...lostDirs, ...untracked, ...untrackedRemoved],
480
+ ref: null,
481
+ message,
482
+ };
483
+ }
484
+
485
+ // The worktree first, as git: the target tree is planned (paths verified, entries
486
+ // checked not to collide) before anything is written; the switched paths the target
487
+ // drops are removed, then its switched files, links and submodule directories written.
488
+ const updated: string[] = [];
489
+ const removed: string[] = [];
490
+ const switching = new Set(switched);
491
+ if (targetTreeId && worktree) {
492
+ const plan = await planTreeRestore(this.trees, this.blobs, targetTreeId, CHECKOUT, {
493
+ symlinks: true,
494
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
495
+ windows: worktree.capabilities?.windowsPaths === true,
496
+ reservedNames: worktree.capabilities?.reservedNames,
497
+ });
498
+ for (const path of switched) {
499
+ if (target.has(path)) continue;
500
+ await worktree.remove(path);
501
+ await pruneEmptyParents(worktree, path);
502
+ removed.push(path);
503
+ }
504
+ // a forced checkout also drops tracked files no tree holds any more
505
+ if (this.force) {
506
+ for (const path of index.keys()) {
507
+ if (!target.has(path) && !switching.has(path)) {
508
+ await worktree.remove(path);
509
+ removed.push(path);
510
+ }
511
+ }
512
+ }
513
+ const only = {
514
+ ...plan,
515
+ entries: plan.entries.filter((e) => switching.has(e.path)),
516
+ gitlinks: plan.gitlinks.filter((e) => switching.has(e.path)),
517
+ };
518
+ // everything in the way was checked above (or the checkout is forced): a file or link
519
+ // where a directory goes, a clean directory where a file goes, are replaced
520
+ await writeTreeRestorePlan(worktree, this.blobs, only, CHECKOUT, {
521
+ symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
522
+ gitlinks: true,
523
+ replaceInTheWay: true,
524
+ });
525
+ updated.push(...only.entries.map((e) => e.path));
409
526
  }
410
527
 
411
528
  // Determine if we should use symbolic ref (branch) or detached HEAD (commit/tag)
@@ -425,21 +542,29 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
425
542
  await this.refsStore.set("HEAD", targetId);
426
543
  }
427
544
 
428
- // Sync staging to match target tree AFTER updating HEAD
429
- const updated: string[] = [];
430
- const removed: string[] = [];
431
-
432
- if (targetTreeId) {
433
- // Use this.trees which is CommandTrees (has loadTree method for TreeStore compatibility)
545
+ // The index: forced, the target's tree; else the switched paths take the target's
546
+ // entries (with the stat of the files just written), every other path keeps its own
547
+ if (targetTreeId && this.force) {
434
548
  await this.staging.readTree(this.trees as any, targetTreeId);
435
-
436
- // Persist staging to .git/index so native git sees the correct state
437
549
  await this.staging.write();
438
-
439
- // Write files to working directory if not a bare repository
440
- if (this.hasFileWriteSupport()) {
441
- await this.writeTreeToWorkdir(targetTreeId, "");
550
+ } else if (switched.length > 0) {
551
+ const editor = this.staging.createEditor();
552
+ for (const path of switched) {
553
+ const t = target.get(path);
554
+ if (!t) {
555
+ editor.remove(path);
556
+ continue;
557
+ }
558
+ const stats = worktree ? await worktree.getEntry(path) : undefined;
559
+ editor.upsert({
560
+ path,
561
+ objectId: t.objectId,
562
+ mode: t.mode,
563
+ ...entryStatOf(stats ?? {}),
564
+ });
442
565
  }
566
+ await editor.finish();
567
+ await this.staging.write();
443
568
  }
444
569
 
445
570
  // Get the ref we checked out
@@ -454,49 +579,6 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
454
579
  };
455
580
  }
456
581
 
457
- /**
458
- * Check if the store supports file writes (not a bare repository).
459
- *
460
- * A repository is considered "bare" if it doesn't have a worktree interface.
461
- */
462
- private hasFileWriteSupport(): boolean {
463
- return !!this.worktreeAccess;
464
- }
465
-
466
- /**
467
- * Write all files from a tree to the working directory.
468
- *
469
- * @param treeId The tree ID to checkout
470
- * @param basePath The base path prefix for entries in this tree
471
- */
472
- private async writeTreeToWorkdir(treeId: ObjectId, basePath: string): Promise<void> {
473
- const worktree = this.worktreeAccess;
474
- if (!worktree) {
475
- throw new Error("Worktree not available for file writes");
476
- }
477
-
478
- for await (const entry of this.trees.loadTree(treeId)) {
479
- const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;
480
- const isDirectory = entry.mode === FileMode.TREE;
481
-
482
- if (isDirectory) {
483
- // Recursively process subdirectories
484
- await this.writeTreeToWorkdir(entry.id, relativePath);
485
- } else {
486
- // Ensure parent directory exists
487
- const lastSlash = relativePath.lastIndexOf("/");
488
- if (lastSlash > 0) {
489
- const parentDir = relativePath.substring(0, lastSlash);
490
- await worktree.mkdir(parentDir);
491
- }
492
-
493
- // Stream the blob into the file (an empty file when the blob is missing)
494
- const blobContent = await this.blobs.load(entry.id);
495
- await worktree.writeContent(relativePath, blobContent ?? []);
496
- }
497
- }
498
- }
499
-
500
582
  /**
501
583
  * Checkout a path from the staging index.
502
584
  */