@statewalker/vcs-commands 0.3.2 → 0.4.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 (77) 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.map +1 -1
  8. package/dist/commands/clean-command.d.ts.map +1 -1
  9. package/dist/commands/clone-command.d.ts +0 -15
  10. package/dist/commands/clone-command.d.ts.map +1 -1
  11. package/dist/commands/fetch-command.d.ts +16 -31
  12. package/dist/commands/fetch-command.d.ts.map +1 -1
  13. package/dist/commands/index.js +2 -2
  14. package/dist/commands/init-command.d.ts.map +1 -1
  15. package/dist/commands/merge-command.d.ts +15 -2
  16. package/dist/commands/merge-command.d.ts.map +1 -1
  17. package/dist/commands/push-command.d.ts +58 -25
  18. package/dist/commands/push-command.d.ts.map +1 -1
  19. package/dist/commands/stash-create-command.d.ts +1 -1
  20. package/dist/commands/stash-drop-command.d.ts +1 -1
  21. package/dist/commands/stash-list-command.d.ts +1 -1
  22. package/dist/commands/tag-command.d.ts.map +1 -1
  23. package/dist/commands/tree-restore.d.ts.map +1 -1
  24. package/dist/{commands-COO4tJhv.js → commands-BpeXZTC3.js} +473 -469
  25. package/dist/core-commands/add.command.impl.d.ts +0 -4
  26. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  27. package/dist/core-commands/checkout.command.impl.d.ts +2 -6
  28. package/dist/core-commands/checkout.command.impl.d.ts.map +1 -1
  29. package/dist/core-commands/index.d.ts +1 -0
  30. package/dist/core-commands/index.d.ts.map +1 -1
  31. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  32. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  33. package/dist/index.js +3 -3
  34. package/dist/remote-config/remote-config-store.d.ts +4 -0
  35. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  36. package/dist/results/diff-formatter.d.ts +14 -7
  37. package/dist/results/diff-formatter.d.ts.map +1 -1
  38. package/dist/results/fetch-result.d.ts +7 -0
  39. package/dist/results/fetch-result.d.ts.map +1 -1
  40. package/dist/results/index.js +27 -22
  41. package/dist/results/push-result.d.ts +9 -2
  42. package/dist/results/push-result.d.ts.map +1 -1
  43. package/dist/{status-result-BwAyxq6R.js → status-result-BapZoQaR.js} +2 -0
  44. package/package.json +13 -12
  45. package/src/commands/add-command.ts +16 -25
  46. package/src/commands/blame-command.ts +41 -0
  47. package/src/commands/branch-command.ts +2 -53
  48. package/src/commands/checkout-command.ts +7 -11
  49. package/src/commands/clean-command.ts +7 -0
  50. package/src/commands/clone-command.ts +102 -109
  51. package/src/commands/fetch-command.ts +103 -197
  52. package/src/commands/gc-command.ts +1 -1
  53. package/src/commands/init-command.ts +83 -11
  54. package/src/commands/merge-command.ts +60 -27
  55. package/src/commands/pack-refs-command.ts +2 -2
  56. package/src/commands/push-command.ts +242 -308
  57. package/src/commands/reflog-command.ts +2 -2
  58. package/src/commands/stash-apply-command.ts +1 -1
  59. package/src/commands/stash-create-command.ts +1 -1
  60. package/src/commands/stash-drop-command.ts +1 -1
  61. package/src/commands/stash-list-command.ts +1 -1
  62. package/src/commands/tag-command.ts +2 -53
  63. package/src/commands/tree-restore.ts +2 -6
  64. package/src/core-commands/add.command.impl.ts +16 -19
  65. package/src/core-commands/checkout.command.impl.ts +18 -40
  66. package/src/core-commands/index.ts +1 -0
  67. package/src/core-commands/store-worktree-file.ts +5 -0
  68. package/src/remote-config/remote-config-store.ts +11 -0
  69. package/src/results/diff-formatter.ts +31 -38
  70. package/src/results/fetch-result.ts +7 -0
  71. package/src/results/push-result.ts +9 -2
  72. package/dist/pack-import/index.d.ts +0 -8
  73. package/dist/pack-import/index.d.ts.map +0 -1
  74. package/dist/pack-import/pack-import.d.ts +0 -11
  75. package/dist/pack-import/pack-import.d.ts.map +0 -1
  76. package/src/pack-import/index.ts +0 -8
  77. package/src/pack-import/pack-import.ts +0 -24
@@ -1,11 +1,10 @@
1
1
  import { CannotDeleteCurrentBranchError, CommitNotFoundError, EmptyCommitError, IncompatibleOptionsError, InvalidArgumentError, InvalidMainlineParentError, InvalidMergeHeadsError, InvalidRefNameError, InvalidRemoteError, InvalidStashIndexError, InvalidTagNameError, MissingArgumentError, MultipleParentsNotAllowedError, NoFilepatternError, NoHeadError, NoMergeBaseError, NoMessageError, NoRebaseInProgressError, NonFastForwardError, NotADirectoryError, NotFastForwardError, NotImplementedError, NotMergedError, PathNotFoundInTreeError, PathNotInIndexError, PushRejectedException, RefAlreadyExistsError, RefNotFoundError, RemoteAlreadyExistsError, RemoteNotFoundError, StashApplyFailedError, StoreNotAvailableError, UnmergedPathsError, UpstreamRequiredError } from "./errors/index.js";
2
- import { C as isMergeSuccessful, d as createAddEntry, m as createModifyEntry, p as createDeleteEntry, t as StatusImpl } from "./status-result-BwAyxq6R.js";
3
- import { DefaultSerializationApi, FileMode, ObjectType, createInMemoryFilesApi, createMemoryHistory, isSymbolicRef, serializeCommit, serializeTree } from "@statewalker/vcs-core";
4
- import { DeleteStagingEntry, MergeStage, UpdateStagingEntry, createMemoryCheckout } from "@statewalker/vcs-working-tree";
2
+ import { C as isMergeSuccessful, d as createAddEntry, m as createModifyEntry, p as createDeleteEntry, t as StatusImpl } from "./status-result-BapZoQaR.js";
3
+ import { DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, FileMode, ObjectType, compareRefNames, createInMemoryFilesApi, createMemoryHistory, isSymbolicRef, isValidBranchName, isValidTagName, isValidWorktreePath, probeBlob } from "@statewalker/vcs-core";
4
+ import { DeleteStagingEntry, MergeStage, UpdateStagingEntry, createMemoryCheckout, storeWorktreeFile } from "@statewalker/vcs-working-tree";
5
5
  import { DEFAULT_ALGORITHM, MergeContentStrategy, RawText, RawTextComparator, getAlgorithm, merge3Way } from "@statewalker/vcs-utils";
6
- import { clone, expandFromSource, fetch, lsRemote, mapRejectReason, matchSource, parseRefSpec, push } from "@statewalker/vcs-transport";
7
- import { bytesToHex } from "@statewalker/vcs-utils/hash/utils";
8
- import { createFileWorktree } from "@statewalker/vcs-store-files";
6
+ import { createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetch, lsRemote, mapRejectReason, matchDestination, matchSource, parseRefSpec, push } from "@statewalker/vcs-transport";
7
+ import { FileStagingStore, createFileWorktree, createGitFilesHistoryFromFiles } from "@statewalker/vcs-store-files";
9
8
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
10
9
  //#region src/git-command.ts
11
10
  /**
@@ -510,19 +509,19 @@ var AddCommand = class extends GitCommand {
510
509
  }
511
510
  if (this.intentToAdd) {
512
511
  const mode = (await worktree.getEntry(file.path))?.mode ?? FileMode.REGULAR_FILE;
513
- editor.add(new UpdateStagingEntry(file.path, "", mode, {
512
+ editor.add(new UpdateStagingEntry(file.path, EMPTY_BLOB_ID, mode, {
514
513
  size: 0,
515
514
  mtime: Date.now()
516
- }));
515
+ }, { intentToAdd: true }));
517
516
  added.push(file.path);
518
517
  continue;
519
518
  }
520
519
  const worktreeEntry = await worktree.getEntry(file.path);
521
520
  if (!worktreeEntry) continue;
522
- const objectId = await this.storeFileContent(worktree, file.path);
523
- editor.add(new UpdateStagingEntry(file.path, objectId, worktreeEntry.mode, {
524
- size: worktreeEntry.size,
525
- mtime: worktreeEntry.mtime
521
+ const stored = await storeWorktreeFile(this.blobs, worktree, file.path, worktreeEntry);
522
+ editor.add(new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, {
523
+ size: stored.entry.size,
524
+ mtime: stored.entry.mtime
526
525
  }));
527
526
  added.push(file.path);
528
527
  }
@@ -535,16 +534,6 @@ var AddCommand = class extends GitCommand {
535
534
  totalProcessed: added.length + removed.length
536
535
  };
537
536
  }
538
- /**
539
- * Store file content as blob and return object ID.
540
- *
541
- * Note: The object store handles blob header internally.
542
- */
543
- async storeFileContent(worktree, path) {
544
- const chunks = [];
545
- for await (const chunk of worktree.readContent(path)) chunks.push(chunk);
546
- return this.blobs.store(chunks);
547
- }
548
537
  };
549
538
  /**
550
539
  * Index structure for computing content similarity.
@@ -666,6 +655,7 @@ var BlameCommand = class extends GitCommand {
666
655
  followRenames = false;
667
656
  renameScore = 50;
668
657
  diffAlgorithm = getAlgorithm(DEFAULT_ALGORITHM);
658
+ bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD;
669
659
  /**
670
660
  * Set the file path to blame.
671
661
  *
@@ -722,6 +712,21 @@ var BlameCommand = class extends GitCommand {
722
712
  return this;
723
713
  }
724
714
  /**
715
+ * Set the size above which a file is never loaded (git's
716
+ * `core.bigFileThreshold`, default 50 MiB).
717
+ *
718
+ * Blaming a file over it rejects. A parent version over it is not compared:
719
+ * the lines it would have taken stay with the child commit, and it is not a
720
+ * rename candidate.
721
+ *
722
+ * @param threshold Size in bytes
723
+ */
724
+ setBigFileThreshold(threshold) {
725
+ this.checkCallable();
726
+ this.bigFileThreshold = threshold;
727
+ return this;
728
+ }
729
+ /**
725
730
  * Execute the blame command.
726
731
  *
727
732
  * Uses a queue-based algorithm similar to JGit's BlameGenerator.
@@ -745,6 +750,8 @@ var BlameCommand = class extends GitCommand {
745
750
  if (!startCommit) throw new RefNotFoundError(`Cannot find commit: ${startId}`);
746
751
  const blobId = await this.getFileBlob(startCommit.tree, resultPath);
747
752
  if (!blobId) throw new Error(`File not found: ${resultPath}`);
753
+ const size = await this.blobs.size(blobId);
754
+ if (size > this.bigFileThreshold) throw new Error(`${resultPath} is ${size} bytes, larger than bigFileThreshold (${this.bigFileThreshold})`);
748
755
  const content = await this.collectBlob(blobId);
749
756
  const lineCount = this.countLines(content);
750
757
  if (lineCount === 0) return this.createBlameResult(resultPath, 0, []);
@@ -807,6 +814,7 @@ var BlameCommand = class extends GitCommand {
807
814
  parentPath = rename.oldPath;
808
815
  }
809
816
  }
817
+ if (parentBlobId && parentBlobId !== candidate.blobId && await this.isBig(parentBlobId)) parentBlobId = void 0;
810
818
  if (!parentBlobId) {
811
819
  this.blameRegions(entries, candidate);
812
820
  return this.countRegionLines(candidate.regions);
@@ -861,6 +869,7 @@ var BlameCommand = class extends GitCommand {
861
869
  parentPath = rename.oldPath;
862
870
  }
863
871
  }
872
+ if (parentBlobId && parentBlobId !== candidate.blobId && await this.isBig(parentBlobId)) parentBlobId = void 0;
864
873
  if (parentBlobId) {
865
874
  if (parentBlobId === candidate.blobId) {
866
875
  const parentContent = await this.collectBlob(parentBlobId);
@@ -1153,6 +1162,7 @@ var BlameCommand = class extends GitCommand {
1153
1162
  const newIndex = SimilarityIndex.create(newContent);
1154
1163
  let bestMatch;
1155
1164
  for (const { path: oldPath, entry } of deletedFiles) {
1165
+ if (await this.isBig(entry.id)) continue;
1156
1166
  const oldContent = await this.collectBlob(entry.id);
1157
1167
  if (SimilarityIndex.isBinary(oldContent)) continue;
1158
1168
  const oldIndex = SimilarityIndex.create(oldContent);
@@ -1180,6 +1190,10 @@ var BlameCommand = class extends GitCommand {
1180
1190
  else entries.set(path, entry);
1181
1191
  }
1182
1192
  }
1193
+ /** Whether a blob is over the threshold (from its size, without reading it). */
1194
+ async isBig(blobId) {
1195
+ return await this.blobs.size(blobId) > this.bigFileThreshold;
1196
+ }
1183
1197
  /**
1184
1198
  * Collect blob content into a single buffer.
1185
1199
  */
@@ -1351,23 +1365,6 @@ let ListBranchMode = /* @__PURE__ */ function(ListBranchMode) {
1351
1365
  //#endregion
1352
1366
  //#region src/commands/branch-command.ts
1353
1367
  /**
1354
- * Validate a branch name according to Git rules.
1355
- *
1356
- * @param name Branch name to validate
1357
- * @returns true if valid
1358
- */
1359
- function isValidBranchName(name) {
1360
- if (!name || name.length === 0) return false;
1361
- if (name.startsWith("/") || name.endsWith("/")) return false;
1362
- if (name.includes("..")) return false;
1363
- if (/[\x00-\x1f\x7f ~^:?*[\\]/.test(name)) return false;
1364
- if (name.endsWith(".lock")) return false;
1365
- if (name.startsWith("-")) return false;
1366
- if (name === "@") return false;
1367
- if (name.includes("@{")) return false;
1368
- return true;
1369
- }
1370
- /**
1371
1368
  * Create a new branch.
1372
1369
  *
1373
1370
  * Equivalent to `git branch <name>`.
@@ -1603,7 +1600,7 @@ var ListBranchCommand = class extends GitCommand {
1603
1600
  }
1604
1601
  branches.push(ref);
1605
1602
  }
1606
- branches.sort((a, b) => a.name.localeCompare(b.name));
1603
+ branches.sort((a, b) => compareRefNames(a.name, b.name));
1607
1604
  return branches;
1608
1605
  }
1609
1606
  };
@@ -1963,6 +1960,7 @@ var CheckoutCommand = class extends GitCommand {
1963
1960
  async checkoutBranch() {
1964
1961
  if (!this.name) throw new MissingArgumentError("name", "Branch name is required for checkout");
1965
1962
  if (this.createBranch) {
1963
+ if (!isValidBranchName(this.name)) throw new InvalidRefNameError(this.name);
1966
1964
  const startPointId = this.startPoint ? await this.resolveCommitId(this.startPoint) : await this.resolveCommitId("HEAD");
1967
1965
  if (!startPointId) throw new RefNotFoundError(this.startPoint ?? "HEAD");
1968
1966
  await this.refsStore.set(`refs/heads/${this.name}`, startPointId);
@@ -2025,10 +2023,8 @@ var CheckoutCommand = class extends GitCommand {
2025
2023
  const parentDir = relativePath.substring(0, lastSlash);
2026
2024
  await worktree.mkdir(parentDir);
2027
2025
  }
2028
- const chunks = [];
2029
2026
  const blobContent = await this.blobs.load(entry.id);
2030
- if (blobContent) for await (const chunk of blobContent) chunks.push(chunk);
2031
- await worktree.writeContent(relativePath, chunks);
2027
+ await worktree.writeContent(relativePath, blobContent ?? []);
2032
2028
  }
2033
2029
  }
2034
2030
  }
@@ -2621,6 +2617,7 @@ var CleanCommand = class extends GitCommand {
2621
2617
  if (this.ignore && entryTyped.isIgnored) continue;
2622
2618
  if (stagedPaths.has(entryTyped.path) || headPaths.has(entryTyped.path)) continue;
2623
2619
  if (entryTyped.isDirectory && !this.directories) continue;
2620
+ if (!isValidWorktreePath(entryTyped.path)) continue;
2624
2621
  const displayPath = entryTyped.isDirectory ? `${entryTyped.path}/` : entryTyped.path;
2625
2622
  cleaned.add(displayPath);
2626
2623
  if (!this.dryRun) toRemove.push({
@@ -2646,23 +2643,6 @@ var CleanCommand = class extends GitCommand {
2646
2643
  }
2647
2644
  };
2648
2645
  //#endregion
2649
- //#region src/pack-import/pack-import.ts
2650
- /**
2651
- * Unpack pack data into a history's object stores.
2652
- *
2653
- * Uses the history's own {@link SerializationApi} when it exposes one
2654
- * (a `HistoryWithOperations`), otherwise builds a default one over its
2655
- * object stores — `WorkingCopy.history` is typed as a plain `History`,
2656
- * so `serialization` is not statically available.
2657
- */
2658
- async function importPackIntoHistory(history, packData) {
2659
- const serialization = history.serialization ?? new DefaultSerializationApi({ history });
2660
- const packStream = (async function* () {
2661
- yield packData;
2662
- })();
2663
- await serialization.importPack(packStream);
2664
- }
2665
- //#endregion
2666
2646
  //#region src/transport-command.ts
2667
2647
  /**
2668
2648
  * Base class for commands that require network transport.
@@ -2930,6 +2910,15 @@ var RemoteConfigStore = class RemoteConfigStore {
2930
2910
  }
2931
2911
  return this.strings(name, "url")[0];
2932
2912
  }
2913
+ /** A config variable (`push.default`, `branch.main.merge`), the last value when repeated. */
2914
+ value(key) {
2915
+ const value = this.config.get(key);
2916
+ return value === void 0 || value === null ? void 0 : String(value);
2917
+ }
2918
+ /** Sets a config variable, replacing every value it had. */
2919
+ setValue(key, value) {
2920
+ this.config.set(key, value);
2921
+ }
2933
2922
  /** Flush to the backing file, if the config has one. */
2934
2923
  async save() {
2935
2924
  await this.config.save?.();
@@ -3247,6 +3236,12 @@ var FetchCommand = class extends TransportCommand {
3247
3236
  /**
3248
3237
  * Execute the fetch operation.
3249
3238
  *
3239
+ * Runs the transport's fetch client (git's fetch-pack): the local refs are offered as
3240
+ * haves, so only the objects the working copy lacks are downloaded; shallow options and
3241
+ * the shallow file are honoured; tags follow the tag option; each tracking ref is
3242
+ * updated when it fast-forwards or its refspec (or {@link setForceUpdate}) forces it, and
3243
+ * rejected otherwise.
3244
+ *
3250
3245
  * @returns Fetch result with updated refs
3251
3246
  * @throws InvalidRemoteError if remote cannot be resolved
3252
3247
  */
@@ -3255,69 +3250,47 @@ var FetchCommand = class extends TransportCommand {
3255
3250
  this.setCallable(false);
3256
3251
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
3257
3252
  if (!remoteUrl) throw new InvalidRemoteError(this.remote);
3258
- const parsedSpecs = this.effectiveRefSpecs().map((s) => parseRefSpec(s));
3259
- const oldRefValues = /* @__PURE__ */ new Map();
3260
- for await (const ref of this.refsStore.list()) if (!isSymbolicRef(ref) && ref.objectId) oldRefValues.set(ref.name, ref.objectId);
3261
- const transportResult = await fetch({
3253
+ const fromConfig = this.refSpecs.length === 0;
3254
+ const configured = this.effectiveRefSpecs();
3255
+ const refspecs = configured.length > 0 ? configured : ["HEAD"];
3256
+ const history = this._workingCopy.history;
3257
+ const result = await fetch({
3262
3258
  url: remoteUrl,
3263
3259
  auth: this.credentials,
3264
3260
  headers: this.headers,
3265
3261
  timeout: this.timeout,
3262
+ repository: createRepositoryFacade({ history }),
3263
+ refStore: createTransportRefStore(history.refs),
3264
+ refspecs,
3265
+ missingRefsOk: fromConfig && configured.length > 0,
3266
+ tags: toTagMode(this.tagOption),
3266
3267
  depth: this.depth,
3267
- onProgressMessage: this.progressMessageCallback
3268
+ deepenSince: this.shallowSince,
3269
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : void 0,
3270
+ unshallow: this.unshallow || void 0,
3271
+ force: this.forceUpdate,
3272
+ dryRun: this.dryRun,
3273
+ onProgress: this.progressMessageCallback,
3274
+ reflogMessage: `fetch: ${remoteUrl}`
3268
3275
  });
3269
- const bytesToHex = (bytes) => Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
3270
3276
  const advertisedRefs = /* @__PURE__ */ new Map();
3271
- for (const [refName, objectId] of transportResult.refs) advertisedRefs.set(refName, bytesToHex(objectId));
3272
- const trackingUpdates = [];
3273
- for (const [serverRefName, objectIdBytes] of transportResult.refs) {
3274
- const objectId = bytesToHex(objectIdBytes);
3275
- const localRefName = this.mapServerRef(serverRefName, parsedSpecs);
3276
- if (!localRefName) continue;
3277
- const isForce = this.forceUpdate || this.isRefSpecForced(serverRefName, parsedSpecs);
3278
- const update = await this.computeRefUpdate(localRefName, serverRefName, objectId, oldRefValues, isForce);
3279
- if (!this.dryRun) await this.refsStore.set(localRefName, objectId);
3280
- trackingUpdates.push(update);
3281
- }
3277
+ for (const ref of result.remoteRefs) if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
3278
+ const trackingUpdates = result.refUpdates.map(toTrackingRefUpdate);
3282
3279
  if (!this.dryRun && this.removeDeletedRefs) {
3283
- const pruned = await this.pruneDeletedRefs(transportResult.refs);
3284
- trackingUpdates.push(...pruned);
3280
+ const parsed = refspecs.map((s) => parseRefSpec(s));
3281
+ trackingUpdates.push(...await this.pruneDeletedRefs(new Set(advertisedRefs.keys()), parsed));
3285
3282
  }
3286
- if (transportResult.packData.length > 0 && !this.dryRun) await this.storePack(transportResult.packData);
3287
3283
  return {
3288
3284
  uri: remoteUrl,
3289
3285
  advertisedRefs,
3290
3286
  trackingRefUpdates: trackingUpdates,
3291
- defaultBranch: transportResult.defaultBranch,
3292
- bytesReceived: transportResult.bytesReceived,
3293
- isEmpty: transportResult.isEmpty,
3287
+ defaultBranch: result.defaultBranch,
3288
+ bytesReceived: result.packBytes,
3289
+ isEmpty: result.isEmpty,
3294
3290
  messages: []
3295
3291
  };
3296
3292
  }
3297
3293
  /**
3298
- * Map a server ref name to a local ref name using parsed refspecs.
3299
- * Returns undefined if no refspec matches.
3300
- */
3301
- mapServerRef(serverRef, specs) {
3302
- for (const spec of specs) {
3303
- if (spec.negative) continue;
3304
- if (!spec.source || !spec.destination) continue;
3305
- if (!matchSource(spec, serverRef)) continue;
3306
- return expandFromSource(spec, serverRef).destination ?? void 0;
3307
- }
3308
- }
3309
- /**
3310
- * Check if any matching refspec has the force flag for a given server ref.
3311
- */
3312
- isRefSpecForced(serverRef, specs) {
3313
- for (const spec of specs) {
3314
- if (spec.negative) continue;
3315
- if (!spec.source) continue;
3316
- if (matchSource(spec, serverRef) && spec.force) return true;
3317
- }
3318
- return false;
3319
- }
3320
- /**
3321
3294
  * The refspecs this fetch runs with.
3322
3295
  *
3323
3296
  * Explicit refspecs win; otherwise a configured remote contributes its
@@ -3342,62 +3315,35 @@ var FetchCommand = class extends TransportCommand {
3342
3315
  return RemoteConfigStore.from(this.workingCopy).urlFor(remote) ?? remote;
3343
3316
  }
3344
3317
  /**
3345
- * Compute ref update status using pre-fetch ref values.
3346
- *
3347
- * Uses saved pre-fetch values to correctly determine
3348
- * NEW vs NO_CHANGE vs FAST_FORWARD status.
3349
- */
3350
- async computeRefUpdate(localRef, remoteRef, newObjectId, oldRefValues, force) {
3351
- const oldObjectId = oldRefValues.get(localRef);
3352
- let status;
3353
- if (!oldObjectId) status = "new";
3354
- else if (oldObjectId === newObjectId) status = "no-change";
3355
- else if (force) status = "forced";
3356
- else status = await this.isAncestor(oldObjectId, newObjectId) ? "fast-forward" : "rejected";
3357
- return {
3358
- localRef,
3359
- remoteRef,
3360
- oldObjectId,
3361
- newObjectId,
3362
- status
3363
- };
3364
- }
3365
- /**
3366
- * Check if one commit is an ancestor of another.
3318
+ * Prune local refs that a refspec maps from a remote ref that no longer exists (git's
3319
+ * `--prune`): for each refspec with a destination, the local refs matching the
3320
+ * destination whose source is not among the remote refs are deleted, unless a negative
3321
+ * refspec excludes that source (git's query_matches_negative_refspec).
3367
3322
  */
3368
- async isAncestor(ancestor, descendant) {
3369
- const visited = /* @__PURE__ */ new Set();
3370
- const queue = [descendant];
3371
- while (queue.length > 0) {
3372
- const current = queue.shift();
3373
- if (current === void 0) break;
3374
- if (current === ancestor) return true;
3375
- if (visited.has(current)) continue;
3376
- visited.add(current);
3377
- try {
3378
- const commit = await this.commits.load(current);
3379
- if (commit) queue.push(...commit.parents);
3380
- } catch {}
3381
- if (visited.size > 1e4) break;
3382
- }
3383
- return false;
3384
- }
3385
- /**
3386
- * Prune refs that no longer exist on remote.
3387
- */
3388
- async pruneDeletedRefs(remoteRefs) {
3323
+ async pruneDeletedRefs(remoteRefNames, specs) {
3389
3324
  const updates = [];
3390
- const prefix = `refs/remotes/${this.remote}/`;
3391
- const remoteRefNames = /* @__PURE__ */ new Set();
3392
- for (const refName of remoteRefs.keys()) remoteRefNames.add(refName);
3393
- for await (const ref of this.refsStore.list(prefix)) {
3394
- if (isSymbolicRef(ref)) continue;
3395
- const remoteRefName = `refs/heads/${ref.name.slice(prefix.length)}`;
3396
- if (!remoteRefNames.has(ref.name) && !remoteRefNames.has(remoteRefName)) {
3325
+ const done = /* @__PURE__ */ new Set();
3326
+ const negative = specs.filter((s) => s.negative && s.source);
3327
+ for (const spec of specs) {
3328
+ if (spec.negative || !spec.source || !spec.destination) continue;
3329
+ const prefix = spec.wildcard ? spec.destination.slice(0, spec.destination.indexOf("*")) : spec.destination;
3330
+ for await (const ref of this.refsStore.list(prefix)) {
3331
+ if (isSymbolicRef(ref) || done.has(ref.name)) continue;
3332
+ let source;
3333
+ if (spec.wildcard) {
3334
+ if (!matchDestination(spec, ref.name)) continue;
3335
+ source = expandFromDestination(spec, ref.name).source;
3336
+ } else {
3337
+ if (ref.name !== spec.destination) continue;
3338
+ source = spec.source;
3339
+ }
3340
+ if (!source || remoteRefNames.has(source)) continue;
3341
+ if (negative.some((n) => matchSource(n, source))) continue;
3342
+ done.add(ref.name);
3397
3343
  await this.refsStore.delete(ref.name);
3398
3344
  updates.push({
3399
3345
  localRef: ref.name,
3400
- remoteRef: remoteRefName,
3346
+ remoteRef: source,
3401
3347
  oldObjectId: ref.objectId,
3402
3348
  newObjectId: "",
3403
3349
  status: "deleted"
@@ -3406,18 +3352,28 @@ var FetchCommand = class extends TransportCommand {
3406
3352
  }
3407
3353
  return updates;
3408
3354
  }
3409
- /**
3410
- * Store received pack data.
3411
- *
3412
- * Unpacks the pack into the working copy's history, so the objects the
3413
- * freshly written tracking refs point at are actually available locally.
3414
- * Import is idempotent: the stores are content-addressed, so re-importing
3415
- * a pack rewrites the same object IDs.
3416
- */
3417
- async storePack(packData) {
3418
- await importPackIntoHistory(this._workingCopy.history, packData);
3419
- }
3420
3355
  };
3356
+ /** The transport's tag mode for a {@link TagOption}. */
3357
+ function toTagMode(option) {
3358
+ switch (option) {
3359
+ case "fetch-tags": return "all";
3360
+ case "no-tags": return "none";
3361
+ default: return "auto";
3362
+ }
3363
+ }
3364
+ /** A transport ref update as a {@link TrackingRefUpdate}. */
3365
+ function toTrackingRefUpdate(update) {
3366
+ const status = update.status === "new" ? "new" : update.status === "up-to-date" ? "no-change" : update.status === "fast-forward" ? "fast-forward" : update.status === "forced" ? "forced" : update.reason === "non-fast-forward" || update.reason === "would clobber existing tag" ? "rejected" : "lock-failure";
3367
+ return {
3368
+ localRef: update.localRef,
3369
+ remoteRef: update.remoteRef,
3370
+ oldObjectId: update.oldOid,
3371
+ newObjectId: update.newOid,
3372
+ status,
3373
+ summary: update.summary,
3374
+ reason: update.reason
3375
+ };
3376
+ }
3421
3377
  //#endregion
3422
3378
  //#region src/commands/clone-command.ts
3423
3379
  /**
@@ -3702,59 +3658,93 @@ var CloneCommand = class extends TransportCommand {
3702
3658
  this.checkCallable();
3703
3659
  this.setCallable(false);
3704
3660
  if (!this.uri) throw new InvalidRemoteError("", "URI must be specified for clone");
3705
- const branchToClone = this.determineBranchToClone();
3706
- const options = {
3661
+ const branchToClone = toBranchName(this.determineBranchToClone());
3662
+ const history = this._workingCopy.history;
3663
+ const tracking = (branch) => this.bare ? `refs/heads/${branch}` : `refs/remotes/${this.remoteName}/${branch}`;
3664
+ const singleBranch = !this.mirror && (branchToClone !== void 0 || this.depth !== void 0 || this.shallowSince !== void 0 || this.shallowExcludes.length > 0);
3665
+ let detachedTag;
3666
+ let refspecs;
3667
+ if (this.mirror) refspecs = ["+refs/*:refs/*"];
3668
+ else if (branchToClone !== void 0) {
3669
+ const b = branchToClone;
3670
+ refspecs = {
3671
+ prefixes: [`refs/heads/${b}`, `refs/tags/${b}`],
3672
+ resolve: (remoteRefs) => {
3673
+ if (remoteRefs.some((r) => r.name === `refs/heads/${b}` && r.oid)) return [`+refs/heads/${b}:${tracking(b)}`];
3674
+ if (remoteRefs.some((r) => r.name === `refs/tags/${b}` && r.oid)) {
3675
+ detachedTag = `refs/tags/${b}`;
3676
+ return [`+refs/tags/${b}:refs/tags/${b}`];
3677
+ }
3678
+ throw new RefNotFoundError(`refs/heads/${b}`, `Remote branch ${b} not found in upstream ${this.remoteName}`);
3679
+ }
3680
+ };
3681
+ } else if (singleBranch) refspecs = {
3682
+ prefixes: ["refs/heads/"],
3683
+ resolve: (remoteRefs) => {
3684
+ const head = remoteRefs.find((r) => r.name === "HEAD")?.symref;
3685
+ const name = toBranchName(head);
3686
+ return name && head?.startsWith("refs/heads/") ? [`+${head}:${tracking(name)}`] : [`+refs/heads/*:${tracking("*")}`];
3687
+ }
3688
+ };
3689
+ else refspecs = [`+refs/heads/*:${tracking("*")}`];
3690
+ const tags = this.tagOption === "auto-follow" && !singleBranch && !this.mirror ? "all" : toTagMode(this.tagOption);
3691
+ const result = await fetch({
3707
3692
  url: this.uri,
3708
- branch: branchToClone,
3709
- depth: this.depth,
3710
- bare: this.bare,
3711
- remoteName: this.remoteName,
3712
3693
  auth: this.credentials,
3713
3694
  headers: this.headers,
3714
3695
  timeout: this.timeout,
3715
- onProgress: this.progressCallback,
3716
- onProgressMessage: this.progressMessageCallback
3717
- };
3718
- const transportResult = await clone(options);
3719
- if (transportResult.packData.length > 0) await this.storePack(transportResult.packData);
3720
- const trackingUpdates = [];
3721
- for (const [refName, objectId] of transportResult.refs) {
3722
- const objectIdHex = bytesToHex(objectId);
3723
- if (this.shouldSkipRef(refName)) continue;
3724
- const localRefName = this.mirror ? this.toMirrorRefName(refName) : refName;
3725
- await this.refsStore.set(localRefName, objectIdHex);
3726
- trackingUpdates.push({
3727
- localRef: localRefName,
3728
- remoteRef: refName,
3729
- newObjectId: objectIdHex,
3730
- status: "new"
3731
- });
3732
- }
3733
- const advertisedDefaultBranch = transportResult.defaultBranch;
3734
- const defaultBranch = toBranchName(advertisedDefaultBranch);
3696
+ repository: createRepositoryFacade({ history }),
3697
+ refStore: createTransportRefStore(history.refs),
3698
+ refspecs,
3699
+ tags,
3700
+ depth: this.depth,
3701
+ deepenSince: this.shallowSince,
3702
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : void 0,
3703
+ onProgress: this.progressMessageCallback,
3704
+ reflogMessage: `clone: from ${this.uri}`
3705
+ });
3706
+ const trackingUpdates = result.refUpdates.map(toTrackingRefUpdate);
3707
+ const advertisedDefaultBranch = result.defaultBranch;
3708
+ let defaultBranch = branchToClone ?? toBranchName(advertisedDefaultBranch);
3735
3709
  let headCommit;
3736
- if (defaultBranch && !this.bare) {
3710
+ if (detachedTag) {
3711
+ defaultBranch = toBranchName(advertisedDefaultBranch);
3712
+ let id = (await this.refsStore.resolve(detachedTag))?.objectId;
3713
+ for (let i = 0; id && i < 16; i++) {
3714
+ const target = await history.tags.getTarget(id);
3715
+ if (!target || !await history.tags.has(id)) break;
3716
+ id = target;
3717
+ }
3718
+ if (id) {
3719
+ await this.refsStore.set("HEAD", id);
3720
+ headCommit = id;
3721
+ if (!this.bare && !this.noCheckout) await this.checkoutHead(id);
3722
+ }
3723
+ } else if (defaultBranch && !this.bare) {
3737
3724
  const localRef = `refs/heads/${defaultBranch}`;
3738
- const tip = await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`) ?? await this.refsStore.resolve(localRef);
3725
+ const tip = await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`);
3739
3726
  if (tip?.objectId) {
3740
3727
  await this.refsStore.set(localRef, tip.objectId);
3741
3728
  headCommit = tip.objectId;
3742
- await this.refsStore.setSymbolic("HEAD", localRef);
3743
3729
  if (!this.noCheckout) await this.checkoutHead(tip.objectId);
3744
3730
  }
3731
+ await this.refsStore.setSymbolic("HEAD", localRef);
3745
3732
  } else if (this.bare || this.mirror) {
3746
- if (defaultBranch) await this.refsStore.setSymbolic("HEAD", `refs/heads/${defaultBranch}`);
3733
+ if (defaultBranch) {
3734
+ await this.refsStore.setSymbolic("HEAD", `refs/heads/${defaultBranch}`);
3735
+ headCommit = (await this.refsStore.resolve("HEAD"))?.objectId;
3736
+ }
3747
3737
  }
3748
3738
  const advertisedRefs = /* @__PURE__ */ new Map();
3749
- for (const [refName, objectId] of transportResult.refs) advertisedRefs.set(refName, bytesToHex(objectId));
3739
+ for (const ref of result.remoteRefs) if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
3750
3740
  return {
3751
3741
  fetchResult: {
3752
3742
  uri: this.uri,
3753
3743
  advertisedRefs,
3754
3744
  trackingRefUpdates: trackingUpdates,
3755
3745
  defaultBranch: advertisedDefaultBranch,
3756
- bytesReceived: transportResult.bytesReceived,
3757
- isEmpty: transportResult.isEmpty,
3746
+ bytesReceived: result.packBytes,
3747
+ isEmpty: result.isEmpty,
3758
3748
  messages: []
3759
3749
  },
3760
3750
  defaultBranch: defaultBranch ?? "main",
@@ -3769,35 +3759,7 @@ var CloneCommand = class extends TransportCommand {
3769
3759
  determineBranchToClone() {
3770
3760
  if (this.branch) return this.branch;
3771
3761
  if (this.mirror || this.cloneAllBranches) return;
3772
- if (this.branchesToClone.length > 0) {
3773
- const first = this.branchesToClone[0];
3774
- if (first.startsWith("refs/heads/")) return first.slice(11);
3775
- return first;
3776
- }
3777
- }
3778
- /**
3779
- * Check if a ref should be skipped based on tag option.
3780
- */
3781
- shouldSkipRef(refName) {
3782
- if (this.tagOption === "no-tags" && refName.startsWith("refs/tags/")) return true;
3783
- return false;
3784
- }
3785
- /**
3786
- * Convert a remote ref name to mirror ref name.
3787
- */
3788
- toMirrorRefName(refName) {
3789
- const remotePrefix = `refs/remotes/${this.remoteName}/`;
3790
- if (refName.startsWith(remotePrefix)) return `refs/heads/${refName.slice(remotePrefix.length)}`;
3791
- return refName;
3792
- }
3793
- /**
3794
- * Store received pack data.
3795
- *
3796
- * Unpacks the pack into the working copy's history, so the objects the
3797
- * cloned refs point at are actually available locally.
3798
- */
3799
- async storePack(packData) {
3800
- await importPackIntoHistory(this._workingCopy.history, packData);
3762
+ if (this.branchesToClone.length > 0) return this.branchesToClone[0];
3801
3763
  }
3802
3764
  /**
3803
3765
  * Checkout HEAD commit to staging area.
@@ -5755,10 +5717,39 @@ var InitCommand = class {
5755
5717
  this.setCallable(false);
5756
5718
  const files = this.files ?? createInMemoryFilesApi();
5757
5719
  const gitDir = this.resolveGitDir();
5758
- const history = createMemoryHistory();
5759
- await history.initialize();
5760
- await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
5761
- const staging = this.stagingStore ?? new MemoryStagingStore();
5720
+ let history;
5721
+ let staging;
5722
+ if (this.files) {
5723
+ const dir = gitDir.replace(/\/+$/, "") || ".";
5724
+ const isFile = async (path) => (await files.stats(path))?.kind === "file";
5725
+ const hasHead = await isFile(`${dir}/HEAD`);
5726
+ const fresh = !hasHead && !await isFile(`${dir}/config`);
5727
+ const open = (create) => createGitFilesHistoryFromFiles({
5728
+ files,
5729
+ gitDir,
5730
+ create,
5731
+ defaultBranch: this.initialBranch
5732
+ });
5733
+ if (fresh && this.bare && dir !== ".") {
5734
+ await open(true);
5735
+ await markBare(files, `${dir}/config`);
5736
+ history = await open(false);
5737
+ } else history = await open(fresh);
5738
+ await history.initialize();
5739
+ if (!hasHead && !fresh) await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
5740
+ if (this.stagingStore) staging = this.stagingStore;
5741
+ else if (this.bare) staging = new MemoryStagingStore();
5742
+ else {
5743
+ const fileStaging = new FileStagingStore(files, `${dir}/index`);
5744
+ await fileStaging.read();
5745
+ staging = fileStaging;
5746
+ }
5747
+ } else {
5748
+ history = createMemoryHistory();
5749
+ await history.initialize();
5750
+ await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
5751
+ staging = this.stagingStore ?? new MemoryStagingStore();
5752
+ }
5762
5753
  let worktree;
5763
5754
  if (this.worktreeEnabled && !this.bare) worktree = this.worktreeStore ?? createFileWorktree({
5764
5755
  files,
@@ -5841,6 +5832,23 @@ var InitCommand = class {
5841
5832
  this.callable = value;
5842
5833
  }
5843
5834
  };
5835
+ /** Sets `core.bare = true` in a config file written by the git directory layout. */
5836
+ async function markBare(files, configPath) {
5837
+ const chunks = [];
5838
+ for await (const chunk of files.read(configPath)) chunks.push(chunk);
5839
+ const text = new TextDecoder().decode(concatChunks(chunks));
5840
+ const updated = /^\s*bare\s*=/m.test(text) ? text.replace(/^(\s*bare\s*=\s*)\S+/m, "$1true") : text.replace(/^\[core\]\s*$/m, "[core]\n bare = true");
5841
+ await files.write(configPath, [new TextEncoder().encode(updated)]);
5842
+ }
5843
+ function concatChunks(chunks) {
5844
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
5845
+ let offset = 0;
5846
+ for (const c of chunks) {
5847
+ out.set(c, offset);
5848
+ offset += c.length;
5849
+ }
5850
+ return out;
5851
+ }
5844
5852
  //#endregion
5845
5853
  //#region src/commands/log-command.ts
5846
5854
  /**
@@ -6433,6 +6441,7 @@ var MergeCommand = class extends GitCommand {
6433
6441
  squash = false;
6434
6442
  commit = true;
6435
6443
  message;
6444
+ bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD;
6436
6445
  /**
6437
6446
  * Add a commit/branch to merge.
6438
6447
  *
@@ -6490,6 +6499,21 @@ var MergeCommand = class extends GitCommand {
6490
6499
  return this;
6491
6500
  }
6492
6501
  /**
6502
+ * Set the size above which files are binary to the content merge (git's
6503
+ * `core.bigFileThreshold`, default 50 MiB).
6504
+ *
6505
+ * A binary file (over the threshold, or a NUL byte in its first 8000 bytes) is
6506
+ * never content-merged and never loaded: as git does, OURS and THEIRS take that
6507
+ * side's file whole, and UNION reports a conflict.
6508
+ *
6509
+ * @param threshold Size in bytes
6510
+ */
6511
+ setBigFileThreshold(threshold) {
6512
+ this.checkCallable();
6513
+ this.bigFileThreshold = threshold;
6514
+ return this;
6515
+ }
6516
+ /**
6493
6517
  * Set squash mode.
6494
6518
  *
6495
6519
  * When true, changes are staged but not committed, and HEAD is not updated.
@@ -6726,12 +6750,23 @@ var MergeCommand = class extends GitCommand {
6726
6750
  if (ours.mode !== FileMode.REGULAR_FILE || theirs.mode !== FileMode.REGULAR_FILE) return;
6727
6751
  if (!this.contentStrategy) return;
6728
6752
  try {
6729
- const baseContent = base ? await this.collectBlobContent(base.id) : /* @__PURE__ */ new Uint8Array(0);
6730
- const oursContent = await this.collectBlobContent(ours.id);
6731
- const theirsContent = await this.collectBlobContent(theirs.id);
6753
+ const contents = await this.loadTexts([
6754
+ base?.id,
6755
+ ours.id,
6756
+ theirs.id
6757
+ ]);
6758
+ if (!contents) switch (this.contentStrategy) {
6759
+ case "ours": return ours;
6760
+ case "theirs": return {
6761
+ ...theirs,
6762
+ name: ours.name
6763
+ };
6764
+ default: return;
6765
+ }
6766
+ const [baseContent, oursContent, theirsContent] = contents;
6732
6767
  const strategy = this.convertContentStrategy(this.contentStrategy);
6733
6768
  const mergeResult = merge3Way(baseContent, oursContent, theirsContent, { strategy });
6734
- const mergedBlobId = await this.blobs.store([mergeResult.content]);
6769
+ const mergedBlobId = await this.blobs.store([mergeResult.content], mergeResult.content.length);
6735
6770
  return {
6736
6771
  name: ours.name,
6737
6772
  mode: ours.mode,
@@ -6742,22 +6777,24 @@ var MergeCommand = class extends GitCommand {
6742
6777
  }
6743
6778
  }
6744
6779
  /**
6745
- * Collect all bytes from a blob into a single Uint8Array.
6780
+ * The blobs' contents, each read once; nothing when one is binary or over the
6781
+ * threshold (then the rest are not read). A missing id is empty content.
6746
6782
  */
6747
- async collectBlobContent(blobId) {
6748
- const chunks = [];
6749
- const blobContent = await this.blobs.load(blobId);
6750
- if (blobContent) for await (const chunk of blobContent) chunks.push(chunk);
6751
- if (chunks.length === 0) return /* @__PURE__ */ new Uint8Array(0);
6752
- if (chunks.length === 1) return chunks[0];
6753
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
6754
- const result = new Uint8Array(totalLength);
6755
- let offset = 0;
6756
- for (const chunk of chunks) {
6757
- result.set(chunk, offset);
6758
- offset += chunk.length;
6783
+ async loadTexts(ids) {
6784
+ const out = [];
6785
+ for (const id of ids) {
6786
+ if (!id) {
6787
+ out.push(/* @__PURE__ */ new Uint8Array(0));
6788
+ continue;
6789
+ }
6790
+ const probe = await probeBlob(this.blobs, id, {
6791
+ bigFileThreshold: this.bigFileThreshold,
6792
+ loadText: true
6793
+ });
6794
+ if (probe.binary || !probe.content) return void 0;
6795
+ out.push(probe.content);
6759
6796
  }
6760
- return result;
6797
+ return out;
6761
6798
  }
6762
6799
  /**
6763
6800
  * Convert ContentMergeStrategy to utils MergeContentStrategy.
@@ -6904,7 +6941,7 @@ var PackRefsCommand = class extends GitCommand {
6904
6941
  async call() {
6905
6942
  this.checkCallable();
6906
6943
  this.setCallable(false);
6907
- if (!this.refsStore.packRefs) throw new Error("RefStore does not support packRefs");
6944
+ if (!this.refsStore.packRefs) throw new Error("This ref store does not support packRefs");
6908
6945
  let refsPacked = 0;
6909
6946
  if (this.all) {
6910
6947
  const allRefs = [];
@@ -7116,16 +7153,11 @@ var PullCommand = class extends TransportCommand {
7116
7153
  /** All-zero object id — Git's "no object", used to express a ref delete. */
7117
7154
  const ZERO_OBJECT_ID = "0".repeat(40);
7118
7155
  /**
7119
- * How the transport's rejection reasons land on the statuses this package
7120
- * reports.
7121
- *
7122
- * The two vocabularies are not the same: the transport tells seven kinds of
7123
- * rejection apart, while PushStatus — following JGit's RemoteRefUpdate — keeps
7124
- * only the non-fast-forward case separate, because that is the one callers act
7125
- * on (callOrThrow raises NonFastForwardError for it). Everything else is a
7126
- * rejection whose detail lives in the server's message, so it collapses to
7127
- * REJECTED_OTHER. Spelled out per reason rather than defaulted, so that a new
7128
- * transport reason is a compile error here instead of a silent REJECTED_OTHER.
7156
+ * How a server's rejection reason (`ng <ref> <reason>`) lands on the statuses this package
7157
+ * reports. PushStatus, following JGit's RemoteRefUpdate, keeps only the non-fast-forward case
7158
+ * separate (callOrThrow raises NonFastForwardError for it); every other refusal is
7159
+ * REJECTED_OTHER with the server's message. Spelled out per reason so that a new transport
7160
+ * reason is a compile error here.
7129
7161
  */
7130
7162
  const REJECT_REASON_STATUS = {
7131
7163
  NOT_ATTEMPTED: "not-attempted",
@@ -7140,29 +7172,21 @@ const REJECT_REASON_STATUS = {
7140
7172
  ATOMIC_REJECTED: "rejected-other"
7141
7173
  };
7142
7174
  /**
7143
- * Classify a server's rejection message.
7144
- *
7145
- * Reuses the transport's `mapRejectReason` so both sides read the same wire
7146
- * text the same way; a message the transport cannot place — or none at all —
7147
- * ends up as REJECTED_OTHER.
7148
- */
7149
- function classifyRejection(message) {
7150
- return REJECT_REASON_STATUS[mapRejectReason(message ?? "")];
7151
- }
7152
- /**
7153
- * Split a refspec into its source and destination ref names.
7154
- *
7155
- * Mirrors the parsing the transport performs so that the destination keys we
7156
- * derive here line up exactly with the ones it reports back:
7157
- * an optional leading `+` (force) is stripped, and a refspec with no `:` pushes
7158
- * a ref to its own name.
7175
+ * The status of a transport update. git's local refusals map as JGit's: "fetch first" (the
7176
+ * remote has a commit we lack) and "non-fast-forward" are both REJECTED_NONFASTFORWARD, a
7177
+ * stale lease is REJECTED_REMOTE_CHANGED, a remote ref the server did not report is FAILED.
7159
7178
  */
7160
- function parseRefSpec$1(refSpec) {
7161
- const [source = "", dest] = (refSpec.startsWith("+") ? refSpec.slice(1) : refSpec).split(":");
7162
- return {
7163
- source,
7164
- dest: dest || source
7165
- };
7179
+ function toPushStatus(update) {
7180
+ switch (update.status) {
7181
+ case "ok": return "ok";
7182
+ case "up-to-date": return "up-to-date";
7183
+ case "rejected-nonfastforward":
7184
+ case "rejected-fetch-first": return "rejected-nonfastforward";
7185
+ case "rejected-stale": return "rejected-remote-changed";
7186
+ case "remote-rejected": return REJECT_REASON_STATUS[mapRejectReason(update.message ?? "")];
7187
+ case "remote-failure": return "failed";
7188
+ default: return "rejected-other";
7189
+ }
7166
7190
  }
7167
7191
  /**
7168
7192
  * Push objects and refs to a remote repository.
@@ -7215,6 +7239,10 @@ var PushCommand = class extends TransportCommand {
7215
7239
  useBitmaps = true;
7216
7240
  pushOptions = [];
7217
7241
  receivePack;
7242
+ prune = false;
7243
+ streamRequestBody;
7244
+ /** Leases (an entry without a ref: every other pushed ref at its tracking value) */
7245
+ leases;
7218
7246
  /**
7219
7247
  * Set the remote to push to.
7220
7248
  *
@@ -7273,6 +7301,49 @@ var PushCommand = class extends TransportCommand {
7273
7301
  return this.force;
7274
7302
  }
7275
7303
  /**
7304
+ * `--force-with-lease`: allow a non-fast-forward of `ref` only while the remote ref still
7305
+ * has `expect` (`""` or the zero id: it must not exist). Without `expect` the remote ref's
7306
+ * remote-tracking value is expected (`refs/remotes/<remote>/...`). Without `ref` every pushed
7307
+ * ref (that no explicit lease names) is leased at its remote-tracking value; `expect` may be
7308
+ * a revision or an abbreviated id. A lease that does not hold is
7309
+ * REJECTED_REMOTE_CHANGED; {@link setForce} overrides it, as in git.
7310
+ *
7311
+ * @param ref The remote ref (full or short name)
7312
+ * @param expect The value it must have
7313
+ */
7314
+ setForceWithLease(ref, expect) {
7315
+ this.checkCallable();
7316
+ this.leases ??= [];
7317
+ this.leases.push(ref === void 0 ? {} : {
7318
+ ref,
7319
+ ...expect !== void 0 ? { expect } : {}
7320
+ });
7321
+ return this;
7322
+ }
7323
+ /**
7324
+ * Stream the smart-HTTP request body (default: outside browsers, where supported); `false`
7325
+ * collects it first, so the request has a `Content-Length` (servers or proxies that refuse
7326
+ * chunked requests).
7327
+ */
7328
+ setStreamRequestBody(stream) {
7329
+ this.checkCallable();
7330
+ this.streamRequestBody = stream;
7331
+ return this;
7332
+ }
7333
+ /** Whether the request body streams (undefined: the transport decides). */
7334
+ isStreamRequestBody() {
7335
+ return this.streamRequestBody;
7336
+ }
7337
+ /**
7338
+ * `--prune`: delete remote refs a pattern refspec's destination covers whose local source is
7339
+ * gone (with `+refs/*:refs/*`, `--mirror`).
7340
+ */
7341
+ setPrune(prune) {
7342
+ this.checkCallable();
7343
+ this.prune = prune;
7344
+ return this;
7345
+ }
7346
+ /**
7276
7347
  * Set atomic push mode.
7277
7348
  *
7278
7349
  * When enabled, either all refs update or none do.
@@ -7398,11 +7469,21 @@ var PushCommand = class extends TransportCommand {
7398
7469
  return this.receivePack;
7399
7470
  }
7400
7471
  /**
7401
- * Execute the push operation.
7472
+ * Execute the push.
7473
+ *
7474
+ * Runs the transport's push client (git's send-pack): the refspecs are mapped onto the
7475
+ * remote refs as `git push` does (short names, `HEAD`, patterns, `:dst` deletes); each ref
7476
+ * is checked first (fast-forward, "fetch first", tags, `--force-with-lease`) and refused
7477
+ * refs are not sent; the pack is thin against the remote refs here. Once the server accepts
7478
+ * a ref, the remote-tracking ref of a named remote follows it (`refs/remotes/<remote>/…`).
7479
+ *
7480
+ * Without refspecs (nor `setPushAll`/`setPushTags`), the configured `remote.<name>.push`
7481
+ * refspecs are used, else `push.default` decides (default `simple`: the current branch to
7482
+ * its upstream of the same name on its own remote, to the same name elsewhere; see
7483
+ * `buildRefSpecs`). A detached HEAD is refused.
7402
7484
  *
7403
- * @returns Push result with updated refs
7485
+ * @returns Push result with each remote ref's status
7404
7486
  * @throws InvalidRemoteError if remote cannot be resolved
7405
- * @throws PushRejectedException if push is rejected
7406
7487
  */
7407
7488
  async call() {
7408
7489
  this.checkCallable();
@@ -7410,11 +7491,6 @@ var PushCommand = class extends TransportCommand {
7410
7491
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
7411
7492
  if (!remoteUrl) throw new InvalidRemoteError(this.remote);
7412
7493
  const refspecs = await this.buildRefSpecs();
7413
- const sourceByDest = /* @__PURE__ */ new Map();
7414
- for (const spec of refspecs) {
7415
- const { source, dest } = parseRefSpec$1(spec);
7416
- sourceByDest.set(dest, source);
7417
- }
7418
7494
  if (refspecs.length === 0) return {
7419
7495
  uri: remoteUrl,
7420
7496
  remoteUpdates: [],
@@ -7423,54 +7499,57 @@ var PushCommand = class extends TransportCommand {
7423
7499
  messages: []
7424
7500
  };
7425
7501
  const history = this._workingCopy.history;
7426
- const serialization = history.serialization;
7427
- const exportPack = serialization ? async function* (wants, exclude) {
7428
- const objectIds = history.collectReachableObjects(wants, exclude);
7429
- yield* serialization.createPack(objectIds);
7430
- } : void 0;
7431
- const resolvedLocalOids = /* @__PURE__ */ new Map();
7432
- const transportResult = await push({
7502
+ const tracking = this.trackingRefMapper();
7503
+ const messages = [];
7504
+ const leases = this.leases;
7505
+ const result = await push({
7433
7506
  url: remoteUrl,
7434
- refspecs,
7435
7507
  auth: this.credentials,
7436
7508
  headers: this.headers,
7437
7509
  timeout: this.timeout,
7510
+ repository: createRepositoryFacade({ history }),
7511
+ refStore: createTransportRefStore(history.refs),
7512
+ refspecs,
7438
7513
  force: this.force,
7439
7514
  atomic: this.atomic,
7440
- onProgressMessage: this.progressMessageCallback,
7441
- exportPack,
7442
- getLocalRef: async (refName) => {
7443
- if (refName === "") {
7444
- resolvedLocalOids.set(refName, ZERO_OBJECT_ID);
7445
- return ZERO_OBJECT_ID;
7446
- }
7447
- const ref = await this.refsStore.resolve(refName);
7448
- if (ref?.objectId !== void 0) resolvedLocalOids.set(refName, ref.objectId);
7449
- return ref?.objectId;
7515
+ thin: this.thin,
7516
+ dryRun: this.dryRun,
7517
+ prune: this.prune,
7518
+ streamRequestBody: this.streamRequestBody,
7519
+ pushOptions: this.pushOptions.length > 0 ? this.pushOptions : void 0,
7520
+ forceWithLease: leases,
7521
+ trackingValue: async (remoteRef) => {
7522
+ const local = tracking(remoteRef);
7523
+ return local ? (await history.refs.resolve(local))?.objectId : void 0;
7450
7524
  },
7451
- getObjectsToPush: (newIds, oldIds) => this.getObjectsToPush(newIds, oldIds)
7525
+ onProgress: (message) => {
7526
+ messages.push(message);
7527
+ this.progressMessageCallback?.(message);
7528
+ }
7452
7529
  });
7453
- const remoteUpdates = [];
7454
- for (const [refName, updateResult] of transportResult.updates) {
7455
- const srcRef = sourceByDest.get(refName);
7456
- const newObjectId = srcRef !== void 0 ? resolvedLocalOids.get(srcRef) : void 0;
7457
- remoteUpdates.push({
7458
- ...srcRef ? { srcRef } : {},
7459
- remoteName: refName,
7460
- expectedOldObjectId: updateResult.oldOid,
7461
- newObjectId: newObjectId ?? "",
7462
- status: updateResult.ok ? "ok" : classifyRejection(updateResult.message),
7463
- message: updateResult.message,
7464
- forceUpdate: this.force,
7465
- delete: newObjectId === ZERO_OBJECT_ID
7466
- });
7530
+ if (!this.dryRun) for (const update of result.updates) {
7531
+ if (update.status !== "ok" && update.status !== "up-to-date") continue;
7532
+ const local = tracking(update.remoteRef);
7533
+ if (!local) continue;
7534
+ if (update.newOid === ZERO_OBJECT_ID) await history.refs.remove(local);
7535
+ else await history.refs.set(local, update.newOid);
7467
7536
  }
7468
7537
  return {
7469
7538
  uri: remoteUrl,
7470
- remoteUpdates,
7471
- bytesSent: transportResult.bytesSent,
7472
- objectCount: transportResult.objectCount,
7473
- messages: []
7539
+ remoteUpdates: result.updates.map((update) => ({
7540
+ ...update.localRef ? { srcRef: update.localRef } : {},
7541
+ remoteName: update.remoteRef,
7542
+ expectedOldObjectId: update.expectedOid ?? update.oldOid,
7543
+ newObjectId: update.newOid,
7544
+ status: toPushStatus(update),
7545
+ message: update.message ?? (update.status === "ok" ? void 0 : update.summary),
7546
+ summary: update.summary,
7547
+ forceUpdate: update.force,
7548
+ delete: update.newOid === ZERO_OBJECT_ID
7549
+ })),
7550
+ bytesSent: result.bytesSent,
7551
+ objectCount: result.packObjects,
7552
+ messages
7474
7553
  };
7475
7554
  }
7476
7555
  /**
@@ -7480,7 +7559,7 @@ var PushCommand = class extends TransportCommand {
7480
7559
  const result = await this.call();
7481
7560
  for (const update of result.remoteUpdates) {
7482
7561
  if (update.status === "rejected-nonfastforward") throw new NonFastForwardError(update.remoteName, result.uri);
7483
- if (update.status === "rejected-other" || update.status === "failed") throw new PushRejectedException(update.remoteName, update.message || "rejected", result.uri);
7562
+ if (update.status === "rejected-other" || update.status === "rejected-remote-changed" || update.status === "failed") throw new PushRejectedException(update.remoteName, update.message || "rejected", result.uri);
7484
7563
  }
7485
7564
  return result;
7486
7565
  }
@@ -7496,121 +7575,65 @@ var PushCommand = class extends TransportCommand {
7496
7575
  return RemoteConfigStore.from(this.workingCopy).urlFor(remote, { push: true }) ?? remote;
7497
7576
  }
7498
7577
  /**
7499
- * Build refspecs for the push.
7500
- */
7501
- async buildRefSpecs() {
7502
- const specs = [];
7503
- for (const spec of this.refSpecs) if (this.force && !spec.startsWith("+")) specs.push(`+${spec}`);
7504
- else specs.push(spec);
7505
- if (this.pushAll) for await (const ref of this.refsStore.list("refs/heads/")) {
7506
- const spec = `${ref.name}:${ref.name}`;
7507
- specs.push(this.force ? `+${spec}` : spec);
7508
- }
7509
- if (this.pushTags) for await (const ref of this.refsStore.list("refs/tags/")) {
7510
- const spec = `${ref.name}:${ref.name}`;
7511
- specs.push(this.force ? `+${spec}` : spec);
7512
- }
7513
- if (specs.length === 0) {
7514
- const currentBranch = await this.getCurrentBranch();
7515
- if (currentBranch) {
7516
- const spec = `${currentBranch}:${currentBranch}`;
7517
- specs.push(this.force ? `+${spec}` : spec);
7518
- }
7519
- }
7520
- return specs;
7521
- }
7522
- /**
7523
- * Get objects to push.
7578
+ * The refspecs to push: the explicit ones, `--all` (every branch), `--tags` (every tag);
7579
+ * else the remote's configured push refspecs; else what `push.default` says (git's
7580
+ * builtin/push.c `setup_default_push_refspecs`, default `simple`):
7524
7581
  *
7525
- * Returns objects reachable from newIds but not from oldIds.
7526
- */
7527
- async *getObjectsToPush(newIds, oldIds) {
7528
- const excludeCommits = /* @__PURE__ */ new Set();
7529
- for (const oldId of oldIds) if (oldId !== "0".repeat(40)) await this.collectReachableCommits(oldId, excludeCommits);
7530
- const visitedObjects = /* @__PURE__ */ new Set();
7531
- const commitQueue = [...newIds.filter((id) => id !== "0".repeat(40))];
7532
- while (commitQueue.length > 0) {
7533
- const commitId = commitQueue.shift();
7534
- if (commitId === void 0) break;
7535
- if (excludeCommits.has(commitId) || visitedObjects.has(commitId)) continue;
7536
- visitedObjects.add(commitId);
7537
- try {
7538
- const commit = await this.commits.load(commitId);
7539
- if (!commit) continue;
7540
- yield await this.loadObjectForPush(commitId, 1);
7541
- yield* this.yieldTreeObjects(commit.tree, visitedObjects);
7542
- for (const parent of commit.parents) if (!excludeCommits.has(parent) && !visitedObjects.has(parent)) commitQueue.push(parent);
7543
- } catch {}
7544
- }
7545
- }
7546
- /**
7547
- * Collect all commits reachable from a given commit.
7548
- */
7549
- async collectReachableCommits(commitId, result, maxDepth = 1e3) {
7550
- const queue = [commitId];
7551
- let depth = 0;
7552
- while (queue.length > 0 && depth < maxDepth) {
7553
- const id = queue.shift();
7554
- if (id === void 0) break;
7555
- if (result.has(id)) continue;
7556
- result.add(id);
7557
- depth++;
7558
- try {
7559
- const commit = await this.commits.load(id);
7560
- if (commit) queue.push(...commit.parents);
7561
- } catch {}
7562
- }
7563
- }
7564
- /**
7565
- * Yield tree and blob objects recursively.
7566
- */
7567
- async *yieldTreeObjects(treeId, visited) {
7568
- if (visited.has(treeId)) return;
7569
- visited.add(treeId);
7570
- yield await this.loadObjectForPush(treeId, 2);
7571
- for await (const entry of this.trees.loadTree(treeId)) {
7572
- if (visited.has(entry.id)) continue;
7573
- if ((entry.mode & 61440) === 16384) yield* this.yieldTreeObjects(entry.id, visited);
7574
- else {
7575
- visited.add(entry.id);
7576
- yield await this.loadObjectForPush(entry.id, 3);
7577
- }
7578
- }
7579
- }
7580
- /**
7581
- * Load an object for pushing.
7582
+ * - `simple`: the current branch to its upstream of the same name when pushing to the
7583
+ * branch's own remote (refused without an upstream, or with one of another name); to the
7584
+ * same name when pushing elsewhere (a URL, another remote)
7585
+ * - `current`: the current branch to the same name
7586
+ * - `upstream` (`tracking`): the current branch to its upstream, on its remote only
7587
+ * - `matching`: `:` (the branches both sides have)
7588
+ * - `nothing`: refused
7582
7589
  *
7583
- * Serializes objects to raw Git format based on type:
7584
- * - type 1 (commit): serialize via serializeCommit()
7585
- * - type 2 (tree): serialize via serializeTree()
7586
- * - type 3 (blob): load raw content from blob store
7590
+ * A detached HEAD is refused, except with `matching`.
7587
7591
  */
7588
- async loadObjectForPush(objectId, type) {
7589
- let content;
7590
- if (type === 1) {
7591
- const commit = await this.commits.load(objectId);
7592
- if (!commit) throw new Error(`Commit not found: ${objectId}`);
7593
- content = serializeCommit(commit);
7594
- } else if (type === 2) {
7595
- const entries = [];
7596
- for await (const entry of this.trees.loadTree(objectId)) entries.push(entry);
7597
- content = serializeTree(entries);
7598
- } else {
7599
- const chunks = [];
7600
- const blobContent = await this.blobs.load(objectId);
7601
- if (blobContent) for await (const chunk of blobContent) chunks.push(chunk);
7602
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
7603
- content = new Uint8Array(totalLength);
7604
- let offset = 0;
7605
- for (const chunk of chunks) {
7606
- content.set(chunk, offset);
7607
- offset += chunk.length;
7608
- }
7609
- }
7610
- return {
7611
- id: objectId,
7612
- type,
7613
- content
7592
+ async buildRefSpecs() {
7593
+ const specs = [...this.refSpecs];
7594
+ if (this.pushAll) specs.push("refs/heads/*:refs/heads/*");
7595
+ if (this.pushTags) specs.push("refs/tags/*:refs/tags/*");
7596
+ if (specs.length > 0) return specs;
7597
+ const store = RemoteConfigStore.from(this.workingCopy);
7598
+ if (store.isConfigured(this.remote)) {
7599
+ const configured = store.read(this.remote).pushRefspecs;
7600
+ if (configured.length > 0) return configured;
7601
+ }
7602
+ const mode = (store.value("push.default") ?? "simple").toLowerCase();
7603
+ if (mode === "matching") return [":"];
7604
+ if (mode === "nothing") throw new InvalidArgumentError("refspecs", void 0, "You didn't specify any refspecs to push, and push.default is \"nothing\".");
7605
+ const ref = await this.getCurrentBranch();
7606
+ if (!ref && !await this.refsStore.get("HEAD")) return [];
7607
+ if (!ref?.startsWith("refs/heads/")) throw new InvalidArgumentError("refspecs", void 0, "You are not currently on a branch. To push the history leading to the current (detached HEAD) state now, use git push <remote> HEAD:<name-of-remote-branch>");
7608
+ const branch = ref.slice(11);
7609
+ if (mode === "current") return [`${ref}:${ref}`];
7610
+ const branchRemote = store.value(`branch.${branch}.remote`) ?? "origin";
7611
+ const merge = store.value(`branch.${branch}.merge`);
7612
+ const triangular = this.remote !== branchRemote;
7613
+ const noUpstream = () => new InvalidArgumentError("refspecs", void 0, `The current branch ${branch} has no upstream branch. To push the current branch and set the remote as upstream, use git push --set-upstream ${this.remote} ${branch}`);
7614
+ if (mode === "upstream" || mode === "tracking") {
7615
+ if (triangular) throw new InvalidArgumentError("refspecs", void 0, `You are pushing to remote '${this.remote}', which is not the upstream of your current branch '${branch}', without telling me what to push to update which remote branch.`);
7616
+ if (!merge) throw noUpstream();
7617
+ return [`${ref}:${merge}`];
7618
+ }
7619
+ if (triangular) return [`${ref}:${ref}`];
7620
+ if (!merge) throw noUpstream();
7621
+ if (merge !== ref) throw new InvalidArgumentError("refspecs", void 0, `The upstream branch of your current branch does not match
7622
+ the name of your current branch. To push to the upstream branch on the remote, use
7623
+ git push ${this.remote} HEAD:${merge.replace(/^refs\/heads\//, "")}`);
7624
+ return [`${ref}:${ref}`];
7625
+ }
7626
+ /**
7627
+ * The remote-tracking ref of a remote ref (`refs/heads/main` → `refs/remotes/origin/main`)
7628
+ * through the named remote's fetch refspecs; none for a URL.
7629
+ */
7630
+ trackingRefMapper() {
7631
+ const store = RemoteConfigStore.from(this.workingCopy);
7632
+ if (!store.isConfigured(this.remote)) return () => void 0;
7633
+ const specs = store.read(this.remote).fetchRefspecs.map((spec) => parseRefSpec(spec)).filter((spec) => !spec.negative && spec.source && spec.destination);
7634
+ return (remoteRef) => {
7635
+ const spec = specs.find((s) => matchSource(s, remoteRef));
7636
+ return spec ? expandFromSource(spec, remoteRef).destination ?? void 0 : void 0;
7614
7637
  };
7615
7638
  }
7616
7639
  };
@@ -8222,7 +8245,7 @@ var ReflogCommand = class extends GitCommand {
8222
8245
  async call() {
8223
8246
  this.checkCallable();
8224
8247
  this.setCallable(false);
8225
- if (!this.refsStore.getReflog) throw new Error("RefStore does not support reflog");
8248
+ if (!this.refsStore.getReflog) throw new Error("This ref store does not support reflog");
8226
8249
  const reader = await this.refsStore.getReflog(this.ref);
8227
8250
  if (!reader) return [];
8228
8251
  return reader.getReverseEntries();
@@ -8586,9 +8609,7 @@ async function writeTreeRestorePlan(worktree, blobs, plan, operation) {
8586
8609
  for (const { path, objectId, mode } of plan.entries) {
8587
8610
  const content = await blobs.load(objectId);
8588
8611
  if (!content) throw new Error(`${operation} cannot restore ${path}: blob ${objectId} is missing`);
8589
- const chunks = [];
8590
- for await (const chunk of content) chunks.push(chunk);
8591
- await worktree.writeContent(path, chunks, {
8612
+ await worktree.writeContent(path, content, {
8592
8613
  mode,
8593
8614
  createParents: true
8594
8615
  });
@@ -9308,7 +9329,7 @@ var StashListCommand = class extends GitCommand {
9308
9329
  /**
9309
9330
  * Get stash entries.
9310
9331
  *
9311
- * Note: Without reflog support in the core RefStore interface,
9332
+ * Note: Without reflog support in the core Refs interface,
9312
9333
  * this returns only the most recent stash (if any).
9313
9334
  */
9314
9335
  async getStashReflog() {
@@ -9806,7 +9827,7 @@ var StashCreateCommand = class extends GitCommand {
9806
9827
  /**
9807
9828
  * Update the stash ref.
9808
9829
  *
9809
- * Note: Reflog support is not part of the core RefStore interface.
9830
+ * Note: Reflog support is not part of the core Refs interface.
9810
9831
  * Stash history is tracked via parent commit chain instead.
9811
9832
  */
9812
9833
  async updateStashRef(ref, commitId, _message) {
@@ -9822,7 +9843,7 @@ var StashCreateCommand = class extends GitCommand {
9822
9843
  *
9823
9844
  * Based on JGit's StashDropCommand.
9824
9845
  *
9825
- * Note: Without reflog support in RefStore, only the most recent stash (index 0)
9846
+ * Note: Without reflog support in Refs, only the most recent stash (index 0)
9826
9847
  * can be dropped. Dropping by index > 0 requires reflog support.
9827
9848
  *
9828
9849
  * @example
@@ -10014,23 +10035,6 @@ function getTimezoneOffset() {
10014
10035
  return `${sign}${Math.floor(absOffset / 60).toString().padStart(2, "0")}${(absOffset % 60).toString().padStart(2, "0")}`;
10015
10036
  }
10016
10037
  /**
10017
- * Validate a tag name according to Git rules.
10018
- *
10019
- * @param name Tag name to validate
10020
- * @returns true if valid
10021
- */
10022
- function isValidTagName(name) {
10023
- if (!name || name.length === 0) return false;
10024
- if (name.startsWith("/") || name.endsWith("/")) return false;
10025
- if (name.includes("..")) return false;
10026
- if (/[\x00-\x1f\x7f ~^:?*[\\]/.test(name)) return false;
10027
- if (name.endsWith(".lock")) return false;
10028
- if (name.startsWith("-")) return false;
10029
- if (name === "@") return false;
10030
- if (name.includes("@{")) return false;
10031
- return true;
10032
- }
10033
- /**
10034
10038
  * Create a tag (lightweight or annotated).
10035
10039
  *
10036
10040
  * Equivalent to `git tag`.
@@ -10266,9 +10270,9 @@ var ListTagCommand = class extends GitCommand {
10266
10270
  this.setCallable(false);
10267
10271
  const tags = [];
10268
10272
  for await (const ref of this.refsStore.list("refs/tags/")) if ("objectId" in ref) tags.push(ref);
10269
- tags.sort((a, b) => a.name.localeCompare(b.name));
10273
+ tags.sort((a, b) => compareRefNames(a.name, b.name));
10270
10274
  return tags;
10271
10275
  }
10272
10276
  };
10273
10277
  //#endregion
10274
- export { DiffCommand as A, CheckoutCommand as B, MergeCommand as C, InitCommand as D, RevFilter as E, FetchCommand as F, ListBranchCommand as G, CheckoutStatus as H, TagOption as I, ResetMode as J, RenameBranchCommand as K, TransportCommand as L, DescribeCommand as M, CommitCommand as N, Git as O, CloneCommand as P, CleanCommand as R, PackRefsCommand as S, LogCommand as T, CreateBranchCommand as U, CheckoutStage as V, DeleteBranchCommand as W, AddCommand as X, BlameCommand as Y, GitCommand as Z, ReflogCommand as _, StashDropCommand as a, PushCommand as b, STASH_REF as c, RevertCommand as d, ResetCommand as f, RemoteSetUrlCommand as g, RemoteRemoveCommand as h, StatusCommand as i, formatDiffEntry as j, GarbageCollectCommand as k, StashListCommand as l, RemoteListCommand as m, ListTagCommand as n, StashCreateCommand as o, RemoteAddCommand as p, ListBranchMode as q, TagCommand as r, StashApplyCommand as s, DeleteTagCommand as t, RmCommand as u, RebaseCommand as v, LsRemoteCommand as w, PullCommand as x, RebaseOperation as y, CherryPickCommand as z };
10278
+ export { GitCommand as $, DiffCommand as A, CleanCommand as B, MergeCommand as C, InitCommand as D, RevFilter as E, FetchCommand as F, CreateBranchCommand as G, CheckoutCommand as H, TagOption as I, RenameBranchCommand as J, DeleteBranchCommand as K, toTagMode as L, DescribeCommand as M, CommitCommand as N, Git as O, CloneCommand as P, AddCommand as Q, toTrackingRefUpdate as R, PackRefsCommand as S, LogCommand as T, CheckoutStage as U, CherryPickCommand as V, CheckoutStatus as W, ResetMode as X, ListBranchMode as Y, BlameCommand as Z, ReflogCommand as _, StashDropCommand as a, PushCommand as b, STASH_REF as c, RevertCommand as d, ResetCommand as f, RemoteSetUrlCommand as g, RemoteRemoveCommand as h, StatusCommand as i, formatDiffEntry as j, GarbageCollectCommand as k, StashListCommand as l, RemoteListCommand as m, ListTagCommand as n, StashCreateCommand as o, RemoteAddCommand as p, ListBranchCommand as q, TagCommand as r, StashApplyCommand as s, DeleteTagCommand as t, RmCommand as u, RebaseCommand as v, LsRemoteCommand as w, PullCommand as x, RebaseOperation as y, TransportCommand as z };