@statewalker/vcs-commands 0.3.2 → 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 (133) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts +7 -24
  8. package/dist/commands/checkout-command.d.ts.map +1 -1
  9. package/dist/commands/clean-command.d.ts +34 -4
  10. package/dist/commands/clean-command.d.ts.map +1 -1
  11. package/dist/commands/clone-command.d.ts +61 -21
  12. package/dist/commands/clone-command.d.ts.map +1 -1
  13. package/dist/commands/core-config.d.ts +16 -0
  14. package/dist/commands/core-config.d.ts.map +1 -0
  15. package/dist/commands/fetch-command.d.ts +104 -37
  16. package/dist/commands/fetch-command.d.ts.map +1 -1
  17. package/dist/commands/index.d.ts +1 -0
  18. package/dist/commands/index.d.ts.map +1 -1
  19. package/dist/commands/index.js +2 -2
  20. package/dist/commands/init-command.d.ts.map +1 -1
  21. package/dist/commands/merge-command.d.ts +15 -2
  22. package/dist/commands/merge-command.d.ts.map +1 -1
  23. package/dist/commands/push-command.d.ts +58 -25
  24. package/dist/commands/push-command.d.ts.map +1 -1
  25. package/dist/commands/remote-command.d.ts +115 -6
  26. package/dist/commands/remote-command.d.ts.map +1 -1
  27. package/dist/commands/reset-command.d.ts.map +1 -1
  28. package/dist/commands/stash-apply-command.d.ts +35 -13
  29. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  30. package/dist/commands/stash-create-command.d.ts +59 -25
  31. package/dist/commands/stash-create-command.d.ts.map +1 -1
  32. package/dist/commands/stash-drop-command.d.ts +8 -2
  33. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  34. package/dist/commands/stash-list-command.d.ts +2 -4
  35. package/dist/commands/stash-list-command.d.ts.map +1 -1
  36. package/dist/commands/stash-working-tree.d.ts +72 -0
  37. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  38. package/dist/commands/status-command.d.ts +29 -22
  39. package/dist/commands/status-command.d.ts.map +1 -1
  40. package/dist/commands/tag-command.d.ts.map +1 -1
  41. package/dist/commands/tree-restore.d.ts +52 -5
  42. package/dist/commands/tree-restore.d.ts.map +1 -1
  43. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  44. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  45. package/dist/{commands-COO4tJhv.js → commands-CsLNyvZ1.js} +3370 -1057
  46. package/dist/core-commands/add.command.impl.d.ts +0 -4
  47. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  48. package/dist/core-commands/index.d.ts +1 -3
  49. package/dist/core-commands/index.d.ts.map +1 -1
  50. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  51. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  52. package/dist/errors/checkout-errors.d.ts +13 -0
  53. package/dist/errors/checkout-errors.d.ts.map +1 -1
  54. package/dist/errors/index.js +18 -1
  55. package/dist/git-command.d.ts +10 -1
  56. package/dist/git-command.d.ts.map +1 -1
  57. package/dist/git.d.ts +21 -3
  58. package/dist/git.d.ts.map +1 -1
  59. package/dist/index.js +4 -4
  60. package/dist/remote-config/index.d.ts +1 -0
  61. package/dist/remote-config/index.d.ts.map +1 -1
  62. package/dist/remote-config/remote-config-store.d.ts +22 -0
  63. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  64. package/dist/remote-config/remote-refs.d.ts +37 -0
  65. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  66. package/dist/results/clone-result.d.ts +6 -0
  67. package/dist/results/clone-result.d.ts.map +1 -1
  68. package/dist/results/diff-formatter.d.ts +14 -7
  69. package/dist/results/diff-formatter.d.ts.map +1 -1
  70. package/dist/results/fetch-result.d.ts +16 -1
  71. package/dist/results/fetch-result.d.ts.map +1 -1
  72. package/dist/results/index.js +28 -23
  73. package/dist/results/push-result.d.ts +9 -2
  74. package/dist/results/push-result.d.ts.map +1 -1
  75. package/dist/results/status-result.d.ts +91 -20
  76. package/dist/results/status-result.d.ts.map +1 -1
  77. package/dist/{status-result-BwAyxq6R.js → status-result-BpyUK1Sg.js} +115 -5
  78. package/dist/transport-command.d.ts +12 -0
  79. package/dist/transport-command.d.ts.map +1 -1
  80. package/package.json +14 -12
  81. package/src/commands/add-command.ts +23 -30
  82. package/src/commands/blame-command.ts +41 -0
  83. package/src/commands/branch-command.ts +2 -53
  84. package/src/commands/checkout-command.ts +205 -127
  85. package/src/commands/clean-command.ts +187 -81
  86. package/src/commands/clone-command.ts +334 -137
  87. package/src/commands/core-config.ts +41 -0
  88. package/src/commands/fetch-command.ts +536 -211
  89. package/src/commands/gc-command.ts +1 -1
  90. package/src/commands/index.ts +1 -0
  91. package/src/commands/init-command.ts +108 -11
  92. package/src/commands/merge-command.ts +60 -27
  93. package/src/commands/pack-refs-command.ts +2 -2
  94. package/src/commands/push-command.ts +242 -308
  95. package/src/commands/reflog-command.ts +2 -2
  96. package/src/commands/remote-command.ts +429 -19
  97. package/src/commands/reset-command.ts +18 -5
  98. package/src/commands/stash-apply-command.ts +632 -97
  99. package/src/commands/stash-create-command.ts +142 -62
  100. package/src/commands/stash-drop-command.ts +53 -5
  101. package/src/commands/stash-list-command.ts +10 -4
  102. package/src/commands/stash-working-tree.ts +243 -0
  103. package/src/commands/status-command.ts +197 -91
  104. package/src/commands/tag-command.ts +2 -53
  105. package/src/commands/tree-restore.ts +143 -18
  106. package/src/commands/worktree-overwrite-checks.ts +215 -0
  107. package/src/core-commands/add.command.impl.ts +15 -20
  108. package/src/core-commands/index.ts +1 -8
  109. package/src/core-commands/store-worktree-file.ts +5 -0
  110. package/src/errors/checkout-errors.ts +20 -0
  111. package/src/git-command.ts +42 -1
  112. package/src/git.ts +30 -2
  113. package/src/remote-config/index.ts +1 -0
  114. package/src/remote-config/remote-config-store.ts +95 -8
  115. package/src/remote-config/remote-refs.ts +103 -0
  116. package/src/results/clone-result.ts +6 -0
  117. package/src/results/diff-formatter.ts +31 -38
  118. package/src/results/fetch-result.ts +16 -1
  119. package/src/results/push-result.ts +9 -2
  120. package/src/results/status-result.ts +212 -29
  121. package/src/transport-command.ts +18 -0
  122. package/dist/core-commands/checkout.command.d.ts +0 -103
  123. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  124. package/dist/core-commands/checkout.command.impl.d.ts +0 -114
  125. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  126. package/dist/pack-import/index.d.ts +0 -8
  127. package/dist/pack-import/index.d.ts.map +0 -1
  128. package/dist/pack-import/pack-import.d.ts +0 -11
  129. package/dist/pack-import/pack-import.d.ts.map +0 -1
  130. package/src/core-commands/checkout.command.impl.ts +0 -586
  131. package/src/core-commands/checkout.command.ts +0 -125
  132. package/src/pack-import/index.ts +0 -8
  133. package/src/pack-import/pack-import.ts +0 -24
@@ -1,20 +1,28 @@
1
- import type { ObjectId } from "@statewalker/vcs-core";
1
+ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
2
2
  import {
3
- type CloneOptions as TransportCloneOptions,
4
- clone as transportClone,
3
+ createRepositoryFacade,
4
+ createTransportRefStore,
5
+ type RefspecResolver,
6
+ fetch as transportFetch,
5
7
  } from "@statewalker/vcs-transport";
6
- import { bytesToHex } from "@statewalker/vcs-utils/hash/utils";
8
+ import { entryStatOf, type Worktree } from "@statewalker/vcs-working-tree";
7
9
 
8
- import { InvalidArgumentError, InvalidRemoteError } from "../errors/index.js";
9
- import { importPackIntoHistory } from "../pack-import/index.js";
10
- import type { CloneResult } from "../results/clone-result.js";
11
10
  import {
12
- type FetchResult,
13
- RefUpdateStatus,
14
- type TrackingRefUpdate,
15
- } from "../results/fetch-result.js";
11
+ CloneCheckoutError,
12
+ InvalidArgumentError,
13
+ InvalidRemoteError,
14
+ RefNotFoundError,
15
+ } from "../errors/index.js";
16
+ import { RemoteConfigStore } from "../remote-config/index.js";
17
+ import type { CloneResult } from "../results/clone-result.js";
18
+ import type { FetchResult, TrackingRefUpdate } from "../results/fetch-result.js";
16
19
  import { TransportCommand } from "../transport-command.js";
17
- import { TagOption } from "./fetch-command.js";
20
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
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";
18
26
 
19
27
  /**
20
28
  * Clone a remote repository.
@@ -27,6 +35,25 @@ import { TagOption } from "./fetch-command.js";
27
35
  * rather than operating on an existing one. The store passed to the
28
36
  * constructor should be an empty/new store that will be populated.
29
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
+ *
30
57
  * @example
31
58
  * ```typescript
32
59
  * // Basic clone
@@ -62,6 +89,7 @@ export class CloneCommand extends TransportCommand<CloneResult> {
62
89
  private remoteName = "origin";
63
90
  private cloneAllBranches = true;
64
91
  private mirror = false;
92
+ private singleBranch?: boolean;
65
93
  private branchesToClone: string[] = [];
66
94
  private tagOption: TagOption = TagOption.AUTO_FOLLOW;
67
95
  private shallowSince?: Date;
@@ -86,10 +114,11 @@ export class CloneCommand extends TransportCommand<CloneResult> {
86
114
  }
87
115
 
88
116
  /**
89
- * Set the branch to clone.
117
+ * Set the branch to check out (`git clone --branch`).
90
118
  *
91
- * If set, only this branch will be fetched.
92
- * 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.
93
122
  *
94
123
  * @param branch Branch name (e.g., "main" or "refs/heads/main")
95
124
  */
@@ -139,7 +168,8 @@ export class CloneCommand extends TransportCommand<CloneResult> {
139
168
  }
140
169
 
141
170
  /**
142
- * 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.
143
173
  *
144
174
  * @param noCheckout Whether to skip checkout
145
175
  */
@@ -176,6 +206,26 @@ export class CloneCommand extends TransportCommand<CloneResult> {
176
206
  return this.remoteName;
177
207
  }
178
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
+
179
229
  /**
180
230
  * Set whether to clone all branches.
181
231
  *
@@ -332,93 +382,181 @@ export class CloneCommand extends TransportCommand<CloneResult> {
332
382
  }
333
383
 
334
384
  // Determine clone branch strategy
335
- const branchToClone = this.determineBranchToClone();
385
+ const branchesToClone = this.mirror || this.cloneAllBranches ? [] : this.branchesToClone;
386
+ const branchToClone = toBranchName(this.branch ?? branchesToClone[0]);
387
+ const history = this._workingCopy.history;
388
+
389
+ // git clone's refspecs: tracking refs, local heads (bare), every ref (mirror)
390
+ const tracking = (branch: string) =>
391
+ this.bare ? `refs/heads/${branch}` : `refs/remotes/${this.remoteName}/${branch}`;
392
+ // git: a shallow clone is a single-branch clone (of --branch, else the remote HEAD's branch)
393
+ const singleBranch =
394
+ !this.mirror &&
395
+ (this.singleBranch ??
396
+ (branchesToClone.length > 0 ||
397
+ this.depth !== undefined ||
398
+ this.shallowSince !== undefined ||
399
+ this.shallowExcludes.length > 0));
400
+ let detachedTag: string | undefined;
401
+ let refspecs: string[] | RefspecResolver;
402
+ if (this.mirror) {
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
+ };
426
+ } else if (branchToClone !== undefined) {
427
+ // --branch names a branch, or else a tag (checked out as a detached HEAD)
428
+ const b = branchToClone;
429
+ refspecs = {
430
+ prefixes: [`refs/heads/${b}`, `refs/tags/${b}`],
431
+ resolve: (remoteRefs) => {
432
+ if (remoteRefs.some((r) => r.name === `refs/heads/${b}` && r.oid)) {
433
+ return [`+refs/heads/${b}:${tracking(b)}`];
434
+ }
435
+ if (remoteRefs.some((r) => r.name === `refs/tags/${b}` && r.oid)) {
436
+ detachedTag = `refs/tags/${b}`;
437
+ return [`+refs/tags/${b}:refs/tags/${b}`];
438
+ }
439
+ throw new RefNotFoundError(
440
+ `refs/heads/${b}`,
441
+ `Remote branch ${b} not found in upstream ${this.remoteName}`,
442
+ );
443
+ },
444
+ };
445
+ } else if (singleBranch) {
446
+ refspecs = {
447
+ prefixes: ["refs/heads/"],
448
+ resolve: (remoteRefs) => {
449
+ const head = remoteRefs.find((r) => r.name === "HEAD")?.symref;
450
+ const name = toBranchName(head);
451
+ return name && head?.startsWith("refs/heads/")
452
+ ? [`+${head}:${tracking(name)}`]
453
+ : [`+refs/heads/*:${tracking("*")}`];
454
+ },
455
+ };
456
+ } else {
457
+ refspecs = [`+refs/heads/*:${tracking("*")}`];
458
+ }
459
+ // git clone takes every tag, unless one branch is cloned (then tags follow) or --no-tags
460
+ const tags =
461
+ this.tagOption === TagOption.AUTO_FOLLOW && !singleBranch && !this.mirror
462
+ ? "all"
463
+ : toTagMode(this.tagOption);
336
464
 
337
- // Execute clone via transport
338
- const options: TransportCloneOptions = {
465
+ const result = await transportFetch({
339
466
  url: this.uri,
340
- branch: branchToClone,
341
- depth: this.depth,
342
- bare: this.bare,
343
- remoteName: this.remoteName,
344
467
  auth: this.credentials,
345
468
  headers: this.headers,
346
469
  timeout: this.timeout,
347
- onProgress: this.progressCallback,
348
- onProgressMessage: this.progressMessageCallback,
349
- };
350
-
351
- const transportResult = await transportClone(options);
352
-
353
- // Store pack data
354
- if (transportResult.packData.length > 0) {
355
- await this.storePack(transportResult.packData);
356
- }
357
-
358
- // Update refs based on clone mode
359
- const trackingUpdates: TrackingRefUpdate[] = [];
360
- for (const [refName, objectId] of transportResult.refs) {
361
- const objectIdHex = bytesToHex(objectId);
362
-
363
- // Filter refs based on tag option
364
- if (this.shouldSkipRef(refName)) {
365
- continue;
366
- }
367
-
368
- // For mirror mode, refs are stored directly without remotes prefix
369
- const localRefName = this.mirror ? this.toMirrorRefName(refName) : refName;
370
-
371
- await this.refsStore.set(localRefName, objectIdHex);
372
- trackingUpdates.push({
373
- localRef: localRefName,
374
- remoteRef: refName,
375
- newObjectId: objectIdHex,
376
- status: RefUpdateStatus.NEW,
377
- });
378
- }
470
+ gzipRequests: this.gzipRequests,
471
+ repository: createRepositoryFacade({ history }),
472
+ refStore: createTransportRefStore(history.refs),
473
+ refspecs,
474
+ tags,
475
+ depth: this.depth,
476
+ deepenSince: this.shallowSince,
477
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : undefined,
478
+ onProgress: this.progressMessageCallback,
479
+ reflogMessage: `clone: from ${this.uri}`,
480
+ });
481
+ const trackingUpdates: TrackingRefUpdate[] = result.refUpdates.map(toTrackingRefUpdate);
379
482
 
380
483
  // Set up HEAD and default branch.
381
484
  //
382
485
  // Two forms, deliberately kept apart: the advertised form goes out on
383
486
  // FetchResult unchanged (it is what the remote said), while the ref work
384
487
  // below and CloneResult use the bare branch name.
385
- const advertisedDefaultBranch = transportResult.defaultBranch;
386
- const defaultBranch = toBranchName(advertisedDefaultBranch);
488
+ const advertisedDefaultBranch = result.defaultBranch;
489
+ let defaultBranch = branchToClone ?? toBranchName(advertisedDefaultBranch);
387
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
+ }
388
498
 
389
- if (defaultBranch && !this.bare) {
390
- // Create local branch from the tip the clone just wrote. Look under the
391
- // remote-tracking name first, then under the local branch name: the ref
392
- // loop above stores each ref under its advertised name, so which of the
393
- // two exists depends on the refspec the remote advertised through.
499
+ if (detachedTag) {
500
+ // git clone --branch <tag>: a detached HEAD at the tag's commit
501
+ defaultBranch = toBranchName(advertisedDefaultBranch);
502
+ const tag = await this.refsStore.resolve(detachedTag);
503
+ let id = tag?.objectId;
504
+ for (let i = 0; id && i < 16; i++) {
505
+ const target = await history.tags.getTarget(id);
506
+ if (!target || !(await history.tags.has(id))) break;
507
+ id = target;
508
+ }
509
+ if (id) {
510
+ await this.refsStore.set("HEAD", id);
511
+ headCommit = id;
512
+ if (!this.bare && !this.noCheckout) checkoutId = id;
513
+ }
514
+ } else if (defaultBranch && !this.bare) {
515
+ // The local branch starts at the tracking ref the clone just wrote
394
516
  const localRef = `refs/heads/${defaultBranch}`;
395
- const tip =
396
- (await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`)) ??
397
- (await this.refsStore.resolve(localRef));
398
-
517
+ const tip = await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`);
399
518
  if (tip?.objectId) {
400
519
  await this.refsStore.set(localRef, tip.objectId);
401
520
  headCommit = tip.objectId;
402
-
403
- // Set HEAD to point to local branch
404
- await this.refsStore.setSymbolic("HEAD", localRef);
405
-
406
- // Set up staging area from HEAD tree
407
- if (!this.noCheckout) {
408
- await this.checkoutHead(tip.objectId);
409
- }
521
+ if (!this.noCheckout) checkoutId = tip.objectId;
410
522
  }
523
+ // HEAD names the default branch, born or not (an empty remote's unborn HEAD)
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;
411
527
  } else if (this.bare || this.mirror) {
412
528
  // For bare/mirror repos, HEAD points to default branch
413
529
  if (defaultBranch) {
414
530
  await this.refsStore.setSymbolic("HEAD", `refs/heads/${defaultBranch}`);
531
+ headCommit = (await this.refsStore.resolve("HEAD"))?.objectId;
415
532
  }
416
533
  }
417
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
+
418
556
  // Build fetch result
419
557
  const advertisedRefs = new Map<string, ObjectId>();
420
- for (const [refName, objectId] of transportResult.refs) {
421
- advertisedRefs.set(refName, bytesToHex(objectId));
558
+ for (const ref of result.remoteRefs) {
559
+ if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
422
560
  }
423
561
 
424
562
  const fetchResult: FetchResult = {
@@ -426,94 +564,153 @@ export class CloneCommand extends TransportCommand<CloneResult> {
426
564
  advertisedRefs,
427
565
  trackingRefUpdates: trackingUpdates,
428
566
  defaultBranch: advertisedDefaultBranch,
429
- bytesReceived: transportResult.bytesReceived,
430
- isEmpty: transportResult.isEmpty,
567
+ bytesReceived: result.packBytes,
568
+ isEmpty: result.isEmpty,
431
569
  messages: [],
432
570
  };
433
571
 
434
- return {
572
+ const cloneResult: CloneResult = {
435
573
  fetchResult,
436
574
  defaultBranch: defaultBranch ?? "main",
437
575
  remoteName: this.remoteName,
438
576
  bare: this.bare,
439
577
  headCommit,
440
578
  };
441
- }
442
579
 
443
- /**
444
- * Determine which branch to clone based on options.
445
- */
446
- private determineBranchToClone(): string | undefined {
447
- // Explicit branch takes precedence
448
- if (this.branch) {
449
- return this.branch;
450
- }
451
-
452
- // Mirror or cloneAllBranches means fetch all
453
- if (this.mirror || this.cloneAllBranches) {
454
- return undefined;
455
- }
456
-
457
- // If specific branches are set, use the first one
458
- if (this.branchesToClone.length > 0) {
459
- // Extract branch name from full ref if provided
460
- const first = this.branchesToClone[0];
461
- if (first.startsWith("refs/heads/")) {
462
- return first.slice("refs/heads/".length);
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);
463
586
  }
464
- return first;
465
587
  }
466
-
467
- return undefined;
588
+ return cloneResult;
468
589
  }
469
590
 
470
591
  /**
471
- * Check if a ref should be skipped based on tag option.
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`).
472
597
  */
473
- private shouldSkipRef(refName: string): boolean {
474
- // Skip tags if NO_TAGS option is set
475
- if (this.tagOption === TagOption.NO_TAGS && refName.startsWith("refs/tags/")) {
476
- return true;
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");
477
620
  }
478
- return false;
479
- }
480
-
481
- /**
482
- * Convert a remote ref name to mirror ref name.
483
- */
484
- private toMirrorRefName(refName: string): string {
485
- // For mirror clones, refs/remotes/origin/* becomes refs/heads/*
486
- const remotePrefix = `refs/remotes/${this.remoteName}/`;
487
- if (refName.startsWith(remotePrefix)) {
488
- return `refs/heads/${refName.slice(remotePrefix.length)}`;
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}`;
632
+ }
633
+ if (fetchRefspec) {
634
+ store.setValue(`${remote}.fetch`, fetchRefspec);
635
+ if (this.mirror) store.setValue(`${remote}.mirror`, "true");
489
636
  }
490
- return refName;
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
+ );
643
+ }
644
+ await store.save();
491
645
  }
492
646
 
493
- /**
494
- * Store received pack data.
495
- *
496
- * Unpacks the pack into the working copy's history, so the objects the
497
- * cloned refs point at are actually available locally.
498
- */
499
- private async storePack(packData: Uint8Array): Promise<void> {
500
- await importPackIntoHistory(this._workingCopy.history, packData);
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;
501
653
  }
502
654
 
503
655
  /**
504
- * 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`.
505
670
  */
506
- private async checkoutHead(commitId: ObjectId): Promise<void> {
507
- try {
508
- const commit = await this.commits.load(commitId);
509
- if (!commit) {
510
- return;
511
- }
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) {
512
676
  await this.staging.readTree(this.trees, commit.tree);
513
677
  await this.staging.write();
514
- } catch {
515
- // Commit not available yet (pack not unpacked)
678
+ return [];
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
+ }
516
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;
517
714
  }
518
715
  }
519
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
+ }