@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
@@ -1,16 +1,28 @@
1
- import type { ObjectId } from "@statewalker/vcs-core";
1
+ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
2
2
  import {
3
3
  createRepositoryFacade,
4
4
  createTransportRefStore,
5
5
  type RefspecResolver,
6
6
  fetch as transportFetch,
7
7
  } from "@statewalker/vcs-transport";
8
+ import { entryStatOf, type Worktree } from "@statewalker/vcs-working-tree";
8
9
 
9
- import { InvalidArgumentError, InvalidRemoteError, RefNotFoundError } from "../errors/index.js";
10
+ import {
11
+ CloneCheckoutError,
12
+ InvalidArgumentError,
13
+ InvalidRemoteError,
14
+ RefNotFoundError,
15
+ } from "../errors/index.js";
16
+ import { RemoteConfigStore } from "../remote-config/index.js";
10
17
  import type { CloneResult } from "../results/clone-result.js";
11
18
  import type { FetchResult, TrackingRefUpdate } from "../results/fetch-result.js";
12
19
  import { TransportCommand } from "../transport-command.js";
20
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
13
21
  import { TagOption, toTagMode, toTrackingRefUpdate } from "./fetch-command.js";
22
+ import { planTreeRestore, writeTreeRestorePlan } from "./tree-restore.js";
23
+
24
+ /** Names the clone's checkout in failure messages. */
25
+ const CLONE = "clone";
14
26
 
15
27
  /**
16
28
  * Clone a remote repository.
@@ -23,6 +35,25 @@ import { TagOption, toTagMode, toTrackingRefUpdate } from "./fetch-command.js";
23
35
  * rather than operating on an existing one. The store passed to the
24
36
  * constructor should be an empty/new store that will be populated.
25
37
  *
38
+ * Like `git clone`, it configures the remote (`remote.<name>.url`, the
39
+ * `remote.<name>.fetch` refspec of the clone, `remote.<name>.tagOpt` for
40
+ * `--no-tags`, `remote.<name>.mirror`), the upstream of the checked-out branch
41
+ * (`branch.<name>.remote` / `branch.<name>.merge`), and points
42
+ * `refs/remotes/<name>/HEAD` at the remote's default branch.
43
+ *
44
+ * A non-bare clone checks out the commit HEAD names, as `git clone` does: the files
45
+ * of its tree are written to the worktree (executable bits and symbolic links where
46
+ * the worktree can represent them, see `Worktree.capabilities`; an empty directory
47
+ * for each submodule) and the index records them with their stat data. When the
48
+ * worktree cannot represent executables or symlinks, `core.filemode` or
49
+ * `core.symlinks` is set to false, as `git init` does after probing the filesystem.
50
+ * `setNoCheckout(true)` writes neither files nor index; a bare clone has neither.
51
+ *
52
+ * As in git, the checkout comes last, once the refs and the configuration are written:
53
+ * when it fails (a tree path git's `verify_path` refuses, entries that collide, a file
54
+ * in the way) the clone throws a `CloneCheckoutError` ("Clone succeeded, but checkout
55
+ * failed") carrying the clone's result, and the repository stays usable.
56
+ *
26
57
  * @example
27
58
  * ```typescript
28
59
  * // Basic clone
@@ -58,6 +89,7 @@ export class CloneCommand extends TransportCommand<CloneResult> {
58
89
  private remoteName = "origin";
59
90
  private cloneAllBranches = true;
60
91
  private mirror = false;
92
+ private singleBranch?: boolean;
61
93
  private branchesToClone: string[] = [];
62
94
  private tagOption: TagOption = TagOption.AUTO_FOLLOW;
63
95
  private shallowSince?: Date;
@@ -82,10 +114,11 @@ export class CloneCommand extends TransportCommand<CloneResult> {
82
114
  }
83
115
 
84
116
  /**
85
- * Set the branch to clone.
117
+ * Set the branch to check out (`git clone --branch`).
86
118
  *
87
- * If set, only this branch will be fetched.
88
- * Otherwise, all branches are fetched.
119
+ * The branch, or else a tag of that name (checked out as a detached HEAD), instead
120
+ * of the remote's default branch. All branches are still fetched unless
121
+ * {@link setSingleBranch} (or a shallow clone) restricts the clone to this one.
89
122
  *
90
123
  * @param branch Branch name (e.g., "main" or "refs/heads/main")
91
124
  */
@@ -135,7 +168,8 @@ export class CloneCommand extends TransportCommand<CloneResult> {
135
168
  }
136
169
 
137
170
  /**
138
- * Set whether to skip checkout.
171
+ * Set whether to skip checkout (`git clone --no-checkout`): HEAD and the branch are
172
+ * set up, but no file is written and the index is left empty.
139
173
  *
140
174
  * @param noCheckout Whether to skip checkout
141
175
  */
@@ -172,6 +206,26 @@ export class CloneCommand extends TransportCommand<CloneResult> {
172
206
  return this.remoteName;
173
207
  }
174
208
 
209
+ /**
210
+ * Clone only one branch (`git clone --single-branch`): the {@link setBranch} branch or
211
+ * tag, else the remote's default branch. The remote's fetch refspec is configured for
212
+ * that branch alone, and tags are auto-followed instead of all fetched.
213
+ *
214
+ * Unset, a shallow clone (`setDepth`, `setShallowSince`, `addShallowExclude`) is
215
+ * single-branch, as in git, and so is a clone restricted by
216
+ * {@link setBranchesToClone}; `setSingleBranch(false)` clones all branches anyway.
217
+ */
218
+ setSingleBranch(singleBranch: boolean): this {
219
+ this.checkCallable();
220
+ this.singleBranch = singleBranch;
221
+ return this;
222
+ }
223
+
224
+ /** Whether `--single-branch` was set (undefined: decided by the other options). */
225
+ isSingleBranch(): boolean | undefined {
226
+ return this.singleBranch;
227
+ }
228
+
175
229
  /**
176
230
  * Set whether to clone all branches.
177
231
  *
@@ -328,23 +382,47 @@ export class CloneCommand extends TransportCommand<CloneResult> {
328
382
  }
329
383
 
330
384
  // Determine clone branch strategy
331
- const branchToClone = toBranchName(this.determineBranchToClone());
385
+ const branchesToClone = this.mirror || this.cloneAllBranches ? [] : this.branchesToClone;
386
+ const branchToClone = toBranchName(this.branch ?? branchesToClone[0]);
332
387
  const history = this._workingCopy.history;
333
388
 
334
389
  // git clone's refspecs: tracking refs, local heads (bare), every ref (mirror)
335
390
  const tracking = (branch: string) =>
336
391
  this.bare ? `refs/heads/${branch}` : `refs/remotes/${this.remoteName}/${branch}`;
337
- // git: a shallow clone is a single-branch clone of the remote HEAD's branch
392
+ // git: a shallow clone is a single-branch clone (of --branch, else the remote HEAD's branch)
338
393
  const singleBranch =
339
394
  !this.mirror &&
340
- (branchToClone !== undefined ||
341
- this.depth !== undefined ||
342
- this.shallowSince !== undefined ||
343
- this.shallowExcludes.length > 0);
395
+ (this.singleBranch ??
396
+ (branchesToClone.length > 0 ||
397
+ this.depth !== undefined ||
398
+ this.shallowSince !== undefined ||
399
+ this.shallowExcludes.length > 0));
344
400
  let detachedTag: string | undefined;
345
401
  let refspecs: string[] | RefspecResolver;
346
402
  if (this.mirror) {
347
403
  refspecs = ["+refs/*:refs/*"];
404
+ } else if (branchToClone !== undefined && !singleBranch) {
405
+ // --branch without --single-branch: every branch, then the branch (or tag) checked out
406
+ const b = branchToClone;
407
+ refspecs = {
408
+ prefixes: ["refs/heads/", `refs/tags/${b}`],
409
+ resolve: (remoteRefs) => {
410
+ const all = [`+refs/heads/*:${tracking("*")}`];
411
+ if (remoteRefs.some((r) => r.name === `refs/heads/${b}` && r.oid)) return all;
412
+ // git finds the tag among the refs it clones: not with --no-tags
413
+ if (
414
+ this.tagOption !== TagOption.NO_TAGS &&
415
+ remoteRefs.some((r) => r.name === `refs/tags/${b}` && r.oid)
416
+ ) {
417
+ detachedTag = `refs/tags/${b}`;
418
+ return all;
419
+ }
420
+ throw new RefNotFoundError(
421
+ `refs/heads/${b}`,
422
+ `Remote branch ${b} not found in upstream ${this.remoteName}`,
423
+ );
424
+ },
425
+ };
348
426
  } else if (branchToClone !== undefined) {
349
427
  // --branch names a branch, or else a tag (checked out as a detached HEAD)
350
428
  const b = branchToClone;
@@ -389,6 +467,7 @@ export class CloneCommand extends TransportCommand<CloneResult> {
389
467
  auth: this.credentials,
390
468
  headers: this.headers,
391
469
  timeout: this.timeout,
470
+ gzipRequests: this.gzipRequests,
392
471
  repository: createRepositoryFacade({ history }),
393
472
  refStore: createTransportRefStore(history.refs),
394
473
  refspecs,
@@ -409,6 +488,13 @@ export class CloneCommand extends TransportCommand<CloneResult> {
409
488
  const advertisedDefaultBranch = result.defaultBranch;
410
489
  let defaultBranch = branchToClone ?? toBranchName(advertisedDefaultBranch);
411
490
  let headCommit: ObjectId | undefined;
491
+ let checkedOutBranch: string | undefined;
492
+ // the commit to check out once refs and configuration are in place (git: last)
493
+ let checkoutId: ObjectId | undefined;
494
+ // an empty remote without unborn HEAD: git's default branch (the one init named)
495
+ if (!detachedTag && !this.bare && defaultBranch === undefined && result.isEmpty) {
496
+ defaultBranch = (await this.localHeadBranch()) ?? "main";
497
+ }
412
498
 
413
499
  if (detachedTag) {
414
500
  // git clone --branch <tag>: a detached HEAD at the tag's commit
@@ -423,7 +509,7 @@ export class CloneCommand extends TransportCommand<CloneResult> {
423
509
  if (id) {
424
510
  await this.refsStore.set("HEAD", id);
425
511
  headCommit = id;
426
- if (!this.bare && !this.noCheckout) await this.checkoutHead(id);
512
+ if (!this.bare && !this.noCheckout) checkoutId = id;
427
513
  }
428
514
  } else if (defaultBranch && !this.bare) {
429
515
  // The local branch starts at the tracking ref the clone just wrote
@@ -432,12 +518,12 @@ export class CloneCommand extends TransportCommand<CloneResult> {
432
518
  if (tip?.objectId) {
433
519
  await this.refsStore.set(localRef, tip.objectId);
434
520
  headCommit = tip.objectId;
435
- if (!this.noCheckout) {
436
- await this.checkoutHead(tip.objectId);
437
- }
521
+ if (!this.noCheckout) checkoutId = tip.objectId;
438
522
  }
439
523
  // HEAD names the default branch, born or not (an empty remote's unborn HEAD)
440
524
  await this.refsStore.setSymbolic("HEAD", localRef);
525
+ // git's install_branch_config: the branch tracks its remote counterpart
526
+ if (tip?.objectId || result.isEmpty) checkedOutBranch = defaultBranch;
441
527
  } else if (this.bare || this.mirror) {
442
528
  // For bare/mirror repos, HEAD points to default branch
443
529
  if (defaultBranch) {
@@ -446,6 +532,27 @@ export class CloneCommand extends TransportCommand<CloneResult> {
446
532
  }
447
533
  }
448
534
 
535
+ // git's update_remote_refs: refs/remotes/<name>/HEAD names the tracking ref of the
536
+ // remote's default branch, when the clone took that branch
537
+ const remoteHead = advertisedDefaultBranch?.startsWith("refs/heads/")
538
+ ? toBranchName(advertisedDefaultBranch)
539
+ : undefined;
540
+ if (!this.bare && remoteHead) {
541
+ const target = `refs/remotes/${this.remoteName}/${remoteHead}`;
542
+ if ((await this.refsStore.resolve(target))?.objectId) {
543
+ await this.refsStore.setSymbolic(`refs/remotes/${this.remoteName}/HEAD`, target);
544
+ }
545
+ }
546
+
547
+ await this.writeConfig({
548
+ worktree: this.bare ? undefined : this.worktreeAccess,
549
+ singleBranch,
550
+ branch: branchToClone,
551
+ detachedTag,
552
+ remoteHead,
553
+ checkedOutBranch,
554
+ });
555
+
449
556
  // Build fetch result
450
557
  const advertisedRefs = new Map<string, ObjectId>();
451
558
  for (const ref of result.remoteRefs) {
@@ -462,51 +569,148 @@ export class CloneCommand extends TransportCommand<CloneResult> {
462
569
  messages: [],
463
570
  };
464
571
 
465
- return {
572
+ const cloneResult: CloneResult = {
466
573
  fetchResult,
467
574
  defaultBranch: defaultBranch ?? "main",
468
575
  remoteName: this.remoteName,
469
576
  bare: this.bare,
470
577
  headCommit,
471
578
  };
579
+
580
+ if (checkoutId) {
581
+ try {
582
+ const collided = await this.checkoutHead(checkoutId);
583
+ if (collided.length > 0) cloneResult.collidedPaths = collided;
584
+ } catch (error) {
585
+ throw new CloneCheckoutError(cloneResult, error);
586
+ }
587
+ }
588
+ return cloneResult;
472
589
  }
473
590
 
474
591
  /**
475
- * Determine which branch to clone based on options.
592
+ * Writes the configuration `git clone` writes (clone.c): `remote.<name>.url`,
593
+ * `remote.<name>.tagOpt` for `--no-tags` and `--mirror` (git 2.49+), the `remote.<name>.fetch` refspec of what was
594
+ * cloned (none for a bare clone; `+refs/*:refs/*` and `remote.<name>.mirror` for a
595
+ * mirror; one branch or tag for a single-branch clone), and the upstream of the
596
+ * checked-out branch (`branch.<b>.remote`, `branch.<b>.merge`).
476
597
  */
477
- private determineBranchToClone(): string | undefined {
478
- // Explicit branch takes precedence
479
- if (this.branch) {
480
- return this.branch;
598
+ private async writeConfig(clone: {
599
+ worktree?: Worktree;
600
+ singleBranch: boolean;
601
+ branch?: string;
602
+ detachedTag?: string;
603
+ remoteHead?: string;
604
+ checkedOutBranch?: string;
605
+ }): Promise<void> {
606
+ const store = RemoteConfigStore.from(this.workingCopy);
607
+ // git init probes the filesystem: what the worktree cannot represent is turned off
608
+ const capabilities = clone.worktree?.capabilities;
609
+ if (capabilities?.executable === false) store.setValue("core.filemode", "false");
610
+ if (capabilities?.symlinks === false) store.setValue("core.symlinks", "false");
611
+ // ...and whether it folds case or Unicode composition (git writes each only when found)
612
+ const folding = await clone.worktree?.probeCaseFolding?.();
613
+ if (folding?.ignoreCase) store.setValue("core.ignorecase", "true");
614
+ if (folding?.precomposeUnicode) store.setValue("core.precomposeunicode", "true");
615
+ const remote = `remote.${this.remoteName}`;
616
+ store.setValue(`${remote}.url`, this.uri as string);
617
+ // git >= 2.49: --mirror implies --no-tags (its refspec still maps every tag)
618
+ if (this.tagOption === TagOption.NO_TAGS || this.mirror) {
619
+ store.setValue(`${remote}.tagOpt`, "--no-tags");
481
620
  }
482
-
483
- // Mirror or cloneAllBranches means fetch all
484
- if (this.mirror || this.cloneAllBranches) {
485
- return undefined;
621
+ let fetchRefspec: string | undefined;
622
+ if (this.mirror) {
623
+ fetchRefspec = "+refs/*:refs/*";
624
+ } else if (!this.bare) {
625
+ const top = `refs/remotes/${this.remoteName}/`;
626
+ if (!clone.singleBranch) fetchRefspec = `+refs/heads/*:${top}*`;
627
+ else if (clone.detachedTag) fetchRefspec = `+${clone.detachedTag}:${clone.detachedTag}`;
628
+ else if (clone.branch) fetchRefspec = `+refs/heads/${clone.branch}:${top}${clone.branch}`;
629
+ // without a remote HEAD branch, a later fetch takes the remote HEAD alone, as in git
630
+ else if (clone.remoteHead)
631
+ fetchRefspec = `+refs/heads/${clone.remoteHead}:${top}${clone.remoteHead}`;
486
632
  }
487
-
488
- // If specific branches are set, use the first one
489
- if (this.branchesToClone.length > 0) {
490
- return this.branchesToClone[0];
633
+ if (fetchRefspec) {
634
+ store.setValue(`${remote}.fetch`, fetchRefspec);
635
+ if (this.mirror) store.setValue(`${remote}.mirror`, "true");
636
+ }
637
+ if (!this.bare && clone.checkedOutBranch) {
638
+ store.setValue(`branch.${clone.checkedOutBranch}.remote`, this.remoteName);
639
+ store.setValue(
640
+ `branch.${clone.checkedOutBranch}.merge`,
641
+ `refs/heads/${clone.checkedOutBranch}`,
642
+ );
491
643
  }
644
+ await store.save();
645
+ }
492
646
 
493
- return undefined;
647
+ /** The branch the local HEAD names (`init.defaultBranch` of the new repository), if any. */
648
+ private async localHeadBranch(): Promise<string | undefined> {
649
+ const head = await this.refsStore.get("HEAD");
650
+ return head && "target" in head && head.target.startsWith("refs/heads/")
651
+ ? head.target.slice("refs/heads/".length)
652
+ : undefined;
494
653
  }
495
654
 
496
655
  /**
497
- * Checkout HEAD commit to staging area.
656
+ * Check out the cloned commit, as `git clone` does: the files of its tree into the
657
+ * worktree, then the index with the stat data of the files written. Without a
658
+ * worktree only the index is filled.
659
+ *
660
+ * The whole tree is planned (and every blob checked) before the first file is
661
+ * written. Symlinks become links where the worktree makes them and `core.symlinks`
662
+ * is not false, else plain files holding the target (the index keeps mode 120000);
663
+ * a submodule becomes an empty directory, as in a clone without `--recurse-submodules`.
664
+ *
665
+ * The index records size, mtime and (where the worktree reports it) ctime, but no inode,
666
+ * device, uid or gid, which FilesApi does not give: `git status` sees the files clean and
667
+ * refreshes the index once, while commands that do not refresh (`git diff-files`,
668
+ * `git diff-index --quiet`) report every file as changed until then, unless
669
+ * `core.checkStat=minimal`.
498
670
  */
499
- private async checkoutHead(commitId: ObjectId): Promise<void> {
500
- try {
501
- const commit = await this.commits.load(commitId);
502
- if (!commit) {
503
- return;
504
- }
671
+ private async checkoutHead(commitId: ObjectId): Promise<string[]> {
672
+ const commit = await this.commits.load(commitId).catch(() => undefined);
673
+ if (!commit) return [];
674
+ const worktree = this.bare ? undefined : this.worktreeAccess;
675
+ if (!worktree) {
505
676
  await this.staging.readTree(this.trees, commit.tree);
506
677
  await this.staging.write();
507
- } catch {
508
- // Commit not available yet (pack not unpacked)
678
+ return [];
509
679
  }
680
+
681
+ // every path checked (verify_path, collisions) before the first file is written
682
+ const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, CLONE, {
683
+ symlinks: true,
684
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
685
+ windows: worktree.capabilities?.windowsPaths === true,
686
+ reservedNames: worktree.capabilities?.reservedNames,
687
+ });
688
+ const symlinks = this.symlinksEnabled(worktree);
689
+ await writeTreeRestorePlan(worktree, this.blobs, plan, CLONE, { symlinks, gitlinks: true });
690
+
691
+ // the index records what was written (the worktree's stat of each file, a link's
692
+ // own when the worktree can lstat): native git then sees the files unchanged
693
+ await this.staging.readTree(this.trees, commit.tree);
694
+ const editor = this.staging.createEditor();
695
+ for (const { path, objectId, mode } of plan.entries) {
696
+ const stats = await worktree.getEntry(path);
697
+ if (stats) {
698
+ editor.upsert({
699
+ path,
700
+ objectId,
701
+ mode,
702
+ ...entryStatOf(stats),
703
+ });
704
+ }
705
+ }
706
+ await editor.finish();
707
+ await this.staging.write();
708
+ return plan.collided;
709
+ }
710
+
711
+ /** Whether symlinks are written as links: the worktree can, and `core.symlinks` allows. */
712
+ private symlinksEnabled(worktree: Worktree): boolean {
713
+ return worktreeModeTrust(this.workingCopy, worktree).symlinks;
510
714
  }
511
715
  }
512
716
 
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The `core.*` settings that decide how the worktree is read and written.
3
+ *
4
+ * Read from the working copy's own configuration: this repository has no chain of
5
+ * global and system configuration files, so a `core.symlinks` set only in `~/.gitconfig`
6
+ * is not seen (native git would honour it).
7
+ */
8
+
9
+ import type { WorkingCopy, Worktree, WorktreeModeTrust } from "@statewalker/vcs-working-tree";
10
+
11
+ import { RemoteConfigStore } from "../remote-config/index.js";
12
+
13
+ /** A git boolean (`true`/`yes`/`on`/`1`, `false`/`no`/`off`/`0`), else `fallback`. */
14
+ export function coreBool(workingCopy: WorkingCopy, name: string, fallback: boolean): boolean {
15
+ const value = RemoteConfigStore.from(workingCopy).value(`core.${name}`)?.trim().toLowerCase();
16
+ if (value === undefined) return fallback;
17
+ if (["false", "no", "off", "0"].includes(value)) return false;
18
+ if (["true", "yes", "on", "1", ""].includes(value)) return true;
19
+ return fallback;
20
+ }
21
+
22
+ /**
23
+ * Whether the worktree's executable bits and symbolic links are real: the worktree can
24
+ * represent them and `core.filemode` / `core.symlinks` are not false.
25
+ */
26
+ export function worktreeModeTrust(workingCopy: WorkingCopy, worktree: Worktree): WorktreeModeTrust {
27
+ const minimal =
28
+ RemoteConfigStore.from(workingCopy).value("core.checkStat")?.trim().toLowerCase() === "minimal";
29
+ return {
30
+ // inode, owner and group compared unless core.checkStat is minimal
31
+ fullStat: !minimal,
32
+ executable:
33
+ worktree.capabilities?.executable !== false && coreBool(workingCopy, "filemode", true),
34
+ symlinks: worktree.capabilities?.symlinks !== false && coreBool(workingCopy, "symlinks", true),
35
+ // git compares ctime unless core.trustctime is false or core.checkStat is minimal
36
+ ctime:
37
+ coreBool(workingCopy, "trustctime", true) &&
38
+ RemoteConfigStore.from(workingCopy).value("core.checkStat")?.trim().toLowerCase() !==
39
+ "minimal",
40
+ };
41
+ }