@statewalker/vcs-commands 0.6.0 → 0.7.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 (166) hide show
  1. package/dist/commands/apply/apply-command.d.ts.map +1 -1
  2. package/dist/commands/apply/apply-engine.d.ts.map +1 -1
  3. package/dist/commands/apply/apply-parse.d.ts.map +1 -1
  4. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -1
  5. package/dist/commands/clone-command.d.ts +17 -0
  6. package/dist/commands/clone-command.d.ts.map +1 -1
  7. package/dist/commands/comment-char-config.d.ts +35 -0
  8. package/dist/commands/comment-char-config.d.ts.map +1 -0
  9. package/dist/commands/commit-command.d.ts.map +1 -1
  10. package/dist/commands/core-config.d.ts.map +1 -1
  11. package/dist/commands/default-branch.d.ts +70 -0
  12. package/dist/commands/default-branch.d.ts.map +1 -0
  13. package/dist/commands/diff-command.d.ts.map +1 -1
  14. package/dist/commands/fetch-command.d.ts.map +1 -1
  15. package/dist/commands/format-patch-command.d.ts.map +1 -1
  16. package/dist/commands/fsck/fsck-command.d.ts +2 -0
  17. package/dist/commands/fsck/fsck-command.d.ts.map +1 -1
  18. package/dist/commands/fsck/fsck-loose.d.ts +3 -0
  19. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -1
  20. package/dist/commands/fsck/fsck-object-checks.d.ts +25 -14
  21. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -1
  22. package/dist/commands/fsck/fsck-object-table.d.ts +15 -7
  23. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -1
  24. package/dist/commands/fsck/fsck-pack.d.ts +11 -4
  25. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -1
  26. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -1
  27. package/dist/commands/gc-command.d.ts +72 -48
  28. package/dist/commands/gc-command.d.ts.map +1 -1
  29. package/dist/commands/git-date.d.ts +1 -65
  30. package/dist/commands/git-date.d.ts.map +1 -1
  31. package/dist/commands/git-hooks.d.ts +8 -0
  32. package/dist/commands/git-hooks.d.ts.map +1 -1
  33. package/dist/commands/index-adder.d.ts +2 -0
  34. package/dist/commands/index-adder.d.ts.map +1 -1
  35. package/dist/commands/index.d.ts +2 -0
  36. package/dist/commands/index.d.ts.map +1 -1
  37. package/dist/commands/index.js +3 -3
  38. package/dist/commands/init-command.d.ts +50 -3
  39. package/dist/commands/init-command.d.ts.map +1 -1
  40. package/dist/commands/legacy-remotes.d.ts +55 -0
  41. package/dist/commands/legacy-remotes.d.ts.map +1 -0
  42. package/dist/commands/log-command.d.ts.map +1 -1
  43. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  44. package/dist/commands/merge-command.d.ts +12 -0
  45. package/dist/commands/merge-command.d.ts.map +1 -1
  46. package/dist/commands/merge-support.d.ts +11 -3
  47. package/dist/commands/merge-support.d.ts.map +1 -1
  48. package/dist/commands/notes-merge-command.d.ts.map +1 -1
  49. package/dist/commands/notes-tree.d.ts +11 -1
  50. package/dist/commands/notes-tree.d.ts.map +1 -1
  51. package/dist/commands/patch-id.d.ts +3 -0
  52. package/dist/commands/patch-id.d.ts.map +1 -1
  53. package/dist/commands/pretty-format.d.ts.map +1 -1
  54. package/dist/commands/pull-command.d.ts +18 -0
  55. package/dist/commands/pull-command.d.ts.map +1 -1
  56. package/dist/commands/push-command.d.ts.map +1 -1
  57. package/dist/commands/read-tree-command.d.ts.map +1 -1
  58. package/dist/commands/rebase-command.d.ts.map +1 -1
  59. package/dist/commands/remote-command.d.ts.map +1 -1
  60. package/dist/commands/reset-command.d.ts.map +1 -1
  61. package/dist/commands/rev-parse-command.d.ts +9 -0
  62. package/dist/commands/rev-parse-command.d.ts.map +1 -1
  63. package/dist/commands/revision-resolver.d.ts +6 -2
  64. package/dist/commands/revision-resolver.d.ts.map +1 -1
  65. package/dist/commands/sequencer-pick.d.ts +1 -1
  66. package/dist/commands/sequencer-pick.d.ts.map +1 -1
  67. package/dist/commands/sequencer-support.d.ts.map +1 -1
  68. package/dist/commands/stash-create-command.d.ts +1 -1
  69. package/dist/commands/stash-create-command.d.ts.map +1 -1
  70. package/dist/commands/status-command.d.ts.map +1 -1
  71. package/dist/commands/submodule-summary-command.d.ts.map +1 -1
  72. package/dist/commands/untracked-cache-support.d.ts +2 -1
  73. package/dist/commands/untracked-cache-support.d.ts.map +1 -1
  74. package/dist/commands/worktree-list-command.d.ts.map +1 -1
  75. package/dist/{commands-DnmlfwGV.js → commands-DIJ91NnD.js} +1111 -506
  76. package/dist/{git-command-DxvwPrPB.js → git-command-BGiOJ8Zk.js} +630 -996
  77. package/dist/git-command.d.ts +16 -1
  78. package/dist/git-command.d.ts.map +1 -1
  79. package/dist/git.d.ts +9 -2
  80. package/dist/git.d.ts.map +1 -1
  81. package/dist/index.js +4 -4
  82. package/dist/remote-config/index.d.ts +1 -1
  83. package/dist/remote-config/index.d.ts.map +1 -1
  84. package/dist/remote-config/remote-config-store.d.ts +62 -3
  85. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  86. package/dist/rename/detect-renames.d.ts.map +1 -1
  87. package/dist/results/clone-result.d.ts +8 -0
  88. package/dist/results/clone-result.d.ts.map +1 -1
  89. package/dist/results/diff-output.d.ts.map +1 -1
  90. package/dist/results/index.js +1 -1
  91. package/dist/results/init-result.d.ts +7 -0
  92. package/dist/results/init-result.d.ts.map +1 -1
  93. package/dist/results/pull-result.d.ts +5 -0
  94. package/dist/results/pull-result.d.ts.map +1 -1
  95. package/dist/results/push-result.d.ts +5 -0
  96. package/dist/results/push-result.d.ts.map +1 -1
  97. package/dist/results/status-result.d.ts.map +1 -1
  98. package/dist/{results-BZGa2Z3I.js → results-WVlBhVb1.js} +11 -10
  99. package/package.json +12 -12
  100. package/src/commands/add-patch/add-interactive.ts +3 -3
  101. package/src/commands/am/am-command.ts +1 -1
  102. package/src/commands/apply/apply-command.ts +12 -2
  103. package/src/commands/apply/apply-engine.ts +5 -6
  104. package/src/commands/apply/apply-parse.ts +3 -2
  105. package/src/commands/attributes-source.ts +1 -1
  106. package/src/commands/bisect/bisect-engine.ts +2 -1
  107. package/src/commands/checkout-command.ts +1 -1
  108. package/src/commands/clone-command.ts +116 -4
  109. package/src/commands/comment-char-config.ts +160 -0
  110. package/src/commands/commit-command.ts +8 -7
  111. package/src/commands/core-config.ts +7 -2
  112. package/src/commands/default-branch.ts +196 -0
  113. package/src/commands/diff-command.ts +45 -27
  114. package/src/commands/fetch-command.ts +19 -5
  115. package/src/commands/format-patch-command.ts +7 -2
  116. package/src/commands/fsck/fsck-command.ts +183 -66
  117. package/src/commands/fsck/fsck-loose.ts +14 -4
  118. package/src/commands/fsck/fsck-object-checks.ts +87 -46
  119. package/src/commands/fsck/fsck-object-table.ts +52 -42
  120. package/src/commands/fsck/fsck-pack.ts +64 -34
  121. package/src/commands/fsck/verify-pack-command.ts +5 -2
  122. package/src/commands/gc-command.ts +208 -107
  123. package/src/commands/git-date.ts +9 -895
  124. package/src/commands/git-hooks.ts +11 -0
  125. package/src/commands/index-adder.ts +8 -3
  126. package/src/commands/index.ts +2 -0
  127. package/src/commands/init-command.ts +167 -11
  128. package/src/commands/legacy-remotes.ts +224 -0
  129. package/src/commands/log-command.ts +37 -22
  130. package/src/commands/ls-remote-command.ts +4 -0
  131. package/src/commands/merge-command.ts +31 -1
  132. package/src/commands/merge-support.ts +29 -8
  133. package/src/commands/notes-merge-command.ts +23 -14
  134. package/src/commands/notes-tree.ts +28 -13
  135. package/src/commands/octopus-merge.ts +3 -2
  136. package/src/commands/patch-id.ts +16 -8
  137. package/src/commands/pretty-format.ts +2 -1
  138. package/src/commands/pull-command.ts +128 -20
  139. package/src/commands/push-command.ts +23 -8
  140. package/src/commands/read-tree-command.ts +6 -2
  141. package/src/commands/rebase-command.ts +24 -13
  142. package/src/commands/remote-command.ts +35 -5
  143. package/src/commands/reset-command.ts +4 -11
  144. package/src/commands/rev-parse-command.ts +22 -0
  145. package/src/commands/revision-resolver.ts +32 -14
  146. package/src/commands/sequencer-pick.ts +7 -2
  147. package/src/commands/sequencer-support.ts +10 -3
  148. package/src/commands/stash-apply-command.ts +1 -1
  149. package/src/commands/stash-create-command.ts +2 -2
  150. package/src/commands/status-command.ts +2 -4
  151. package/src/commands/status-header.ts +3 -1
  152. package/src/commands/submodule-summary-command.ts +6 -7
  153. package/src/commands/untracked-cache-support.ts +16 -12
  154. package/src/commands/worktree-list-command.ts +3 -5
  155. package/src/core-commands/add.command.impl.ts +1 -1
  156. package/src/git-command.ts +32 -2
  157. package/src/git.ts +16 -3
  158. package/src/remote-config/index.ts +2 -0
  159. package/src/remote-config/remote-config-store.ts +137 -11
  160. package/src/rename/detect-renames.ts +5 -1
  161. package/src/results/clone-result.ts +9 -0
  162. package/src/results/diff-output.ts +9 -7
  163. package/src/results/init-result.ts +9 -0
  164. package/src/results/pull-result.ts +5 -0
  165. package/src/results/push-result.ts +5 -0
  166. package/src/results/status-result.ts +5 -2
@@ -1,19 +1,19 @@
1
1
  import { AddFailedError, BranchUsedByWorktreeError, CannotDeleteCurrentBranchError, CloneCheckoutError, CloneDestinationError, CommitNotFoundError, EmptyCommitError, FetchIntoCheckedOutBranchError, GitApiError, HookFailedError, IncompatibleOptionsError, IndexLockFailedError, InvalidArgumentError, InvalidConfigError, InvalidMainlineParentError, InvalidMergeHeadsError, InvalidRefNameError, InvalidRemoteError, InvalidStashIndexError, InvalidTagNameError, MissingArgumentError, MultipleParentsNotAllowedError, MvFailedError, NoFilepatternError, NoHeadError, NoMergeBaseError, NoMessageError, NoRebaseInProgressError, NonFastForwardError, NotACommitError, NotFastForwardError, NotMergedError, PushRejectedException, ReadTreeFailedError, RebaseTodoMissingError, RefAlreadyExistsError, RefNotFoundError, RemoteAlreadyExistsError, RemoteNotFoundError, ResetRefusedError, RevisionError, RmFailedError, StashApplyFailedError, StoreNotAvailableError, SwitchRefusedError, TransportError, UnmergedPathsError, UpstreamRequiredError, WorktreeError, WorktreesUnsupportedError } from "./errors/index.js";
2
- import { $ as pruneEmptyParents, $t as deleteRefs, A as registerPartialClone, At as coreBool, B as pushSparseWarnings, C as updateHeadExpecting, Ct as isKnownHook, Dt as sequencerPostCommit, E as hasPromisorRemote, Et as runPostCheckoutHook, Ft as configValue$1, G as sparsePathAdvice, H as readSparseCheckoutPatterns, Ht as committerIdentOf, I as openUntrackedCache, It as conflictStyleOf, J as IndexCaseFolding, K as sparseWarningText, L as SparseUnpack, Mt as worktreeModeTrust, Nt as bareAttributesResolver, O as promisorOf, Ot as sequencerPrepareMessage, P as markReaddedEntries, Pt as configBool$1, Q as overwriteMessage, Qt as parseGitDate, R as cleanTrackedSparseDirectories, S as updateHead, St as hookSettingsFromEntries, T as createPromisorFetcher, Tt as refTransactionHookOf, U as sparseCheckoutConfig, V as readSparseCheckoutFile, Vt as authorIdentOf, W as sparseDirectoriesOf, Wt as hostEnvironmentOf, X as findInTheWay, Xt as formatRfc2822Date, Y as entryNotUptodate, Yt as withoutCrud, Z as flaggedEntryDiffers, Zt as localTimezoneOffset, _ as unknownRevisionMessage, _t as gitCommitAfterHooks, a as guessRemoteBranch, at as worktreeDiffers, b as reflogMessages, c as trackableStart, ct as planFlatRestore, dt as writeTreeRestorePlan, en as moveRefs, et as removeCaseVariants, f as parseRevisionAndPathArgs, ft as markIndexUpdate, g as parseRevisionArgs, h as handleRevisionArg, i as endOfSymbolicChain, it as untrackedUnder, jt as createIdAbbreviator, k as promisorRemotes, kt as abbrevLengths, lt as planTreeRestore, mt as LOCAL_REPO_ENV, nn as defaultFetchRefspec, nt as statFollowingLinks, o as installTracking, ot as worktreeModified, p as verifyFilename, pt as HookSession, q as updateSparsity, rn as listRemoteNames, rt as statThroughLeadingLinks, s as planTracking, st as checkoutFreshTree, t as GitCommand, tn as RemoteConfigStore, tt as removeDirectoryIfEmpty, ut as restoreCaseOptions, vt as gitCommitMessageHooks, y as reflogLine, yt as hookHostOf, z as entryList } from "./git-command-DxvwPrPB.js";
3
- import { A as blobSide, B as formatShortstat, C as submoduleToken, E as parseOrderFile, F as formatNameOnly, G as statSummary, H as formatSummary, I as formatNameStatus, M as contentSide, N as diffDriverOf, O as diffEntryToPair, R as formatNumstat, S as formatStatusPorcelain, V as formatStat, et as writeCombinedDiff, i as isRebaseSuccessful, j as computeDiffstat, nt as quotePath$1, q as writePairPatch, tt as quoteCStyleBody, w as orderByPatterns, x as StatusImpl, y as isMergeSuccessful } from "./results-BZGa2Z3I.js";
4
- import { DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, EMPTY_TREE_ID, FileMode, ObjectIdMismatchError, ObjectType, PACK_ENTRY_HEAD_MAX, PACK_MAX_CHAIN, PACK_MAX_OBJECT_SIZE, PACK_SCAN_MAX, PromisorFetchError, PromisorObjectReadError, TreeEntryCursor, badPackIntIdAt, bloomFilterContains, bloomKey, canonTreeMode, collectTreeBytes, commitFromBytes, commitGraphCompatible, compareRefNames, compareTreeEntries, countAheadBehind, createInMemoryFilesApi, createMemoryHistory, formatPersonIdent, graftFileBaseDir, graftFileReader, historyWithoutLazyFetch, inflateExactly, isDotGitComponent, isGitWorktreeFile, isNtfsGitWorktreeFile, isSymbolicRef, isValidBranchName, isValidRefName, isValidTagName, isValidWorktreePath, joinPath, listObjectsWithPrefix, loadMultiPackIndex, objectsWithoutLazyFetch, openPack, packEntryOrder, packIdxLookups, parseCoreAbbrev, parseGraftFile, parseGraphCommit, parseObjectFilter, parsePackEntryHead, parsePersonIdent, readCommitGraph, readPackIndex, replacementOf, runSteps, scanPackObjects, verifyCommitGraph } from "@statewalker/vcs-core";
2
+ import { $ as sparseDirectoriesOf, A as registerPartialClone, Bt as coreBool, C as updateHeadExpecting, Ct as LOCAL_REPO_ENV, Dt as gitCommitAfterHooks, E as hasPromisorRemote, Ft as refTransactionHookOf, G as openUntrackedCache, Ht as worktreeModeTrust, It as runPostCheckoutHook, J as entryList, Jt as configValue$1, K as SparseUnpack, Kt as bareAttributesResolver, L as defaultInitialBranch, Lt as sequencerPostCommit, Mt as hookSettingsFromEntries, N as InvalidInitialBranchError, Nt as isKnownHook, O as promisorOf, Ot as gitCommitMessageHooks, Q as sparseCheckoutConfig, R as defaultRefFormat, Rt as sequencerPrepareMessage, S as updateHead, St as HookSession, T as createPromisorFetcher, U as markReaddedEntries, Vt as createIdAbbreviator, X as readSparseCheckoutFile, Y as pushSparseWarnings, Yt as conflictStyleOf, Z as readSparseCheckoutPatterns, _ as unknownRevisionMessage, _t as planFlatRestore, a as guessRemoteBranch, at as findInTheWay, b as reflogMessages, bt as writeTreeRestorePlan, c as trackableStart, cn as withoutCrud, ct as pruneEmptyParents, dn as parseGitDate, dt as statFollowingLinks, en as authorIdentOf, et as sparsePathAdvice, f as parseRevisionAndPathArgs, fn as deleteRefs, ft as statThroughLeadingLinks, g as parseRevisionArgs, gn as listRemoteNames, gt as checkoutFreshTree, h as handleRevisionArg, hn as defaultFetchRefspec, ht as worktreeModified, i as endOfSymbolicChain, it as entryNotUptodate, j as removeLegacyRemoteFile, k as promisorRemotes, kt as hookHostOf, ln as formatRfc2822Date, lt as removeCaseVariants, mn as RemoteConfigStore, mt as worktreeDiffers, nt as updateSparsity, o as installTracking, ot as flaggedEntryDiffers, p as verifyFilename, pn as moveRefs, pt as untrackedUnder, q as cleanTrackedSparseDirectories, qt as configBool$1, rn as hostEnvironmentOf, rt as IndexCaseFolding, s as planTracking, st as overwriteMessage, t as GitCommand, tn as committerIdentOf, tt as sparseWarningText, un as localTimezoneOffset, ut as removeDirectoryIfEmpty, vt as planTreeRestore, xt as markIndexUpdate, y as reflogLine, yt as restoreCaseOptions, z as isValidBranchName$1, zt as abbrevLengths } from "./git-command-BGiOJ8Zk.js";
3
+ import { A as blobSide, B as formatShortstat, C as submoduleToken, E as parseOrderFile, F as formatNameOnly, G as statSummary, H as formatSummary, I as formatNameStatus, M as contentSide, N as diffDriverOf, O as diffEntryToPair, R as formatNumstat, S as formatStatusPorcelain, V as formatStat, et as writeCombinedDiff, i as isRebaseSuccessful, j as computeDiffstat, nt as quotePath$1, q as writePairPatch, tt as quoteCStyleBody, w as orderByPatterns, x as StatusImpl, y as isMergeSuccessful } from "./results-WVlBhVb1.js";
4
+ import { DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, EMPTY_TREE_ID, FileMode, ObjectIdMismatchError, ObjectType, PACK_ENTRY_HEAD_MAX, PACK_MAX_CHAIN, PACK_MAX_OBJECT_SIZE, PACK_SCAN_MAX, PromisorFetchError, PromisorObjectReadError, TreeEntryCursor, badPackIntIdAt, bloomFilterContains, bloomKey, canonTreeMode, collectTreeBytes, commitFromBytes, commitGraphCompatible, compareRefNames, compareTreeEntries, countAheadBehind, createInMemoryFilesApi, createMemoryHistory, formatPersonIdent, graftFileBaseDir, graftFileReader, historyWithoutLazyFetch, inflateExactly, isDotGitComponent, isGitWorktreeFile, isNtfsGitWorktreeFile, isSymbolicRef, isValidBranchName, isValidRefName, isValidTagName, isValidWorktreePath, joinPath, listObjectsWithPrefix, loadMultiPackIndex, objectFormatOf, objectsWithoutLazyFetch, openPack, packEntryOrder, packIdxLookups, parseCoreAbbrev, parseGraftFile, parseGraphCommit, parseObjectFilter, parsePackEntryHead, parsePersonIdent, readCommitGraph, readPackIndex, replacementOf, runSteps, scanPackObjects, verifyCommitGraph, verifyReverseIndexFile } from "@statewalker/vcs-core";
5
5
  import { compareGitPaths, decodeGitPath, encodeGitPath, foldAsciiCase, gitCharWidth, parseGitBool, parseGitInt, unquoteGitPath } from "@statewalker/vcs-utils/encoding";
6
6
  import { DIR_HIDE_EMPTY_DIRECTORIES, DIR_SHOW_IGNORED_TOO, DIR_SHOW_IGNORED_TOO_MODE_MATCHING, DIR_SHOW_OTHER_DIRECTORIES, DeleteStagingEntry, IndexCorruptError, IndexPathLookup, MergeStage, UpdateStagingEntry, applyStatUpdate, attributesIndexOf, basicStatMatches, cacheTreeFullyValid, cacheTreeOfTree, collectChunks, compareWithWorktree, compareWithWorktreeStat, copyCacheTree, createIndexTree, createMemoryCheckout, createUntrackedTree, createWorktreeTree, entryStatOf, expandUserPath, findUntrackedFiles, flattenTree, getStageState, getWorktreeEntries, hasTrackedChanges, invalidateCacheTreeAgainstIndex, invalidateCacheTreeForIntentToAdd, invalidateCacheTreePath, isCleanByStat, isIndexUnborn, modeFromWorktree, parseCacheTree, parseResolveUndo, readCleanContent, readConvertedContent, readIndexFileEntries, refreshIndexStats, refreshableEntries, repairCacheTree, scanIndex, scanUntracked, smudgeContent, sparseFilterMatcher, sparsePatternsFromCone, sparsePatternsFromLines, splitPatternLines, statUpdateOf, storeWorktreeFile, unreadableDirectoryWarning, untrackedIndexPredicates, updateCacheTree, walkUntrackedScanHost, wholeSeconds, wildmatch, wildmatchBytes, withWorktreeEntries, worktreeEntryChunks } from "@statewalker/vcs-working-tree";
7
- import { ByteSink, LineInterner, OrderedMap, PosixRegexError, RawText, bytesToHex, compareGitPaths as compareGitPaths$1, compilePosixRegex, createInflater, createSha1, decodeGitBinaryDelta, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, mergeLines, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1, unifiedDiffHunks, whitespaceFlags, xdiffHunks } from "@statewalker/vcs-utils";
8
- import { FetchCheckError, PushRefusedByHookError, ReceivePackDiedError, ZERO_OID, anonymizeUrl, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetchFromConnection, fetchRefcolWidth, fetchUpdateDisplay, formatFetchDisplay, formatFetchHead, formatPushStatus, isGitUrl, lsRefs, mapRejectReason, matchDestination, matchSource, openDuplexConnection, openDuplexReceivePackConnection, openReceivePack, openUploadPack, parseGitUrl, parseRefSpec, protocolVersionFor, pushToConnection, serveOverDuplex, servedGitFilesOf, serverSettingsFromConfig, transportSummaryWidth } from "@statewalker/vcs-transport";
9
- import { bytesToHex as bytesToHex$1, sha1Of } from "@statewalker/vcs-utils/hash";
7
+ import { ByteSink, LineInterner, OrderedMap, PosixRegexError, RawText, SHA1_OBJECT_FORMAT, SHA256_OBJECT_FORMAT, bytesToHex, compareGitPaths as compareGitPaths$1, compilePosixRegex, createInflater, createSha1, decodeGitBinaryDelta, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, isNullObjectId, mergeLines, nullObjectIdLike, objectFormatByHexLength, objectFormatByName, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1, unifiedDiffHunks, whitespaceFlags, xdiffHunks } from "@statewalker/vcs-utils";
8
+ import { SHA1_OBJECT_FORMAT as SHA1_OBJECT_FORMAT$1, bytesToHex as bytesToHex$1, isNullObjectId as isNullObjectId$1, nullObjectIdLike as nullObjectIdLike$1, sha1Of } from "@statewalker/vcs-utils/hash";
9
+ import { FileStagingStore, GitWorkingCopyConfig, HostPaths, computeAlternatePath, createFileWorktree, createGitFilesHistoryFromFiles, gc, hostRootOf, multiPackIndexVerify, parseExpiryDate, probeCaseFolding, readProtectedConfig, readRepositoryFormat, resolveLinkedGitDir, writeCommitGraph } from "@statewalker/vcs-store-files";
10
+ import { FetchCheckError, ObjectFormatMismatchError, PushRefusedByHookError, ReceivePackDiedError, anonymizeUrl, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetchFromConnection, fetchRefcolWidth, fetchUpdateDisplay, formatFetchDisplay, formatFetchHead, formatPushStatus, isGitUrl, lsRefs, mapRejectReason, matchDestination, matchSource, openDuplexConnection, openDuplexReceivePackConnection, openReceivePack, openUploadPack, parseGitUrl, parseRefSpec, protocolVersionFor, pushToConnection, serveOverDuplex, servedGitFilesOf, serverSettingsFromConfig, transportSummaryWidth } from "@statewalker/vcs-transport";
10
11
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
11
12
  import { allocBytes, collect } from "@statewalker/vcs-utils/streams";
12
13
  import { bytesToHex as bytesToHex$2, hexToBytes } from "@statewalker/vcs-utils/hash/utils";
13
- import { FileStagingStore, GitWorkingCopyConfig, HostPaths, computeAlternatePath, createFileWorktree, createGitFilesHistoryFromFiles, hostRootOf, multiPackIndexVerify, probeCaseFolding, resolveLinkedGitDir, writeCommitGraph } from "@statewalker/vcs-store-files";
14
14
  import { readFile } from "@statewalker/vcs-utils/files";
15
- import { Sha1, createSha1 as createSha1$1, sha1Of as sha1Of$1 } from "@statewalker/vcs-utils/hash/hasher";
16
15
  import { InflateError, InflateOverflowError, TruncatedStreamError, createInflater as createInflater$1, inflateWhole } from "@statewalker/vcs-utils/compression";
16
+ import { createSha1 as createSha1$1, sha1Of as sha1Of$1 } from "@statewalker/vcs-utils/hash/hasher";
17
17
  import { applyGitDelta } from "@statewalker/vcs-utils/diff";
18
18
  import { CRC32 } from "@statewalker/vcs-utils/hash/crc32";
19
19
  //#region \0rolldown/runtime.js
@@ -258,7 +258,7 @@ async function detectRenames(sources, destinations, options) {
258
258
  const minimumScore = options.minimumScore ?? 3e4;
259
259
  const configured = options.renameLimit ?? 1e3;
260
260
  const renameLimit = configured <= 0 ? MAX_RENAME_LIMIT : configured;
261
- const keep = (c) => options.renameEmpty !== false || c.id !== EMPTY_BLOB_ID;
261
+ const keep = (c) => options.renameEmpty !== false || c.id !== EMPTY_BLOB_ID && c.id !== SHA256_OBJECT_FORMAT.emptyBlobId;
262
262
  const src = options.keepOrder ? sources.filter(keep) : sources.filter(keep).sort(byPath);
263
263
  const dst = options.keepOrder ? destinations.filter(keep) : destinations.filter(keep).sort(byPath);
264
264
  const pairs = [];
@@ -1783,6 +1783,8 @@ async function indexDirs(index) {
1783
1783
  files: /* @__PURE__ */ new Map(),
1784
1784
  dirs: /* @__PURE__ */ new Map()
1785
1785
  };
1786
+ const first = index.values().next().value;
1787
+ const newHasher = objectFormatByHexLength(first?.objectId.length ?? 40)?.createHasher ?? createSha1;
1786
1788
  for (const [path, entry] of index) {
1787
1789
  let dir = root;
1788
1790
  let from = 0;
@@ -1816,7 +1818,7 @@ async function indexDirs(index) {
1816
1818
  let id;
1817
1819
  try {
1818
1820
  const bytes = await collectTreeBytes(entries);
1819
- const hasher = createSha1().update(new TextEncoder().encode(`tree ${bytes.length}\0`));
1821
+ const hasher = newHasher().update(new TextEncoder().encode(`tree ${bytes.length}\0`));
1820
1822
  id = bytesToHex(hasher.update(bytes).digest());
1821
1823
  } catch {
1822
1824
  id = "";
@@ -2043,12 +2045,12 @@ async function readIndex(staging) {
2043
2045
  * one. That write smudges racily clean entries and gives the index a new timestamp, which
2044
2046
  * later overwrite checks compare entries with (an entry as new as it is read again).
2045
2047
  */
2046
- async function writeIndexAsTree(staging, trees, options = {}) {
2048
+ async function writeIndexAsTree(staging, trees, format, options = {}) {
2047
2049
  if (!staging.getCacheTree || !staging.setCacheTree) return staging.writeTree(trees);
2048
2050
  const previous = staging.getCacheTree();
2049
2051
  const treeId = await staging.writeTree(trees);
2050
2052
  if (!previous || !cacheTreeFullyValid(previous)) {
2051
- const cacheTree = await updateCacheTree(trees, treeId, previous);
2053
+ const cacheTree = await updateCacheTree(trees, treeId, previous, format);
2052
2054
  for (const entry of await indexEntryList(staging)) if (entry.intentToAdd) invalidateCacheTreeForIntentToAdd(cacheTree, entry.path);
2053
2055
  staging.setCacheTree(cacheTree);
2054
2056
  if (options.write !== false) await staging.write();
@@ -2062,13 +2064,13 @@ async function writeIndexAsTree(staging, trees, options = {}) {
2062
2064
  * directories of intent-to-add entries left invalid; nothing where the index has conflicts.
2063
2065
  * Sets the cache-tree the next `write` writes.
2064
2066
  */
2065
- async function updateIndexCacheTree(staging, trees) {
2067
+ async function updateIndexCacheTree(staging, trees, format) {
2066
2068
  if (!staging.getCacheTree || !staging.setCacheTree) return;
2067
2069
  if (await staging.hasConflicts()) return;
2068
2070
  const previous = staging.getCacheTree();
2069
2071
  if (previous && cacheTreeFullyValid(previous)) return;
2070
2072
  const treeId = await staging.writeTree(trees);
2071
- const cacheTree = await updateCacheTree(trees, treeId, previous);
2073
+ const cacheTree = await updateCacheTree(trees, treeId, previous, format);
2072
2074
  for (const entry of await indexEntryList(staging)) if (entry.intentToAdd) invalidateCacheTreeForIntentToAdd(cacheTree, entry.path);
2073
2075
  staging.setCacheTree(cacheTree);
2074
2076
  }
@@ -2125,7 +2127,10 @@ async function rewriteIndex(staging, changes, options = {}) {
2125
2127
  while (a < added.length) builder.add(added[a++]);
2126
2128
  await builder.finish({ upToDate: options.upToDate ?? true });
2127
2129
  if (options.cacheTree) staging.setCacheTree?.(options.cacheTree);
2128
- if (options.updateCacheTreeWith) await updateIndexCacheTree(staging, options.updateCacheTreeWith);
2130
+ if (options.updateCacheTreeWith) {
2131
+ const { trees, format } = options.updateCacheTreeWith;
2132
+ await updateIndexCacheTree(staging, trees, format);
2133
+ }
2129
2134
  if (options.write !== false) await staging.write();
2130
2135
  }
2131
2136
  /** The paths where the index differs from `tree`, sorted. */
@@ -2461,7 +2466,7 @@ async function switchTreesWith(ctx, head, target, options, sparse) {
2461
2466
  if (options.targetTree && ctx.staging.setCacheTree) {
2462
2467
  const previous = ctx.staging.getCacheTree?.();
2463
2468
  if (previous) for (const path of [...updates, ...removes]) invalidateCacheTreePath(previous, path);
2464
- const cacheTree = await updateCacheTree(ctx.trees, options.targetTree, previous);
2469
+ const cacheTree = await updateCacheTree(ctx.trees, options.targetTree, previous, objectFormatOf(ctx.workingCopy.history));
2465
2470
  const result = /* @__PURE__ */ new Map();
2466
2471
  for (const [path, entry] of index) {
2467
2472
  const e = entry;
@@ -3384,7 +3389,7 @@ function formatBranchComparison(stat, short, options, advice) {
3384
3389
  * header.state.mergeInProgress; // true while MERGE_HEAD exists
3385
3390
  * ```
3386
3391
  */
3387
- const HEX$2 = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
3392
+ const HEX$1 = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
3388
3393
  /** The header of a status: the branch, the state, the tracking reports. */
3389
3394
  async function readStatusHeader(source, options) {
3390
3395
  const warnings = [];
@@ -3427,7 +3432,8 @@ async function getBranch(source, name) {
3427
3432
  if (!value) return void 0;
3428
3433
  if (value.startsWith("refs/heads/")) return value.slice(11);
3429
3434
  if (value.startsWith("refs/")) return value;
3430
- if (/^[0-9a-fA-F]{40}/.test(value)) return source.abbreviate(value.slice(0, 40).toLowerCase());
3435
+ const hex = /^[0-9a-fA-F]{64}/.test(value) ? 64 : /^[0-9a-fA-F]{40}/.test(value) ? 40 : 0;
3436
+ if (hex) return source.abbreviate(value.slice(0, hex).toLowerCase());
3431
3437
  if (value === "detached HEAD") return void 0;
3432
3438
  return value;
3433
3439
  }
@@ -3605,7 +3611,7 @@ async function formatTodoLine(source, line) {
3605
3611
  }
3606
3612
  if (!ABBREVIATED_COMMANDS.has(command)) return line;
3607
3613
  const word = /^[^ \t]*/.exec(rest)?.[0] ?? "";
3608
- if (!/^[0-9a-fA-F]+$/.test(word) || !HEX$2.test(word.toLowerCase())) return line;
3614
+ if (!/^[0-9a-fA-F]+$/.test(word) || !HEX$1.test(word.toLowerCase())) return line;
3609
3615
  if (!await source.objectExists(word.toLowerCase())) return line;
3610
3616
  const abbrev = await source.abbreviate(word.toLowerCase());
3611
3617
  if (!word.startsWith(abbrev)) return line;
@@ -4934,12 +4940,12 @@ var ApplyParser = class {
4934
4940
  const dot = buf.indexOf(".", line);
4935
4941
  const eol0 = buf.indexOf("\n", line);
4936
4942
  const eol = eol0 < 0 ? buf.length : eol0;
4937
- if (dot < 0 || buf[dot + 1] !== "." || 40 < dot - line) return 0;
4943
+ if (dot < 0 || buf[dot + 1] !== "." || 64 < dot - line) return 0;
4938
4944
  const oldPrefix = buf.slice(line, dot);
4939
4945
  const l2 = dot + 2;
4940
4946
  let ptr = buf.indexOf(" ", l2);
4941
4947
  if (ptr < 0 || eol < ptr) ptr = eol;
4942
- if (40 < ptr - l2) return 0;
4948
+ if (64 < ptr - l2) return 0;
4943
4949
  patch.oldOidPrefix = oldPrefix;
4944
4950
  patch.newOidPrefix = buf.slice(l2, ptr);
4945
4951
  if (buf[ptr] === " ") return mode(ptr + 1 - at, (m) => patch.oldMode = m);
@@ -6011,7 +6017,7 @@ var ApplyEngine = class extends ApplyParser {
6011
6017
  }
6012
6018
  async applyBinary(img, patch) {
6013
6019
  const name = patch.oldName ?? patch.newName;
6014
- const hex = /^[0-9a-f]{40}$/;
6020
+ const hex = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
6015
6021
  if (!hex.test(patch.oldOidPrefix) || !hex.test(patch.newOidPrefix)) return this.error(`cannot apply binary patch to '${name}' without full index line`);
6016
6022
  if (patch.oldName !== null) {
6017
6023
  const oid = await this.io.hashBlob(img.buf);
@@ -6472,15 +6478,15 @@ var ApplyEngine = class extends ApplyParser {
6472
6478
  }
6473
6479
  async addIndexFile(name, mode, buf) {
6474
6480
  if (this.itaOnly) {
6475
- await this.io.writeBlob("");
6481
+ const emptyBlob = await this.io.writeBlob("");
6476
6482
  return this.addIndexEntries(name, [{
6477
6483
  mode,
6478
- oid: "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
6484
+ oid: emptyBlob,
6479
6485
  intentToAdd: true
6480
6486
  }]);
6481
6487
  }
6482
6488
  if (isGitlink$5(mode)) {
6483
- const m = /^Subproject commit ([0-9a-f]{40})/.exec(buf);
6489
+ const m = /^Subproject commit ([0-9a-f]{64}|[0-9a-f]{40})/.exec(buf);
6484
6490
  if (!m) return this.error(`corrupt patch for submodule ${name}`);
6485
6491
  return this.addIndexEntries(name, [{
6486
6492
  mode,
@@ -7139,6 +7145,7 @@ var ApplyCommand = class extends GitCommand {
7139
7145
  }
7140
7146
  makeIO(worktree, trust, filter, rejectWorktree) {
7141
7147
  const blobs = this.blobs;
7148
+ const format = this.objectFormat;
7142
7149
  const toPath = latin1ToPath;
7143
7150
  const readAll = async (content) => {
7144
7151
  const chunks = [];
@@ -7248,9 +7255,9 @@ var ApplyCommand = class extends GitCommand {
7248
7255
  },
7249
7256
  hasObject: (oid) => blobs.has(oid),
7250
7257
  writeBlob: async (content) => blobs.store([latin1ToBytes(content)]),
7251
- hashBlob: async (content) => bytesToHex$1(sha1Of(latin1ToBytes(`blob ${content.length}\0`), latin1ToBytes(content))),
7258
+ hashBlob: async (content) => format.name === "sha1" ? bytesToHex$1(sha1Of(latin1ToBytes(`blob ${content.length}\0`), latin1ToBytes(content))) : bytesToHex$1(format.createHasher().update(latin1ToBytes(`blob ${content.length}\0`)).update(latin1ToBytes(content)).digest()),
7252
7259
  resolveBlob: async (prefix) => {
7253
- if (!/^[0-9a-f]{4,40}$/.test(prefix)) return void 0;
7260
+ if (!/^[0-9a-f]{4,64}$/.test(prefix) || prefix.length > format.hexLength) return void 0;
7254
7261
  try {
7255
7262
  const id = await resolver().resolve(prefix);
7256
7263
  return id && await blobs.has(id) ? id : void 0;
@@ -9458,7 +9465,7 @@ var StashApplyCommand = class extends GitCommand {
9458
9465
  else editor.remove(path);
9459
9466
  }
9460
9467
  await editor.finish();
9461
- await updateIndexCacheTree(this.staging, this.trees);
9468
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
9462
9469
  } else {
9463
9470
  const added = /* @__PURE__ */ new Set();
9464
9471
  for (const path of changed) {
@@ -10070,13 +10077,13 @@ var IndexAdder = class IndexAdder {
10070
10077
  await this.storeEmptyBlob();
10071
10078
  if (indexed) {
10072
10079
  if (!this.pretend) this.touched.add(name);
10073
- return indexed.objectId === EMPTY_BLOB_ID ? "same" : "added";
10080
+ return indexed.objectId === this.emptyBlobId ? "same" : "added";
10074
10081
  }
10075
10082
  if (this.pretend) return "added";
10076
10083
  this.resolve(name);
10077
10084
  this.clearConflicts(name);
10078
10085
  const mode = modeFromWorktree(entry.mode, void 0, this.trust);
10079
- this.editor.add(new UpdateStagingEntry(name, EMPTY_BLOB_ID, mode, {
10086
+ this.editor.add(new UpdateStagingEntry(name, this.emptyBlobId, mode, {
10080
10087
  size: 0,
10081
10088
  mtime: 0
10082
10089
  }, { intentToAdd: true }));
@@ -10117,7 +10124,7 @@ var IndexAdder = class IndexAdder {
10117
10124
  if (this.pretend) return "added";
10118
10125
  this.resolve(path);
10119
10126
  this.clearConflicts(path);
10120
- this.editor.add(new UpdateStagingEntry(path, EMPTY_BLOB_ID, FileMode.GITLINK, {
10127
+ this.editor.add(new UpdateStagingEntry(path, this.emptyBlobId, FileMode.GITLINK, {
10121
10128
  size: 0,
10122
10129
  mtime: 0
10123
10130
  }, { intentToAdd: true }));
@@ -10148,6 +10155,10 @@ var IndexAdder = class IndexAdder {
10148
10155
  return !indexed.intentToAdd && this.indexTime > 0 && wholeSeconds(indexed.mtime, indexed.mtimeNs) < wholeSeconds(this.indexTime) && modeFromWorktree(entry.mode, indexed.mode, this.trust) === indexed.mode && basicStatMatches(indexed, entry, this.trust);
10149
10156
  }
10150
10157
  /** git's `set_object_name_for_intent_to_add_entry`: the empty blob written (once). */
10158
+ /** The empty blob's id in the repository's format (the id an intent-to-add entry gets) */
10159
+ get emptyBlobId() {
10160
+ return this.blobs.objectFormat?.emptyBlobId ?? EMPTY_BLOB_ID;
10161
+ }
10151
10162
  async storeEmptyBlob() {
10152
10163
  if (this.emptyBlobStored) return;
10153
10164
  this.emptyBlobStored = true;
@@ -10411,8 +10422,8 @@ var ResetCommand = class extends GitCommand {
10411
10422
  if (this.modeSet) throw new IncompatibleOptionsError(["--patch", "--{hard,mixed,soft}"], "fatal: options '--patch' and '--{hard,mixed,soft}' cannot be used together");
10412
10423
  const rev = this.ref === void 0 || this.ref === "@" ? "HEAD" : this.ref;
10413
10424
  const head = await this.refsStore.resolve("HEAD");
10414
- const diffRevision = rev === "HEAD" && !head?.objectId ? EMPTY_TREE_ID : rev;
10415
- if (diffRevision !== EMPTY_TREE_ID) await this.resolveRef(rev);
10425
+ const diffRevision = rev === "HEAD" && !head?.objectId ? this.objectFormat.emptyTreeId : rev;
10426
+ if (diffRevision !== this.objectFormat.emptyTreeId) await this.resolveRef(rev);
10416
10427
  this.patchResult = await runPatchSelection(this.workingCopy, {
10417
10428
  hookSource: this,
10418
10429
  ...this.patchOptions,
@@ -10790,7 +10801,7 @@ var ResetCommand = class extends GitCommand {
10790
10801
  changes.set(path, [{
10791
10802
  path,
10792
10803
  mode: t ? t.mode : FileMode.REGULAR_FILE,
10793
- objectId: t ? t.objectId : EMPTY_BLOB_ID,
10804
+ objectId: t ? t.objectId : this.objectFormat.emptyBlobId,
10794
10805
  stage: 0,
10795
10806
  size: 0,
10796
10807
  mtime: 0,
@@ -11869,7 +11880,7 @@ Cannot save the current worktree state`);
11869
11880
  }
11870
11881
  let keepIndex = this.keepIndex;
11871
11882
  let checkoutErrors = [];
11872
- if (keepIndex && indexTree !== EMPTY_TREE_ID) {
11883
+ if (keepIndex && indexTree !== this.objectFormat.emptyTreeId) {
11873
11884
  const seen = items.map(() => 0);
11874
11885
  const mark = (path, mode) => matchPathspecSeen(items, path, mode === 57344 ? 1 : 0, seen);
11875
11886
  for await (const entry of this.staging.entries()) if (!inScope(entry.path, entry.mode === 57344 ? 1 : 0)) mark(entry.path, entry.mode);
@@ -12129,7 +12140,10 @@ async function resetMergeWith(ctx, targetId, label, options, sparse) {
12129
12140
  }]);
12130
12141
  }
12131
12142
  ctx.staging.clearResolveUndo?.();
12132
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
12143
+ await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: {
12144
+ trees: ctx.trees,
12145
+ format: objectFormatOf(ctx.workingCopy.history)
12146
+ } });
12133
12147
  return { written: worktree ? writing : /* @__PURE__ */ new Set() };
12134
12148
  }
12135
12149
  /**
@@ -12184,7 +12198,10 @@ async function resetUnmergedToHead(ctx, headId) {
12184
12198
  }]);
12185
12199
  }
12186
12200
  ctx.staging.clearResolveUndo?.();
12187
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
12201
+ await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: {
12202
+ trees: ctx.trees,
12203
+ format: objectFormatOf(ctx.workingCopy.history)
12204
+ } });
12188
12205
  }
12189
12206
  /**
12190
12207
  * git's `reset --keep <commit>` of the index and the worktree: unpack-trees' `twoway_merge`
@@ -12304,7 +12321,10 @@ async function resetKeepWith(ctx, headId, targetId, label, sparse) {
12304
12321
  }]);
12305
12322
  }
12306
12323
  ctx.staging.clearResolveUndo?.();
12307
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
12324
+ await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: {
12325
+ trees: ctx.trees,
12326
+ format: objectFormatOf(ctx.workingCopy.history)
12327
+ } });
12308
12328
  return { written: worktree ? writing : /* @__PURE__ */ new Set() };
12309
12329
  }
12310
12330
  /**
@@ -12921,11 +12941,12 @@ async function loadRefDecorations(options) {
12921
12941
  if (name.startsWith(replaceBase)) {
12922
12942
  if (options.useReplaceRefs === false) return;
12923
12943
  const hex = name.slice(replaceBase.length);
12944
+ const hexLength = /^[0-9a-fA-F]{64}/.test(hex) ? 64 : 40;
12924
12945
  if (!/^[0-9a-fA-F]{40}/.test(hex)) {
12925
12946
  options.onWarning?.(`warning: invalid replace ref ${name}`);
12926
12947
  return;
12927
12948
  }
12928
- const original = hex.slice(0, 40).toLowerCase();
12949
+ const original = hex.slice(0, hexLength).toLowerCase();
12929
12950
  if (options.hasObject && !await options.hasObject(original)) return;
12930
12951
  add(original, {
12931
12952
  type: "grafted",
@@ -14092,7 +14113,7 @@ function readDiffSubmoduleConfig(workingCopy) {
14092
14113
  return out;
14093
14114
  }
14094
14115
  /** git's null object id: the side of a submodule that is not there. */
14095
- const NULL_OBJECT_ID$1 = "0".repeat(40);
14116
+ const NULL_OBJECT_ID = "0".repeat(40);
14096
14117
  const isNull = (id) => /^0+$/.test(id);
14097
14118
  const SEEN$2 = 1;
14098
14119
  const UNINTERESTING$2 = 2;
@@ -14510,7 +14531,7 @@ var SubmoduleSummaryCommand = class extends GitCommand {
14510
14531
  const first = this.commit ?? "HEAD";
14511
14532
  const resolved = await this.resolveTree(first);
14512
14533
  if (resolved !== void 0) head = resolved;
14513
- else if (first === "HEAD") head = EMPTY_TREE_ID;
14534
+ else if (first === "HEAD") head = this.objectFormat.emptyTreeId;
14514
14535
  else {
14515
14536
  paths.unshift(first);
14516
14537
  const fallback = await this.resolveTree("HEAD");
@@ -14563,8 +14584,8 @@ var SubmoduleSummaryCommand = class extends GitCommand {
14563
14584
  out.push({
14564
14585
  modSrc,
14565
14586
  modDst,
14566
- oidSrc: modSrc ? e.oldId ?? NULL_OBJECT_ID$1 : NULL_OBJECT_ID$1,
14567
- oidDst: modDst ? e.newId ?? NULL_OBJECT_ID$1 : NULL_OBJECT_ID$1,
14587
+ oidSrc: modSrc ? e.oldId ?? this.objectFormat.nullId : this.objectFormat.nullId,
14588
+ oidDst: modDst ? e.newId ?? this.objectFormat.nullId : this.objectFormat.nullId,
14568
14589
  status,
14569
14590
  path: e.oldPath ?? e.newPath
14570
14591
  });
@@ -14612,9 +14633,9 @@ var SubmoduleSummaryCommand = class extends GitCommand {
14612
14633
  /** generate_submodule_summary and print_submodule_summary for one submodule. */
14613
14634
  async generate(p) {
14614
14635
  const worktree = this.worktreeAccess;
14615
- if (!this.cached && p.oidDst === NULL_OBJECT_ID$1 && isGitlink$3(p.modDst)) {
14636
+ if (!this.cached && p.oidDst === this.objectFormat.nullId && isGitlink$3(p.modDst)) {
14616
14637
  const sub = await openSubmoduleRepository(this.workingCopy, p.path);
14617
- if (sub?.populated) p.oidDst = await sub.head() ?? NULL_OBJECT_ID$1;
14638
+ if (sub?.populated) p.oidDst = await sub.head() ?? this.objectFormat.nullId;
14618
14639
  }
14619
14640
  const repo = worktree ? await this.repositoryAt(p.path) : void 0;
14620
14641
  let missingSrc = false;
@@ -14818,7 +14839,6 @@ function parseExpiry(value, now = /* @__PURE__ */ new Date()) {
14818
14839
  }
14819
14840
  //#endregion
14820
14841
  //#region src/commands/worktree-list-command.ts
14821
- const ZERO_ID$3 = "0000000000000000000000000000000000000000";
14822
14842
  /**
14823
14843
  * List the worktrees.
14824
14844
  *
@@ -14904,7 +14924,7 @@ var WorktreeListCommand = class extends GitCommand {
14904
14924
  let out = `worktree ${wt.path}${lt}`;
14905
14925
  if (wt.bare) out += `bare${lt}`;
14906
14926
  else {
14907
- out += `HEAD ${wt.head ?? ZERO_ID$3}${lt}`;
14927
+ out += `HEAD ${wt.head ?? this.objectFormat.nullId}${lt}`;
14908
14928
  if (wt.detached) out += `detached${lt}`;
14909
14929
  else if (wt.headRef) out += `branch ${wt.headRef}${lt}`;
14910
14930
  }
@@ -14922,7 +14942,7 @@ var WorktreeListCommand = class extends GitCommand {
14922
14942
  /** git's `measure_widths` and `show_worktree`. */
14923
14943
  async lines(entries) {
14924
14944
  const verbose = this.format === "verbose";
14925
- const ids = entries.map((wt) => wt.head ?? ZERO_ID$3);
14945
+ const ids = entries.map((wt) => wt.head ?? this.objectFormat.nullId);
14926
14946
  const lengths = await abbrevLengths(this.workingCopy, ids);
14927
14947
  const abbrevLen = Math.max(...ids.map((id) => lengths.get(id) ?? 7));
14928
14948
  const fully = this.quotePathFully();
@@ -14936,7 +14956,7 @@ var WorktreeListCommand = class extends GitCommand {
14936
14956
  let line = `${display[i]}${" ".repeat(pad + maxWidth - width(display[i]))}`;
14937
14957
  if (wt.bare) line += "(bare)";
14938
14958
  else {
14939
- const id = wt.head ?? ZERO_ID$3;
14959
+ const id = wt.head ?? this.objectFormat.nullId;
14940
14960
  line += `${id.slice(0, lengths.get(id) ?? 7).padEnd(abbrevLen)} `;
14941
14961
  if (wt.detached) line += "(detached HEAD)";
14942
14962
  else if (wt.headRef) line += `[${await shortenUnambiguousRef(this.refsStore, wt.headRef)}]`;
@@ -15483,7 +15503,7 @@ var StatusCommand = class extends GitCommand {
15483
15503
  dstPrefix: "i/"
15484
15504
  };
15485
15505
  }
15486
- const cached = new DiffCommand(this.workingCopy).setCached(true).setOldTree(o.referenceId ?? EMPTY_TREE$2).setOptions({ ...cachedPrefixes ?? {} });
15506
+ const cached = new DiffCommand(this.workingCopy).setCached(true).setOldTree(o.referenceId ?? this.objectFormat.emptyTreeId).setOptions({ ...cachedPrefixes ?? {} });
15487
15507
  if (this.renames !== void 0) cached.setRenames(this.renames);
15488
15508
  out += await cached.callText("patch");
15489
15509
  if (twoLevels && o.worktreeChanges) {
@@ -15725,7 +15745,7 @@ var StatusCommand = class extends GitCommand {
15725
15745
  const warnings = [];
15726
15746
  if (this.detectsRenames()) await this.pairRenames(files, renamed, worktree, warnings);
15727
15747
  const host = worktree ? await worktree.untrackedScanHost?.() : void 0;
15728
- const untrackedCache = openUntrackedCache(this.staging, this.config, hostEnvironmentOf(this.workingCopy), host);
15748
+ const untrackedCache = openUntrackedCache(this.staging, this.config, hostEnvironmentOf(this.workingCopy), host, this.objectFormat);
15729
15749
  if (worktree && this.resolvedUntracked !== "no") {
15730
15750
  let flags = this.resolvedUntracked === "all" ? 0 : DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
15731
15751
  if (this.ignoredMode !== "no") {
@@ -16077,8 +16097,6 @@ function cfgBool(config, key, fallback) {
16077
16097
  const value = config.value(key);
16078
16098
  return value === void 0 ? fallback : parseGitBool$1(value) ?? fallback;
16079
16099
  }
16080
- /** git's empty tree, the side compared with before the first commit. */
16081
- const EMPTY_TREE$2 = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
16082
16100
  /** The comment-line string of status's commented lines. */
16083
16101
  function commentLineString(workingCopy) {
16084
16102
  return commentPrefixOf(workingCopy);
@@ -16135,7 +16153,7 @@ const PREFETCH_FORMATS = /* @__PURE__ */ new Set([
16135
16153
  function prefetchIds(entries) {
16136
16154
  const out = [];
16137
16155
  const add = (id, mode) => {
16138
- if (id && id !== NULL_ID$1 && mode !== GITLINK && mode !== void 0 && mode !== 0) out.push(id);
16156
+ if (id && !isNullObjectId(id) && mode !== GITLINK && mode !== void 0 && mode !== 0) out.push(id);
16139
16157
  };
16140
16158
  for (const e of entries) {
16141
16159
  if (e.unmerged) continue;
@@ -16173,7 +16191,6 @@ function submoduleIgnoreValue(value) {
16173
16191
  }
16174
16192
  const S_IFMT$3 = 61440;
16175
16193
  const GITLINK = 57344;
16176
- const NULL_ID$1 = "0".repeat(40);
16177
16194
  const encoder$1 = new TextEncoder();
16178
16195
  /** The chunks as one array. */
16179
16196
  function concatChunks$1(chunks) {
@@ -16671,7 +16688,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
16671
16688
  for (const entry of entries) {
16672
16689
  const pair = entry.unmerged ? {
16673
16690
  status: "M",
16674
- old: contentSide(entry.oldPath ?? "", 0, NULL_ID$1, async () => /* @__PURE__ */ new Uint8Array(0))
16691
+ old: contentSide(entry.oldPath ?? "", 0, this.objectFormat.nullId, async () => /* @__PURE__ */ new Uint8Array(0))
16675
16692
  } : this.withTextconvInputs(diffEntryToPair(entry, this.blobs), entry);
16676
16693
  if (entry.unmerged) unmerged.add(pair);
16677
16694
  pairs.push(pair);
@@ -16689,7 +16706,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
16689
16706
  if (combined.length > 0 && formats.includes("patch")) {
16690
16707
  let combinedLengths;
16691
16708
  if (!options.fullIndex) {
16692
- const ids = /* @__PURE__ */ new Set([NULL_ID$1]);
16709
+ const ids = /* @__PURE__ */ new Set([this.objectFormat.nullId]);
16693
16710
  for (const c of combined) {
16694
16711
  ids.add(c.ours.objectId);
16695
16712
  ids.add(c.theirs.objectId);
@@ -16720,8 +16737,8 @@ var DiffCommand = class DiffCommand extends GitCommand {
16720
16737
  const ids = /* @__PURE__ */ new Set();
16721
16738
  for (const pair of pairs) {
16722
16739
  if (unmerged.has(pair)) continue;
16723
- ids.add(pair.old?.id ?? NULL_ID$1);
16724
- ids.add(pair.new?.id ?? NULL_ID$1);
16740
+ ids.add(pair.old?.id ?? this.objectFormat.nullId);
16741
+ ids.add(pair.new?.id ?? this.objectFormat.nullId);
16725
16742
  }
16726
16743
  options.abbrevLengths = await this.idAbbreviator().lengths(ids, options.abbrev);
16727
16744
  }
@@ -16769,8 +16786,8 @@ var DiffCommand = class DiffCommand extends GitCommand {
16769
16786
  */
16770
16787
  async writeSubmodulePatch(sink, pair, options, format) {
16771
16788
  const path = pair.old?.path ?? pair.new?.path ?? "";
16772
- const one = pair.old?.id ?? NULL_ID$1;
16773
- const two = pair.new?.id ?? NULL_ID$1;
16789
+ const one = pair.old?.id ?? this.objectFormat.nullId;
16790
+ const two = pair.new?.id ?? this.objectFormat.nullId;
16774
16791
  const dirt = pair.new?.submoduleDirt;
16775
16792
  const abbreviate = (id) => this.idAbbreviator().abbreviate(id);
16776
16793
  const workingCopy = this.workingCopy;
@@ -16795,18 +16812,18 @@ var DiffCommand = class DiffCommand extends GitCommand {
16795
16812
  abbreviate
16796
16813
  });
16797
16814
  sink.text(header.text);
16798
- if (!(header.left || one === NULL_ID$1) || !(header.right || two === NULL_ID$1)) return;
16815
+ if (!(header.left || one === this.objectFormat.nullId) || !(header.right || two === this.objectFormat.nullId)) return;
16799
16816
  if (!sub) return;
16800
16817
  const failed = "(diff failed)\n";
16801
16818
  if (!sub.populated && (await this.worktreeIfAny?.getEntry(path))?.isDirectory) {
16802
16819
  sink.text(failed);
16803
16820
  return;
16804
16821
  }
16805
- const inner = new DiffCommand(sub.repository).setOldTree(header.left ? one : EMPTY_TREE_ID).setSubmoduleFormat("diff").setOptions({
16822
+ const inner = new DiffCommand(sub.repository).setOldTree(header.left ? one : this.objectFormat.emptyTreeId).setSubmoduleFormat("diff").setOptions({
16806
16823
  srcPrefix: `${options.srcPrefix ?? "a/"}${path}/`,
16807
16824
  dstPrefix: `${options.dstPrefix ?? "b/"}${path}/`
16808
16825
  });
16809
- if (!dirt?.modified) inner.setNewTree(header.right ? two : EMPTY_TREE_ID);
16826
+ if (!dirt?.modified) inner.setNewTree(header.right ? two : this.objectFormat.emptyTreeId);
16810
16827
  try {
16811
16828
  sink.push(await inner.callBytes("patch"));
16812
16829
  } catch {
@@ -16820,7 +16837,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
16820
16837
  const textconv = driver?.textconv;
16821
16838
  const stage = async (e) => {
16822
16839
  const side = blobSide(this.blobs, c.path, e.mode, e.objectId);
16823
- const convert = textconv && (e.mode & S_IFMT$3) !== GITLINK && e.objectId !== NULL_ID$1;
16840
+ const convert = textconv && (e.mode & S_IFMT$3) !== GITLINK && e.objectId !== this.objectFormat.nullId;
16824
16841
  return {
16825
16842
  id: e.objectId,
16826
16843
  mode: e.mode,
@@ -16833,7 +16850,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
16833
16850
  if (worktree && file) {
16834
16851
  if (file.isDirectory) {
16835
16852
  mode = GITLINK;
16836
- content = encoder$1.encode(`Subproject commit ${NULL_ID$1}\n`);
16853
+ content = encoder$1.encode(`Subproject commit ${this.objectFormat.nullId}\n`);
16837
16854
  } else {
16838
16855
  const kind = file.mode & S_IFMT$3;
16839
16856
  mode = kind === 40960 ? 40960 : file.mode & 73 ? 33261 : 33188;
@@ -16844,14 +16861,14 @@ var DiffCommand = class DiffCommand extends GitCommand {
16844
16861
  path: c.path,
16845
16862
  parents: [await stage(c.ours), await stage(c.theirs)],
16846
16863
  result: {
16847
- id: NULL_ID$1,
16864
+ id: this.objectFormat.nullId,
16848
16865
  mode,
16849
16866
  content
16850
16867
  }
16851
16868
  }, {
16852
16869
  ...options,
16853
16870
  ...textconv ? { binary: false } : driver?.binary !== void 0 ? { binary: driver.binary } : {},
16854
- abbreviate: (id) => id.slice(0, options.fullIndex ? 40 : lengths?.get(id) ?? 7)
16871
+ abbreviate: (id) => id.slice(0, options.fullIndex ? id.length : lengths?.get(id) ?? 7)
16855
16872
  });
16856
16873
  }
16857
16874
  /**
@@ -17334,7 +17351,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
17334
17351
  */
17335
17352
  async treeSide(refOrId, implicitHead = false) {
17336
17353
  const out = /* @__PURE__ */ new Map();
17337
- if (refOrId === EMPTY_TREE_ID) return out;
17354
+ if (refOrId === this.objectFormat.emptyTreeId) return out;
17338
17355
  let treeId;
17339
17356
  try {
17340
17357
  treeId = await this.resolveTreeId(refOrId);
@@ -17354,9 +17371,9 @@ var DiffCommand = class DiffCommand extends GitCommand {
17354
17371
  const oldSide = /* @__PURE__ */ new Map();
17355
17372
  const newSide = /* @__PURE__ */ new Map();
17356
17373
  const treeOf = async (ref, implicit) => {
17357
- if (ref === EMPTY_TREE_ID) return void 0;
17374
+ if (ref === this.objectFormat.emptyTreeId) return void 0;
17358
17375
  const trees = this.trees;
17359
- if (/^[0-9a-f]{40}$/.test(ref)) {
17376
+ if (this.isFullObjectId(ref)) {
17360
17377
  const known = trees.raw ? trees.raw(ref) : trees.entries?.(ref);
17361
17378
  if (known && await known) return ref;
17362
17379
  }
@@ -17380,8 +17397,8 @@ var DiffCommand = class DiffCommand extends GitCommand {
17380
17397
  async diffTreeSides(a, b, prefix, oldSide, newSide) {
17381
17398
  if (a === b) return;
17382
17399
  if (this.trees.raw) return this.diffRawTrees(a, b, prefix, oldSide, newSide);
17383
- const ea = a === void 0 || a === EMPTY_TREE_ID ? [] : await this.treeEntries(a);
17384
- const eb = b === void 0 || b === EMPTY_TREE_ID ? [] : await this.treeEntries(b);
17400
+ const ea = a === void 0 || a === this.objectFormat.emptyTreeId ? [] : await this.treeEntries(a);
17401
+ const eb = b === void 0 || b === this.objectFormat.emptyTreeId ? [] : await this.treeEntries(b);
17385
17402
  let i = 0;
17386
17403
  let j = 0;
17387
17404
  while (i < ea.length || j < eb.length) {
@@ -17419,9 +17436,9 @@ var DiffCommand = class DiffCommand extends GitCommand {
17419
17436
  async diffRawTrees(a, b, prefix, oldSide, newSide) {
17420
17437
  if (a === b) return;
17421
17438
  const trees = this.trees;
17422
- const read = async (id) => id === void 0 || id === EMPTY_TREE_ID ? NO_BYTES : await trees.raw?.(id) ?? NO_BYTES;
17423
- const x = new TreeEntryCursor(await read(a));
17424
- const y = new TreeEntryCursor(await read(b));
17439
+ const read = async (id) => id === void 0 || id === this.objectFormat.emptyTreeId ? NO_BYTES : await trees.raw?.(id) ?? NO_BYTES;
17440
+ const x = new TreeEntryCursor(await read(a), this.objectFormat.rawLength);
17441
+ const y = new TreeEntryCursor(await read(b), this.objectFormat.rawLength);
17425
17442
  const pathOf = (name) => prefix ? `${prefix}/${name}` : name;
17426
17443
  while (!x.done || !y.done) {
17427
17444
  const order = x.done ? 1 : y.done ? -1 : x.compare(y);
@@ -17610,7 +17627,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
17610
17627
  * `RefNotFoundError` for anything else that names no commit or tree.
17611
17628
  */
17612
17629
  async resolveTreeId(refOrId) {
17613
- if (/^[0-9a-f]{40}$/.test(refOrId)) {
17630
+ if (this.isFullObjectId(refOrId)) {
17614
17631
  const tree = await this.revisionResolver().peelToType(refOrId, "tree").catch(() => void 0);
17615
17632
  if (tree !== void 0) return tree;
17616
17633
  }
@@ -17618,7 +17635,7 @@ var DiffCommand = class DiffCommand extends GitCommand {
17618
17635
  try {
17619
17636
  id = await this.resolveRevision(refOrId);
17620
17637
  } catch (e) {
17621
- if (/^[0-9a-f]{40}$/.test(refOrId) && await this.isTree(refOrId)) return refOrId;
17638
+ if (this.isFullObjectId(refOrId) && await this.isTree(refOrId)) return refOrId;
17622
17639
  if (refOrId === "HEAD") throw new NoHeadError("HEAD cannot be resolved");
17623
17640
  if (e instanceof RefNotFoundError) throw new RefNotFoundError(refOrId, `bad revision '${refOrId}'`);
17624
17641
  throw e;
@@ -19004,13 +19021,6 @@ function pathPatchMode(index, worktree, revision) {
19004
19021
  }
19005
19022
  //#endregion
19006
19023
  //#region src/commands/add-patch/add-interactive.ts
19007
- /**
19008
- * `git add -i` (add-interactive.c's `run_add_i`) as a library: the status listing, the
19009
- * "*** Commands ***" menu and its actions (status, update, revert, add untracked, patch,
19010
- * diff, quit, help), each read git makes from standard input answered by the selector (a
19011
- * `choose` request for the menus, the hunk prompts of patch mode as `add -p` asks them), and
19012
- * what git prints gathered as its standard output and standard error.
19013
- */
19014
19024
  const newAddDel = () => ({
19015
19025
  add: 0,
19016
19026
  del: 0,
@@ -19390,7 +19400,7 @@ var AddInteractiveSession = class extends GitCommand {
19390
19400
  const fromIndex = filter === "index-only" ? i === 0 : i === 1;
19391
19401
  const skipUnseen = filter !== "none" && i === 1;
19392
19402
  const diff = new DiffCommand(this.workingCopy).setRenames(false).setCombineMerges(false);
19393
- if (fromIndex) diff.setOldTree(head ?? EMPTY_TREE_ID).setCached(true).setIntentToAddVisible(true);
19403
+ if (fromIndex) diff.setOldTree(head ?? this.objectFormat.emptyTreeId).setCached(true).setIntentToAddVisible(true);
19394
19404
  else diff.setIgnoreSubmodules("dirty");
19395
19405
  if (paths.length > 0) diff.setPathspec(paths);
19396
19406
  for (const stat of await diff.callDiffstat()) {
@@ -19696,7 +19706,7 @@ var AddInteractiveSession = class extends GitCommand {
19696
19706
  }
19697
19707
  if (await this.listAndChoose(this.files, this.sortedFiles(), this.fileChooser("Review diff", true)) > 0) {
19698
19708
  const { context, interHunkContext } = this.options;
19699
- const diff = new DiffCommand(this.workingCopy).setCached(true).setOldTree(head ?? EMPTY_TREE_ID).setPathspec(this.chosen());
19709
+ const diff = new DiffCommand(this.workingCopy).setCached(true).setOldTree(head ?? this.objectFormat.emptyTreeId).setPathspec(this.chosen());
19700
19710
  if (this.modern) diff.setOptions({
19701
19711
  ...context !== void 0 ? { context } : {},
19702
19712
  ...interHunkContext !== void 0 ? { interHunkContext } : {}
@@ -22541,7 +22551,7 @@ var AmCommand = class extends GitCommand {
22541
22551
  if (p.isNew > 0) continue;
22542
22552
  let oid;
22543
22553
  try {
22544
- oid = /^[0-9a-f]{4,40}$/.test(p.oldOidPrefix) ? await resolver.resolve(p.oldOidPrefix) : void 0;
22554
+ oid = /^[0-9a-f]{4,64}$/.test(p.oldOidPrefix) ? await resolver.resolve(p.oldOidPrefix) : void 0;
22545
22555
  if (oid && !await this.blobs.has(oid)) oid = void 0;
22546
22556
  } catch {
22547
22557
  oid = void 0;
@@ -22888,6 +22898,13 @@ var RevParseCommand = class extends GitCommand {
22888
22898
  this.prefix = prefix === "" || prefix.endsWith("/") ? prefix : `${prefix}/`;
22889
22899
  return this;
22890
22900
  }
22901
+ /**
22902
+ * `git rev-parse --show-object-format`: the repository's object format (`sha1`, `sha256`),
22903
+ * as the result's `lines` give it with `addArgument("--show-object-format")`.
22904
+ */
22905
+ showObjectFormat() {
22906
+ return this.objectFormat.name;
22907
+ }
22891
22908
  /** The revision to resolve (`HEAD~2`, `@{u}`, `main@{yesterday}`, `:/fix`, `HEAD:a.txt`). */
22892
22909
  setRevision(revision) {
22893
22910
  this.checkCallable();
@@ -22952,6 +22969,12 @@ var RevParseCommand = class extends GitCommand {
22952
22969
  lines.push(arg);
22953
22970
  continue;
22954
22971
  }
22972
+ if (arg === "--show-object-format" || arg.startsWith("--show-object-format=")) {
22973
+ const mode = arg.slice(21);
22974
+ if (arg.includes("=") && mode !== "storage" && mode !== "input" && mode !== "output") throw new RevisionError(arg, `fatal: unknown mode for --show-object-format: ${mode}`);
22975
+ lines.push(this.objectFormat.name);
22976
+ continue;
22977
+ }
22955
22978
  if (await this.tryDifference(resolver, arg, lines)) continue;
22956
22979
  if (await this.tryParentShorthands(resolver, arg, lines)) continue;
22957
22980
  const reversed = arg.startsWith("^");
@@ -24880,7 +24903,7 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
24880
24903
  * checkout do before the write).
24881
24904
  */
24882
24905
  async writeSwitchedIndex() {
24883
- await updateIndexCacheTree(this.staging, this.trees);
24906
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
24884
24907
  markIndexUpdate(this.staging, { workdir: true });
24885
24908
  await this.staging.write();
24886
24909
  }
@@ -27636,32 +27659,15 @@ var Mailmap = class {
27636
27659
  };
27637
27660
  }
27638
27661
  };
27639
- //#endregion
27640
- //#region src/commands/notes-tree.ts
27641
- /**
27642
- * A notes tree as git's notes.c holds it in memory: a non-balancing 16-tree keyed by the
27643
- * nibbles of the annotated object's id, whose leaves are notes or not-yet-read subtrees of
27644
- * the stored tree (read when a lookup or a change reaches them), and the entries that are no
27645
- * notes (kept and written back). Written back, it takes git's fanout (`determine_fanout`):
27646
- * notes move into 2-digit directories once every slot of a level is taken, so the trees
27647
- * written are those native git writes for the same history of changes.
27648
- *
27649
- * @example
27650
- * ```typescript
27651
- * const t = await NotesTree.load({ blobs, trees }, treeId);
27652
- * await t.add(commitId, noteBlobId, combineNotesOverwrite);
27653
- * const newTree = await t.write();
27654
- * ```
27655
- */
27656
- const NULL_ID = "0".repeat(40);
27657
- const RAW = 20;
27662
+ "0".repeat(40);
27658
27663
  const PTR_NULL = 0;
27659
27664
  const PTR_INTERNAL = 1;
27660
27665
  const PTR_NOTE = 2;
27661
27666
  const PTR_SUBTREE = 3;
27662
27667
  const typeOf$1 = (p) => p === null ? PTR_NULL : p.type;
27663
27668
  const nibble$1 = (n, key) => Number.parseInt(key[n] ?? "0", 16);
27664
- const prefixLength = (subtreeKey) => Number.parseInt(subtreeKey.slice(38), 16);
27669
+ /** A subtree key's prefix length in bytes: its last byte (the key is an id's length long) */
27670
+ const prefixLength = (subtreeKey) => Number.parseInt(subtreeKey.slice(-2), 16);
27665
27671
  /** SUBTREE_SHA1_PREFIXCMP: whether `key` starts with the prefix of `subtree` (0: it does). */
27666
27672
  const prefixMatches = (key, subtreeKey) => {
27667
27673
  const len = prefixLength(subtreeKey) * 2;
@@ -27683,7 +27689,7 @@ function compareBytes$3(a, b) {
27683
27689
  return x.length - y.length;
27684
27690
  }
27685
27691
  async function readBytes(blobs, id) {
27686
- if (id === NULL_ID) return void 0;
27692
+ if (isNullObjectId(id)) return void 0;
27687
27693
  const content = await blobs.load(id).catch(() => void 0);
27688
27694
  if (!content) return void 0;
27689
27695
  const chunks = [];
@@ -27756,9 +27762,16 @@ var NotesTree = class NotesTree {
27756
27762
  nonNotes = [];
27757
27763
  /** A change was made since loading (t->dirty) */
27758
27764
  dirty = false;
27765
+ /** Raw id bytes of the repository's format (20 for SHA-1, 32 for SHA-256): notes' path lengths */
27766
+ raw;
27767
+ /** The repository's null id: adding it as a note removes one */
27768
+ nullId;
27759
27769
  constructor(stores, combine) {
27760
27770
  this.stores = stores;
27761
27771
  this.combine = combine;
27772
+ const format = stores.objectFormat ?? stores.blobs.objectFormat ?? SHA1_OBJECT_FORMAT;
27773
+ this.raw = format.rawLength;
27774
+ this.nullId = format.nullId;
27762
27775
  }
27763
27776
  /**
27764
27777
  * init_notes's load: the stored tree `treeId` as an unread subtree of the root (read
@@ -27768,7 +27781,7 @@ var NotesTree = class NotesTree {
27768
27781
  const t = new NotesTree(stores, combine);
27769
27782
  if (treeId) await t.loadSubtree({
27770
27783
  type: PTR_SUBTREE,
27771
- key: NULL_ID,
27784
+ key: t.nullId,
27772
27785
  val: treeId
27773
27786
  }, t.root, 0);
27774
27787
  return t;
@@ -27803,7 +27816,7 @@ var NotesTree = class NotesTree {
27803
27816
  const existing = await this.get(to);
27804
27817
  if (!force && existing) return false;
27805
27818
  if (note) await this.add(to, note, combine);
27806
- else if (existing) await this.add(to, NULL_ID, combine);
27819
+ else if (existing) await this.add(to, this.nullId, combine);
27807
27820
  return true;
27808
27821
  }
27809
27822
  /** for_each_note: the notes (and with the flags, subtrees) in id order. */
@@ -27923,7 +27936,7 @@ var NotesTree = class NotesTree {
27923
27936
  const { node, n, i } = await this.search(tree, n0, entry.key);
27924
27937
  const l = node.a[i] ?? null;
27925
27938
  if (l === null) {
27926
- if (entry.val !== NULL_ID) node.a[i] = entry;
27939
+ if (!isNullObjectId(entry.val)) node.a[i] = entry;
27927
27940
  return;
27928
27941
  }
27929
27942
  if (l.type === PTR_NOTE) {
@@ -27931,7 +27944,7 @@ var NotesTree = class NotesTree {
27931
27944
  if (l.key === entry.key) {
27932
27945
  if (l.val === entry.val) return;
27933
27946
  l.val = await combine(this.stores, l.val, entry.val);
27934
- if (l.val === NULL_ID) await this.removeLeaf(node, n, entry.key);
27947
+ if (isNullObjectId(l.val)) await this.removeLeaf(node, n, entry.key);
27935
27948
  return;
27936
27949
  }
27937
27950
  } else if (prefixMatches(l.key, entry.key)) {
@@ -27945,7 +27958,7 @@ var NotesTree = class NotesTree {
27945
27958
  return this.insert(node, n, entry, combine);
27946
27959
  }
27947
27960
  }
27948
- if (entry.val === NULL_ID) return;
27961
+ if (isNullObjectId(entry.val)) return;
27949
27962
  const created = newNode();
27950
27963
  await this.insert(created, n + 1, l, combine);
27951
27964
  node.a[i] = created;
@@ -27982,7 +27995,7 @@ var NotesTree = class NotesTree {
27982
27995
  for (const entry of entries) {
27983
27996
  const name = entry.name;
27984
27997
  let leaf;
27985
- if (name.length === 2 * (RAW - prefixLen)) {
27998
+ if (name.length === 2 * (this.raw - prefixLen)) {
27986
27999
  if (isRegular(entry.mode) && isHex(name)) leaf = {
27987
28000
  type: PTR_NOTE,
27988
28001
  key: prefix + name.toLowerCase(),
@@ -27991,7 +28004,7 @@ var NotesTree = class NotesTree {
27991
28004
  } else if (name.length === 2) {
27992
28005
  if (isDir$1(entry.mode) && isHex(name)) {
27993
28006
  const len = prefixLen + 1;
27994
- const key = prefix + name.toLowerCase() + "00".repeat(RAW - len - 1) + len.toString(16).padStart(2, "0");
28007
+ const key = prefix + name.toLowerCase() + "00".repeat(this.raw - len - 1) + len.toString(16).padStart(2, "0");
27995
28008
  leaf = {
27996
28009
  type: PTR_SUBTREE,
27997
28010
  key,
@@ -28101,8 +28114,6 @@ function pathWithFanout(key, fanout) {
28101
28114
  }
28102
28115
  return out + key.slice(j);
28103
28116
  }
28104
- /** The null object id, which adding as a note removes one. */
28105
- const NOTES_NULL_ID = NULL_ID;
28106
28117
  /** Reads a note blob's bytes (undefined for a missing one). */
28107
28118
  function readNoteBytes(blobs, id) {
28108
28119
  return readBytes(blobs, id);
@@ -28359,7 +28370,6 @@ async function copyNotesForRebase(ctx, rewrittenList) {
28359
28370
  }
28360
28371
  //#endregion
28361
28372
  //#region src/commands/log-command.ts
28362
- const NULL_OBJECT_ID = "0".repeat(40);
28363
28373
  /** git log reads no index: the in-tree attributes files are the worktree's only. */
28364
28374
  const NO_INDEX = { attributesBlob: () => void 0 };
28365
28375
  /**
@@ -29310,7 +29320,7 @@ var LogCommand = class extends GitCommand {
29310
29320
  return mailmap;
29311
29321
  },
29312
29322
  diff: async (entry, parent, formats, options) => {
29313
- const diff = new DiffCommand(this._workingCopy).setOldTree(parent ? await treeOf(parent) : EMPTY_TREE_ID).setNewTree(entry.commit.tree).shareReadsOf(this);
29323
+ const diff = new DiffCommand(this._workingCopy).setOldTree(parent ? await treeOf(parent) : this.objectFormat.emptyTreeId).setNewTree(entry.commit.tree).shareReadsOf(this);
29314
29324
  diff.setOptions({
29315
29325
  ...this.diffOptions,
29316
29326
  ...options.statWidth !== void 0 ? { stat: {
@@ -29370,7 +29380,7 @@ var LogCommand = class extends GitCommand {
29370
29380
  }
29371
29381
  /** The blobs of a tree, by path (empty for a missing tree) */
29372
29382
  async flatTree(tree, prefix = "", out = /* @__PURE__ */ new Map()) {
29373
- if (tree === EMPTY_TREE_ID) return out;
29383
+ if (tree === this.objectFormat.emptyTreeId) return out;
29374
29384
  for await (const entry of this.trees.loadTree(tree)) {
29375
29385
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
29376
29386
  if ((entry.mode & 61440) === 16384) await this.flatTree(entry.id, path, out);
@@ -29426,7 +29436,7 @@ var LogCommand = class extends GitCommand {
29426
29436
  names: names.bytes(),
29427
29437
  patch: sink.bytes()
29428
29438
  };
29429
- const ids = /* @__PURE__ */ new Set([NULL_OBJECT_ID]);
29439
+ const ids = /* @__PURE__ */ new Set([this.objectFormat.nullId]);
29430
29440
  for (const path of paths) {
29431
29441
  const r = result.get(path);
29432
29442
  if (r) ids.add(r.id);
@@ -29461,7 +29471,7 @@ var LogCommand = class extends GitCommand {
29461
29471
  for (let k = 0; k < parents.length; k++) {
29462
29472
  const e = sideOf(parents[k], k, path);
29463
29473
  sides.push({
29464
- id: e?.id ?? NULL_OBJECT_ID,
29474
+ id: e?.id ?? this.objectFormat.nullId,
29465
29475
  mode: e?.mode ?? 0,
29466
29476
  content: await read(e)
29467
29477
  });
@@ -29470,7 +29480,7 @@ var LogCommand = class extends GitCommand {
29470
29480
  path,
29471
29481
  parents: sides,
29472
29482
  result: {
29473
- id: r?.id ?? NULL_OBJECT_ID,
29483
+ id: r?.id ?? this.objectFormat.nullId,
29474
29484
  mode: r?.mode ?? 0,
29475
29485
  content: await read(r)
29476
29486
  }
@@ -29479,7 +29489,7 @@ var LogCommand = class extends GitCommand {
29479
29489
  dense,
29480
29490
  workingTreeFile: false,
29481
29491
  context: this.diffOptions.context ?? (Number.isFinite(context) ? context : 3),
29482
- abbreviate: (id) => id.slice(0, this.diffOptions.fullIndex ? 40 : lengths.get(id) ?? 7),
29492
+ abbreviate: (id) => id.slice(0, this.diffOptions.fullIndex ? id.length : lengths.get(id) ?? 7),
29483
29493
  quotePath: quote
29484
29494
  });
29485
29495
  }
@@ -29594,7 +29604,7 @@ var LogCommand = class extends GitCommand {
29594
29604
  if (!obj && !failed) return void 0;
29595
29605
  if (obj?.bytes && obj.type === "commit") try {
29596
29606
  return {
29597
- ...parseGraphCommit(obj.bytes, id),
29607
+ ...parseGraphCommit(obj.bytes, id, this.objectFormat),
29598
29608
  raw: obj.bytes
29599
29609
  };
29600
29610
  } catch {}
@@ -29707,7 +29717,7 @@ var LogCommand = class extends GitCommand {
29707
29717
  differs = true;
29708
29718
  break;
29709
29719
  }
29710
- } else differs = await this.treesDiffer(from, to, pathspec, EMPTY_TREE$1);
29720
+ } else differs = await this.treesDiffer(from, to, pathspec, EMPTY_TREE);
29711
29721
  if (maybe && !differs) stats.bloomFalsePositive++;
29712
29722
  return differs;
29713
29723
  }
@@ -29719,10 +29729,10 @@ var LogCommand = class extends GitCommand {
29719
29729
  */
29720
29730
  async treesDiffer(a, b, ps, base) {
29721
29731
  this.statistics.treeEntryReads++;
29722
- const da = a ? await this.requireTree(a) : EMPTY_TREE$1;
29723
- const db = b ? await this.requireTree(b) : EMPTY_TREE$1;
29724
- const ca = new RawEntries(da);
29725
- const cb = new RawEntries(db);
29732
+ const da = a ? await this.requireTree(a) : EMPTY_TREE;
29733
+ const db = b ? await this.requireTree(b) : EMPTY_TREE;
29734
+ const ca = new RawEntries(da, this.objectFormat.rawLength);
29735
+ const cb = new RawEntries(db, this.objectFormat.rawLength);
29726
29736
  const skip = (c) => {
29727
29737
  while (!c.done) {
29728
29738
  c.read();
@@ -29815,7 +29825,8 @@ var LogCommand = class extends GitCommand {
29815
29825
  * the path itself, or anything below it). Equal subtrees end the walk down.
29816
29826
  */
29817
29827
  async differsAtPath(a, b, parts, i) {
29818
- if (parts.length === 0) return (a ?? EMPTY_TREE_ID) !== (b ?? EMPTY_TREE_ID);
29828
+ const empty = this.objectFormat.emptyTreeId;
29829
+ if (parts.length === 0) return (a ?? empty) !== (b ?? empty);
29819
29830
  const name = parts[i];
29820
29831
  const ea = a ? await this.entryOf(a, name) : void 0;
29821
29832
  const eb = b ? await this.entryOf(b, name) : void 0;
@@ -29836,7 +29847,7 @@ var LogCommand = class extends GitCommand {
29836
29847
  const raw = await this.rawTree(tree);
29837
29848
  if (raw === null) return this.trees.getEntry(tree, NAME_DECODER.decode(name));
29838
29849
  if (raw === void 0) throw new GitApiError(`unable to read tree (${tree})`);
29839
- return findRawEntry(raw, name);
29850
+ return findRawEntry(raw, name, this.objectFormat.rawLength);
29840
29851
  }
29841
29852
  /** The replace refs a walk's tree reads follow; undefined without any. */
29842
29853
  treeReplacements;
@@ -29846,7 +29857,7 @@ var LogCommand = class extends GitCommand {
29846
29857
  /** The raw bytes of a tree; undefined when it is missing, null without a raw object store. */
29847
29858
  async rawTree(tree) {
29848
29859
  const id = this.treeReplacements ? replacementOf(this.treeReplacements, tree) : tree;
29849
- if (id === EMPTY_TREE_ID) return EMPTY_TREE$1;
29860
+ if (id === this.objectFormat.emptyTreeId) return EMPTY_TREE;
29850
29861
  const cached = this.rawTrees.get(id);
29851
29862
  if (cached) {
29852
29863
  this.rawTrees.delete(id);
@@ -29905,7 +29916,7 @@ const NAME_DECODER = new TextDecoder();
29905
29916
  const RAW_TREE_CACHE = 512;
29906
29917
  /** The bytes of raw trees a path-limited walk keeps at most (besides the one just read). */
29907
29918
  const RAW_TREE_CACHE_BYTES = 33554432;
29908
- const EMPTY_TREE$1 = /* @__PURE__ */ new Uint8Array(0);
29919
+ const EMPTY_TREE = /* @__PURE__ */ new Uint8Array(0);
29909
29920
  const UNINTERESTING$1 = 2;
29910
29921
  const BOTTOM = 4;
29911
29922
  const SEEN$1 = 8;
@@ -30088,7 +30099,7 @@ function concatBytes(chunks) {
30088
30099
  return out;
30089
30100
  }
30090
30101
  /** The entry named `name` (raw bytes) in raw tree `d`: its id and mode, or undefined. */
30091
- function findRawEntry(d, name) {
30102
+ function findRawEntry(d, name, idLength) {
30092
30103
  let p = 0;
30093
30104
  const n = name.length;
30094
30105
  while (p < d.length) {
@@ -30102,11 +30113,11 @@ function findRawEntry(d, name) {
30102
30113
  let k = 0;
30103
30114
  while (k < n && d[start + k] === name[k]) k++;
30104
30115
  if (k === n) return {
30105
- id: bytesToHex$2(d.subarray(idAt, idAt + 20)),
30116
+ id: bytesToHex$2(d.subarray(idAt, idAt + idLength)),
30106
30117
  mode
30107
30118
  };
30108
30119
  }
30109
- p = idAt + 20;
30120
+ p = idAt + idLength;
30110
30121
  }
30111
30122
  }
30112
30123
  /** A path's components, without empty ones and "." (git's pathspec normalisation). */
@@ -30181,13 +30192,16 @@ var CommitQueue$1 = class {
30181
30192
  */
30182
30193
  var RawEntries = class {
30183
30194
  d;
30195
+ idLength;
30184
30196
  at = 0;
30185
30197
  mode = 0;
30186
30198
  nameStart = 0;
30187
30199
  /** where the name ends (its NUL; the id follows) */
30188
30200
  nul = 0;
30189
- constructor(d) {
30201
+ /** @param idLength raw id bytes per entry: 20 (SHA-1) or 32 (SHA-256) */
30202
+ constructor(d, idLength = 20) {
30190
30203
  this.d = d;
30204
+ this.idLength = idLength;
30191
30205
  }
30192
30206
  get done() {
30193
30207
  return this.at >= this.d.length;
@@ -30203,10 +30217,10 @@ var RawEntries = class {
30203
30217
  this.nul = p;
30204
30218
  }
30205
30219
  next() {
30206
- this.at = this.nul + 21;
30220
+ this.at = this.nul + 1 + this.idLength;
30207
30221
  }
30208
30222
  id() {
30209
- return bytesToHex$2(this.d.subarray(this.nul + 1, this.nul + 21));
30223
+ return bytesToHex$2(this.d.subarray(this.nul + 1, this.nul + 1 + this.idLength));
30210
30224
  }
30211
30225
  /** The base of the entries below this one (a directory): `base`, its name and "/". */
30212
30226
  below(base) {
@@ -30218,7 +30232,7 @@ var RawEntries = class {
30218
30232
  return out;
30219
30233
  }
30220
30234
  sameId(other) {
30221
- for (let k = 1; k <= 20; k++) if (this.d[this.nul + k] !== other.d[other.nul + k]) return false;
30235
+ for (let k = 1; k <= this.idLength; k++) if (this.d[this.nul + k] !== other.d[other.nul + k]) return false;
30222
30236
  return true;
30223
30237
  }
30224
30238
  /** git's base_name_compare of the names: a tree's name is followed by "/". */
@@ -31542,7 +31556,7 @@ Maybe you mistook '${this.termGood}' and '${this.termBad}' revs?\n`);
31542
31556
  id = await this.ctx.resolve(head);
31543
31557
  }
31544
31558
  if (!id) this.error(`Bad rev input: ${head}`);
31545
- revs.push(id ?? "0000000000000000000000000000000000000000");
31559
+ revs.push(id ?? nullObjectIdLike(revs[0]));
31546
31560
  }
31547
31561
  for (const arg of revArgs) {
31548
31562
  const id = await this.ctx.resolve(arg);
@@ -34284,7 +34298,7 @@ var CommitCommand = class extends GitCommand {
34284
34298
  committable = status.committable;
34285
34299
  template += p.out + status.text;
34286
34300
  } else {
34287
- const parentTree = ctx.firstParent ? (await this.commits.load(ctx.firstParent))?.tree : EMPTY_TREE_ID;
34301
+ const parentTree = ctx.firstParent ? (await this.commits.load(ctx.firstParent))?.tree : this.objectFormat.emptyTreeId;
34288
34302
  committable = ctx.treeId !== parentTree;
34289
34303
  }
34290
34304
  await state.write("COMMIT_EDITMSG", template);
@@ -34560,7 +34574,7 @@ var CommitCommand = class extends GitCommand {
34560
34574
  hostPath: await this.hooks.gitPath(name, true),
34561
34575
  reread: async () => {
34562
34576
  await temp.read();
34563
- return writeIndexAsTree(temp, this.trees, { write: false });
34577
+ return writeIndexAsTree(temp, this.trees, this.objectFormat, { write: false });
34564
34578
  },
34565
34579
  remove
34566
34580
  };
@@ -34608,9 +34622,9 @@ var CommitCommand = class extends GitCommand {
34608
34622
  let treeId;
34609
34623
  if (partialTree) treeId = partialTree;
34610
34624
  else if (index) {
34611
- treeId = await writeIndexAsTree(this.staging, this.trees, { write: false });
34625
+ treeId = await writeIndexAsTree(this.staging, this.trees, this.objectFormat, { write: false });
34612
34626
  await index.write();
34613
- } else treeId = await writeIndexAsTree(this.staging, this.trees);
34627
+ } else treeId = await writeIndexAsTree(this.staging, this.trees, this.objectFormat);
34614
34628
  let previousCommit;
34615
34629
  let amendedId;
34616
34630
  if (this.amend) {
@@ -34697,7 +34711,7 @@ var CommitCommand = class extends GitCommand {
34697
34711
  async refuseNothingToCommit(treeId, parents, mergeHeads, previousCommit) {
34698
34712
  if (this.allowEmpty || mergeHeads.length > 0) return;
34699
34713
  if (parents.length === 0) {
34700
- if (treeId === EMPTY_TREE_ID) throw new EmptyCommitError();
34714
+ if (treeId === this.objectFormat.emptyTreeId) throw new EmptyCommitError();
34701
34715
  return;
34702
34716
  }
34703
34717
  if (this.amend && (previousCommit?.parents.length ?? 0) > 1) return;
@@ -35005,7 +35019,7 @@ var CommitCommand = class extends GitCommand {
35005
35019
  }
35006
35020
  await adder.finish();
35007
35021
  }
35008
- await updateIndexCacheTree(this.staging, this.trees);
35022
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
35009
35023
  await index.write();
35010
35024
  const edits = /* @__PURE__ */ new Map();
35011
35025
  for (const path of taken) {
@@ -35389,8 +35403,9 @@ async function mergeOneFile(ctx, s, index, worktree, conflicts, output, errors,
35389
35403
  }
35390
35404
  const [n1, n2] = [tempName(), tempName()];
35391
35405
  output.push(o ? `Auto-merging ${path}` : `Added ${path} in both, but differently.`);
35392
- if (!o && !await ctx.blobs.has(EMPTY_BLOB_ID)) {
35393
- errors.push(`fatal: unable to read blob object ${EMPTY_BLOB_ID}`, "error: Could not stat : No such file or directory", `ERROR: content conflict in ${path}`);
35406
+ const emptyBlob = ctx.blobs.objectFormat?.emptyBlobId ?? EMPTY_BLOB_ID;
35407
+ if (!o && !await ctx.blobs.has(emptyBlob)) {
35408
+ errors.push(`fatal: unable to read blob object ${emptyBlob}`, "error: Could not stat : No such file or directory", `ERROR: content conflict in ${path}`);
35394
35409
  return leave();
35395
35410
  }
35396
35411
  const nO = tempName();
@@ -35793,6 +35808,35 @@ var MergeCommand = class extends GitCommand {
35793
35808
  warnings: this.sparseWarnings
35794
35809
  } : result;
35795
35810
  }
35811
+ /**
35812
+ * merge.c's `checkout_fast_forward(head, remote)`: a two-way switch of the index and worktree
35813
+ * from `from`'s tree to `to`'s, refusing (unpack-trees' porcelain "merge" messages) where
35814
+ * local changes are in the way; no ref moves. `git pull` runs it when the fetch moved the
35815
+ * checked-out branch itself.
35816
+ *
35817
+ * @returns git's refusal, or undefined once the index and worktree are at `to`
35818
+ */
35819
+ async callCheckoutFastForward(from, to) {
35820
+ this.checkCallable();
35821
+ this.setCallable(false);
35822
+ await this.readCurrentIndex();
35823
+ const worktree = this.worktreeAccess;
35824
+ const run = async () => {
35825
+ const head = await flatTree(this.trees, await this.commits.getTree(from));
35826
+ const targetTree = await this.commits.getTree(to);
35827
+ const target = await flatTree(this.trees, targetTree);
35828
+ const refused = await switchTrees(this.context(worktree), head, target, {
35829
+ action: "merge",
35830
+ operation: "merge",
35831
+ targetTree
35832
+ });
35833
+ return refused ? {
35834
+ message: refused.message,
35835
+ paths: [...refused.paths]
35836
+ } : void 0;
35837
+ };
35838
+ return worktree?.batch ? worktree.batch(run) : run();
35839
+ }
35796
35840
  /** What the sparse checkout printed while the result was written (see MergeResult.warnings). */
35797
35841
  sparseWarnings = [];
35798
35842
  async run(worktree) {
@@ -36383,7 +36427,7 @@ var MergeCommand = class extends GitCommand {
36383
36427
  let savedTree;
36384
36428
  let indexTree;
36385
36429
  if (await provider.hasLocalChanges()) {
36386
- indexTree = await writeIndexAsTree(this.staging, this.trees);
36430
+ indexTree = await writeIndexAsTree(this.staging, this.trees, this.objectFormat);
36387
36431
  savedTree = await provider.getWorkingTree();
36388
36432
  }
36389
36433
  await this.resetAssumeUnchanged(worktree, savedTree ? void 0 : headTree);
@@ -36686,6 +36730,13 @@ function favorOf(strategy) {
36686
36730
  }
36687
36731
  //#endregion
36688
36732
  //#region src/commands/sequencer-pick.ts
36733
+ /**
36734
+ * git's sequencer for `cherry-pick` and `revert`: each commit's change merged into HEAD by
36735
+ * merge-ort and written to the index and the worktree, committed or stopped at a conflict
36736
+ * with git's state (`CHERRY_PICK_HEAD` / `REVERT_HEAD`, `MERGE_MSG`, `AUTO_MERGE`, and for
36737
+ * several commits `sequencer/` with `head`, `todo` and `abort-safety`), so native git can
36738
+ * `--continue`, `--skip` or `--abort` what we started and the other way round.
36739
+ */
36689
36740
  /** What a cherry-pick or revert is asked to do. */
36690
36741
  let SequencerOperation = /* @__PURE__ */ function(SequencerOperation) {
36691
36742
  /** Start picking (reverting) the included commits */
@@ -36827,7 +36878,7 @@ var PickSequencer = class {
36827
36878
  const headId = await this.headId();
36828
36879
  const headCommit = await deps.commits.load(headId);
36829
36880
  if (!headCommit) throw new RefNotFoundError(headId, "HEAD commit not found");
36830
- const headTreeId = this.options.noCommit ? await writeIndexAsTree(deps.staging, deps.trees) : headCommit.tree;
36881
+ const headTreeId = this.options.noCommit ? await writeIndexAsTree(deps.staging, deps.trees, objectFormatOf(deps.workingCopy.history)) : headCommit.tree;
36831
36882
  const { index } = await readIndex(deps.staging);
36832
36883
  if (!this.options.noCommit && (await indexChangesFromTree(index, deps.trees, headTreeId)).length > 0) return this.fail(`error: your local changes would be overwritten by ${ACTION_NAME[action]}.\nhint: commit your changes or stash them to proceed.\nfatal: ${ACTION_NAME[action]} failed`);
36833
36884
  let parentId;
@@ -38307,7 +38358,7 @@ var ReadTreeCommand = class extends GitCommand {
38307
38358
  async repairedCacheTree() {
38308
38359
  const entries = await this.entryList();
38309
38360
  const trees = this.trees;
38310
- return repairCacheTree({ has: async (id) => id === EMPTY_TREE_ID || await trees.has(id) }, entries);
38361
+ return repairCacheTree({ has: async (id) => id === this.objectFormat.emptyTreeId || await trees.has(id) }, entries, this.objectFormat);
38311
38362
  }
38312
38363
  async entryList() {
38313
38364
  const list = this.staging.entryList?.();
@@ -39930,7 +39981,11 @@ const GT = 62;
39930
39981
  const ZERO = 48;
39931
39982
  const SLASH = 47;
39932
39983
  const NUL = 0;
39933
- const HEX$1 = 40;
39984
+ /** SHA-1's ids: 20 bytes, 40 hex digits */
39985
+ const SHA1_ID_SHAPE = {
39986
+ rawLength: 20,
39987
+ hexLength: 40
39988
+ };
39934
39989
  const S_IFMT$1 = 61440;
39935
39990
  const S_IFREG = 32768;
39936
39991
  const S_IFDIR = 16384;
@@ -39946,10 +40001,10 @@ function startsWith(buf, at, prefix) {
39946
40001
  for (let i = 0; i < prefix.length; i++) if (buf[at + i] !== prefix.charCodeAt(i)) return false;
39947
40002
  return true;
39948
40003
  }
39949
- /** git's `parse_oid_hex`: 40 hex digits (either case) at `at`; the end, or -1. */
39950
- function parseOidHex(buf, at) {
39951
- for (let i = 0; i < HEX$1; i++) if (!isHexDigit(buf[at + i])) return -1;
39952
- return at + HEX$1;
40004
+ /** git's `parse_oid_hex`: 40 (64) hex digits (either case) at `at`; the end, or -1. */
40005
+ function parseOidHex(buf, at, hex) {
40006
+ for (let i = 0; i < hex; i++) if (!isHexDigit(buf[at + i])) return -1;
40007
+ return at + hex;
39953
40008
  }
39954
40009
  function indexOf(buf, byte, from, end = buf.length) {
39955
40010
  for (let i = from; i < end; i++) if (buf[i] === byte) return i;
@@ -40027,14 +40082,15 @@ function fsckIdent(buf, start, report) {
40027
40082
  };
40028
40083
  }
40029
40084
  /** git's `fsck_commit`. Returns nonzero when an error was reported (or a fatal check stopped it). */
40030
- function fsckCommit(buf, report) {
40085
+ function fsckCommit(buf, report, shape = SHA1_ID_SHAPE) {
40086
+ const HEX = shape.hexLength;
40031
40087
  const headers = verifyHeaders(buf, report);
40032
40088
  if (headers.stop) return headers.value || -1;
40033
40089
  const end = buf.length;
40034
40090
  let p = 0;
40035
40091
  if (p >= end || !startsWith(buf, p, "tree ")) return report("missingTree", "invalid format - expected 'tree' line");
40036
40092
  p += 5;
40037
- let q = parseOidHex(buf, p);
40093
+ let q = parseOidHex(buf, p, HEX);
40038
40094
  if (q < 0 || buf[q] !== NL) {
40039
40095
  const err = report("badTreeSha1", "invalid 'tree' line format - bad sha1");
40040
40096
  if (err) return err;
@@ -40044,7 +40100,7 @@ function fsckCommit(buf, report) {
40044
40100
  p = q + 1;
40045
40101
  while (p < end && startsWith(buf, p, "parent ")) {
40046
40102
  p += 7;
40047
- q = parseOidHex(buf, p);
40103
+ q = parseOidHex(buf, p, HEX);
40048
40104
  if (q < 0 || buf[q] !== NL) {
40049
40105
  const err = report("badParentSha1", "invalid 'parent' line format - bad sha1");
40050
40106
  if (err) return err;
@@ -40091,7 +40147,7 @@ function fsckTag(buf, report, options = {}) {
40091
40147
  let p = 0;
40092
40148
  if (p >= end || !startsWith(buf, p, "object ")) return report("missingObject", "invalid format - expected 'object' line");
40093
40149
  p += 7;
40094
- let q = parseOidHex(buf, p);
40150
+ let q = parseOidHex(buf, p, (options.shape ?? SHA1_ID_SHAPE).hexLength);
40095
40151
  if (q < 0 || buf[q] !== NL) {
40096
40152
  const ret = report("badObjectSha1", "invalid 'object' line format - bad sha1");
40097
40153
  if (ret) return ret;
@@ -40147,21 +40203,21 @@ function fsckTag(buf, report, options = {}) {
40147
40203
  return ret;
40148
40204
  }
40149
40205
  /** The id of a tree entry, as hex. */
40150
- function treeEntryId(buf, entry) {
40151
- return bytesToHex$2(buf.subarray(entry.idAt, entry.idAt + 20));
40206
+ function treeEntryId(buf, entry, shape = SHA1_ID_SHAPE) {
40207
+ return bytesToHex$2(buf.subarray(entry.idAt, entry.idAt + shape.rawLength));
40152
40208
  }
40153
- /** Whether the 20 id bytes at `at` are all zero (the null id). */
40154
- function isNullIdAt(buf, at) {
40155
- for (let i = at; i < at + 20; i++) if (buf[i] !== 0) return false;
40209
+ /** Whether the `raw` id bytes at `at` are all zero (the null id). */
40210
+ function isNullIdAt(buf, at, raw) {
40211
+ for (let i = at; i < at + raw; i++) if (buf[i] !== 0) return false;
40156
40212
  return true;
40157
40213
  }
40158
40214
  /**
40159
40215
  * Decodes the entry at `at` as git's `decode_tree_entry`: returns it, or the error git prints
40160
40216
  * (`too-short tree object`, `malformed mode in tree entry`, `empty filename in tree entry`).
40161
40217
  */
40162
- function decodeTreeEntry(buf, at) {
40218
+ function decodeTreeEntry(buf, at, raw) {
40163
40219
  const size = buf.length - at;
40164
- if (size < 23 || buf[at + size - 21] !== NUL) return "too-short tree object";
40220
+ if (size < raw + 3 || buf[at + size - raw - 1] !== NUL) return "too-short tree object";
40165
40221
  if (buf[at] === SP) return "malformed mode in tree entry";
40166
40222
  let p = at;
40167
40223
  let mode = 0;
@@ -40186,17 +40242,18 @@ function decodeTreeEntry(buf, at) {
40186
40242
  * walk with `die("too-short tree file")` when an entry runs past the end; that is reported as a
40187
40243
  * decoding error here.
40188
40244
  */
40189
- function walkTree(buf) {
40245
+ function walkTree(buf, shape = SHA1_ID_SHAPE) {
40246
+ const raw = shape.rawLength;
40190
40247
  const entries = [];
40191
40248
  if (buf.length === 0) return { entries };
40192
40249
  let at = 0;
40193
- let entry = decodeTreeEntry(buf, at);
40250
+ let entry = decodeTreeEntry(buf, at, raw);
40194
40251
  if (typeof entry === "string") return {
40195
40252
  entries,
40196
40253
  initError: entry
40197
40254
  };
40198
40255
  for (;;) {
40199
- const next = entry.idAt + 20;
40256
+ const next = entry.idAt + raw;
40200
40257
  if (next > buf.length) return {
40201
40258
  entries,
40202
40259
  error: "too-short tree file"
@@ -40206,7 +40263,7 @@ function walkTree(buf) {
40206
40263
  entries.push(entry);
40207
40264
  return { entries };
40208
40265
  }
40209
- const decoded = decodeTreeEntry(buf, at);
40266
+ const decoded = decodeTreeEntry(buf, at, raw);
40210
40267
  if (typeof decoded === "string") return {
40211
40268
  entries,
40212
40269
  error: decoded
@@ -40221,7 +40278,8 @@ const NO_FIELDS = /* @__PURE__ */ new Int32Array(0);
40221
40278
  * `reuse`, the table and its fields are that table's, overwritten (grown when too short): a
40222
40279
  * walk that decodes one tree at a time allocates nothing per tree.
40223
40280
  */
40224
- function scanTree(buf, reuse) {
40281
+ function scanTree(buf, reuse, shape = SHA1_ID_SHAPE) {
40282
+ const raw = shape.rawLength;
40225
40283
  const len = buf.length;
40226
40284
  const out = reuse ?? {
40227
40285
  count: 0,
@@ -40234,17 +40292,17 @@ function scanTree(buf, reuse) {
40234
40292
  if (!reuse) out.fields = NO_FIELDS;
40235
40293
  return out;
40236
40294
  }
40237
- const need = 3 * (Math.floor(len / 23) + 2);
40295
+ const need = 3 * (Math.floor(len / (raw + 3)) + 2);
40238
40296
  if (out.fields.length < need) out.fields = new Int32Array(reuse ? Math.max(need, 192) : need);
40239
40297
  const fields = out.fields;
40240
- let err = decodeTreeEntryInto(buf, 0, fields, 0);
40298
+ let err = decodeTreeEntryInto(buf, 0, fields, 0, raw);
40241
40299
  if (err) {
40242
40300
  out.initError = err;
40243
40301
  return out;
40244
40302
  }
40245
40303
  let count = 0;
40246
40304
  for (;;) {
40247
- const next = fields[3 * count + 2] + 20;
40305
+ const next = fields[3 * count + 2] + raw;
40248
40306
  if (next > len) {
40249
40307
  out.count = count;
40250
40308
  out.error = "too-short tree file";
@@ -40254,7 +40312,7 @@ function scanTree(buf, reuse) {
40254
40312
  out.count = count + 1;
40255
40313
  return out;
40256
40314
  }
40257
- err = decodeTreeEntryInto(buf, next, fields, count + 1);
40315
+ err = decodeTreeEntryInto(buf, next, fields, count + 1, raw);
40258
40316
  if (err) {
40259
40317
  out.count = count;
40260
40318
  out.error = err;
@@ -40264,9 +40322,9 @@ function scanTree(buf, reuse) {
40264
40322
  }
40265
40323
  }
40266
40324
  /** `decodeTreeEntry` into slot `k` of a `TreeEntryTable`'s fields: undefined, or its error. */
40267
- function decodeTreeEntryInto(buf, at, fields, k) {
40325
+ function decodeTreeEntryInto(buf, at, fields, k, raw) {
40268
40326
  const size = buf.length - at;
40269
- if (size < 23 || buf[at + size - 21] !== NUL) return "too-short tree object";
40327
+ if (size < raw + 3 || buf[at + size - raw - 1] !== NUL) return "too-short tree object";
40270
40328
  if (buf[at] === SP) return "malformed mode in tree entry";
40271
40329
  let p = at;
40272
40330
  let mode = 0;
@@ -40340,7 +40398,9 @@ function verifyOrdered(buf, mode1, s1, e1, mode2, s2, e2, candidates) {
40340
40398
  * it with `error()` before reporting `badTree`). `table` is the tree's `scanTree`, when the
40341
40399
  * caller has it already.
40342
40400
  */
40343
- function fsckTree(buf, types, report, onDecodeError, found, table = scanTree(buf)) {
40401
+ function fsckTree(buf, types, report, onDecodeError, found, table, shape = SHA1_ID_SHAPE) {
40402
+ const raw = shape.rawLength;
40403
+ table ??= scanTree(buf, void 0, shape);
40344
40404
  let retval = 0;
40345
40405
  let hasNullSha1 = false;
40346
40406
  let hasFullPath = false;
@@ -40369,9 +40429,9 @@ function fsckTree(buf, types, report, onDecodeError, found, table = scanTree(buf
40369
40429
  const start = f[3 * i + 1];
40370
40430
  const idAt = f[3 * i + 2];
40371
40431
  const end = idAt - 1;
40372
- hasNullSha1 ||= isNullIdAt(buf, idAt);
40432
+ hasNullSha1 ||= isNullIdAt(buf, idAt, raw);
40373
40433
  hasEmptyName ||= end === start;
40374
- hasZeroPad ||= buf[i === 0 ? 0 : f[3 * i - 1] + 20] === ZERO;
40434
+ hasZeroPad ||= buf[i === 0 ? 0 : f[3 * i - 1] + raw] === ZERO;
40375
40435
  hasLargeName ||= end - start > types.maxTreeEntryLength;
40376
40436
  let plain = buf[start] !== 46;
40377
40437
  for (let k = start; k < end; k++) {
@@ -40380,7 +40440,7 @@ function fsckTree(buf, types, report, onDecodeError, found, table = scanTree(buf
40380
40440
  else if (c === 126 || c === 92 || c >= 128) plain = false;
40381
40441
  }
40382
40442
  if (!plain) {
40383
- const entryId = () => bytesToHex$2(buf.subarray(idAt, idAt + 20));
40443
+ const entryId = () => bytesToHex$2(buf.subarray(idAt, idAt + raw));
40384
40444
  const text = dec$2.decode(buf.subarray(start, end));
40385
40445
  hasDot ||= text === ".";
40386
40446
  hasDotdot ||= text === "..";
@@ -40642,40 +40702,41 @@ function parseGitmodulesConfig(text) {
40642
40702
  * git's `parse_commit_buffer`: the tree and parents, or the error it prints. Ids are
40643
40703
  * lowercased (git's `get_oid_hex` accepts either case).
40644
40704
  */
40645
- function parseCommitBuffer(buf, id) {
40646
- const links = parseCommitLinks(buf, id);
40705
+ function parseCommitBuffer(buf, id, shape = SHA1_ID_SHAPE) {
40706
+ const links = parseCommitLinks(buf, id, shape);
40647
40707
  if ("error" in links) return links;
40648
40708
  return {
40649
- tree: hexIdAt(buf, links.tree),
40650
- parents: links.parents.map((at) => hexIdAt(buf, at))
40709
+ tree: hexIdAt(buf, links.tree, shape),
40710
+ parents: links.parents.map((at) => hexIdAt(buf, at, shape))
40651
40711
  };
40652
40712
  }
40653
- /** `parseCommitBuffer` with the ids left in place: where each one's 40 hex digits start. */
40654
- function parseCommitLinks(buf, id) {
40713
+ /** `parseCommitBuffer` with the ids left in place: where each one's 40 (64) hex digits start. */
40714
+ function parseCommitLinks(buf, id, shape = SHA1_ID_SHAPE) {
40715
+ const HEX = shape.hexLength;
40655
40716
  const tail = buf.length;
40656
- const treeLen = 45;
40657
- const parentLen = 47;
40658
- if (tail <= 46 || !startsWith(buf, 0, "tree ") || buf[treeLen] !== NL) return { error: `bogus commit object ${id}` };
40659
- if (parseOidHex(buf, 5) < 0) return { error: `bad tree pointer in commit ${id}` };
40717
+ const treeLen = HEX + 5;
40718
+ const parentLen = HEX + 7;
40719
+ if (tail <= treeLen + 1 || !startsWith(buf, 0, "tree ") || buf[treeLen] !== NL) return { error: `bogus commit object ${id}` };
40720
+ if (parseOidHex(buf, 5, HEX) < 0) return { error: `bad tree pointer in commit ${id}` };
40660
40721
  const parents = [];
40661
- let p = 46;
40722
+ let p = treeLen + 1;
40662
40723
  while (p + parentLen < tail && startsWith(buf, p, "parent ")) {
40663
- if (tail <= p + parentLen + 1 || parseOidHex(buf, p + 7) < 0 || buf[p + parentLen] !== NL) return { error: `bad parents in commit ${id}` };
40724
+ if (tail <= p + parentLen + 1 || parseOidHex(buf, p + 7, HEX) < 0 || buf[p + parentLen] !== NL) return { error: `bad parents in commit ${id}` };
40664
40725
  parents.push(p + 7);
40665
- p += 48;
40726
+ p += parentLen + 1;
40666
40727
  }
40667
40728
  return {
40668
40729
  tree: 5,
40669
40730
  parents
40670
40731
  };
40671
40732
  }
40672
- /** The 40 hex digits at `at` (checked by `parseOidHex`), lowercased. */
40673
- function hexIdAt(buf, at) {
40674
- return dec$2.decode(buf.subarray(at, at + HEX$1)).toLowerCase();
40733
+ /** The 40 (64) hex digits at `at` (checked by `parseOidHex`), lowercased. */
40734
+ function hexIdAt(buf, at, shape = SHA1_ID_SHAPE) {
40735
+ return dec$2.decode(buf.subarray(at, at + shape.hexLength)).toLowerCase();
40675
40736
  }
40676
- /** The 20 bytes of the 40 hex digits at `at` (either case, checked), written into `out`. */
40737
+ /** The bytes of the hex id at `at` (either case, checked), written into `out` (its length). */
40677
40738
  function rawIdAt(buf, at, out) {
40678
- for (let i = 0; i < 20; i++) {
40739
+ for (let i = 0; i < out.length; i++) {
40679
40740
  const hi = buf[at + 2 * i];
40680
40741
  const lo = buf[at + 2 * i + 1];
40681
40742
  out[i] = nibble(hi) << 4 | nibble(lo);
@@ -40689,11 +40750,12 @@ const nibble = (c) => c <= 57 ? c - 48 : (c | 32) - 87;
40689
40750
  * with the message git prints before looking the tagged object up (undefined where git fails
40690
40751
  * silently).
40691
40752
  */
40692
- function parseTagBuffer(buf, id) {
40753
+ function parseTagBuffer(buf, id, shape = SHA1_ID_SHAPE) {
40754
+ const HEX = shape.hexLength;
40693
40755
  const tail = buf.length;
40694
- if (tail < 64) return { error: void 0 };
40756
+ if (tail < HEX + 24) return { error: void 0 };
40695
40757
  if (!startsWith(buf, 0, "object ")) return { error: void 0 };
40696
- const q = parseOidHex(buf, 7);
40758
+ const q = parseOidHex(buf, 7, HEX);
40697
40759
  if (q < 0 || buf[q] !== NL) return { error: void 0 };
40698
40760
  const object = dec$2.decode(buf.subarray(7, q)).toLowerCase();
40699
40761
  let p = q + 1;
@@ -40962,7 +41024,7 @@ async function readLooseObject(files, path, id, options = {}) {
40962
41024
  const size = Number(match[2]);
40963
41025
  const headerLength = nul + 1;
40964
41026
  if (type === "blob" && size > (options.bigFileThreshold ?? 536870912)) {
40965
- const streamed = checkStreamOid(data, headerLength, size, path, id);
41027
+ const streamed = checkStreamOid(data, headerLength, size, path, id, options.newHasher ?? createSha1$1);
40966
41028
  if (streamed.length > 0) return { errors: streamed };
40967
41029
  return {
40968
41030
  errors,
@@ -41002,7 +41064,7 @@ async function readLooseObject(files, path, id, options = {}) {
41002
41064
  errors.push(`unable to unpack contents of ${path}`);
41003
41065
  return { errors };
41004
41066
  }
41005
- const hasher = createSha1$1().update(enc$1.encode(`${type} ${size}\0`)).update(content);
41067
+ const hasher = (options.newHasher ?? createSha1$1)().update(enc$1.encode(`${type} ${size}\0`)).update(content);
41006
41068
  for (let left = missing; left > 0; left -= ZEROS.length) hasher.update(left >= ZEROS.length ? ZEROS : ZEROS.subarray(0, left));
41007
41069
  const realId = bytesToHex$2(hasher.digest());
41008
41070
  if (realId !== id) return {
@@ -41027,8 +41089,8 @@ async function readLooseObject(files, path, id, options = {}) {
41027
41089
  * git's `check_stream_oid` for a blob above `core.bigFileThreshold`: the errors it prints, none
41028
41090
  * when the stream hashes to `id`. Output is hashed as it inflates, in bounded pieces.
41029
41091
  */
41030
- function checkStreamOid(data, headerLength, size, path, id) {
41031
- const hasher = createSha1$1();
41092
+ function checkStreamOid(data, headerLength, size, path, id, newHasher) {
41093
+ const hasher = newHasher();
41032
41094
  const inflater = createInflater$1();
41033
41095
  let produced = 0;
41034
41096
  const limit = headerLength + size;
@@ -41080,9 +41142,10 @@ const HEX_VALUE = (() => {
41080
41142
  * replaying git's lookups) goes to its slot without probing (`slotOf`).
41081
41143
  */
41082
41144
  var ObjectTable = class {
41145
+ rawLength;
41083
41146
  n = 0;
41084
- /** The ids' bytes, 20 per object number. */
41085
- raw = /* @__PURE__ */ new Uint8Array(20480);
41147
+ /** The ids' bytes, `rawLength` per object number. */
41148
+ raw;
41086
41149
  /** Each id's first four bytes as git's `hash_obj` reads them. */
41087
41150
  keys = /* @__PURE__ */ new Int32Array(1024);
41088
41151
  /** Each object's slot. */
@@ -41097,10 +41160,23 @@ var ObjectTable = class {
41097
41160
  slots = /* @__PURE__ */ new Int32Array(0);
41098
41161
  /** `slots` as bytes. */
41099
41162
  slotBytes = /* @__PURE__ */ new Uint8Array(0);
41100
- scratch = /* @__PURE__ */ new Uint8Array(20);
41163
+ scratch;
41101
41164
  /** The char codes `id` builds a string from. */
41102
- codes = new Array(40).fill(0);
41165
+ codes;
41103
41166
  links = /* @__PURE__ */ new Map();
41167
+ /** Words per slot: the object number and its id's words (6 for SHA-1, 9 for SHA-256) */
41168
+ slot;
41169
+ /**
41170
+ * @param rawLength The raw id length of the repository's object format: 20 (SHA-1) or 32
41171
+ * (SHA-256)
41172
+ */
41173
+ constructor(rawLength = 20) {
41174
+ this.rawLength = rawLength;
41175
+ this.raw = new Uint8Array(rawLength * 1024);
41176
+ this.scratch = new Uint8Array(rawLength);
41177
+ this.codes = new Array(2 * rawLength).fill(0);
41178
+ this.slot = 1 + rawLength / 4;
41179
+ }
41104
41180
  get size() {
41105
41181
  return this.n;
41106
41182
  }
@@ -41111,7 +41187,7 @@ var ObjectTable = class {
41111
41187
  id(n) {
41112
41188
  const raw = this.raw;
41113
41189
  const codes = this.codes;
41114
- for (let i = 0, at = n * 20; i < 20; i++, at++) {
41190
+ for (let i = 0, at = n * this.rawLength; i < this.rawLength; i++, at++) {
41115
41191
  const b = raw[at];
41116
41192
  codes[2 * i] = HEX_CODE[b >> 4];
41117
41193
  codes[2 * i + 1] = HEX_CODE[b & 15];
@@ -41120,7 +41196,7 @@ var ObjectTable = class {
41120
41196
  }
41121
41197
  /** The 20 bytes of object `n`'s id (a view, valid until the next object is created). */
41122
41198
  idBytes(n) {
41123
- return this.raw.subarray(n * 20, n * 20 + 20);
41199
+ return this.raw.subarray(n * this.rawLength, n * this.rawLength + this.rawLength);
41124
41200
  }
41125
41201
  type(n) {
41126
41202
  return this.types[n];
@@ -41142,22 +41218,22 @@ var ObjectTable = class {
41142
41218
  const raw = this.parse(id);
41143
41219
  return raw ? this.lookupRaw(raw, 0) : -1;
41144
41220
  }
41145
- /** `lookup` for the 20 id bytes at `at` in `buf`. */
41221
+ /** `lookup` for the id bytes at `at` in `buf`. */
41146
41222
  lookupRaw(buf, at) {
41147
41223
  const i = this.probe(buf, at);
41148
41224
  if (i < 0) return -1;
41149
- const n = this.slots[SLOT * i];
41225
+ const n = this.slots[this.slot * i];
41150
41226
  this.moveFirst(n, i);
41151
41227
  return n;
41152
41228
  }
41153
41229
  /** git's move of a found object to the slot its probe started from: `n` is in slot `i`. */
41154
41230
  moveFirst(n, i) {
41155
41231
  const slots = this.slots;
41156
- const first = this.keys[n] >>> 0 & slots.length / SLOT - 1;
41232
+ const first = this.keys[n] >>> 0 & slots.length / this.slot - 1;
41157
41233
  if (i === first) return;
41158
- const a = SLOT * i;
41159
- const b = SLOT * first;
41160
- for (let w = 0; w < SLOT; w++) {
41234
+ const a = this.slot * i;
41235
+ const b = this.slot * first;
41236
+ for (let w = 0; w < this.slot; w++) {
41161
41237
  const x = slots[a + w];
41162
41238
  slots[a + w] = slots[b + w];
41163
41239
  slots[b + w] = x;
@@ -41169,30 +41245,30 @@ var ObjectTable = class {
41169
41245
  /** The slot holding the id at `at` in `buf`, or -1. */
41170
41246
  probe(buf, at) {
41171
41247
  const slots = this.slots;
41172
- const size = slots.length / SLOT;
41248
+ const size = slots.length / this.slot;
41173
41249
  if (size === 0) return -1;
41174
41250
  const key = keyOf(buf, at);
41175
41251
  const bytes = this.slotBytes;
41176
41252
  for (let i = key >>> 0 & size - 1;;) {
41177
- const b = SLOT * i;
41253
+ const b = this.slot * i;
41178
41254
  if (slots[b] < 0) return -1;
41179
41255
  if (slots[b + 1] === key) {
41180
41256
  let k = 4;
41181
41257
  const o = 4 * b + 4;
41182
- while (k < 20 && bytes[o + k] === buf[at + k]) k++;
41183
- if (k === 20) return i;
41258
+ while (k < this.rawLength && bytes[o + k] === buf[at + k]) k++;
41259
+ if (k === this.rawLength) return i;
41184
41260
  }
41185
41261
  i++;
41186
41262
  if (i === size) i = 0;
41187
41263
  }
41188
41264
  }
41189
41265
  /**
41190
- * The object whose id is the 20 bytes at `at` in `buf`, or -1, without moving it (a lookup
41266
+ * The object whose id is the id bytes at `at` in `buf`, or -1, without moving it (a lookup
41191
41267
  * git does not make: the layout stays as git's lookups leave it).
41192
41268
  */
41193
41269
  peekRaw(buf, at) {
41194
41270
  const i = this.probe(buf, at);
41195
- return i < 0 ? -1 : this.slots[SLOT * i];
41271
+ return i < 0 ? -1 : this.slots[this.slot * i];
41196
41272
  }
41197
41273
  /**
41198
41274
  * `lookupTyped` of object `n` (the move its lookup makes included): `n`, typed `type` if it
@@ -41216,13 +41292,13 @@ var ObjectTable = class {
41216
41292
  create(id, type) {
41217
41293
  return this.createRaw(this.parseOrThrow(id), 0, type);
41218
41294
  }
41219
- /** `create` for the 20 id bytes at `at` in `buf`. */
41295
+ /** `create` for the id bytes at `at` in `buf`. */
41220
41296
  createRaw(buf, at, type) {
41221
41297
  const n = this.n;
41222
- if (this.slots.length / SLOT - 1 <= n * 2) this.grow();
41298
+ if (this.slots.length / this.slot - 1 <= n * 2) this.grow();
41223
41299
  if (n >= this.types.length) {
41224
41300
  const cap = this.types.length * 2;
41225
- const raw = new Uint8Array(cap * 20);
41301
+ const raw = new Uint8Array(cap * this.rawLength);
41226
41302
  raw.set(this.raw);
41227
41303
  this.raw = raw;
41228
41304
  const keys = new Int32Array(cap);
@@ -41238,11 +41314,11 @@ var ObjectTable = class {
41238
41314
  slotOf.set(this.slotOf);
41239
41315
  this.slotOf = slotOf;
41240
41316
  }
41241
- this.raw.set(buf.subarray(at, at + 20), n * 20);
41317
+ this.raw.set(buf.subarray(at, at + this.rawLength), n * this.rawLength);
41242
41318
  this.keys[n] = keyOf(buf, at);
41243
41319
  this.types[n] = type;
41244
41320
  this.n = n + 1;
41245
- this.insert(n, this.slots, this.slotBytes, this.raw, n * 20);
41321
+ this.insert(n, this.slots, this.slotBytes, this.raw, n * this.rawLength);
41246
41322
  return n;
41247
41323
  }
41248
41324
  /**
@@ -41252,7 +41328,7 @@ var ObjectTable = class {
41252
41328
  lookupTyped(id, type) {
41253
41329
  return this.lookupTypedRaw(this.parseOrThrow(id), 0, type);
41254
41330
  }
41255
- /** `lookupTyped` for the 20 id bytes at `at` in `buf`. */
41331
+ /** `lookupTyped` for the id bytes at `at` in `buf`. */
41256
41332
  lookupTypedRaw(buf, at, type) {
41257
41333
  const n = this.lookupRaw(buf, at);
41258
41334
  if (n < 0) return this.createRaw(buf, at, type);
@@ -41272,16 +41348,16 @@ var ObjectTable = class {
41272
41348
  /** Object numbers in slot order (git's `get_indexed_object` loop). */
41273
41349
  *inSlotOrder() {
41274
41350
  const slots = this.slots;
41275
- for (let i = 0; i < slots.length; i += SLOT) {
41351
+ for (let i = 0; i < slots.length; i += this.slot) {
41276
41352
  const n = slots[i];
41277
41353
  if (n >= 0) yield n;
41278
41354
  }
41279
41355
  }
41280
- /** The bytes of a 40-digit lowercase hex id, in a scratch buffer; undefined if not one. */
41356
+ /** The bytes of a 40 (64) digit lowercase hex id, in a scratch buffer; undefined if not one. */
41281
41357
  parse(id) {
41282
- if (id.length !== 40) return void 0;
41358
+ if (id.length !== 2 * this.rawLength) return void 0;
41283
41359
  const out = this.scratch;
41284
- for (let i = 0; i < 20; i++) {
41360
+ for (let i = 0; i < this.rawLength; i++) {
41285
41361
  const hi = HEX_VALUE[id.charCodeAt(2 * i)] ?? -1;
41286
41362
  const lo = HEX_VALUE[id.charCodeAt(2 * i + 1)] ?? -1;
41287
41363
  if (hi < 0 || lo < 0) return void 0;
@@ -41297,35 +41373,33 @@ var ObjectTable = class {
41297
41373
  grow() {
41298
41374
  const old = this.slots;
41299
41375
  const oldBytes = this.slotBytes;
41300
- const oldSize = old.length / SLOT;
41376
+ const oldSize = old.length / this.slot;
41301
41377
  const size = oldSize < 32 ? 32 : oldSize * 2;
41302
- const slots = new Int32Array(SLOT * size);
41303
- for (let i = 0; i < slots.length; i += SLOT) slots[i] = -1;
41378
+ const slots = new Int32Array(this.slot * size);
41379
+ for (let i = 0; i < slots.length; i += this.slot) slots[i] = -1;
41304
41380
  const bytes = new Uint8Array(slots.buffer);
41305
41381
  for (let i = 0; i < oldSize; i++) {
41306
- const n = old[SLOT * i];
41307
- if (n >= 0) this.insert(n, slots, bytes, oldBytes, 4 * SLOT * i + 4);
41382
+ const n = old[this.slot * i];
41383
+ if (n >= 0) this.insert(n, slots, bytes, oldBytes, 4 * this.slot * i + 4);
41308
41384
  }
41309
41385
  this.slots = slots;
41310
41386
  this.slotBytes = bytes;
41311
41387
  }
41312
- /** Puts object `n`, whose id is the 20 bytes at `at` in `id`, in its slot. */
41388
+ /** Puts object `n`, whose id is the id bytes at `at` in `id`, in its slot. */
41313
41389
  insert(n, slots, bytes, id, at) {
41314
- const size = slots.length / SLOT;
41390
+ const size = slots.length / this.slot;
41315
41391
  const key = this.keys[n];
41316
41392
  let j = key >>> 0 & size - 1;
41317
- while (slots[SLOT * j] >= 0) {
41393
+ while (slots[this.slot * j] >= 0) {
41318
41394
  j++;
41319
41395
  if (j >= size) j = 0;
41320
41396
  }
41321
- slots[SLOT * j] = n;
41397
+ slots[this.slot * j] = n;
41322
41398
  this.slotOf[n] = j;
41323
- bytes.set(id.subarray(at, at + 20), 4 * SLOT * j + 4);
41324
- slots[SLOT * j + 1] = key;
41399
+ bytes.set(id.subarray(at, at + this.rawLength), 4 * this.slot * j + 4);
41400
+ slots[this.slot * j + 1] = key;
41325
41401
  }
41326
41402
  };
41327
- /** Words per slot: the object number and its id's five words. */
41328
- const SLOT = 6;
41329
41403
  /** git's `hash_obj` before the mask: the id's first four bytes as a little-endian int. */
41330
41404
  function keyOf(buf, at) {
41331
41405
  return buf[at] | buf[at + 1] << 8 | buf[at + 2] << 16 | buf[at + 3] << 24;
@@ -41398,9 +41472,11 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41398
41472
  let idxBytes;
41399
41473
  let idx;
41400
41474
  const read = options.read;
41475
+ const format = options.objectFormat ?? SHA1_OBJECT_FORMAT$1;
41476
+ const raw = format.rawLength;
41401
41477
  try {
41402
41478
  idxBytes = read?.bytes ?? await readAll$1(files, idxPath);
41403
- idx = read?.idx ?? readPackIndex(idxBytes);
41479
+ idx = read?.idx ?? readPackIndex(idxBytes, raw);
41404
41480
  } catch {
41405
41481
  hooks.error(`packfile ${packPath} index not opened`);
41406
41482
  return {
@@ -41408,7 +41484,7 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41408
41484
  opened: false
41409
41485
  };
41410
41486
  }
41411
- if (!sameBytes(new Sha1().update(idxBytes.subarray(0, idxBytes.length - 20)).digest(), 0, idxBytes, idxBytes.length - 20)) {
41487
+ if (!sameBytes(format.createHasher().update(idxBytes.subarray(0, idxBytes.length - raw)).digest(), 0, idxBytes, idxBytes.length - raw, raw)) {
41412
41488
  hooks.error(`Packfile index for ${packPath} hash mismatch`);
41413
41489
  failed = true;
41414
41490
  }
@@ -41417,6 +41493,7 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41417
41493
  try {
41418
41494
  pack = await openPack(files, packPath, idxPath, {
41419
41495
  idxBytes,
41496
+ ...format === SHA1_OBJECT_FORMAT$1 ? {} : { objectFormat: format },
41420
41497
  externalBase: externalBase ? async (id) => {
41421
41498
  const obj = await externalBase(id);
41422
41499
  if (!obj) return void 0;
@@ -41436,15 +41513,15 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41436
41513
  hooks.opened?.();
41437
41514
  try {
41438
41515
  const packLength = (await files.stats(packPath))?.size ?? 0;
41439
- const trailerAt = packLength - 20;
41516
+ const trailerAt = packLength - raw;
41440
41517
  const v2 = idx.version > 1;
41441
41518
  const idsAt = v2 ? 1032 : 1028;
41442
- const idStride = v2 ? 20 : 24;
41519
+ const idStride = v2 ? raw : raw + 4;
41443
41520
  const count = idx.objectCount;
41444
- const lookups = packIdxLookups(idxBytes, v2, count);
41445
- const ids = hexIds(idxBytes, idsAt, idStride, count);
41446
- const crcAt = idsAt + count * 20;
41447
- const { order, sorted } = packEntryOrder(idxBytes, v2, count);
41521
+ const lookups = packIdxLookups(idxBytes, v2, count, raw);
41522
+ const ids = hexIds(idxBytes, idsAt, idStride, count, raw);
41523
+ const crcAt = idsAt + count * raw;
41524
+ const { order, sorted } = packEntryOrder(idxBytes, v2, count, raw);
41448
41525
  const n = count;
41449
41526
  const offsetOf = (k) => sorted[k];
41450
41527
  const posOf = (k) => order[k];
@@ -41502,7 +41579,7 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41502
41579
  type = TYPES[keptType[b]];
41503
41580
  depth[k] = depth[b] + 1;
41504
41581
  } else return;
41505
- if (!hashesTo(type, data, idxBytes, idAtK(k))) return void 0;
41582
+ if (!hashesTo(type, data, idxBytes, idAtK(k), format)) return void 0;
41506
41583
  keepBase(k, type, data);
41507
41584
  return {
41508
41585
  type,
@@ -41514,7 +41591,7 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41514
41591
  /** Entry `k`, its bytes read (or undefined when they were not kept): to `hooks.entry`. */
41515
41592
  const visit = (k, bytes) => {
41516
41593
  const offset = offsetOf(k);
41517
- const head = v2 && bytes && fastAt(k) ? parsePackEntryHead(bytes, sorted, k, entryEnd(k), (b) => ids(posOf(b))) : void 0;
41594
+ const head = v2 && bytes && fastAt(k) ? parsePackEntryHead(bytes, sorted, k, entryEnd(k), (b) => ids(posOf(b)), raw) : void 0;
41518
41595
  const id = ids(posOf(k));
41519
41596
  const entry = {
41520
41597
  id,
@@ -41551,12 +41628,12 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41551
41628
  base: `failed to read delta base object ${baseId} at offset ${baseAt} from ${packPath}`
41552
41629
  };
41553
41630
  };
41554
- const slow = unpackEntry(pack, packPath, entry, keepBlob);
41631
+ const slow = unpackEntry(pack, packPath, entry, keepBlob, format);
41555
41632
  if (slow instanceof Promise) return slow.then((u) => hooks.entry(entry, noted(u), pack));
41556
41633
  return hooks.entry(entry, noted(slow), pack);
41557
41634
  };
41558
- const sha = new Sha1();
41559
- const trailer = /* @__PURE__ */ new Uint8Array(20);
41635
+ const sha = format.createHasher();
41636
+ const trailer = new Uint8Array(raw);
41560
41637
  let at = 0;
41561
41638
  let k = 0;
41562
41639
  let crc = new CRC32();
@@ -41628,11 +41705,11 @@ async function checkPack(files, packPath, idxPath, hooks, options) {
41628
41705
  const r = visit(k, void 0);
41629
41706
  if (r instanceof Promise) await r;
41630
41707
  }
41631
- if (!sameBytes(sha.digest(), 0, trailer, 0)) {
41708
+ if (!sameBytes(sha.digest(), 0, trailer, 0, raw)) {
41632
41709
  hooks.checksumError(`${packPath} pack checksum mismatch`);
41633
41710
  failed = true;
41634
41711
  }
41635
- if (!sameBytes(idx.packChecksum, 0, trailer, 0)) {
41712
+ if (!sameBytes(idx.packChecksum, 0, trailer, 0, raw)) {
41636
41713
  hooks.checksumError(`${packPath} pack checksum does not match its index`);
41637
41714
  failed = true;
41638
41715
  }
@@ -41654,31 +41731,33 @@ const HEX_DIGITS = new TextEncoder().encode("0123456789abcdef");
41654
41731
  * flat string (hashing or comparing one does not first copy it, as it would a string built a
41655
41732
  * digit pair at a time).
41656
41733
  */
41657
- function hexIds(idx, idsAt, stride, n) {
41658
- const text = new Uint8Array(n * 40);
41659
- for (let i = 0; i < n; i++) for (let k = 0, at = idsAt + i * stride, o = i * 40; k < 20; k++, o += 2) {
41734
+ function hexIds(idx, idsAt, stride, n, raw = 20) {
41735
+ const hex = 2 * raw;
41736
+ const text = new Uint8Array(n * hex);
41737
+ for (let i = 0; i < n; i++) for (let k = 0, at = idsAt + i * stride, o = i * hex; k < raw; k++, o += 2) {
41660
41738
  const b = idx[at + k] ?? 0;
41661
41739
  text[o] = HEX_DIGITS[b >> 4];
41662
41740
  text[o + 1] = HEX_DIGITS[b & 15];
41663
41741
  }
41664
41742
  const all = new TextDecoder().decode(text);
41665
- return (pos) => all.slice(pos * 40, pos * 40 + 40);
41743
+ return (pos) => all.slice(pos * hex, pos * hex + hex);
41666
41744
  }
41667
- function sameBytes(a, at, b, bt) {
41668
- for (let i = 0; i < 20; i++) if (a[at + i] !== b[bt + i]) return false;
41745
+ function sameBytes(a, at, b, bt, n = 20) {
41746
+ for (let i = 0; i < n; i++) if (a[at + i] !== b[bt + i]) return false;
41669
41747
  return true;
41670
41748
  }
41671
41749
  /** Where `hashesTo` writes an object's `"<type> <size>\0"` header (it runs synchronously). */
41672
41750
  const header = /* @__PURE__ */ new Uint8Array(32);
41673
- /** Whether `content` as `type` hashes to the 20 id bytes at `idAt` in `ids`. */
41674
- function hashesTo(type, content, ids, idAt) {
41751
+ /** Whether `content` as `type` hashes (in `format`) to the id bytes at `idAt` in `ids`. */
41752
+ function hashesTo(type, content, ids, idAt, format) {
41675
41753
  let n = 0;
41676
41754
  for (let i = 0; i < type.length; i++) header[n++] = type.charCodeAt(i);
41677
41755
  header[n++] = 32;
41678
41756
  const size = String(content.length);
41679
41757
  for (let i = 0; i < size.length; i++) header[n++] = size.charCodeAt(i);
41680
41758
  header[n++] = 0;
41681
- return sameBytes(sha1Of$1(header.subarray(0, n), content), 0, ids, idAt);
41759
+ if (format.name === "sha1") return sameBytes(sha1Of$1(header.subarray(0, n), content), 0, ids, idAt);
41760
+ return sameBytes(format.createHasher().update(header.subarray(0, n)).update(content).digest(), 0, ids, idAt, format.rawLength);
41682
41761
  }
41683
41762
  /** The whole content of an object read from a store. */
41684
41763
  async function collect$1(obj) {
@@ -41709,24 +41788,25 @@ async function collect$1(obj) {
41709
41788
  * the object comes whole from `getNow` and is hashed in one call. A large whole object streams
41710
41789
  * (asynchronously) through the hash.
41711
41790
  */
41712
- function unpackEntry(pack, packPath, entry, keepBlob) {
41791
+ function unpackEntry(pack, packPath, entry, keepBlob, format = SHA1_OBJECT_FORMAT$1) {
41713
41792
  let obj;
41714
41793
  try {
41715
41794
  obj = pack.getNow(entry.id);
41716
41795
  } catch (e) {
41717
41796
  return unpackError(entry, packPath, e);
41718
41797
  }
41719
- if (obj instanceof Promise) return obj.then((o) => hashEntry(o, packPath, entry, keepBlob), (e) => unpackError(entry, packPath, e));
41720
- return hashEntry(obj, packPath, entry, keepBlob);
41798
+ if (obj instanceof Promise) return obj.then((o) => hashEntry(o, packPath, entry, keepBlob, format), (e) => unpackError(entry, packPath, e));
41799
+ return hashEntry(obj, packPath, entry, keepBlob, format);
41721
41800
  }
41722
- function hashEntry(obj, packPath, entry, keepBlob) {
41801
+ function hashEntry(obj, packPath, entry, keepBlob, format) {
41723
41802
  if (!obj) return {
41724
41803
  error: cannotUnpack(entry, packPath),
41725
41804
  corrupt: false
41726
41805
  };
41727
41806
  const bytes = obj.bytes;
41728
- if (!bytes) return streamEntry(obj, packPath, entry, keepBlob);
41729
- if (objectIdOf(obj.type, bytes) !== entry.id) return {
41807
+ if (!bytes) return streamEntry(obj, packPath, entry, keepBlob, format);
41808
+ const sha1 = format.name === "sha1";
41809
+ if (objectIdOf(obj.type, bytes, sha1 ? void 0 : format.createHasher) !== entry.id) return {
41730
41810
  error: `packed ${entry.id} from ${packPath} is corrupt`,
41731
41811
  corrupt: true
41732
41812
  };
@@ -41736,9 +41816,9 @@ function hashEntry(obj, packPath, entry, keepBlob) {
41736
41816
  };
41737
41817
  }
41738
41818
  /** A large object (or one whose stream is broken): streamed through the hash. */
41739
- async function streamEntry(obj, packPath, entry, keepBlob) {
41819
+ async function streamEntry(obj, packPath, entry, keepBlob, format) {
41740
41820
  const keep = obj.type !== "blob" || keepBlob(entry.id);
41741
- const h = createSha1$1().update(enc.encode(`${obj.type} ${obj.size}\0`));
41821
+ const h = format.createHasher().update(enc.encode(`${obj.type} ${obj.size}\0`));
41742
41822
  const parts = [];
41743
41823
  let n = 0;
41744
41824
  try {
@@ -41782,14 +41862,18 @@ function unpackError(entry, packPath, e) {
41782
41862
  };
41783
41863
  }
41784
41864
  const enc = new TextEncoder();
41785
- /** The git object id of `content` as `type`: SHA-1 over its header and content, as hex. */
41786
- function objectIdOf(type, content) {
41865
+ /**
41866
+ * The git object id of `content` as `type`: SHA-1 (or `newHasher`'s hash) over its header and
41867
+ * content, as hex.
41868
+ */
41869
+ function objectIdOf(type, content, newHasher) {
41787
41870
  let n = 0;
41788
41871
  for (let i = 0; i < type.length; i++) header[n++] = type.charCodeAt(i);
41789
41872
  header[n++] = 32;
41790
41873
  const size = String(content.length);
41791
41874
  for (let i = 0; i < size.length; i++) header[n++] = size.charCodeAt(i);
41792
41875
  header[n++] = 0;
41876
+ if (newHasher) return bytesToHex$2(newHasher().update(header.subarray(0, n)).update(content).digest());
41793
41877
  return bytesToHex$2(sha1Of$1(header.subarray(0, n), content));
41794
41878
  }
41795
41879
  function cannotUnpack(entry, packPath) {
@@ -41806,14 +41890,14 @@ const FSCK_ERROR_REFS = 8;
41806
41890
  const FSCK_ERROR_COMMIT_GRAPH = 16;
41807
41891
  /** `git multi-pack-index verify` failed, in git 2.43 (its ERROR_MULTI_PACK_INDEX; 2.5x: object bit). */
41808
41892
  const FSCK_ERROR_MULTI_PACK_INDEX_243 = 32;
41893
+ /** A pack's `.rev` file is invalid, in git 2.43 (its ERROR_PACK_REV_INDEX; 2.5x: object bit). */
41894
+ const FSCK_ERROR_PACK_REV_INDEX_243 = 64;
41809
41895
  /** A bitmap file's checksum is wrong, in git 2.43 (its ERROR_BITMAP; 2.5x sets the object bit). */
41810
41896
  const FSCK_ERROR_BITMAP_243 = 128;
41811
41897
  const DEFAULT_LINKS_KEPT = 33554432;
41812
41898
  const DEFAULT_GRAPH_COMMITS_KEPT = 262144;
41813
- const ZERO_ID$2 = "0000000000000000000000000000000000000000";
41814
- const OID = /^[0-9a-f]{40}$/;
41815
- const LOOSE_NAME = /^[0-9a-f]{38}$/;
41816
- const PACK_IDX = /^pack-[0-9a-f]{40}\.idx$/;
41899
+ const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
41900
+ const PACK_IDX = /^pack-(?:[0-9a-f]{40}|[0-9a-f]{64})\.idx$/;
41817
41901
  /** Refs one worktree has of its own (git's `is_per_worktree_ref`). */
41818
41902
  const PER_WORKTREE = /^(?:refs\/(?:bisect|worktree|rewritten)\/|[A-Z_]+$)/;
41819
41903
  const dec = new TextDecoder();
@@ -42106,7 +42190,13 @@ var FsckRun = class {
42106
42190
  objects;
42107
42191
  types;
42108
42192
  o;
42109
- t = new ObjectTable();
42193
+ t;
42194
+ /** The repository's object format: its ids' lengths in trees, commits, tags and names */
42195
+ format;
42196
+ /** Whether the format is SHA-1 (its own fast hash paths) */
42197
+ sha1;
42198
+ /** A loose object's file name: the id after its fan-out directory (38 or 62 digits) */
42199
+ looseName;
42110
42200
  findings = [];
42111
42201
  errorsFound = 0;
42112
42202
  pending = [];
@@ -42167,7 +42257,7 @@ var FsckRun = class {
42167
42257
  */
42168
42258
  badCopy = /* @__PURE__ */ new Set();
42169
42259
  /** Where an id parsed from hex is written for a lookup. */
42170
- idScratch = /* @__PURE__ */ new Uint8Array(20);
42260
+ idScratch;
42171
42261
  /**
42172
42262
  * The object `parseObject` read last: the connectivity walk of a tree it parsed walks these
42173
42263
  * bytes instead of reading the tree again (git's parse_tree reads it once).
@@ -42209,15 +42299,30 @@ var FsckRun = class {
42209
42299
  this.objects = objects;
42210
42300
  this.types = types;
42211
42301
  this.o = o;
42302
+ this.format = objectFormatOf(objects);
42303
+ this.sha1 = this.format.name === "sha1";
42304
+ this.t = new ObjectTable(this.format.rawLength);
42305
+ this.idScratch = new Uint8Array(this.format.rawLength);
42306
+ this.looseName = new RegExp(`^[0-9a-f]{${this.format.hexLength - 2}}$`);
42212
42307
  if (o.nameObjects) this.names = /* @__PURE__ */ new Map();
42213
42308
  this.showUnreachable = o.unreachable;
42214
42309
  this.recordTrees = !o.connectivityOnly && !o.nameObjects;
42215
42310
  this.files = o.repository?.files;
42216
42311
  this.gitDir = (o.repository?.gitDir ?? ".git").replace(/\/+$/, "");
42217
42312
  }
42313
+ /** The commit-graph read settings, in the repository's object format. */
42314
+ get graphSettings() {
42315
+ return {
42316
+ ...this.o.commitGraph,
42317
+ objectFormat: this.format
42318
+ };
42319
+ }
42218
42320
  async run() {
42219
42321
  if (this.files && this.o.multiPackIndex !== false) {
42220
- const loaded = await loadMultiPackIndex(this.files, pathOf(this.looseDir(), "pack"), { compatibility: this.o.compatibility });
42322
+ const loaded = await loadMultiPackIndex(this.files, pathOf(this.looseDir(), "pack"), {
42323
+ compatibility: this.o.compatibility,
42324
+ objectFormat: this.format
42325
+ });
42221
42326
  if (loaded.fatal) return this.death(loaded.errors);
42222
42327
  const bad = loaded.midx && badPackIntIdAt(loaded.midx);
42223
42328
  if (bad && loaded.midx) this.midxBadEntry = {
@@ -42259,6 +42364,7 @@ var FsckRun = class {
42259
42364
  else {
42260
42365
  const packs = step.packs.map((k) => this.packs[k]);
42261
42366
  await this.fsckPacks(packs);
42367
+ if (this.o.compatibility === "2.56" && await this.verifyReverseIndexes(packs)) this.errorsFound |= 1;
42262
42368
  if (this.o.compatibility === "2.56" && await this.verifyBitmapFiles(packs, step.dir ?? this.looseDir())) this.errorsFound |= 1;
42263
42369
  if (this.o.compatibility === "2.56" && await this.verifyMultiPackIndex(step.dir)) this.errorsFound |= 1;
42264
42370
  }
@@ -42306,6 +42412,7 @@ var FsckRun = class {
42306
42412
  }
42307
42413
  }
42308
42414
  await this.verifyCommitGraph();
42415
+ if (this.files && this.o.compatibility === "2.43" && await this.verifyReverseIndexes(this.packs)) this.errorsFound |= 64;
42309
42416
  if (this.files && this.o.compatibility === "2.43" && await this.verifyBitmapFiles(this.packs)) this.errorsFound |= 128;
42310
42417
  if (this.files && this.o.compatibility === "2.43") {
42311
42418
  for (const dir of this.sourceDirs()) if (await this.verifyMultiPackIndex(dir)) this.errorsFound |= 32;
@@ -42405,12 +42512,13 @@ var FsckRun = class {
42405
42512
  * stderr follows, and a failure sets ERROR_COMMIT_GRAPH.
42406
42513
  */
42407
42514
  async verifyCommitGraph() {
42408
- const settings = this.o.commitGraph;
42515
+ const settings = this.graphSettings;
42409
42516
  if (!this.files || !settings.enabled) return;
42410
42517
  if (await this.hasRefs() && await commitGraphCompatible({
42411
42518
  files: this.files,
42412
42519
  gitDir: this.gitDir,
42413
42520
  useReplaceRefs: false,
42521
+ objectFormat: this.format,
42414
42522
  readGraftFile: () => this.graftFileText()
42415
42523
  })) for (const dir of this.sourceDirs()) {
42416
42524
  const read = await readCommitGraph(this.files, dir, settings, this.sourceDirs());
@@ -42425,7 +42533,7 @@ var FsckRun = class {
42425
42533
  }
42426
42534
  /** One `git commit-graph verify --object-dir <objectsDir>` child of fsck. */
42427
42535
  async verifySourceCommitGraph(objectsDir) {
42428
- const settings = this.o.commitGraph;
42536
+ const settings = this.graphSettings;
42429
42537
  if (!this.files) return;
42430
42538
  const packs = this.packs;
42431
42539
  const mru = [...packs];
@@ -42484,7 +42592,7 @@ var FsckRun = class {
42484
42592
  const parse = (o, data) => {
42485
42593
  if (o?.type !== "commit") return void 0;
42486
42594
  reachGrafts(note, data);
42487
- return parseGraphCommit(data, id);
42595
+ return parseGraphCommit(data, id, this.format);
42488
42596
  };
42489
42597
  const slow = async (o) => {
42490
42598
  try {
@@ -42513,7 +42621,7 @@ var FsckRun = class {
42513
42621
  if (obj?.type !== "commit") return void 0;
42514
42622
  const data = await collect$1(obj);
42515
42623
  parsing(data);
42516
- return parseGraphCommit(data, id);
42624
+ return parseGraphCommit(data, id, this.format);
42517
42625
  } catch {
42518
42626
  return;
42519
42627
  }
@@ -42539,7 +42647,7 @@ var FsckRun = class {
42539
42647
  const map = this.graphCommits;
42540
42648
  if (!map || this.graphCommitsKept >= this.o.graphCommitsKept || map.has(id)) return;
42541
42649
  try {
42542
- map.set(id, parseGraphCommit(content, id));
42650
+ map.set(id, parseGraphCommit(content, id, this.format));
42543
42651
  this.graphCommitsKept++;
42544
42652
  } catch {
42545
42653
  map.set(id, null);
@@ -42556,13 +42664,14 @@ var FsckRun = class {
42556
42664
  * loads. Undefined otherwise: commits are read from the object store.
42557
42665
  */
42558
42666
  async loadCommitGraph() {
42559
- const settings = this.o.commitGraph;
42667
+ const settings = this.graphSettings;
42560
42668
  if (!this.files || !settings.enabled) return void 0;
42561
42669
  try {
42562
42670
  if (!await commitGraphCompatible({
42563
42671
  files: this.files,
42564
42672
  gitDir: this.gitDir,
42565
42673
  useReplaceRefs: false,
42674
+ objectFormat: this.format,
42566
42675
  readGraftFile: () => this.graftFileText()
42567
42676
  })) return;
42568
42677
  for (const dir of this.sourceDirs()) {
@@ -42871,13 +42980,14 @@ var FsckRun = class {
42871
42980
  const found = [];
42872
42981
  for await (const e of files.list(dir)) {
42873
42982
  if (e.kind !== "file" || !PACK_IDX.test(e.name)) continue;
42983
+ if (e.name.length !== 9 + this.format.hexLength) continue;
42874
42984
  const idxPath = pathOf(dir, e.name);
42875
42985
  const packPath = `${idxPath.slice(0, -4)}.pack`;
42876
42986
  const stats = await files.stats(packPath);
42877
42987
  if (stats?.kind !== "file") continue;
42878
42988
  try {
42879
42989
  const idxBytes = await readAll(files, idxPath);
42880
- const idx = readPackIndex(idxBytes);
42990
+ const idx = readPackIndex(idxBytes, this.format.rawLength);
42881
42991
  found.push({
42882
42992
  packPath,
42883
42993
  idxPath,
@@ -42908,7 +43018,7 @@ var FsckRun = class {
42908
43018
  });
42909
43019
  for (const e of entries) {
42910
43020
  const path = pathOf(dir, e.name);
42911
- yield LOOSE_NAME.test(e.name) ? {
43021
+ yield this.looseName.test(e.name) ? {
42912
43022
  id: sub + e.name,
42913
43023
  path,
42914
43024
  name: e.name
@@ -42939,10 +43049,11 @@ var FsckRun = class {
42939
43049
  * each pack's in idx order (git's for_each_*_object). A pack's ids are read from its idx.
42940
43050
  */
42941
43051
  async forEachStored(visit) {
42942
- const scratch = /* @__PURE__ */ new Uint8Array(20);
43052
+ const raw = this.format.rawLength;
43053
+ const scratch = new Uint8Array(raw);
42943
43054
  const nibble = (c) => c <= 57 ? c - 48 : c - 87;
42944
43055
  const parsed = (id) => {
42945
- for (let i = 0; i < 20; i++) scratch[i] = nibble(id.charCodeAt(2 * i)) << 4 | nibble(id.charCodeAt(2 * i + 1));
43056
+ for (let i = 0; i < raw; i++) scratch[i] = nibble(id.charCodeAt(2 * i)) << 4 | nibble(id.charCodeAt(2 * i + 1));
42946
43057
  return scratch;
42947
43058
  };
42948
43059
  if (!this.files) {
@@ -42996,7 +43107,7 @@ var FsckRun = class {
42996
43107
  if (type === 1) {
42997
43108
  if (this.graftsHint) this.adviseGrafts();
42998
43109
  if (this.graftErrors.length > 0) this.reportGraftErrors();
42999
- const parsed = parseCommitLinks(content, id);
43110
+ const parsed = parseCommitLinks(content, id, this.format);
43000
43111
  if ("error" in parsed) {
43001
43112
  this.error(parsed.error, id);
43002
43113
  return;
@@ -43005,7 +43116,7 @@ var FsckRun = class {
43005
43116
  const tree = t.lookupTypedRaw(rawIdAt(content, parsed.tree, raw), 0, 2);
43006
43117
  if (typeof tree !== "number") {
43007
43118
  this.error(tree.error);
43008
- this.error(`bad tree pointer ${hexIdAt(content, parsed.tree)} in commit ${id}`, id);
43119
+ this.error(`bad tree pointer ${hexIdAt(content, parsed.tree, this.format)} in commit ${id}`, id);
43009
43120
  return;
43010
43121
  }
43011
43122
  const parents = [];
@@ -43023,7 +43134,7 @@ var FsckRun = class {
43023
43134
  const parent = t.lookupTypedRaw(rawIdAt(content, at, raw), 0, 1);
43024
43135
  if (typeof parent !== "number") {
43025
43136
  this.error(parent.error);
43026
- this.error(`bad parent ${hexIdAt(content, at)} in commit ${id}`, id);
43137
+ this.error(`bad parent ${hexIdAt(content, at, this.format)} in commit ${id}`, id);
43027
43138
  return;
43028
43139
  }
43029
43140
  parents.push(parent);
@@ -43035,7 +43146,7 @@ var FsckRun = class {
43035
43146
  t.addFlags(n, 16);
43036
43147
  return n;
43037
43148
  }
43038
- const parsed = parseTagBuffer(content, id);
43149
+ const parsed = parseTagBuffer(content, id, this.format);
43039
43150
  if ("error" in parsed) {
43040
43151
  if (parsed.error) this.error(parsed.error, id);
43041
43152
  return;
@@ -43074,7 +43185,7 @@ var FsckRun = class {
43074
43185
  * the store: a verified read would mark the copy bad there, and git reads it again as it is.
43075
43186
  */
43076
43187
  parseVerified(id, obj) {
43077
- if (obj && objectIdOf(obj.type, obj.content) !== id) {
43188
+ if (obj && objectIdOf(obj.type, obj.content, this.sha1 ? void 0 : this.format.createHasher) !== id) {
43078
43189
  this.error(`hash mismatch ${id}`, id);
43079
43190
  return;
43080
43191
  }
@@ -43204,7 +43315,7 @@ var FsckRun = class {
43204
43315
  const t = this.t;
43205
43316
  const type = t.type(n);
43206
43317
  if (type === 2) {
43207
- const walk = scanTree(content, this.usedTable);
43318
+ const walk = scanTree(content, this.usedTable, this.format);
43208
43319
  this.lastTree = {
43209
43320
  content,
43210
43321
  table: walk
@@ -43259,13 +43370,16 @@ var FsckRun = class {
43259
43370
  };
43260
43371
  const last = this.lastTree;
43261
43372
  this.lastTree = void 0;
43262
- const r = fsckTree(content, this.types, report, (m) => this.error(m), found, last?.content === content ? last.table : void 0);
43373
+ const r = fsckTree(content, this.types, report, (m) => this.error(m), found, last?.content === content ? last.table : void 0, this.format);
43263
43374
  for (const g of found.gitmodules) this.gitmodulesFound.add(g);
43264
43375
  for (const g of found.gitattributes) this.gitattributesFound.add(g);
43265
43376
  return r;
43266
43377
  }
43267
- case 1: return fsckCommit(content, report);
43268
- case 4: return fsckTag(content, report, { gpgsig: this.o.compatibility !== "2.43" });
43378
+ case 1: return fsckCommit(content, report, this.format);
43379
+ case 4: return fsckTag(content, report, {
43380
+ gpgsig: this.o.compatibility !== "2.43",
43381
+ shape: this.format
43382
+ });
43269
43383
  default: return report("unknownType", `unknown type '${type}' (internal fsck error)`);
43270
43384
  }
43271
43385
  }
@@ -43318,7 +43432,10 @@ var FsckRun = class {
43318
43432
  });
43319
43433
  continue;
43320
43434
  }
43321
- const read = await readLooseObject(files, e.path, e.id, { bigFileThreshold: this.o.bigFileThreshold });
43435
+ const read = await readLooseObject(files, e.path, e.id, {
43436
+ bigFileThreshold: this.o.bigFileThreshold,
43437
+ newHasher: this.format.createHasher
43438
+ });
43322
43439
  for (const m of read.errors) this.error(m, e.id);
43323
43440
  if (read.errors.length > 0) this.badCopy.add(e.id);
43324
43441
  if (!read.object) {
@@ -43332,15 +43449,33 @@ var FsckRun = class {
43332
43449
  }
43333
43450
  }
43334
43451
  /**
43335
- * git's `verify_bitmap_files`: the trailing SHA-1 of each pack's `.bitmap` (a missing file
43336
- * is fine). True if one is wrong.
43452
+ * git's check of each pack's `.rev` (`verify_reverse_indices`; 2.43's
43453
+ * check_pack_rev_indexes): a missing file is fine. True if one is wrong.
43454
+ */
43455
+ async verifyReverseIndexes(packs) {
43456
+ const files = this.files;
43457
+ let bad = false;
43458
+ for (const p of packs) {
43459
+ const lines = await verifyReverseIndexFile(files, p.packPath, p.idx.objectCount, (i) => p.idx.getOffset(i), this.format);
43460
+ if (!lines) continue;
43461
+ for (const line of lines) this.error(line.replace(/^error: /, ""));
43462
+ bad = true;
43463
+ }
43464
+ return bad;
43465
+ }
43466
+ /**
43467
+ * git's `verify_bitmap_files`: the trailing hash (SHA-1, or SHA-256 in a SHA-256 repository)
43468
+ * of each pack's `.bitmap` (a missing file is fine). True if one is wrong.
43337
43469
  */
43338
43470
  async verifyBitmapFiles(packs, objectsDir = this.looseDir()) {
43339
43471
  const files = this.files;
43340
43472
  let bad = false;
43341
43473
  const paths = [];
43342
43474
  if (this.o.multiPackIndex !== false) {
43343
- const loaded = await loadMultiPackIndex(files, pathOf(objectsDir, "pack"), { compatibility: this.o.compatibility });
43475
+ const loaded = await loadMultiPackIndex(files, pathOf(objectsDir, "pack"), {
43476
+ compatibility: this.o.compatibility,
43477
+ objectFormat: this.format
43478
+ });
43344
43479
  if (loaded.midx) paths.push(pathOf(objectsDir, "pack", `multi-pack-index-${loaded.midx.checksum}.bitmap`));
43345
43480
  }
43346
43481
  for (const p of packs) paths.push(`${p.packPath.replace(/\.pack$/, "")}.bitmap`);
@@ -43348,20 +43483,21 @@ var FsckRun = class {
43348
43483
  const st = await files.stats(path).catch(() => void 0);
43349
43484
  if (st?.kind !== "file") continue;
43350
43485
  const size = st.size ?? 0;
43351
- let valid = size >= 20;
43486
+ const raw = this.format.rawLength;
43487
+ let valid = size >= raw;
43352
43488
  if (valid) {
43353
- const hasher = createSha1$1();
43489
+ const hasher = this.format.createHasher();
43354
43490
  for await (const c of files.read(path, {
43355
43491
  start: 0,
43356
- length: size - 20
43492
+ length: size - raw
43357
43493
  })) hasher.update(c);
43358
43494
  const sum = hasher.digest();
43359
43495
  const tail = [];
43360
43496
  for await (const c of files.read(path, {
43361
- start: size - 20,
43362
- length: 20
43497
+ start: size - raw,
43498
+ length: raw
43363
43499
  })) tail.push(...c);
43364
- valid = tail.length === 20 && sum.every((b, i) => b === tail[i]);
43500
+ valid = tail.length === raw && sum.every((b, i) => b === tail[i]);
43365
43501
  }
43366
43502
  if (!valid) {
43367
43503
  this.error(`bitmap file '${path}' has invalid checksum`);
@@ -43416,7 +43552,8 @@ var FsckRun = class {
43416
43552
  bytes: p.idxBytes,
43417
43553
  idx: p.idx
43418
43554
  },
43419
- keepBlob: this.keepBlob
43555
+ keepBlob: this.keepBlob,
43556
+ ...this.sha1 ? {} : { objectFormat: this.format }
43420
43557
  })).failed) err = 1;
43421
43558
  if (err) this.errorsFound |= this.o.compatibility === "2.56" ? 1 : 4;
43422
43559
  }
@@ -43558,7 +43695,7 @@ var FsckRun = class {
43558
43695
  }
43559
43696
  /** git's `fsck_handle_reflog_oid`. */
43560
43697
  async handleReflogOid(refname, id, timestamp) {
43561
- if (id === ZERO_ID$2) return;
43698
+ if (isNullObjectId$1(id)) return;
43562
43699
  const n = this.t.lookup(id);
43563
43700
  if (n >= 0 && this.t.flags(n) & 4) {
43564
43701
  if (timestamp) this.putName(id, `${refname}@{${timestamp}}`);
@@ -43575,9 +43712,9 @@ var FsckRun = class {
43575
43712
  */
43576
43713
  async resolvedId(name) {
43577
43714
  try {
43578
- return (await this.followChain(name, 0))?.id || ZERO_ID$2;
43715
+ return (await this.followChain(name, 0))?.id || this.format.nullId;
43579
43716
  } catch {
43580
- return ZERO_ID$2;
43717
+ return this.format.nullId;
43581
43718
  }
43582
43719
  }
43583
43720
  /** git's `get_default_heads`. */
@@ -43631,7 +43768,7 @@ var FsckRun = class {
43631
43768
  for (const name of [...new Set(listed)]) await snapshotRef(name, await this.resolvedId(name));
43632
43769
  for (const wt of await this.worktrees()) {
43633
43770
  const id = await this.headId(wt);
43634
- if (id && id !== ZERO_ID$2) await snapshotRef(wt.headName, id);
43771
+ if (id && !isNullObjectId$1(id)) await snapshotRef(wt.headName, id);
43635
43772
  }
43636
43773
  return snapshot;
43637
43774
  }
@@ -43668,8 +43805,8 @@ var FsckRun = class {
43668
43805
  }
43669
43806
  /** What a worktree's HEAD resolves to, if anything (within git's 5 reads, HEAD's included). */
43670
43807
  async headId(wt) {
43671
- if (wt.current) {
43672
- const head = await this.stores.refs.get("HEAD");
43808
+ if (wt.current || this.isReftable()) {
43809
+ const head = await this.repositoryRefs().get(wt.headName);
43673
43810
  if (!head) return void 0;
43674
43811
  if (!isSymbolicRef(head)) return head.objectId;
43675
43812
  return (await this.followChain(head.target, 1))?.id;
@@ -43677,7 +43814,8 @@ var FsckRun = class {
43677
43814
  const text = (await readText$2(this.files, pathOf(wt.dir, "HEAD")))?.trim();
43678
43815
  if (!text) return void 0;
43679
43816
  if (text.startsWith("ref:")) return (await this.followChain(text.slice(4).trim(), 1))?.id;
43680
- return OID.test(text.slice(0, 40)) ? text.slice(0, 40) : void 0;
43817
+ const id = text.slice(0, this.format.hexLength);
43818
+ return OID.test(id) ? id : void 0;
43681
43819
  }
43682
43820
  /**
43683
43821
  * Whether the ref of the reflog `logName` is a symbolic ref chain deeper than git's 5 reads
@@ -43691,6 +43829,10 @@ var FsckRun = class {
43691
43829
  }
43692
43830
  if (logName.startsWith("worktrees/")) {
43693
43831
  if (!wt.dir || !logName.endsWith("/HEAD") || logName.split("/").length !== 3) return false;
43832
+ if (this.isReftable()) {
43833
+ const head = await this.repositoryRefs().get(logName);
43834
+ return !!head && isSymbolicRef(head) && !await this.followChain(head.target, 1);
43835
+ }
43694
43836
  const text = (await readText$2(this.files, pathOf(wt.dir, "HEAD")))?.trim();
43695
43837
  return !!text?.startsWith("ref:") && !await this.followChain(text.slice(4).trim(), 1);
43696
43838
  }
@@ -43699,6 +43841,19 @@ var FsckRun = class {
43699
43841
  return false;
43700
43842
  }
43701
43843
  }
43844
+ /**
43845
+ * The refs of the repository's own git directory: a reftable store opened for a linked
43846
+ * worktree reads that worktree's HEAD, so fsck asks the repository's store
43847
+ * (`ReftableRefStore.repositoryStore`) for the main worktree's; other stores as they are.
43848
+ */
43849
+ repositoryRefs() {
43850
+ const refs = this.stores.refs;
43851
+ return refs.repositoryStore?.() ?? refs;
43852
+ }
43853
+ /** Whether the refs are a reftable store (whose linked worktrees' HEADs are in their stacks). */
43854
+ isReftable() {
43855
+ return "reflogNames" in this.stores.refs;
43856
+ }
43702
43857
  /** The main worktree, then the linked ones (`.git/worktrees/<id>`). */
43703
43858
  async worktrees() {
43704
43859
  const list = [{
@@ -43750,7 +43905,12 @@ var FsckRun = class {
43750
43905
  };
43751
43906
  let symref;
43752
43907
  if (wt.current) {
43753
- const head = await this.stores.refs.get("HEAD");
43908
+ const head = await this.repositoryRefs().get("HEAD");
43909
+ if (!head) return invalid();
43910
+ if (isSymbolicRef(head)) symref = head.target;
43911
+ else id = head.objectId;
43912
+ } else if (this.isReftable()) {
43913
+ const head = await this.repositoryRefs().get(name);
43754
43914
  if (!head) return invalid();
43755
43915
  if (isSymbolicRef(head)) symref = head.target;
43756
43916
  else id = head.objectId;
@@ -43758,7 +43918,7 @@ var FsckRun = class {
43758
43918
  const text = (await readText$2(this.files, pathOf(wt.dir, "HEAD")))?.trim();
43759
43919
  if (!text) return invalid();
43760
43920
  if (text.startsWith("ref:")) symref = text.slice(4).trim();
43761
- else if (OID.test(text.slice(0, 40))) id = text.slice(0, 40);
43921
+ else if (OID.test(text.slice(0, this.format.hexLength))) id = text.slice(0, this.format.hexLength);
43762
43922
  else return invalid();
43763
43923
  }
43764
43924
  if (symref !== void 0) {
@@ -43770,10 +43930,10 @@ var FsckRun = class {
43770
43930
  if (target !== void 0 && !target.startsWith("refs/heads/")) {
43771
43931
  this.errorsFound |= 8;
43772
43932
  this.error(`${name} points to something strange (${target})`);
43773
- if (id && id !== ZERO_ID$2) await this.handleRef(name, id);
43933
+ if (id && !isNullObjectId$1(id)) await this.handleRef(name, id);
43774
43934
  return;
43775
43935
  }
43776
- if (!id || id === ZERO_ID$2) {
43936
+ if (!id || isNullObjectId$1(id)) {
43777
43937
  if (target === void 0) {
43778
43938
  this.errorsFound |= 8;
43779
43939
  this.error(`${name}: detached HEAD points at nothing`);
@@ -43791,6 +43951,12 @@ var FsckRun = class {
43791
43951
  /** The reflogs of one worktree, in git's order (sorted by name, as git 2.45+ lists them). */
43792
43952
  async reflogs(wt) {
43793
43953
  const files = this.files;
43954
+ const reftable = this.repositoryRefs();
43955
+ if (reftable.reflogNames) {
43956
+ const dir = wt.dir;
43957
+ const id = wt.current ? void 0 : dir.slice(dir.lastIndexOf("/") + 1);
43958
+ return this.storeReflogs(await reftable.reflogNames(id), this.repositoryRefs());
43959
+ }
43794
43960
  if (!files) return wt.current ? this.storeReflogs() : [];
43795
43961
  const logs = [];
43796
43962
  const collectDir = async (base, keep, prefix) => {
@@ -43813,7 +43979,7 @@ var FsckRun = class {
43813
43979
  for (const f of found) logs.push({
43814
43980
  name: prefix + f.name,
43815
43981
  path: pathOf(base, f.name),
43816
- entries: parseReflog(await readText$2(files, f.path))
43982
+ entries: parseReflog(await readText$2(files, f.path), this.format.hexLength)
43817
43983
  });
43818
43984
  };
43819
43985
  if (wt.current) await collectDir(pathOf(this.gitDir, "logs"), () => true, "");
@@ -43831,12 +43997,14 @@ var FsckRun = class {
43831
43997
  return logs;
43832
43998
  }
43833
43999
  /** Reflogs through the refs store (a store without files): HEAD and every ref. */
43834
- async storeReflogs() {
43835
- const refs = this.stores.refs;
44000
+ async storeReflogs(listed, refs = this.stores.refs) {
43836
44001
  if (!refs.getReflog) return [];
43837
- const names = ["HEAD"];
43838
- for await (const ref of refs.list("refs/")) names.push(ref.name);
43839
- const sorted = [...new Set(names)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
44002
+ let sorted = listed;
44003
+ if (!sorted) {
44004
+ const names = ["HEAD"];
44005
+ for await (const ref of refs.list("refs/")) names.push(ref.name);
44006
+ sorted = [...new Set(names)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
44007
+ }
43840
44008
  const logs = [];
43841
44009
  for (const name of sorted) {
43842
44010
  const reader = await refs.getReflog(name);
@@ -43874,12 +44042,16 @@ var FsckRun = class {
43874
44042
  read = await readIndexFileEntries(files, indexPath, {
43875
44043
  gitDir: wt.dir,
43876
44044
  trees: this.stores.trees(),
43877
- verifyChecksum: true
44045
+ verifyChecksum: true,
44046
+ objectFormat: this.format
43878
44047
  });
43879
44048
  } catch (error) {
43880
44049
  if (error instanceof IndexCorruptError) return error.lines;
43881
44050
  try {
43882
- read = await readIndexFileEntries(files, indexPath, { gitDir: wt.dir });
44051
+ read = await readIndexFileEntries(files, indexPath, {
44052
+ gitDir: wt.dir,
44053
+ objectFormat: this.format
44054
+ });
43883
44055
  } catch (again) {
43884
44056
  if (again instanceof IndexCorruptError) return again.lines;
43885
44057
  throw again;
@@ -43898,8 +44070,11 @@ var FsckRun = class {
43898
44070
  }));
43899
44071
  let cacheTree;
43900
44072
  let resolveUndo = [];
43901
- for (const ext of parsed.extensionData) if (ext.signature === "TREE") cacheTree = parseCacheTree(ext.data);
43902
- else if (ext.signature === "REUC") resolveUndo = parseResolveUndo(ext.data);
44073
+ for (const ext of parsed.extensionData) {
44074
+ const raw = this.format.rawLength;
44075
+ if (ext.signature === "TREE") cacheTree = parseCacheTree(ext.data, raw);
44076
+ else if (ext.signature === "REUC") resolveUndo = parseResolveUndo(ext.data, raw);
44077
+ }
43903
44078
  await this.fsckIndex(entries, cacheTree, resolveUndo, indexPath, prefix);
43904
44079
  }
43905
44080
  }
@@ -43993,8 +44168,9 @@ var FsckRun = class {
43993
44168
  const n = ns[pos];
43994
44169
  if (type === 1 && decided && !decided[n]) {
43995
44170
  decided[n] = 1;
43996
- const at = p.idx.version > 1 ? 1032 + pos * 20 : 1028 + pos * 24;
43997
- this.keepGraphCommit(bytesToHex$2(p.idxBytes.subarray(at, at + 20)), content);
44171
+ const raw = this.format.rawLength;
44172
+ const at = p.idx.version > 1 ? 1032 + pos * raw : 1028 + pos * (raw + 4);
44173
+ this.keepGraphCommit(bytesToHex$2(p.idxBytes.subarray(at, at + raw)), content);
43998
44174
  }
43999
44175
  if (type === 1 && !withCommits) return;
44000
44176
  if (claimed[n]) return;
@@ -44021,12 +44197,13 @@ var FsckRun = class {
44021
44197
  let at = start + 1;
44022
44198
  if (type === 2) {
44023
44199
  const len = content.length;
44024
- if (len > 0 && (len < 23 || content[len - 21] !== 0)) return true;
44025
- if (!this.reserveScanKids(1 + Math.floor(len / 23))) return false;
44200
+ const raw = this.format.rawLength;
44201
+ if (len > 0 && (len < raw + 3 || content[len - raw - 1] !== 0)) return true;
44202
+ if (!this.reserveScanKids(1 + Math.floor(len / (raw + 3)))) return false;
44026
44203
  const kids = this.scanKids;
44027
44204
  let p = 0;
44028
44205
  while (p < len) {
44029
- if (len - p < 23 || content[p] === 32) return true;
44206
+ if (len - p < raw + 3 || content[p] === 32) return true;
44030
44207
  let mode = 0;
44031
44208
  for (;;) {
44032
44209
  const c = content[p++];
@@ -44036,9 +44213,9 @@ var FsckRun = class {
44036
44213
  }
44037
44214
  if (content[p] === 0) return true;
44038
44215
  while (p < len && content[p] !== 0) p++;
44039
- if (p + 21 > len) return true;
44216
+ if (p + 1 + raw > len) return true;
44040
44217
  const idAt = p + 1;
44041
- p = idAt + 20;
44218
+ p = idAt + raw;
44042
44219
  const format = mode & 61440;
44043
44220
  if (format !== 32768 && format !== 40960 && format !== 16384) continue;
44044
44221
  const c = t.peekRaw(content, idAt);
@@ -44046,7 +44223,7 @@ var FsckRun = class {
44046
44223
  kids[at++] = c << 1 | (format === 16384 ? 1 : 0);
44047
44224
  }
44048
44225
  } else {
44049
- const parsed = parseCommitLinks(content, "");
44226
+ const parsed = parseCommitLinks(content, "", this.format);
44050
44227
  if ("error" in parsed) return true;
44051
44228
  if (!this.reserveScanKids(2 + parsed.parents.length)) return false;
44052
44229
  const kids = this.scanKids;
@@ -44186,7 +44363,7 @@ var FsckRun = class {
44186
44363
  return;
44187
44364
  }
44188
44365
  t.addFlags(n, 16);
44189
- const walk = scanTree(obj.content, this.walkTable);
44366
+ const walk = scanTree(obj.content, this.walkTable, this.format);
44190
44367
  if (walk.initError) {
44191
44368
  this.error(walk.initError);
44192
44369
  return;
@@ -44426,14 +44603,14 @@ async function readText$2(files, path) {
44426
44603
  return dec.decode(await readAll(files, path));
44427
44604
  }
44428
44605
  /** The entries of a reflog file, oldest first: old id, new id and the entry's timestamp. */
44429
- function parseReflog(text) {
44606
+ function parseReflog(text, hex = 40) {
44430
44607
  const entries = [];
44431
44608
  for (const line of text?.split("\n") ?? []) {
44432
- const oldId = line.slice(0, 40);
44433
- const newId = line.slice(41, 81);
44609
+ const oldId = line.slice(0, hex);
44610
+ const newId = line.slice(hex + 1, 2 * hex + 1);
44434
44611
  if (!OID.test(oldId) || !OID.test(newId)) continue;
44435
44612
  const tab = line.indexOf(" ");
44436
- const ident = tab < 0 ? line.slice(82) : line.slice(82, tab);
44613
+ const ident = tab < 0 ? line.slice(2 * hex + 2) : line.slice(2 * hex + 2, tab);
44437
44614
  const m = /> (\d+) [+-]\d{4}$/.exec(ident);
44438
44615
  entries.push({
44439
44616
  oldId,
@@ -44508,7 +44685,7 @@ var VerifyPackCommand = class extends GitCommand {
44508
44685
  let exitCode = 0;
44509
44686
  for (const path of this._packs) {
44510
44687
  const base = path.endsWith(".idx") ? path.slice(0, -4) : path.endsWith(".pack") ? path.slice(0, -5) : path;
44511
- const report = await verifyOnePack(files, `${base}.pack`, `${base}.idx`);
44688
+ const report = await verifyOnePack(files, `${base}.pack`, `${base}.idx`, this.objectFormat);
44512
44689
  packs.push(report);
44513
44690
  for (const e of report.errors) err.push(`${e}\n`);
44514
44691
  if (report.ok && (this._verbose || this._statOnly)) {
@@ -44537,7 +44714,7 @@ var VerifyPackCommand = class extends GitCommand {
44537
44714
  }
44538
44715
  };
44539
44716
  const noBlob = () => false;
44540
- async function verifyOnePack(files, packPath, idxPath) {
44717
+ async function verifyOnePack(files, packPath, idxPath, objectFormat) {
44541
44718
  const errors = [];
44542
44719
  const report = {
44543
44720
  pack: packPath,
@@ -44584,7 +44761,10 @@ async function verifyOnePack(files, packPath, idxPath) {
44584
44761
  ok = false;
44585
44762
  });
44586
44763
  }
44587
- }, { keepBlob: noBlob });
44764
+ }, {
44765
+ keepBlob: noBlob,
44766
+ ...objectFormat.name === "sha1" ? {} : { objectFormat }
44767
+ });
44588
44768
  if (!result.opened) return report;
44589
44769
  if (result.failed) ok = false;
44590
44770
  const depth = (id) => {
@@ -44623,12 +44803,14 @@ var fsck_exports = /* @__PURE__ */ __exportAll({
44623
44803
  FSCK_ERROR_MULTI_PACK_INDEX_243: () => 32,
44624
44804
  FSCK_ERROR_OBJECT: () => 1,
44625
44805
  FSCK_ERROR_PACK: () => 4,
44806
+ FSCK_ERROR_PACK_REV_INDEX_243: () => 64,
44626
44807
  FSCK_ERROR_REACHABLE: () => 2,
44627
44808
  FSCK_ERROR_REFS: () => 8,
44628
44809
  FSCK_MSG_IDS: () => FSCK_MSG_IDS,
44629
44810
  FsckCommand: () => FsckCommand,
44630
44811
  FsckConfigError: () => FsckConfigError,
44631
44812
  FsckMessageTypes: () => FsckMessageTypes,
44813
+ SHA1_ID_SHAPE: () => SHA1_ID_SHAPE,
44632
44814
  UnknownFsckMsgIdError: () => UnknownFsckMsgIdError,
44633
44815
  VerifyPackCommand: () => VerifyPackCommand,
44634
44816
  canonMode: () => canonMode,
@@ -45203,6 +45385,7 @@ var FetchCommand = class extends TransportCommand {
45203
45385
  async call() {
45204
45386
  this.checkCallable();
45205
45387
  this.setCallable(false);
45388
+ const legacyMessages = await this.loadLegacyRemote(this.remote);
45206
45389
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
45207
45390
  if (!remoteUrl) throw new InvalidRemoteError(this.remote);
45208
45391
  const store = RemoteConfigStore.from(this.workingCopy);
@@ -45226,7 +45409,7 @@ var FetchCommand = class extends TransportCommand {
45226
45409
  const history = this._workingCopy.history;
45227
45410
  const opportunistic = fromConfig ? [] : (this.refmap ?? configured).filter((spec) => spec !== "");
45228
45411
  const followHead = fromConfig && configured.length > 0 ? this.followRemoteHead(store) : null;
45229
- const messages = [];
45412
+ const messages = [...legacyMessages];
45230
45413
  const errors = [];
45231
45414
  const trackingUpdates = [];
45232
45415
  const remote = await this.prepareRemote(remoteUrl);
@@ -45279,7 +45462,7 @@ var FetchCommand = class extends TransportCommand {
45279
45462
  return defer ? { deletes: pruned.map((u) => u.localRef) } : void 0;
45280
45463
  },
45281
45464
  missingRefsOk: useConfig,
45282
- tags: toTagMode(this.effectiveTagOption()),
45465
+ tags: !this.tagOptionSet && store.followsTagsAlways(this.remote) ? "auto-always" : toTagMode(this.effectiveTagOption()),
45283
45466
  depth: this.depth,
45284
45467
  deepenSince: this.shallowSince,
45285
45468
  deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : void 0,
@@ -45308,6 +45491,7 @@ var FetchCommand = class extends TransportCommand {
45308
45491
  }, (connection) => fetchFromConnection(connection, fetchOptions)).catch((error) => {
45309
45492
  const message = error instanceof Error ? error.message : "";
45310
45493
  if (message.startsWith("couldn't find remote ref ")) throw new TransportError(`fatal: ${message}`, void 0, { cause: error });
45494
+ if (error instanceof ObjectFormatMismatchError) throw new TransportError(`fatal: ${message}`, void 0, { cause: error });
45311
45495
  if (error instanceof FetchCheckError) {
45312
45496
  const lines = [...fsckWarnings, ...error.lines];
45313
45497
  if (error.check === "refs") {
@@ -45402,6 +45586,7 @@ var FetchCommand = class extends TransportCommand {
45402
45586
  const lines = [];
45403
45587
  const pruned = tracking.filter((u) => u.status === "deleted");
45404
45588
  if (pruned.length > 0) {
45589
+ const ZERO_OID = this.objectFormat.nullId;
45405
45590
  const ids = pruned.flatMap((u) => [ZERO_OID, u.oldObjectId ?? ZERO_OID]);
45406
45591
  const width = transportSummaryWidth(ids, await this.idAbbreviator().lengths(ids));
45407
45592
  const prunedEntries = pruned.map((u) => ({
@@ -45439,7 +45624,7 @@ var FetchCommand = class extends TransportCommand {
45439
45624
  summary: fetchHeadKind(f.remoteRef),
45440
45625
  remote: f.remoteRef,
45441
45626
  local: "FETCH_HEAD",
45442
- oldOid: ZERO_OID,
45627
+ oldOid: this.objectFormat.nullId,
45443
45628
  newOid: f.oid
45444
45629
  });
45445
45630
  }
@@ -45771,7 +45956,8 @@ function refusedUpdate(result) {
45771
45956
  * the old and new ids in full (zeros for none), the local ref's full name.
45772
45957
  */
45773
45958
  function porcelainLine(entry) {
45774
- return `${entry.code} ${entry.oldOid ?? ZERO_OID} ${entry.newOid ?? ZERO_OID} ${entry.local}`;
45959
+ const zero = nullObjectIdLike$1(entry.oldOid ?? entry.newOid);
45960
+ return `${entry.code} ${entry.oldOid ?? zero} ${entry.newOid ?? zero} ${entry.local}`;
45775
45961
  }
45776
45962
  //#endregion
45777
45963
  //#region src/commands/local-clone.ts
@@ -45876,7 +46062,6 @@ async function copyLocalObjects(copy) {
45876
46062
  }
45877
46063
  //#endregion
45878
46064
  //#region src/commands/remote-command.ts
45879
- const ZERO_ID$1 = "0".repeat(40);
45880
46065
  /**
45881
46066
  * Add a remote to the repository.
45882
46067
  *
@@ -46113,9 +46298,29 @@ var RemoteRenameCommand = class extends GitCommand {
46113
46298
  if (!oldName) throw new MissingArgumentError("oldName", "Old remote name must be specified");
46114
46299
  if (!newName) throw new MissingArgumentError("newName", "New remote name must be specified");
46115
46300
  const store = RemoteConfigStore.from(this.workingCopy);
46301
+ const warnings = (await this.loadLegacyRemote(oldName)).filter((m) => m.startsWith("warning: ")).map((m) => m.slice(9));
46116
46302
  if (!store.isConfigured(oldName)) throw new RemoteNotFoundError(oldName, `No such remote: '${oldName}'`);
46303
+ const legacyOrigin = store.legacyOrigin(oldName);
46304
+ if (oldName === newName && legacyOrigin) {
46305
+ const urls = store.remoteUrls(oldName);
46306
+ const push = store.pushRefspecs(oldName);
46307
+ const fetch = store.configuredFetchRefspecs(oldName);
46308
+ for (const url of urls) store.addValue(`remote.${oldName}.url`, url);
46309
+ for (const spec of push) store.addValue(`remote.${oldName}.push`, spec);
46310
+ for (const spec of fetch) store.addValue(`remote.${oldName}.fetch`, spec);
46311
+ await store.save();
46312
+ await removeLegacyRemoteFile(this.workingCopy, legacyOrigin, oldName);
46313
+ return {
46314
+ remote: store.read(oldName),
46315
+ warnings
46316
+ };
46317
+ }
46318
+ if (oldName !== newName) {
46319
+ for (const m of await this.loadLegacyRemote(newName)) if (m.startsWith("warning: ")) warnings.push(m.slice(9));
46320
+ }
46117
46321
  if (store.isConfigured(newName)) throw new RemoteAlreadyExistsError(newName, `remote ${newName} already exists.`);
46118
46322
  if (!isValidRemoteName(newName)) throw new InvalidArgumentError("newName", newName, `'${newName}' is not a valid remote name`);
46323
+ if (!store.hasSection(oldName)) throw new GitApiError(`Could not rename config section 'remote.${oldName}' to 'remote.${newName}'`, { exitCode: 1 });
46119
46324
  const fetch = store.configuredFetchRefspecs(oldName);
46120
46325
  const oldContext = `:refs/remotes/${oldName}/`;
46121
46326
  const refspecsNeedUpdate = fetch.some((spec) => spec.includes(oldContext));
@@ -46138,8 +46343,8 @@ var RemoteRenameCommand = class extends GitCommand {
46138
46343
  message: entry.comment
46139
46344
  });
46140
46345
  reflog.push({
46141
- oldId: id ?? ZERO_ID$1,
46142
- newId: id ?? ZERO_ID$1,
46346
+ oldId: id ?? this.objectFormat.nullId,
46347
+ newId: id ?? this.objectFormat.nullId,
46143
46348
  ...renameLine.ident !== void 0 ? { ident: renameLine.ident } : {},
46144
46349
  message: `remote: renamed ${ref.name} to ${to}`
46145
46350
  });
@@ -46153,7 +46358,6 @@ var RemoteRenameCommand = class extends GitCommand {
46153
46358
  await moveRefs(this.refsStore, moves, (target) => target.startsWith(oldTop) ? renamed(target) : target);
46154
46359
  }
46155
46360
  store.rename(oldName, newName);
46156
- const warnings = [];
46157
46361
  if (fetch.length > 0) {
46158
46362
  const rewritten = fetch.map((spec) => {
46159
46363
  const at = spec.indexOf(oldContext);
@@ -47593,6 +47797,47 @@ function normalizePath$1(src) {
47593
47797
  }
47594
47798
  //#endregion
47595
47799
  //#region src/commands/clone-command.ts
47800
+ /** The settings a clone reopened with another object format runs with again. */
47801
+ const CLONE_SETTINGS = [
47802
+ "uri",
47803
+ "branch",
47804
+ "depth",
47805
+ "filterSpec",
47806
+ "uploadPack",
47807
+ "bare",
47808
+ "noCheckout",
47809
+ "sparse",
47810
+ "remoteName",
47811
+ "cloneAllBranches",
47812
+ "mirror",
47813
+ "singleBranch",
47814
+ "branchesToClone",
47815
+ "tagOption",
47816
+ "shallowSince",
47817
+ "shallowExcludes",
47818
+ "directory",
47819
+ "shared",
47820
+ "local",
47821
+ "dissociate",
47822
+ "references",
47823
+ "credentials",
47824
+ "timeout",
47825
+ "headers",
47826
+ "gzipRequests",
47827
+ "progressCallback",
47828
+ "progressMessageCallback",
47829
+ "transportRegistry",
47830
+ "useReplaceRefsOverride",
47831
+ "reflogActionOverride"
47832
+ ];
47833
+ /** The remote names objects with another hash than the destination (see `cloneReopenedAs`). */
47834
+ var RemoteObjectFormatSwitch = class extends Error {
47835
+ format;
47836
+ constructor(format) {
47837
+ super(`the remote repository's object format is ${format.name}`);
47838
+ this.format = format;
47839
+ }
47840
+ };
47596
47841
  /** Names the clone's checkout in failure messages. */
47597
47842
  const CLONE = "clone";
47598
47843
  /**
@@ -47651,7 +47896,7 @@ const CLONE = "clone";
47651
47896
  * .call();
47652
47897
  * ```
47653
47898
  */
47654
- var CloneCommand = class extends TransportCommand {
47899
+ var CloneCommand = class CloneCommand extends TransportCommand {
47655
47900
  uri;
47656
47901
  /** The source as clone.c records it: an existing path made absolute, else the URL */
47657
47902
  repoUrl;
@@ -48056,6 +48301,58 @@ var CloneCommand = class extends TransportCommand {
48056
48301
  async call() {
48057
48302
  this.checkCallable();
48058
48303
  this.setCallable(false);
48304
+ try {
48305
+ return await this.cloneOnce();
48306
+ } catch (error) {
48307
+ if (!(error instanceof RemoteObjectFormatSwitch)) throw error;
48308
+ return this.cloneReopenedAs(error.format);
48309
+ }
48310
+ }
48311
+ /**
48312
+ * Called with the working copy a clone reopened with the remote's object format (see
48313
+ * {@link CloneResult.workingCopy}): `Git.clone()` takes it as its own.
48314
+ */
48315
+ onWorkingCopyReopened(listener) {
48316
+ this.reopenedListener = listener;
48317
+ return this;
48318
+ }
48319
+ reopenedListener;
48320
+ /**
48321
+ * git's clone initializes the new repository with the hash the remote names
48322
+ * (`initialize_repository_version` with `transport_get_hash_algo`): the destination, still
48323
+ * empty, is switched to `format` and reopened (`LinkedWorktrees.reopenWithObjectFormat`),
48324
+ * and the clone runs again into it. What the first attempt wrote before it learned the
48325
+ * format (the alternates of `--reference` / `--shared`) is removed once the destination
48326
+ * passed the check.
48327
+ */
48328
+ async cloneReopenedAs(format) {
48329
+ const worktrees = this._workingCopy.worktrees;
48330
+ if (!worktrees?.reopenWithObjectFormat) throw new TransportError(`fatal: cannot clone a ${format.name} repository into this ${this.objectFormat.name} repository`);
48331
+ const place = repositoryPlaceOf(this.workingCopy);
48332
+ const files = place?.getFiles?.();
48333
+ const gitDir = place?.getGitDir?.();
48334
+ const admin = await worktrees.reopenWithObjectFormat(format);
48335
+ if (files && gitDir !== void 0) {
48336
+ const file = `${gitDir}/objects/info/alternates`;
48337
+ if ((await files.stats(file))?.kind === "file") {
48338
+ await files.remove(file);
48339
+ await admin.history.objects?.alternates?.refresh();
48340
+ }
48341
+ }
48342
+ const workingCopy = worktreeAdminWorkingCopy(admin);
48343
+ const next = new CloneCommand(workingCopy);
48344
+ const self = this;
48345
+ const other = next;
48346
+ for (const key of CLONE_SETTINGS) if (key in self) other[key] = self[key];
48347
+ next.shareHooksOf(this);
48348
+ const result = await next.call();
48349
+ this.reopenedListener?.(workingCopy);
48350
+ return {
48351
+ ...result,
48352
+ workingCopy
48353
+ };
48354
+ }
48355
+ async cloneOnce() {
48059
48356
  if (!this.uri) throw new InvalidRemoteError("", "URI must be specified for clone");
48060
48357
  if (!isValidRemoteName(this.remoteName)) throw new InvalidArgumentError("remote", this.remoteName, `'${this.remoteName}' is not a valid remote name`);
48061
48358
  const uri = this.uri;
@@ -48178,6 +48475,9 @@ var CloneCommand = class extends TransportCommand {
48178
48475
  onWarning: (line) => messages.push(`${line}\n`)
48179
48476
  } : {},
48180
48477
  ...fsck ? { fsckObjects: fsck } : {},
48478
+ onRemoteObjectFormat: (format) => {
48479
+ if (format.name !== this.objectFormat.name) throw new RemoteObjectFormatSwitch(format);
48480
+ },
48181
48481
  ...copyObjects ? { beforeFetch: async (remoteRefs) => {
48182
48482
  const { warnings } = await copyObjects();
48183
48483
  for (const w of warnings) messages.push(`${w}\n`);
@@ -48205,7 +48505,7 @@ var CloneCommand = class extends TransportCommand {
48205
48505
  let headCommit;
48206
48506
  let checkedOutBranch;
48207
48507
  let checkoutId;
48208
- if (!detachedTag && !this.bare && defaultBranch === void 0 && result.isEmpty) defaultBranch = await this.localHeadBranch() ?? "main";
48508
+ if (!detachedTag && !this.bare && defaultBranch === void 0 && result.isEmpty) defaultBranch = await this.localHeadBranch() ?? (await defaultInitialBranch(hostEnvironmentOf(this._workingCopy))).name;
48209
48509
  const remoteHead = advertisedDefaultBranch?.startsWith("refs/heads/") ? toBranchName(advertisedDefaultBranch) : void 0;
48210
48510
  if (!this.bare && remoteHead) {
48211
48511
  const target = `refs/remotes/${this.remoteName}/${remoteHead}`;
@@ -48265,7 +48565,7 @@ var CloneCommand = class extends TransportCommand {
48265
48565
  isEmpty: result.isEmpty,
48266
48566
  messages: []
48267
48567
  },
48268
- defaultBranch: defaultBranch ?? "main",
48568
+ defaultBranch: defaultBranch ?? await this.localHeadBranch() ?? (await defaultInitialBranch(hostEnvironmentOf(this._workingCopy))).name,
48269
48569
  remoteName: this.remoteName,
48270
48570
  bare: this.bare,
48271
48571
  headCommit,
@@ -48976,9 +49276,10 @@ async function patchId(trees, blobs, parentTree, tree, options = {}) {
48976
49276
  * found by the caller, as `git format-patch --base` finds them).
48977
49277
  */
48978
49278
  async function patchIdOfChanges(blobs, changes, options = {}) {
48979
- const sum = /* @__PURE__ */ new Uint8Array(20);
49279
+ const format = options.objectFormat ?? blobs.objectFormat ?? SHA1_OBJECT_FORMAT;
49280
+ const sum = new Uint8Array(format.rawLength);
48980
49281
  for (const change of changes) {
48981
- const h = createSha1();
49282
+ const h = format.createHasher();
48982
49283
  const newPath = removeSpace(encodeGitPath(change.path));
48983
49284
  const oldPath = change.oldPath !== void 0 ? removeSpace(encodeGitPath(change.oldPath)) : newPath;
48984
49285
  str(h, "diff--git");
@@ -49001,8 +49302,8 @@ async function patchIdOfChanges(blobs, changes, options = {}) {
49001
49302
  const a = change.old && !options.headerOnly ? await contentOf(blobs, change.old) : /* @__PURE__ */ new Uint8Array(0);
49002
49303
  const b = change.new && !options.headerOnly ? await contentOf(blobs, change.new) : /* @__PURE__ */ new Uint8Array(0);
49003
49304
  if (options.headerOnly) {} else if (isBinary(a) || isBinary(b)) {
49004
- str(h, change.old?.id ?? "0".repeat(40));
49005
- str(h, change.new?.id ?? "0".repeat(40));
49305
+ str(h, change.old?.id ?? format.nullId);
49306
+ str(h, change.new?.id ?? format.nullId);
49006
49307
  } else {
49007
49308
  if (!change.old) {
49008
49309
  str(h, "---/dev/null");
@@ -49027,7 +49328,7 @@ async function patchIdOfChanges(blobs, changes, options = {}) {
49027
49328
  }
49028
49329
  const digest = h.digest();
49029
49330
  let carry = 0;
49030
- for (let i = 0; i < 20; i++) {
49331
+ for (let i = 0; i < sum.length; i++) {
49031
49332
  carry += sum[i] + digest[i];
49032
49333
  sum[i] = carry & 255;
49033
49334
  carry >>= 8;
@@ -49657,7 +49958,7 @@ var FormatPatchCommand = class extends GitCommand {
49657
49958
  } } : {}
49658
49959
  });
49659
49960
  }
49660
- ids.push(changes.length ? await patchIdOfChanges(this.blobs, changes) : "0".repeat(40));
49961
+ ids.push(changes.length ? await patchIdOfChanges(this.blobs, changes, { objectFormat: this.objectFormat }) : this.objectFormat.nullId);
49661
49962
  }
49662
49963
  let text = `\nbase-commit: ${base}\n`;
49663
49964
  for (let i = ids.length - 1; i >= 0; i--) text += `prerequisite-patch-id: ${ids[i]}\n`;
@@ -49684,7 +49985,7 @@ var FormatPatchCommand = class extends GitCommand {
49684
49985
  timestamp: mail.committer.timestamp,
49685
49986
  tzOffset: mail.committer.tzOffset
49686
49987
  };
49687
- let text = `From ${mail.zeroCommit ? "0".repeat(40) : head} Mon Sep 17 00:00:00 2001\n`;
49988
+ let text = `From ${mail.zeroCommit ? nullObjectIdLike(head) : head} Mon Sep 17 00:00:00 2001\n`;
49688
49989
  text += mail.thread;
49689
49990
  text += mailFromHeader(who.name, who.email, { encodeHeaders: mail.encodeHeaders });
49690
49991
  text += `Date: ${showDate(date.timestamp, date.tzOffset, {
@@ -49954,52 +50255,53 @@ var WorktreePruneCommand = class extends GitCommand {
49954
50255
  const GC_AUTO_DEFAULT = 6700;
49955
50256
  const GC_AUTO_PACK_LIMIT_DEFAULT = 50;
49956
50257
  /**
49957
- * Run garbage collection on the repository.
50258
+ * Run garbage collection on the repository: `git gc`.
49958
50259
  *
49959
- * Equivalent to `git gc`.
49960
- *
49961
- * Garbage collection removes unreachable objects and optimizes
49962
- * repository storage. This includes:
49963
- * - Removing objects not reachable from any ref
49964
- * - Packing loose refs into packed-refs
49965
- * - Repacking objects into pack files (optional)
49966
- *
49967
- * Based on JGit's GarbageCollectCommand.
50260
+ * Over a files repository it runs what `git gc` runs, in git's order (builtin/gc.c): `pack-refs
50261
+ * --all --prune` (`gc.packRefs`), `reflog expire --all` (`gc.reflogExpire*`), `worktree prune
50262
+ * --expire <gc.worktreePruneExpire>` and `rerere gc` (`gc.rerereResolved`/`Unresolved`), the
50263
+ * repack (`repack -d -l` with `--cruft --cruft-expiration=<gc.pruneExpire>` (`gc.cruftPacks`,
50264
+ * default), `-A --unpack-unreachable=<expire>` without cruft packs, or `-a` for `--prune=now`;
50265
+ * `--keep-pack` for `--keep-largest-pack`/`gc.bigPackThreshold`; `-f --depth --window` for
50266
+ * `--aggressive`; a bitmap in a bare repository), `update-server-info`, `prune --expire
50267
+ * <expire>` (with `prune_shallow`), and the commit-graph (`gc.writeCommitGraph`). git 2.43 runs
50268
+ * the worktree prune and rerere gc after the prune, 2.5x before the repack: the hook runner's
50269
+ * compatibility decides. Without a files repository only refs are packed and worktrees pruned.
49968
50270
  *
49969
50271
  * @example
49970
50272
  * ```typescript
49971
- * // Basic garbage collection
49972
50273
  * const result = await git.gc().call();
49973
50274
  * console.log(`Removed ${result.objectsRemoved} objects`);
49974
50275
  *
49975
- * // Aggressive GC with repacking
49976
- * const result = await git.gc()
49977
- * .setAggressive(true)
49978
- * .call();
50276
+ * // git gc --aggressive --prune=now
50277
+ * await git.gc().setAggressive(true).setPrune("now").call();
49979
50278
  *
49980
- * // GC with expiration date (keep recent unreachable objects)
49981
- * const twoWeeksAgo = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000);
49982
- * const result = await git.gc()
49983
- * .setExpire(twoWeeksAgo)
49984
- * .call();
50279
+ * // git gc --no-prune
50280
+ * await git.gc().setPrune(false).call();
49985
50281
  * ```
49986
50282
  */
49987
50283
  var GarbageCollectCommand = class extends GitCommand {
49988
- _packRefs = true;
50284
+ _packRefs;
49989
50285
  /** git's fsck and gc read the objects as stored, never through replace refs. */
49990
50286
  readsReplacedObjects() {
49991
50287
  return false;
49992
50288
  }
49993
50289
  _aggressive = false;
49994
50290
  _expire;
50291
+ _prune;
49995
50292
  _auto = false;
50293
+ _quiet = false;
50294
+ _cruft;
50295
+ _maxCruftSize;
50296
+ _keepLargestPack;
49996
50297
  /**
49997
50298
  * `git gc --auto`: housekeeping only when needed (git's `need_to_gc`: more loose objects
49998
50299
  * than `gc.auto`, estimated from `objects/17` as git does, default 6700, or more packs
49999
50300
  * without a `.keep` than `gc.autoPackLimit`, default 50; 0 or less turns either check
50000
50301
  * off, `gc.auto=0` all of auto gc), and only when the pre-auto-gc hook, run first, agrees.
50001
- * No command runs it by itself: callers decide when (git's `maintenance.auto` after a
50002
- * commit, merge or fetch is not reproduced).
50302
+ * With too many packs the repack is a full one, else an incremental one (the reachable loose
50303
+ * objects into a new pack). No command runs it by itself: callers decide when (git's
50304
+ * `maintenance.auto` after a commit, merge or fetch is not reproduced).
50003
50305
  *
50004
50306
  * @example
50005
50307
  * ```typescript
@@ -50012,10 +50314,45 @@ var GarbageCollectCommand = class extends GitCommand {
50012
50314
  this._auto = auto;
50013
50315
  return this;
50014
50316
  }
50317
+ /** `--quiet`: no "Auto packing the repository ..." messages. */
50318
+ setQuiet(quiet) {
50319
+ this.checkCallable();
50320
+ this._quiet = quiet;
50321
+ return this;
50322
+ }
50323
+ /**
50324
+ * `--prune=<date>` (a git expiry date: `now`, `never`, `2.weeks.ago`, a `Date`), `--prune`
50325
+ * (true: `gc.pruneExpire`, default two weeks) or `--no-prune` (false: nothing unreachable
50326
+ * expires, `git prune` does not run).
50327
+ */
50328
+ setPrune(prune) {
50329
+ this.checkCallable();
50330
+ if (prune instanceof Date) this._expire = prune;
50331
+ else this._prune = prune;
50332
+ return this;
50333
+ }
50334
+ /** `--cruft` / `--no-cruft` (default `gc.cruftPacks`, true). */
50335
+ setCruft(cruft) {
50336
+ this.checkCallable();
50337
+ this._cruft = cruft;
50338
+ return this;
50339
+ }
50340
+ /** `--max-cruft-size=<bytes>` (default `gc.maxCruftSize`). */
50341
+ setMaxCruftSize(bytes) {
50342
+ this.checkCallable();
50343
+ this._maxCruftSize = bytes;
50344
+ return this;
50345
+ }
50015
50346
  /**
50016
- * Whether `gc --auto` has work to do (git's `need_to_gc` / `odb_optimize_required` for the
50017
- * incremental strategy), read from the common directory's `objects/`.
50347
+ * `--keep-largest-pack` (true) / `--no-keep-largest-pack` (false): the largest non-cruft
50348
+ * pack is kept as it is; false also ignores `gc.bigPackThreshold`.
50018
50349
  */
50350
+ setKeepLargestPack(keep) {
50351
+ this.checkCallable();
50352
+ this._keepLargestPack = keep;
50353
+ return this;
50354
+ }
50355
+ /** git's `need_to_gc`: whether `gc --auto` has work to do. */
50019
50356
  async needsAutoGc() {
50020
50357
  const config = RemoteConfigStore.from(this.workingCopy);
50021
50358
  const int = (key, fallback) => {
@@ -50047,14 +50384,12 @@ var GarbageCollectCommand = class extends GitCommand {
50047
50384
  }
50048
50385
  if (packs > packLimit) return true;
50049
50386
  }
50050
- return (await names("17")).filter((n) => /^[0-9a-f]{38}$/.test(n)).length * 256 > Math.ceil(gcAuto / 256) * 256;
50387
+ const loose = new RegExp(`^[0-9a-f]{${this.objectFormat.hexLength - 2}}$`);
50388
+ return (await names("17")).filter((n) => loose.test(n)).length * 256 > Math.ceil(gcAuto / 256) * 256;
50051
50389
  }
50052
50390
  /**
50053
- * Set aggressive mode.
50054
- *
50055
- * In aggressive mode, GC will also repack objects for better compression.
50056
- *
50057
- * @param aggressive Whether to run aggressive GC
50391
+ * `--aggressive`: deltas searched again (`repack -f`) with `gc.aggressiveWindow` (250) and
50392
+ * `gc.aggressiveDepth` (50).
50058
50393
  */
50059
50394
  setAggressive(aggressive) {
50060
50395
  this.checkCallable();
@@ -50062,11 +50397,8 @@ var GarbageCollectCommand = class extends GitCommand {
50062
50397
  return this;
50063
50398
  }
50064
50399
  /**
50065
- * Set whether to pack refs.
50066
- *
50067
- * When true (default), loose refs are packed into packed-refs.
50068
- *
50069
- * @param packRefs Whether to pack refs
50400
+ * Whether to pack refs (`git pack-refs --all --prune`). Default: `gc.packRefs` (true;
50401
+ * `notbare` packs them only in a repository with a worktree).
50070
50402
  */
50071
50403
  setPackRefs(packRefs) {
50072
50404
  this.checkCallable();
@@ -50074,19 +50406,48 @@ var GarbageCollectCommand = class extends GitCommand {
50074
50406
  return this;
50075
50407
  }
50076
50408
  /**
50077
- * Set expiration date for unreachable objects.
50078
- *
50079
- * Objects unreachable but modified after this date will not be deleted.
50080
- * This provides a grace period to prevent deleting objects that might
50081
- * still be needed by in-progress operations.
50082
- *
50083
- * @param expire Expiration date (objects older than this may be deleted)
50409
+ * `--prune=<date>`: unreachable objects older than this date expire; younger ones stay
50410
+ * (loose, or in a cruft pack) in case a write in progress needs them.
50084
50411
  */
50085
50412
  setExpire(expire) {
50086
50413
  this.checkCallable();
50087
50414
  this._expire = expire;
50088
50415
  return this;
50089
50416
  }
50417
+ /** The repository's files backend: its FilesApi, common git directory and history. */
50418
+ async filesRepository() {
50419
+ const history = this.workingCopy.history;
50420
+ if (!history?.objects || !history.packs) return void 0;
50421
+ const objects = await this.hooks.commonGitFile("objects");
50422
+ if (!objects) return void 0;
50423
+ return {
50424
+ files: objects.files,
50425
+ gitDir: objects.path.replace(/\/?objects$/, ""),
50426
+ history
50427
+ };
50428
+ }
50429
+ /** The prune expiry in milliseconds before now, undefined for the config's. */
50430
+ pruneExpireMs() {
50431
+ if (this._expire) return Math.max(0, Date.now() - this._expire.getTime());
50432
+ if (typeof this._prune !== "string") return void 0;
50433
+ const nowMs = Date.now();
50434
+ const cutoff = parseExpiryDate(this._prune, Math.floor(nowMs / 1e3), "--prune");
50435
+ if (cutoff === 0) return Number.POSITIVE_INFINITY;
50436
+ if (cutoff === Number.POSITIVE_INFINITY) return 0;
50437
+ return Math.max(0, nowMs - cutoff * 1e3);
50438
+ }
50439
+ /** `gc.packRefs`: a boolean, or `notbare` (packed unless the repository is bare). */
50440
+ packRefsConfigured() {
50441
+ if (this._packRefs !== void 0) return this._packRefs;
50442
+ const config = RemoteConfigStore.from(this.workingCopy);
50443
+ const value = config.value("gc.packRefs");
50444
+ if (value === void 0) return true;
50445
+ if (value === "notbare") {
50446
+ const bare = config.value("core.bare");
50447
+ return !(bare !== void 0 && (parseGitBool(bare) ?? false));
50448
+ }
50449
+ return parseGitBool(value) ?? true;
50450
+ }
50090
50451
  /**
50091
50452
  * Execute the garbage collection.
50092
50453
  *
@@ -50096,30 +50457,25 @@ var GarbageCollectCommand = class extends GitCommand {
50096
50457
  this.checkCallable();
50097
50458
  this.setCallable(false);
50098
50459
  const startTime = Date.now();
50099
- const objectsRemoved = 0;
50100
- const bytesFreed = 0;
50101
50460
  let refsPacked = false;
50102
50461
  const messages = [];
50462
+ const skipped = (autoSkipped) => ({
50463
+ objectsRemoved: 0,
50464
+ bytesFreed: 0,
50465
+ refsPacked,
50466
+ durationMs: Date.now() - startTime,
50467
+ worktreesPruned: [],
50468
+ autoSkipped
50469
+ });
50103
50470
  if (this._auto) {
50104
- const skipped = (autoSkipped) => ({
50105
- objectsRemoved,
50106
- bytesFreed,
50107
- refsPacked,
50108
- durationMs: Date.now() - startTime,
50109
- worktreesPruned: [],
50110
- autoSkipped
50111
- });
50112
50471
  if (!await this.needsAutoGc()) return skipped("not-needed");
50113
50472
  const hook = await this.hooks.run("pre-auto-gc");
50114
50473
  if (hook && hook.exitCode !== 0) return skipped("hook");
50115
- messages.push("Auto packing the repository for optimum performance.", "See \"git help gc\" for manual housekeeping.");
50474
+ if (!this._quiet) messages.push("Auto packing the repository for optimum performance.", "See \"git help gc\" for manual housekeeping.");
50116
50475
  }
50117
- const roots = [];
50118
- for await (const ref of this.refsStore.list("refs/")) if ("objectId" in ref && ref.objectId) roots.push(ref.objectId);
50119
- const head = await this.refsStore.resolve("HEAD");
50120
- if (head?.objectId) roots.push(head.objectId);
50121
50476
  const errors = [];
50122
- if (this._packRefs && this.refsStore.packRefs) {
50477
+ const packRefs = async () => {
50478
+ if (!this.refsStore.packRefs) return;
50123
50479
  await this.refsStore.packRefs([], {
50124
50480
  all: true,
50125
50481
  deleteLoose: true,
@@ -50130,23 +50486,69 @@ var GarbageCollectCommand = class extends GitCommand {
50130
50486
  }
50131
50487
  });
50132
50488
  refsPacked = true;
50133
- }
50489
+ };
50134
50490
  const worktreesPruned = [];
50135
- if (this.workingCopy.worktrees) {
50491
+ const pruneWorktrees = async () => {
50492
+ if (!this.workingCopy.worktrees) return;
50136
50493
  const expire = RemoteConfigStore.from(this.workingCopy).value("gc.worktreePruneExpire") ?? "3.months.ago";
50137
50494
  const { pruned } = await new WorktreePruneCommand(this.workingCopy).setExpire(expire).call();
50138
50495
  for (const p of pruned) worktreesPruned.push(p.id);
50496
+ };
50497
+ const repository = await this.filesRepository();
50498
+ if (!repository) {
50499
+ if (this.packRefsConfigured()) await packRefs();
50500
+ await pruneWorktrees();
50501
+ return {
50502
+ objectsRemoved: 0,
50503
+ bytesFreed: 0,
50504
+ refsPacked,
50505
+ durationMs: Date.now() - startTime,
50506
+ worktreesPruned,
50507
+ ...this._auto ? { messages } : {},
50508
+ ...errors.length > 0 || this.alternatesErrors().length > 0 ? { errors: [...this.alternatesErrors(), ...errors] } : {}
50509
+ };
50139
50510
  }
50140
- this._aggressive;
50141
- this._expire;
50511
+ const environment = hostEnvironmentOf(this.workingCopy);
50512
+ const pruneExpireMs = this.pruneExpireMs();
50513
+ const details = await gc({
50514
+ history: repository.history,
50515
+ files: repository.files,
50516
+ gitDir: repository.gitDir,
50517
+ compatibility: this.hooks.compatibility,
50518
+ ...environment ? { environment } : {},
50519
+ packRefs: this.packRefsConfigured(),
50520
+ packRefsStep: packRefs,
50521
+ beforeObjects: pruneWorktrees,
50522
+ afterObjects: pruneWorktrees,
50523
+ ...this._prune === false ? { prune: false } : {},
50524
+ ...pruneExpireMs !== void 0 ? { pruneExpireMs } : {},
50525
+ ...this._cruft !== void 0 ? { cruftPacks: this._cruft } : {},
50526
+ ...this._maxCruftSize !== void 0 ? { maxCruftSize: this._maxCruftSize } : {},
50527
+ ...this._keepLargestPack !== void 0 ? { keepLargestPack: this._keepLargestPack } : {},
50528
+ ...this._aggressive ? { aggressive: true } : {},
50529
+ ...this._auto ? { auto: true } : {}
50530
+ });
50531
+ if (details.skipped) {
50532
+ if (this._auto) return skipped("running");
50533
+ throw new GitApiError("fatal: gc is already running on this repository (gc.pid is held; remove it if no gc runs)");
50534
+ }
50535
+ const storage = details.storage;
50536
+ const allErrors = [
50537
+ ...this.alternatesErrors(),
50538
+ ...errors,
50539
+ ...details.errors ?? []
50540
+ ];
50541
+ const uniqueErrors = allErrors.filter((line, i) => !this.alternatesErrors().includes(line) || allErrors.indexOf(line) === i);
50142
50542
  return {
50143
- objectsRemoved,
50144
- bytesFreed,
50543
+ objectsRemoved: storage ? storage.before.objects - storage.after.objects : 0,
50544
+ bytesFreed: storage ? storage.before.bytes - storage.after.bytes : 0,
50145
50545
  refsPacked,
50146
50546
  durationMs: Date.now() - startTime,
50147
50547
  worktreesPruned,
50148
50548
  ...this._auto ? { messages } : {},
50149
- ...errors.length > 0 || this.alternatesErrors().length > 0 ? { errors: [...this.alternatesErrors(), ...errors] } : {}
50549
+ ...uniqueErrors.length > 0 ? { errors: uniqueErrors } : {},
50550
+ ...details.warnings ? { warnings: details.warnings } : {},
50551
+ details
50150
50552
  };
50151
50553
  }
50152
50554
  };
@@ -51283,7 +51685,9 @@ var Git = class Git {
51283
51685
  */
51284
51686
  clone() {
51285
51687
  this.checkClosed();
51286
- return this.withTransports(new CloneCommand(this._workingCopy));
51688
+ return this.withTransports(new CloneCommand(this._workingCopy).onWorkingCopyReopened((workingCopy) => {
51689
+ this._workingCopy = workingCopy;
51690
+ }));
51287
51691
  }
51288
51692
  /**
51289
51693
  * Create an LsRemoteCommand for listing remote refs.
@@ -51519,12 +51923,19 @@ var Git = class Git {
51519
51923
  /**
51520
51924
  * Create a StashCreateCommand for stashing changes.
51521
51925
  *
51926
+ * Despite its name this is `git stash push`: the stash is stored in `refs/stash` and the
51927
+ * index and the worktree are reset to HEAD. git's `git stash create` (the stash commit
51928
+ * only: worktree, index and `refs/stash` untouched) is `stashCreate().setRef(null)`.
51929
+ *
51522
51930
  * @example
51523
51931
  * ```typescript
51524
- * // the working copy's index and worktree are stashed, then reset to HEAD
51932
+ * // git stash push -m "WIP: feature work": stashed, then reset to HEAD
51525
51933
  * const stashCommit = await git.stashCreate()
51526
51934
  * .setMessage("WIP: feature work")
51527
51935
  * .call();
51936
+ *
51937
+ * // git stash create "msg": the commit id only, nothing else changes
51938
+ * const id = await git.stashCreate().setRef(null).setMessage("msg").call();
51528
51939
  * ```
51529
51940
  */
51530
51941
  stashCreate() {
@@ -51766,13 +52177,34 @@ var InitCommand = class {
51766
52177
  directory;
51767
52178
  gitDir;
51768
52179
  bare = false;
51769
- initialBranch = "main";
52180
+ /** `--initial-branch`; undefined: git's default (see {@link defaultInitialBranch}) */
52181
+ initialBranch;
51770
52182
  stagingStore;
51771
52183
  worktreeEnabled = false;
51772
52184
  worktreeStore;
51773
52185
  environment;
52186
+ /** `--object-format`; undefined: `$GIT_DEFAULT_HASH`, `init.defaultObjectFormat`, else sha1 */
52187
+ objectFormatName;
52188
+ /** `--ref-format`; undefined: git's default (see {@link defaultRefFormat}) */
52189
+ refFormat;
51774
52190
  callable = true;
51775
52191
  /**
52192
+ * Set the object format of the new repository (`git init --object-format=<format>`):
52193
+ * `sha1` (git's default) or `sha256`. Without it, `$GIT_DEFAULT_HASH`
52194
+ * (`GitHostEnvironment.defaultHash`), then `init.defaultObjectFormat` from the system or
52195
+ * global configuration (or `git -c`), else SHA-1. A name git does not know fails the call
52196
+ * (`UnknownHashAlgorithmError`), and so does re-initialising an existing repository with
52197
+ * another format (`ReinitializeHashError`); an existing repository keeps its own otherwise.
52198
+ *
52199
+ * @param format `sha1` or `sha256`
52200
+ * @returns this for method chaining
52201
+ */
52202
+ setObjectFormat(format) {
52203
+ this.checkCallable();
52204
+ this.objectFormatName = format;
52205
+ return this;
52206
+ }
52207
+ /**
51776
52208
  * Set the FilesApi implementation for storage.
51777
52209
  *
51778
52210
  * If not set, an in-memory FilesApi will be used.
@@ -51830,8 +52262,9 @@ var InitCommand = class {
51830
52262
  /**
51831
52263
  * Set the initial branch name.
51832
52264
  *
51833
- * This is the branch that HEAD will point to after initialization.
51834
- * Defaults to "main".
52265
+ * This is the branch that HEAD will point to after initialization. Without it, git's
52266
+ * default: `init.defaultBranch` from the system or global configuration (or `git -c`),
52267
+ * else `master`, or `main` with `GitHostEnvironment.breakingChanges` (git 3.0).
51835
52268
  *
51836
52269
  * @param branch The initial branch name
51837
52270
  * @returns this for method chaining
@@ -51842,6 +52275,20 @@ var InitCommand = class {
51842
52275
  return this;
51843
52276
  }
51844
52277
  /**
52278
+ * Set the ref storage format of a new repository (`git init --ref-format`): `files` (loose
52279
+ * refs and packed-refs) or `reftable` (`.git/reftable`). Without it, git's default:
52280
+ * `$GIT_DEFAULT_REF_FORMAT`, `init.defaultRefFormat`, else `files`, or `reftable` with
52281
+ * `GitHostEnvironment.breakingChanges` (git 3.0). An existing repository keeps its format.
52282
+ *
52283
+ * @param format "files" or "reftable"
52284
+ * @returns this for method chaining
52285
+ */
52286
+ setRefFormat(format) {
52287
+ this.checkCallable();
52288
+ this.refFormat = format;
52289
+ return this;
52290
+ }
52291
+ /**
51845
52292
  * Set a custom staging store.
51846
52293
  *
51847
52294
  * If not set, a MemoryStagingStore will be used.
@@ -51931,6 +52378,17 @@ var InitCommand = class {
51931
52378
  async call() {
51932
52379
  this.checkCallable();
51933
52380
  this.setCallable(false);
52381
+ let initialBranch = "";
52382
+ let hints;
52383
+ const warnings = [];
52384
+ const chooseBranch = async () => {
52385
+ if (this.initialBranch !== void 0 && !isValidBranchName$1(this.initialBranch)) throw new InvalidInitialBranchError(this.initialBranch);
52386
+ const chosen = this.initialBranch !== void 0 ? { name: this.initialBranch } : await defaultInitialBranch(this.environment);
52387
+ initialBranch = chosen.name;
52388
+ hints = chosen.hint;
52389
+ };
52390
+ const explicitFormat = this.objectFormatName === void 0 ? void 0 : knownHashAlgorithm(this.objectFormatName);
52391
+ let objectFormat = SHA1_OBJECT_FORMAT;
51934
52392
  const files = this.files ?? createInMemoryFilesApi();
51935
52393
  const gitDir = this.resolveGitDir();
51936
52394
  let history;
@@ -51941,11 +52399,22 @@ var InitCommand = class {
51941
52399
  const isFile = async (path) => (await repoFiles.stats(path))?.kind === "file";
51942
52400
  const hasHead = await isFile(`${dir}/HEAD`);
51943
52401
  const fresh = !hasHead && !await isFile(`${dir}/config`);
52402
+ if (fresh) objectFormat = explicitFormat ?? await this.defaultObjectFormat(warnings);
52403
+ else {
52404
+ objectFormat = (await readRepositoryFormat(repoFiles, dir)).objectFormat;
52405
+ if (explicitFormat && explicitFormat.name !== objectFormat.name) throw new ReinitializeHashError();
52406
+ }
52407
+ if (!hasHead) await chooseBranch();
52408
+ else if (this.initialBranch !== void 0) warnings.push(`warning: re-init: ignored --initial-branch=${this.initialBranch}`);
52409
+ const refFormat = fresh ? await defaultRefFormat(this.environment, this.refFormat) : void 0;
52410
+ if (refFormat) warnings.push(...refFormat.warnings);
51944
52411
  const open = (create) => createGitFilesHistoryFromFiles({
51945
52412
  files: repoFiles,
51946
52413
  gitDir,
51947
52414
  create,
51948
- defaultBranch: this.initialBranch,
52415
+ defaultBranch: initialBranch,
52416
+ ...create ? { objectFormat } : {},
52417
+ ...create && refFormat ? { refFormat: refFormat.format } : {},
51949
52418
  ...this.environment ? { environment: this.environment } : {}
51950
52419
  });
51951
52420
  if (fresh && this.bare && dir !== ".") {
@@ -51954,23 +52423,29 @@ var InitCommand = class {
51954
52423
  history = await open(false);
51955
52424
  } else history = await open(fresh);
51956
52425
  await history.initialize();
52426
+ if (hasHead) {
52427
+ const head = await history.refs.get("HEAD");
52428
+ initialBranch = head && "target" in head && head.target.startsWith("refs/heads/") ? head.target.slice(11) : "";
52429
+ }
51957
52430
  if (fresh) {
51958
52431
  const folding = await probeCaseFolding(repoFiles, dir);
51959
52432
  if (folding.ignoreCase) await setCoreValue(repoFiles, `${dir}/config`, "ignorecase", "true");
51960
52433
  if (folding.precomposeUnicode) await setCoreValue(repoFiles, `${dir}/config`, "precomposeunicode", "true");
51961
52434
  }
51962
- if (!hasHead && !fresh) await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
52435
+ if (!hasHead && !fresh) await history.refs.setSymbolic("HEAD", `refs/heads/${initialBranch}`);
51963
52436
  if (this.stagingStore) staging = this.stagingStore;
51964
52437
  else if (this.bare) staging = new MemoryStagingStore();
51965
52438
  else {
51966
- const fileStaging = new FileStagingStore(repoFiles, `${dir}/index`);
51967
- await fileStaging.read();
52439
+ const fileStaging = new FileStagingStore(repoFiles, `${dir}/index`, { objectFormat });
52440
+ if (objectFormat.name === "sha1") await fileStaging.read();
51968
52441
  staging = fileStaging;
51969
52442
  }
51970
52443
  } else {
51971
- history = createMemoryHistory();
52444
+ objectFormat = explicitFormat ?? await this.defaultObjectFormat(warnings);
52445
+ await chooseBranch();
52446
+ history = createMemoryHistory({ objectFormat });
51972
52447
  await history.initialize();
51973
- await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
52448
+ await history.refs.setSymbolic("HEAD", `refs/heads/${initialBranch}`);
51974
52449
  staging = this.stagingStore ?? new MemoryStagingStore();
51975
52450
  }
51976
52451
  let worktree;
@@ -52026,12 +52501,30 @@ var InitCommand = class {
52026
52501
  git: Git.fromWorkingCopy(workingCopy),
52027
52502
  workingCopy,
52028
52503
  repository: history,
52029
- initialBranch: this.initialBranch,
52504
+ initialBranch,
52505
+ ...hints ? { hints } : {},
52506
+ ...warnings.length > 0 ? { warnings } : {},
52030
52507
  bare: this.bare,
52031
52508
  gitDir
52032
52509
  };
52033
52510
  }
52034
52511
  /**
52512
+ * The format of a new repository without `--object-format` (validate_hash_algorithm):
52513
+ * `$GIT_DEFAULT_HASH` (an unknown name dies), else `init.defaultObjectFormat` (git 2.45+;
52514
+ * an unknown name warns and is ignored), else SHA-1.
52515
+ */
52516
+ async defaultObjectFormat(warnings) {
52517
+ const env = this.environment?.defaultHash;
52518
+ if (env !== void 0) return knownHashAlgorithm(env);
52519
+ const configured = (await readProtectedConfig(this.environment)).filter((e) => e.key.toLowerCase() === "init.defaultobjectformat").at(-1);
52520
+ if (configured?.value !== void 0) {
52521
+ const found = objectFormatByName(configured.value);
52522
+ if (found) return found;
52523
+ warnings.push(`warning: unknown hash algorithm '${configured.value}'`);
52524
+ }
52525
+ return SHA1_OBJECT_FORMAT;
52526
+ }
52527
+ /**
52035
52528
  * Resolve the git directory path based on configuration.
52036
52529
  */
52037
52530
  resolveGitDir() {
@@ -52056,6 +52549,32 @@ var InitCommand = class {
52056
52549
  this.callable = value;
52057
52550
  }
52058
52551
  };
52552
+ /** `--object-format` or `$GIT_DEFAULT_HASH` names no format git knows: git dies (exit 128). */
52553
+ var UnknownHashAlgorithmError = class extends Error {
52554
+ value;
52555
+ name = "UnknownHashAlgorithmError";
52556
+ lines;
52557
+ constructor(value) {
52558
+ const line = `fatal: unknown hash algorithm '${value}'`;
52559
+ super(line);
52560
+ this.value = value;
52561
+ this.lines = [line];
52562
+ }
52563
+ };
52564
+ /** `--object-format` names another format than the existing repository's: git dies (exit 128). */
52565
+ var ReinitializeHashError = class extends Error {
52566
+ name = "ReinitializeHashError";
52567
+ lines = ["fatal: attempt to reinitialize repository with different hash"];
52568
+ constructor() {
52569
+ super("fatal: attempt to reinitialize repository with different hash");
52570
+ }
52571
+ };
52572
+ /** The format named `name`, or `UnknownHashAlgorithmError` (git's `hash_algo_by_name`). */
52573
+ function knownHashAlgorithm(name) {
52574
+ const found = objectFormatByName(name);
52575
+ if (!found) throw new UnknownHashAlgorithmError(name);
52576
+ return found;
52577
+ }
52059
52578
  /** Sets `core.bare = true` in a config file written by the git directory layout. */
52060
52579
  async function markBare(files, configPath) {
52061
52580
  await setCoreValue(files, configPath, "bare", "true");
@@ -52260,6 +52779,7 @@ var LsRemoteCommand = class extends TransportCommand {
52260
52779
  const store = RemoteConfigStore.from(this.workingCopy);
52261
52780
  if (this.remote !== void 0) {
52262
52781
  this.remoteName = this.remote;
52782
+ await this.loadLegacyRemote(this.remote);
52263
52783
  return store.remoteUrlOf(this.remote);
52264
52784
  }
52265
52785
  const head = await this.refsStore.get("HEAD");
@@ -52268,11 +52788,13 @@ var LsRemoteCommand = class extends TransportCommand {
52268
52788
  const explicit = store.value(`branch.${branch}.remote`);
52269
52789
  if (explicit !== void 0) {
52270
52790
  this.remoteName = explicit;
52791
+ await this.loadLegacyRemote(explicit);
52271
52792
  return store.remoteUrlOf(explicit);
52272
52793
  }
52273
52794
  }
52274
52795
  const names = store.configuredNames();
52275
52796
  const name = names.length === 1 ? names[0] ?? "origin" : "origin";
52797
+ await this.loadLegacyRemote(name);
52276
52798
  const url = store.urlFor(name);
52277
52799
  if (url === void 0) throw new InvalidRemoteError(name, "fatal: No remote configured to list refs from.");
52278
52800
  this.remoteName = name;
@@ -53815,7 +54337,6 @@ const STRATEGIES = [
53815
54337
  const WORKTREE = "NOTES_MERGE_WORKTREE";
53816
54338
  /** notes-merge.c's `uninitialized`: no local change recorded */
53817
54339
  const UNINITIALIZED = "f".repeat(40);
53818
- const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
53819
54340
  /**
53820
54341
  * `git notes merge [-s <strategy>] <notes-ref>`: the notes of another notes ref merged into
53821
54342
  * the notes ref used (a fast-forward when one contains the other; else a merge commit
@@ -54027,11 +54548,12 @@ var NotesMergeCommand = class extends NotesSubcommand {
54027
54548
  const ctx = this.ctx;
54028
54549
  const msg = partial.message;
54029
54550
  for (const name of names) {
54030
- if (!/^[0-9a-fA-F]{40}/.test(name)) {
54551
+ const hexLength = this.objectFormat.hexLength;
54552
+ if (!new RegExp(`^[0-9a-fA-F]{${hexLength}}`).test(name)) {
54031
54553
  if (this.verbosity >= 3) output.push(`Skipping non-SHA1 entry '${this.gitPath(WORKTREE)}/${name}'\n`);
54032
54554
  continue;
54033
54555
  }
54034
- const obj = name.slice(0, 40).toLowerCase();
54556
+ const obj = name.slice(0, hexLength).toLowerCase();
54035
54557
  const blob = await this.storeResolvedNote(name, errors);
54036
54558
  await tree.add(obj, blob);
54037
54559
  if (this.verbosity >= 4) output.push(`Added resolved note for object ${obj}: ${blob}\n`);
@@ -54177,6 +54699,13 @@ var NotesMerge = class {
54177
54699
  conflicts = [];
54178
54700
  hasWorktree = false;
54179
54701
  commitMsg;
54702
+ /** The repository's object format: its null id, empty tree and note path lengths */
54703
+ get format() {
54704
+ return this.ctx.objectFormat ?? SHA1_OBJECT_FORMAT;
54705
+ }
54706
+ get nullId() {
54707
+ return this.format.nullId;
54708
+ }
54180
54709
  constructor(ctx, checkout, o) {
54181
54710
  this.ctx = ctx;
54182
54711
  this.checkout = checkout;
@@ -54214,8 +54743,8 @@ var NotesMerge = class {
54214
54743
  let baseId;
54215
54744
  let baseTree;
54216
54745
  if (bases.length === 0) {
54217
- baseId = NOTES_NULL_ID;
54218
- baseTree = EMPTY_TREE;
54746
+ baseId = this.nullId;
54747
+ baseTree = this.format.emptyTreeId;
54219
54748
  this.say(4, "No merge base found; doing history-less merge\n");
54220
54749
  } else {
54221
54750
  baseId = bases[0];
@@ -54250,7 +54779,7 @@ var NotesMerge = class {
54250
54779
  for await (const e of this.ctx.trees.loadTree(id)) if ((e.mode & 61440) === 16384) await walk(e.id, `${prefix}${e.name}/`);
54251
54780
  else {
54252
54781
  const hex = `${prefix}${e.name}`.replaceAll("/", "");
54253
- if (/^[0-9a-fA-F]{40}$/.test(hex)) out.set(hex.toLowerCase(), e.id);
54782
+ if (hex.length === this.format.hexLength && /^[0-9a-fA-F]+$/.test(hex)) out.set(hex.toLowerCase(), e.id);
54254
54783
  }
54255
54784
  };
54256
54785
  await walk(tree, "");
@@ -54263,10 +54792,10 @@ var NotesMerge = class {
54263
54792
  const r = await this.flatNotes(remote);
54264
54793
  const changes = [];
54265
54794
  for (const obj of [.../* @__PURE__ */ new Set([...b.keys(), ...r.keys()])].sort()) {
54266
- const bv = b.get(obj) ?? NOTES_NULL_ID;
54267
- const rv = r.get(obj) ?? NOTES_NULL_ID;
54795
+ const bv = b.get(obj) ?? this.nullId;
54796
+ const rv = r.get(obj) ?? this.nullId;
54268
54797
  if (bv === rv) continue;
54269
- const lv = l.get(obj) ?? NOTES_NULL_ID;
54798
+ const lv = l.get(obj) ?? this.nullId;
54270
54799
  changes.push({
54271
54800
  obj,
54272
54801
  base: bv,
@@ -54327,14 +54856,14 @@ var NotesMerge = class {
54327
54856
  this.commitMsg += `\t${p.obj}\n`;
54328
54857
  this.say(2, `Auto-merging notes for ${p.obj}\n`);
54329
54858
  await this.checkWorktree();
54330
- if (p.local === NOTES_NULL_ID) {
54859
+ if (p.local === this.nullId) {
54331
54860
  this.say(1, `CONFLICT (delete/modify): Notes for object ${p.obj} deleted in ${lref} and modified in ${rref}. Version from ${rref} left in tree.\n`);
54332
54861
  await this.writeToWorktree(p.obj, await this.readBlob(p.remote));
54333
- } else if (p.remote === NOTES_NULL_ID) {
54862
+ } else if (p.remote === this.nullId) {
54334
54863
  this.say(1, `CONFLICT (delete/modify): Notes for object ${p.obj} deleted in ${rref} and modified in ${lref}. Version from ${lref} left in tree.\n`);
54335
54864
  await this.writeToWorktree(p.obj, await this.readBlob(p.local));
54336
54865
  } else {
54337
- const reason = p.base === NOTES_NULL_ID ? "add/add" : "content";
54866
+ const reason = p.base === this.nullId ? "add/add" : "content";
54338
54867
  this.say(1, `CONFLICT (${reason}): Merge conflict in notes for object ${p.obj}\n`);
54339
54868
  await this.llMerge(p);
54340
54869
  }
@@ -55094,7 +55623,6 @@ let RebaseOperation = /* @__PURE__ */ function(RebaseOperation) {
55094
55623
  RebaseOperation["EDIT_TODO"] = "edit-todo";
55095
55624
  return RebaseOperation;
55096
55625
  }({});
55097
- const ZERO_ID = "0000000000000000000000000000000000000000";
55098
55626
  /** sequencer.c's staged_changes_advice (no `-S`). */
55099
55627
  const STAGED_CHANGES_ADVICE = `error: you have staged changes in your working tree
55100
55628
  If these changes are meant to be squashed into the previous commit, run:
@@ -56115,7 +56643,7 @@ var RebaseCommand = class extends GitCommand {
56115
56643
  await state.write("MERGE_MSG", pickedMessage);
56116
56644
  let allowEmpty = false;
56117
56645
  if (treeId === headTreeId) {
56118
- if (commit.tree === (parentTreeId ?? EMPTY_TREE_ID)) allowEmpty = true;
56646
+ if (commit.tree === (parentTreeId ?? this.objectFormat.emptyTreeId)) allowEmpty = true;
56119
56647
  else if (await state.exists(`${DIR}/keep_redundant_commits`)) allowEmpty = true;
56120
56648
  else if (await state.exists(`${DIR}/drop_redundant_commits`)) {
56121
56649
  await state.removeRef("AUTO_MERGE");
@@ -56129,7 +56657,7 @@ var RebaseCommand = class extends GitCommand {
56129
56657
  const head = await this.commits.load(headId);
56130
56658
  if (!head) throw new NoHeadError("HEAD cannot be resolved");
56131
56659
  if (!allowEmpty && head.parents.length <= 1) {
56132
- if ((head.parents[0] ? await this.commits.getTree(head.parents[0]) : EMPTY_TREE_ID) === treeId) {
56660
+ if ((head.parents[0] ? await this.commits.getTree(head.parents[0]) : this.objectFormat.emptyTreeId) === treeId) {
56133
56661
  await state.setRef("REBASE_HEAD", item.id);
56134
56662
  return {
56135
56663
  kind: "conflicts",
@@ -56765,7 +57293,7 @@ var RebaseCommand = class extends GitCommand {
56765
57293
  }
56766
57294
  }
56767
57295
  if (buf === "") buf = `rev-${await this.abbreviateObjectId(oid)}`;
56768
- if (buf.length === 40 && /^[0-9a-fA-F]{40}$/.test(buf) || buf === "#" || labels.has(buf)) {
57296
+ if (buf.length === this.objectFormat.hexLength && /^[0-9a-fA-F]+$/.test(buf) || buf === "#" || labels.has(buf)) {
56769
57297
  let i = 2;
56770
57298
  while (labels.has(`${buf}-${i}`)) i++;
56771
57299
  buf = `${buf}-${i}`;
@@ -56790,7 +57318,7 @@ var RebaseCommand = class extends GitCommand {
56790
57318
  for (const id of range) {
56791
57319
  const commit = await this.loadCommit(id);
56792
57320
  if (!commit) throw new CommitNotFoundError(id);
56793
- const parentTree = commit.parents[0] ? (await this.loadCommit(commit.parents[0]))?.tree : EMPTY_TREE_ID;
57321
+ const parentTree = commit.parents[0] ? (await this.loadCommit(commit.parents[0]))?.tree : this.objectFormat.emptyTreeId;
56794
57322
  const empty = commit.tree === parentTree;
56795
57323
  if (!empty && skipped.has(id)) continue;
56796
57324
  if (empty && !keepEmpty) continue;
@@ -57435,7 +57963,7 @@ var RebaseCommand = class extends GitCommand {
57435
57963
  async originallyEmpty(id) {
57436
57964
  const commit = await this.loadCommit(id);
57437
57965
  if (!commit) return false;
57438
- const parentTree = commit.parents[0] ? (await this.loadCommit(commit.parents[0]))?.tree : EMPTY_TREE_ID;
57966
+ const parentTree = commit.parents[0] ? (await this.loadCommit(commit.parents[0]))?.tree : this.objectFormat.emptyTreeId;
57439
57967
  return commit.tree === parentTree;
57440
57968
  }
57441
57969
  /** rebase.missingCommitsCheck (ignore, warn, error; anything else warned about). */
@@ -57662,8 +58190,8 @@ var RebaseCommand = class extends GitCommand {
57662
58190
  });
57663
58191
  if (!records.some((r) => r.ref === name)) records.push({
57664
58192
  ref: name,
57665
- before: values.get(name) ?? ZERO_ID,
57666
- after: ZERO_ID
58193
+ before: values.get(name) ?? this.objectFormat.nullId,
58194
+ after: this.objectFormat.nullId
57667
58195
  });
57668
58196
  }
57669
58197
  }
@@ -57680,7 +58208,7 @@ var RebaseCommand = class extends GitCommand {
57680
58208
  const named = items.filter((item) => item.action === "update-ref" && !item.invalid).map((item) => item.rest ?? "");
57681
58209
  let updated = false;
57682
58210
  const kept = records.filter((r) => {
57683
- const keep = r.after !== ZERO_ID || named.includes(r.ref);
58211
+ const keep = r.after !== this.objectFormat.nullId || named.includes(r.ref);
57684
58212
  if (!keep) updated = true;
57685
58213
  return keep;
57686
58214
  });
@@ -57688,8 +58216,8 @@ var RebaseCommand = class extends GitCommand {
57688
58216
  const value = (await this.refsStore.resolve(ref).catch(() => void 0))?.objectId;
57689
58217
  kept.push({
57690
58218
  ref,
57691
- before: value ?? ZERO_ID,
57692
- after: ZERO_ID
58219
+ before: value ?? this.objectFormat.nullId,
58220
+ after: this.objectFormat.nullId
57693
58221
  });
57694
58222
  updated = true;
57695
58223
  }
@@ -57714,7 +58242,7 @@ var RebaseCommand = class extends GitCommand {
57714
58242
  const updated = [];
57715
58243
  const failed = [];
57716
58244
  for (const record of records) {
57717
- if (((await this.refsStore.resolve(record.ref).catch(() => void 0))?.objectId ?? ZERO_ID) !== record.before || record.after === ZERO_ID) {
58245
+ if (((await this.refsStore.resolve(record.ref).catch(() => void 0))?.objectId ?? this.objectFormat.nullId) !== record.before || record.after === this.objectFormat.nullId) {
57718
58246
  failed.push(record.ref);
57719
58247
  continue;
57720
58248
  }
@@ -57862,7 +58390,10 @@ var RebaseCommand = class extends GitCommand {
57862
58390
  const commit = await this.loadCommit(id);
57863
58391
  if (!commit || commit.parents.length > 1) return void 0;
57864
58392
  const parentTree = commit.parents[0] ? (await this.loadCommit(commit.parents[0]))?.tree : void 0;
57865
- return patchId(trees, this.blobs, parentTree, commit.tree, { headerOnly });
58393
+ return patchId(trees, this.blobs, parentTree, commit.tree, {
58394
+ headerOnly,
58395
+ objectFormat: this.objectFormat
58396
+ });
57866
58397
  };
57867
58398
  const full = /* @__PURE__ */ new Map();
57868
58399
  const fullOf = async (id) => {
@@ -58254,7 +58785,11 @@ var PullCommand = class extends TransportCommand {
58254
58785
  if (!currentBranch) throw new NoHeadError("Cannot pull with detached HEAD");
58255
58786
  const localBranchName = currentBranch.replace("refs/heads/", "");
58256
58787
  const remoteBranch = this.remoteBranchName || localBranchName;
58257
- const refspec = `refs/heads/${remoteBranch}:refs/remotes/${this.remote}/${remoteBranch}`;
58788
+ await this.loadLegacyRemote(this.remote);
58789
+ const store = RemoteConfigStore.from(this._workingCopy);
58790
+ const legacy = store.legacyOrigin(this.remote) !== void 0;
58791
+ const trackingRef = `refs/remotes/${this.remote}/${remoteBranch}`;
58792
+ const refspecs = legacy ? this.remoteBranchName ? [this.remoteBranchName] : [] : [`refs/heads/${remoteBranch}:${trackingRef}`];
58258
58793
  const action = this.reflogAction([
58259
58794
  "pull",
58260
58795
  ...this.rebase === true ? ["--rebase"] : this.rebase === false ? ["--no-rebase"] : [],
@@ -58291,7 +58826,7 @@ var PullCommand = class extends TransportCommand {
58291
58826
  const fetchCommand = new FetchCommand(this._workingCopy);
58292
58827
  fetchCommand.setTransports(this.getTransports());
58293
58828
  fetchCommand.setRemote(this.remote);
58294
- fetchCommand.setRefSpecs(refspec);
58829
+ fetchCommand.setRefSpecs(...refspecs);
58295
58830
  fetchCommand.setUpdateHeadOk(true);
58296
58831
  fetchCommand.setReflogAction(action);
58297
58832
  if (this.credentials) fetchCommand.setCredentials(this.credentials);
@@ -58302,20 +58837,35 @@ var PullCommand = class extends TransportCommand {
58302
58837
  if (this.tagOption) fetchCommand.setTagOpt(this.tagOption);
58303
58838
  if (this.repositoryFiles) fetchCommand.setRepositoryFiles(this.repositoryFiles);
58304
58839
  const fetchResult = await fetchCommand.call();
58305
- if (fetchResult.isEmpty || fetchResult.trackingRefUpdates.length === 0) return {
58306
- fetchResult,
58307
- successful: true,
58308
- rebaseUsed: false,
58309
- fetchedFrom: this.remote
58310
- };
58311
- const trackingRef = `refs/remotes/${this.remote}/${remoteBranch}`;
58312
- const trackingRefResolved = await this.refsStore.resolve(trackingRef);
58313
- if (!trackingRefResolved?.objectId) return {
58840
+ let warnings = [];
58841
+ let mergeTarget;
58842
+ if (legacy) {
58843
+ if (fetchResult.isEmpty) return {
58844
+ fetchResult,
58845
+ successful: true,
58846
+ rebaseUsed: false,
58847
+ fetchedFrom: this.remote
58848
+ };
58849
+ warnings = await this.fastForwardMovedHead(origHead);
58850
+ mergeTarget = await this.mergeHeadFromFetchHead(localBranchName);
58851
+ } else {
58852
+ if (fetchResult.isEmpty || fetchResult.trackingRefUpdates.length === 0) return {
58853
+ fetchResult,
58854
+ successful: true,
58855
+ rebaseUsed: false,
58856
+ fetchedFrom: this.remote
58857
+ };
58858
+ const resolved = await this.refsStore.resolve(trackingRef);
58859
+ if (resolved?.objectId) mergeTarget = { objectId: resolved.objectId };
58860
+ }
58861
+ if (!mergeTarget) return {
58314
58862
  fetchResult,
58315
58863
  successful: true,
58316
58864
  rebaseUsed: false,
58317
58865
  fetchedFrom: this.remote
58318
58866
  };
58867
+ const trackingRefResolved = mergeTarget;
58868
+ const shown = warnings.length > 0 ? { warnings } : {};
58319
58869
  const headNow = (await this.refsStore.resolve("HEAD").catch(() => void 0))?.objectId;
58320
58870
  if (origHead === void 0 && headNow === void 0) {
58321
58871
  const mergeResult = await new MergeCommand(this._workingCopy).shareHooksOf(this).callIntoVoid(trackingRefResolved.objectId);
@@ -58324,7 +58874,8 @@ var PullCommand = class extends TransportCommand {
58324
58874
  mergeResult,
58325
58875
  successful: isMergeSuccessful(mergeResult.status),
58326
58876
  rebaseUsed: false,
58327
- fetchedFrom: this.remote
58877
+ fetchedFrom: this.remote,
58878
+ ...shown
58328
58879
  };
58329
58880
  }
58330
58881
  const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
@@ -58336,14 +58887,15 @@ var PullCommand = class extends TransportCommand {
58336
58887
  rebaseResult,
58337
58888
  successful: isRebaseSuccessful(rebaseResult.status),
58338
58889
  rebaseUsed: true,
58339
- fetchedFrom: this.remote
58890
+ fetchedFrom: this.remote,
58891
+ ...shown
58340
58892
  };
58341
58893
  }
58342
58894
  const mergeCommand = new MergeCommand(this._workingCopy).shareHooksOf(this);
58343
58895
  mergeCommand.include(trackingRefResolved.objectId);
58344
- const url = (configValue$1(this._workingCopy, `remote.${this.remote}.url`) ?? this.remote).replace(/\/+$/, "").replace(/\.git$/, "");
58896
+ const url = (configValue$1(this._workingCopy, `remote.${this.remote}.url`) ?? store.remoteUrls(this.remote)[0] ?? this.remote).replace(/\/+$/, "").replace(/\.git$/, "");
58345
58897
  const into = localBranchName === "main" || localBranchName === "master" ? "" : ` into ${localBranchName}`;
58346
- mergeCommand.setMessage(`Merge branch '${remoteBranch}' of ${url}${into}`);
58898
+ mergeCommand.setMessage(mergeTarget.description ? `Merge ${mergeTarget.description}${into}` : `Merge branch '${remoteBranch}' of ${url}${into}`);
58347
58899
  mergeCommand.setReflogAction(action);
58348
58900
  if (canFastForward) mergeCommand.setFastForwardMode("ff-only");
58349
58901
  if (autoStash !== void 0) mergeCommand.setAutoStash(autoStash);
@@ -58363,16 +58915,66 @@ var PullCommand = class extends TransportCommand {
58363
58915
  },
58364
58916
  successful,
58365
58917
  rebaseUsed: true,
58366
- fetchedFrom: this.remote
58918
+ fetchedFrom: this.remote,
58919
+ ...shown
58367
58920
  };
58368
58921
  return {
58369
58922
  fetchResult,
58370
58923
  mergeResult,
58371
58924
  successful,
58372
58925
  rebaseUsed: false,
58373
- fetchedFrom: this.remote
58926
+ fetchedFrom: this.remote,
58927
+ ...shown
58374
58928
  };
58375
58929
  }
58930
+ /**
58931
+ * pull.c after its fetch: when the fetch moved the checked-out branch itself
58932
+ * (`--update-head-ok`, a branches remote named after it), the index and worktree still at
58933
+ * `origHead` are fast-forwarded to the new HEAD (merge.c `checkout_fast_forward`), with
58934
+ * git's warning; local changes in the way are git's death.
58935
+ *
58936
+ * @returns the warning git printed, if any
58937
+ * @throws GitApiError with git's stderr: the warning, unpack-trees' refusal and pull.c's
58938
+ * `Cannot fast-forward your working tree.` lines (exit 128)
58939
+ */
58940
+ async fastForwardMovedHead(origHead) {
58941
+ const currHead = (await this.refsStore.resolve("HEAD").catch(() => void 0))?.objectId;
58942
+ if (origHead === void 0 || currHead === void 0 || origHead === currHead) return [];
58943
+ const warning = `warning: fetch updated the current branch head.
58944
+ fast-forwarding your working tree from
58945
+ commit ${origHead}.`;
58946
+ const refused = await new MergeCommand(this._workingCopy).shareHooksOf(this).callCheckoutFastForward(origHead, currHead);
58947
+ if (refused) throw new GitApiError(`${warning}\n${refused.message}\nfatal: Cannot fast-forward your working tree.
58948
+ After making sure that you saved anything precious from
58949
+ $ git diff ${origHead}\noutput, run
58950
+ \$ git reset --hard
58951
+ to recover.`, { exitCode: 128 });
58952
+ return [warning];
58953
+ }
58954
+ /**
58955
+ * pull.c's `get_merge_heads`: the first FETCH_HEAD entry not marked `not-for-merge`, with
58956
+ * its description (`branch 'x' of <url>`, as fmt-merge-msg titles the merge).
58957
+ *
58958
+ * @throws GitApiError with `die_no_merge_candidates`' lines (exit 1) when there is none
58959
+ */
58960
+ async mergeHeadFromFetchHead(branch) {
58961
+ const text = await this._workingCopy.checkout?.readFetchHead?.() ?? "";
58962
+ for (const line of text.split("\n")) {
58963
+ const m = /^([0-9a-f]{40,64})\t([^\t]*)\t(.*)$/.exec(line);
58964
+ if (!m || m[2] === "not-for-merge") continue;
58965
+ return {
58966
+ objectId: m[1],
58967
+ description: m[3]
58968
+ };
58969
+ }
58970
+ const store = RemoteConfigStore.from(this._workingCopy);
58971
+ let message;
58972
+ if (this.remoteBranchName) message = "There are no candidates for merging among the refs that you just fetched.\nGenerally this means that you provided a wildcard refspec which had no\nmatches on the remote end.";
58973
+ else if (store.value(`branch.${branch}.remote`) !== this.remote) message = `You asked to pull from the remote '${this.remote}', but did not specify\na branch. Because this is not the default configured remote
58974
+ for your current branch, you must specify a branch on the command line.`;
58975
+ else message = `Your configuration specifies to merge with the ref '${store.value(`branch.${branch}.merge`) ?? ""}'\nfrom the remote, but no such ref was fetched.`;
58976
+ throw new GitApiError(message, { exitCode: 1 });
58977
+ }
58376
58978
  config(key) {
58377
58979
  return configValue$1(this._workingCopy, key);
58378
58980
  }
@@ -58400,8 +59002,6 @@ var PullCommand = class extends TransportCommand {
58400
59002
  };
58401
59003
  //#endregion
58402
59004
  //#region src/commands/push-command.ts
58403
- /** All-zero object id — Git's "no object", used to express a ref delete. */
58404
- const ZERO_OBJECT_ID = "0".repeat(40);
58405
59005
  /**
58406
59006
  * How a server's rejection reason (`ng <ref> <reason>`) lands on the statuses this package
58407
59007
  * reports. PushStatus, following JGit's RemoteRefUpdate, keeps only the non-fast-forward case
@@ -58760,6 +59360,8 @@ var PushCommand = class extends TransportCommand {
58760
59360
  async call() {
58761
59361
  this.checkCallable();
58762
59362
  this.setCallable(false);
59363
+ const legacyWarnings = await this.loadLegacyRemote(this.remote);
59364
+ const warnings = legacyWarnings.length > 0 ? { warnings: legacyWarnings } : {};
58763
59365
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
58764
59366
  if (!remoteUrl) throw new InvalidRemoteError(this.remote);
58765
59367
  const resolved = this.resolveRemote(remoteUrl);
@@ -58769,7 +59371,8 @@ var PushCommand = class extends TransportCommand {
58769
59371
  remoteUpdates: [],
58770
59372
  bytesSent: 0,
58771
59373
  objectCount: 0,
58772
- messages: []
59374
+ messages: [],
59375
+ ...warnings
58773
59376
  };
58774
59377
  const remote = await this.openRemote(resolved);
58775
59378
  const localRemote = remote.kind === "local" ? remote.repository : void 0;
@@ -58819,6 +59422,7 @@ var PushCommand = class extends TransportCommand {
58819
59422
  ...receivePack !== void 0 ? { program: receivePack } : {}
58820
59423
  }, (connection) => pushToConnection(connection, pushOptions), localRemote === void 0 ? void 0 : remoteHookSession(this.workingCopy, localRemote, { localPush: true }), transactionHooks);
58821
59424
  } catch (error) {
59425
+ if (error instanceof ObjectFormatMismatchError) throw new TransportError(`fatal: ${error.message}`, void 0, { cause: error });
58822
59426
  if (error instanceof PushRefusedByHookError) throw new HookFailedError("pre-push", prePushExit, `error: failed to push some refs to '${remoteUrl}'`, this.hooks.output);
58823
59427
  throw error;
58824
59428
  } finally {
@@ -58848,7 +59452,7 @@ var PushCommand = class extends TransportCommand {
58848
59452
  for (const target of targets) {
58849
59453
  const local = tracking(target.ref);
58850
59454
  if (!local) continue;
58851
- if (target.oid === ZERO_OBJECT_ID) {
59455
+ if (isNullObjectId$1(target.oid)) {
58852
59456
  if (!refNameIsSafe(local)) {
58853
59457
  trackingErrors.push(`error: refusing to update ref with bad name '${local}'`);
58854
59458
  continue;
@@ -58889,7 +59493,7 @@ var PushCommand = class extends TransportCommand {
58889
59493
  message: update.message ?? (update.status === "ok" ? void 0 : update.summary),
58890
59494
  summary: update.summary,
58891
59495
  forceUpdate: update.force,
58892
- delete: update.newOid === ZERO_OBJECT_ID,
59496
+ delete: isNullObjectId$1(update.newOid),
58893
59497
  ...update.reports?.length ? { reports: update.reports.map((r) => ({
58894
59498
  ...r.refName !== void 0 ? { refName: r.refName } : {},
58895
59499
  ...r.oldOid !== void 0 ? { oldObjectId: r.oldOid } : {},
@@ -58900,6 +59504,7 @@ var PushCommand = class extends TransportCommand {
58900
59504
  bytesSent: result.bytesSent,
58901
59505
  objectCount: result.packObjects,
58902
59506
  messages,
59507
+ ...warnings,
58903
59508
  display: formatPushStatus(result, { dest: remoteUrl }),
58904
59509
  porcelain: formatPushStatus(result, {
58905
59510
  dest: remoteUrl,
@@ -58921,7 +59526,7 @@ var PushCommand = class extends TransportCommand {
58921
59526
  "rejected-stale",
58922
59527
  "up-to-date"
58923
59528
  ]);
58924
- const zero = "0".repeat(40);
59529
+ const zero = this.objectFormat.nullId;
58925
59530
  const stdin = updates.filter((u) => !skipped.has(u.status)).map((u) => {
58926
59531
  return `${u.localRef ?? u.source ?? (/^0+$/.test(u.newOid) ? "(delete)" : u.newOid)} ${u.newOid || zero} ${u.remoteRef} ${u.oldOid || zero}\n`;
58927
59532
  }).join("");
@@ -58977,7 +59582,7 @@ var PushCommand = class extends TransportCommand {
58977
59582
  if (specs.length > 0) return specs;
58978
59583
  const store = RemoteConfigStore.from(this.workingCopy);
58979
59584
  if (store.isConfigured(this.remote)) {
58980
- const configured = store.read(this.remote).pushRefspecs;
59585
+ const configured = store.pushRefspecs(this.remote);
58981
59586
  if (configured.length > 0) return configured;
58982
59587
  }
58983
59588
  const mode = (store.value("push.default") ?? "simple").toLowerCase();
@@ -61617,4 +62222,4 @@ var WorktreeRepairCommand = class extends GitCommand {
61617
62222
  }
61618
62223
  };
61619
62224
  //#endregion
61620
- export { RemoteRenameCommand as $, hostZoneName as $n, parseColorSpec as $r, CommitCommand as $t, NotesListCommand as A, latin1ToPath as Ai, PRN_MODULO as An, cutLine as Ar, parseTagBuffer as At, HookRunCommand as B, textconvRunnerOf as Bi, NotesError as Bn, SubmoduleRepository as Br, remote_transport_exports as Bt, NotesCommands as C, installMergeDrivers as Ci, strbufRtrim as Cn, patchModeFor as Cr, fsckCommit as Ct, NotesCopyCommand as D, ApplyEngine as Di, BisectNode as Dn, DiffCommand as Dr, parseCommitBuffer as Dt, NotesAppendCommand as E, parseWhitespaceAction as Ei, BisectGraph as En, createPatchBackend as Er, hexIdAt as Et, MvCommand as F, formatStatusText as Fi, managedSkipped as Fn, WorktreeListCommand as Fr, FSCK_MSG_IDS as Ft, FormatPatchError as G, combineNotesOverwrite as Gn, readGitmodulesEntries as Gr, CleanCommand as Gt, GarbageCollectCommand as H, combineNotesCatSortUniq as Hn, openSubmoduleRepository as Hr, quarantineEnv as Ht, LsRemoteCommand as I, statusCommitInfo as Ii, skipAway as In, shortenUnambiguousRef as Ir, FsckMessageTypes as It, SparseCheckoutCommand as J, mailFromHeader as Jn, PrettyFormatError as Jr, MergeCommand as Jt, DescribeCommand as K, Mailmap as Kn, showSubmoduleDiffSummary as Kr, CherryPickCommand as Kt, InitCommand as L, CleanupMode as Li, skipAwayIndex as Ln, parseExpiry as Lr, UnknownFsckMsgIdError as Lt, NotesRemoveCommand as M, createRefDecorationFilter as Mi, UNINTERESTING as Mn, parseUntrackedFilesMode as Mr, scanTree as Mt, NotesShowCommand as N, decorateFullRefs as Ni, estimateBisectSteps as Nn, readShowUntrackedFiles as Nr, treeEntryId as Nt, NotesEditCommand as O, bytesToLatin1 as Oi, FIND_BISECTION_ALL as On, formatDiffEntry as Or, parseCommitLinks as Ot, NotesSubcommand as P, StatusPrinter as Pi, findBisection as Pn, readSubmoduleDirt as Pr, walkTree as Pt, RemoteRemoveCommand as Q, DateModeError as Qn, loadRefDecorations as Qr, favorOf as Qt, Git as R, stripspace as Ri, LogCommand as Rn, SubmoduleSummaryCommand as Rr, parseFsckMsgId as Rt, PackRefsCommand as S, createMergeDriver as Si, sqQuoteArgv as Sn, PATCH_MODES as Sr, fsckBlob as St, NotesAddCommand as T, ApplyCommand as Ti, BisectDie as Tn, IndexRefresh as Tr, fsckTree as Tt, WorktreePruneCommand as U, combineNotesConcatenate as Un, parseSubmoduleDiffFormat as Ur, remoteHookSession as Ut, createDescriber as V, NotesTree as Vn, SubmoduleWalkError as Vr, httpBackendEnv as Vt, FormatPatchCommand as W, combineNotesIgnore as Wn, readDiffSubmoduleConfig as Wr, ReadTreeCommand as Wt, RemoteGetUrlCommand as X, LogGraph as Xn, formatRefDecorations as Xr, UNMERGED_FILES_MESSAGE as Xt, RemoteAddCommand as Y, mergesMode as Yn, formatCommitPretty as Yr, MergeOperation as Yt, RemoteListCommand as Z, DEFAULT_DATE_MODE as Zn, humanDate as Zr, UNRELATED_HISTORIES_MESSAGE as Zt, ReflogCommand as _, ListBranchMode as _i, BisectCode as _n, runAddInteractive as _r, FsckConfigError as _t, WorktreeUnlockCommand as a, formatTrailersOf as ai, BlameCommand as an, nonCommitSwitchError as ar, toTagMode as at, RebaseCommand as b, STASH_REF as bi, sqDequoteToArgv as bn, runPatchSelection as br, checkSubmoduleName as bt, ListTagCommand as c, NoStagedChangesError as ci, BisectNextCommand as cn, runPathCheckout as cr, VerifyPackCommand as ct, StashDropCommand as d, StashWorktreeRemovalError as di, BisectRunCommand as dn, revisionMergeBases as dr, FSCK_ERROR_MULTI_PACK_INDEX_243 as dt, relativeDate as ei, CopyBranchCommand as en, parseDateMode as er, RemoteSetHeadCommand as et, servedRepositoryOf as f, WorkingCopyStashProvider as fi, BisectSkipCommand as fn, AmCommand as fr, FSCK_ERROR_OBJECT as ft, RestoreCommand as g, restoreWorktreeHard as gi, BISECT_USAGE as gn, AddCommand as gr, FsckCommand as gt, RevListCommand as h, recordWrittenStat as hi, BisectTermsCommand as hn, mailsplit as hr, FSCK_ERROR_REFS as ht, WorktreeLockCommand as i, appendTrailers as ii, RenameBranchCommand as in, CheckoutStatus as ir, TagOption as it, NotesPruneCommand as j, pathToLatin1 as ji, TREESAME as jn, parseIgnoredMode as jr, rawIdAt as jt, NotesGetRefCommand as k, latin1ToBytes as ki, FIND_BISECTION_FIRST_PARENT_ONLY as kn, StatusCommand as kr, parseGitmodulesConfig as kt, TagCommand as l, StashCreateCommand as li, BisectReplayCommand as ln, BackfillCommand as lr, FSCK_ERROR_BITMAP_243 as lt, RevertCommand as m, checkFlaggedEntries as mi, BisectStateCommand as mn, mailinfo as mr, FSCK_ERROR_REACHABLE as mt, WorktreeMoveCommand as n, wrapText as ni, DeleteBranchCommand as nn, CheckoutCommand as nr, isValidRemoteName as nt, WorktreeAddCommand as o, trailerConfigOf as oi, BisectCommand as on, pathCheckoutResult as or, toTrackingRefUpdate as ot, RmCommand as p, ResetCommand as pi, BisectStartCommand as pn, ensureUtf8 as pr, FSCK_ERROR_PACK as pt, CloneCommand as q, LogPrinter as qn, submoduleHeader as qr, SequencerOperation as qt, WorktreeRemoveCommand as r, appendSignoff as ri, ListBranchCommand as rn, CheckoutStage as rr, FetchCommand as rt, DeleteTagCommand as s, NoChangesSelectedError as si, BisectLogCommand as sn, checkoutPaths as sr, fsck_exports as st, WorktreeRepairCommand as t, sanitizedSubject as ti, CreateBranchCommand as tn, showDate as tr, RemoteSetUrlCommand as tt, SwitchCommand as u, StashPathspecResetError as ui, BisectResetCommand as un, RevParseCommand as ur, FSCK_ERROR_COMMIT_GRAPH as ut, PushCommand as v, ResetMode as vi, BisectEngine as vn, patchRevisionOf as vr, fetchFsckOf as vt, NotesMergeCommand as w, mergeDriversOf as wi, strbufTrim as wn, promptIndex as wr, fsckTag as wt, RebaseOperation as x, StashListCommand as xi, sqQuote as xn, runAddPatch as xr, checkSubmoduleUrl as xt, PullCommand as y, StashApplyCommand as yi, isBisectSuccess as yn, pathPatchMode as yr, canonMode as yt, HookListCommand as z, installTextconvRunner as zi, RevFilter as zn, NULL_OBJECT_ID$1 as zr, TransportCommand as zt };
62225
+ export { RemoteListCommand as $, mergesMode as $n, formatCommitPretty as $r, MergeOperation as $t, NotesListCommand as A, parseWhitespaceAction as Ai, BisectGraph as An, createPatchBackend as Ar, hexIdAt as At, Git as B, statusCommitInfo as Bi, skipAway as Bn, shortenUnambiguousRef as Br, FsckMessageTypes as Bt, NotesCommands as C, StashApplyCommand as Ci, isBisectSuccess as Cn, pathPatchMode as Cr, canonMode as Ct, NotesCopyCommand as D, installMergeDrivers as Di, strbufRtrim as Dn, patchModeFor as Dr, fsckCommit as Dt, NotesAppendCommand as E, createMergeDriver as Ei, sqQuoteArgv as En, PATCH_MODES as Er, fsckBlob as Et, MvCommand as F, pathToLatin1 as Fi, TREESAME as Fn, parseIgnoredMode as Fr, rawIdAt as Ft, WorktreePruneCommand as G, NotesTree as Gn, SubmoduleWalkError as Gr, httpBackendEnv as Gt, HookRunCommand as H, stripspace as Hi, LogCommand as Hn, SubmoduleSummaryCommand as Hr, parseFsckMsgId as Ht, LsRemoteCommand as I, createRefDecorationFilter as Ii, UNINTERESTING as In, parseUntrackedFilesMode as Ir, scanTree as It, DescribeCommand as J, combineNotesIgnore as Jn, readDiffSubmoduleConfig as Jr, ReadTreeCommand as Jt, FormatPatchCommand as K, combineNotesCatSortUniq as Kn, openSubmoduleRepository as Kr, quarantineEnv as Kt, InitCommand as L, decorateFullRefs as Li, estimateBisectSteps as Ln, readShowUntrackedFiles as Lr, treeEntryId as Lt, NotesRemoveCommand as M, bytesToLatin1 as Mi, FIND_BISECTION_ALL as Mn, formatDiffEntry as Mr, parseCommitLinks as Mt, NotesShowCommand as N, latin1ToBytes as Ni, FIND_BISECTION_FIRST_PARENT_ONLY as Nn, StatusCommand as Nr, parseGitmodulesConfig as Nt, NotesEditCommand as O, mergeDriversOf as Oi, strbufTrim as On, promptIndex as Or, fsckTag as Ot, NotesSubcommand as P, latin1ToPath as Pi, PRN_MODULO as Pn, cutLine as Pr, parseTagBuffer as Pt, RemoteGetUrlCommand as Q, mailFromHeader as Qn, PrettyFormatError as Qr, MergeCommand as Qt, ReinitializeHashError as R, StatusPrinter as Ri, findBisection as Rn, readSubmoduleDirt as Rr, walkTree as Rt, PackRefsCommand as S, ResetMode as Si, BisectEngine as Sn, patchRevisionOf as Sr, SHA1_ID_SHAPE as St, NotesAddCommand as T, StashListCommand as Ti, sqQuote as Tn, runAddPatch as Tr, checkSubmoduleUrl as Tt, createDescriber as U, installTextconvRunner as Ui, RevFilter as Un, NULL_OBJECT_ID as Ur, TransportCommand as Ut, HookListCommand as V, CleanupMode as Vi, skipAwayIndex as Vn, parseExpiry as Vr, UnknownFsckMsgIdError as Vt, GarbageCollectCommand as W, textconvRunnerOf as Wi, NotesError as Wn, SubmoduleRepository as Wr, remote_transport_exports as Wt, SparseCheckoutCommand as X, Mailmap as Xn, showSubmoduleDiffSummary as Xr, CherryPickCommand as Xt, CloneCommand as Y, combineNotesOverwrite as Yn, readGitmodulesEntries as Yr, CleanCommand as Yt, RemoteAddCommand as Z, LogPrinter as Zn, submoduleHeader as Zr, SequencerOperation as Zt, ReflogCommand as _, ResetCommand as _i, BisectStartCommand as _n, ensureUtf8 as _r, FSCK_ERROR_REACHABLE as _t, WorktreeUnlockCommand as a, sanitizedSubject as ai, CreateBranchCommand as an, showDate as ar, FetchCommand as at, RebaseCommand as b, restoreWorktreeHard as bi, BISECT_USAGE as bn, AddCommand as br, FsckConfigError as bt, ListTagCommand as c, appendTrailers as ci, RenameBranchCommand as cn, CheckoutStatus as cr, toTrackingRefUpdate as ct, StashDropCommand as d, NoChangesSelectedError as di, BisectLogCommand as dn, checkoutPaths as dr, FSCK_ERROR_BITMAP_243 as dt, formatRefDecorations as ei, UNMERGED_FILES_MESSAGE as en, LogGraph as er, RemoteRemoveCommand as et, servedRepositoryOf as f, NoStagedChangesError as fi, BisectNextCommand as fn, runPathCheckout as fr, FSCK_ERROR_COMMIT_GRAPH as ft, RestoreCommand as g, WorkingCopyStashProvider as gi, BisectSkipCommand as gn, AmCommand as gr, FSCK_ERROR_PACK_REV_INDEX_243 as gt, RevListCommand as h, StashWorktreeRemovalError as hi, BisectRunCommand as hn, revisionMergeBases as hr, FSCK_ERROR_PACK as ht, WorktreeLockCommand as i, relativeDate as ii, CopyBranchCommand as in, parseDateMode as ir, isValidRemoteName as it, NotesPruneCommand as j, ApplyEngine as ji, BisectNode as jn, DiffCommand as jr, parseCommitBuffer as jt, NotesGetRefCommand as k, ApplyCommand as ki, BisectDie as kn, IndexRefresh as kr, fsckTree as kt, TagCommand as l, formatTrailersOf as li, BlameCommand as ln, nonCommitSwitchError as lr, fsck_exports as lt, RevertCommand as m, StashPathspecResetError as mi, BisectResetCommand as mn, RevParseCommand as mr, FSCK_ERROR_OBJECT as mt, WorktreeMoveCommand as n, loadRefDecorations as ni, favorOf as nn, DateModeError as nr, RemoteSetHeadCommand as nt, WorktreeAddCommand as o, wrapText as oi, DeleteBranchCommand as on, CheckoutCommand as or, TagOption as ot, RmCommand as p, StashCreateCommand as pi, BisectReplayCommand as pn, BackfillCommand as pr, FSCK_ERROR_MULTI_PACK_INDEX_243 as pt, FormatPatchError as q, combineNotesConcatenate as qn, parseSubmoduleDiffFormat as qr, remoteHookSession as qt, WorktreeRemoveCommand as r, parseColorSpec as ri, CommitCommand as rn, hostZoneName as rr, RemoteSetUrlCommand as rt, DeleteTagCommand as s, appendSignoff as si, ListBranchCommand as sn, CheckoutStage as sr, toTagMode as st, WorktreeRepairCommand as t, humanDate as ti, UNRELATED_HISTORIES_MESSAGE as tn, DEFAULT_DATE_MODE as tr, RemoteRenameCommand as tt, SwitchCommand as u, trailerConfigOf as ui, BisectCommand as un, pathCheckoutResult as ur, VerifyPackCommand as ut, PushCommand as v, checkFlaggedEntries as vi, BisectStateCommand as vn, mailinfo as vr, FSCK_ERROR_REFS as vt, NotesMergeCommand as w, STASH_REF as wi, sqDequoteToArgv as wn, runPatchSelection as wr, checkSubmoduleName as wt, RebaseOperation as x, ListBranchMode as xi, BisectCode as xn, runAddInteractive as xr, fetchFsckOf as xt, PullCommand as y, recordWrittenStat as yi, BisectTermsCommand as yn, mailsplit as yr, FsckCommand as yt, UnknownHashAlgorithmError as z, formatStatusText as zi, managedSkipped as zn, WorktreeListCommand as zr, FSCK_MSG_IDS as zt };