@statewalker/vcs-commands 0.14.0 → 0.15.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 (265) hide show
  1. package/dist/commands/add-command.d.ts.map +1 -1
  2. package/dist/commands/add-patch/patch-backend.d.ts +1 -1
  3. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -1
  4. package/dist/commands/archive/remote-archive-command.d.ts +4 -1
  5. package/dist/commands/archive/remote-archive-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts +14 -2
  7. package/dist/commands/branch-command.d.ts.map +1 -1
  8. package/dist/commands/cat-file/batch-format.d.ts +8 -12
  9. package/dist/commands/cat-file/batch-format.d.ts.map +1 -1
  10. package/dist/commands/cat-file/cat-file-command.d.ts +39 -5
  11. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  12. package/dist/commands/check-ignore-command.d.ts.map +1 -1
  13. package/dist/commands/checkout-command.d.ts +4 -0
  14. package/dist/commands/checkout-command.d.ts.map +1 -1
  15. package/dist/commands/checkout-paths.d.ts +9 -0
  16. package/dist/commands/checkout-paths.d.ts.map +1 -1
  17. package/dist/commands/cherry-pick-command.d.ts +3 -0
  18. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  19. package/dist/commands/clean-interactive.d.ts +0 -9
  20. package/dist/commands/clean-interactive.d.ts.map +1 -1
  21. package/dist/commands/clone-command.d.ts +2 -0
  22. package/dist/commands/clone-command.d.ts.map +1 -1
  23. package/dist/commands/column/column-config.d.ts +23 -0
  24. package/dist/commands/column/column-config.d.ts.map +1 -0
  25. package/dist/commands/column/column-layout.d.ts +129 -0
  26. package/dist/commands/column/column-layout.d.ts.map +1 -0
  27. package/dist/commands/column/index.d.ts +3 -0
  28. package/dist/commands/column/index.d.ts.map +1 -0
  29. package/dist/commands/column-command.d.ts +59 -0
  30. package/dist/commands/column-command.d.ts.map +1 -0
  31. package/dist/commands/comment-char-config.d.ts +15 -0
  32. package/dist/commands/comment-char-config.d.ts.map +1 -1
  33. package/dist/commands/commit-command.d.ts +21 -2
  34. package/dist/commands/commit-command.d.ts.map +1 -1
  35. package/dist/commands/config-command.d.ts +12 -0
  36. package/dist/commands/config-command.d.ts.map +1 -1
  37. package/dist/commands/credential-helper.d.ts +214 -0
  38. package/dist/commands/credential-helper.d.ts.map +1 -0
  39. package/dist/commands/default-branch.d.ts +17 -1
  40. package/dist/commands/default-branch.d.ts.map +1 -1
  41. package/dist/commands/diff-color-config.d.ts +4 -0
  42. package/dist/commands/diff-color-config.d.ts.map +1 -1
  43. package/dist/commands/diff-command.d.ts +12 -0
  44. package/dist/commands/diff-command.d.ts.map +1 -1
  45. package/dist/commands/fast-export/fast-export-command.d.ts +89 -2
  46. package/dist/commands/fast-export/fast-export-command.d.ts.map +1 -1
  47. package/dist/commands/fast-export/fast-import-command.d.ts +113 -8
  48. package/dist/commands/fast-export/fast-import-command.d.ts.map +1 -1
  49. package/dist/commands/fast-export/fast-stream-support.d.ts +0 -9
  50. package/dist/commands/fast-export/fast-stream-support.d.ts.map +1 -1
  51. package/dist/commands/fetch-command.d.ts +21 -0
  52. package/dist/commands/fetch-command.d.ts.map +1 -1
  53. package/dist/commands/git-hooks.d.ts +28 -0
  54. package/dist/commands/git-hooks.d.ts.map +1 -1
  55. package/dist/commands/history-command.d.ts +173 -7
  56. package/dist/commands/history-command.d.ts.map +1 -1
  57. package/dist/commands/index-host.d.ts +19 -0
  58. package/dist/commands/index-host.d.ts.map +1 -1
  59. package/dist/commands/index-refresh.d.ts +36 -0
  60. package/dist/commands/index-refresh.d.ts.map +1 -0
  61. package/dist/commands/index.d.ts +9 -0
  62. package/dist/commands/index.d.ts.map +1 -1
  63. package/dist/commands/index.js +7 -6
  64. package/dist/commands/init-command.d.ts +20 -0
  65. package/dist/commands/init-command.d.ts.map +1 -1
  66. package/dist/commands/local-transport.d.ts +29 -1
  67. package/dist/commands/local-transport.d.ts.map +1 -1
  68. package/dist/commands/log-command.d.ts +7 -0
  69. package/dist/commands/log-command.d.ts.map +1 -1
  70. package/dist/commands/log-output.d.ts +11 -0
  71. package/dist/commands/log-output.d.ts.map +1 -1
  72. package/dist/commands/maintenance-schedule-command.d.ts +122 -0
  73. package/dist/commands/maintenance-schedule-command.d.ts.map +1 -0
  74. package/dist/commands/merge-command.d.ts +2 -0
  75. package/dist/commands/merge-command.d.ts.map +1 -1
  76. package/dist/commands/merge-index-command.d.ts +42 -0
  77. package/dist/commands/merge-index-command.d.ts.map +1 -0
  78. package/dist/commands/merge-one-file.d.ts +129 -0
  79. package/dist/commands/merge-one-file.d.ts.map +1 -0
  80. package/dist/commands/merge-support.d.ts +21 -2
  81. package/dist/commands/merge-support.d.ts.map +1 -1
  82. package/dist/commands/object-disk-info.d.ts +35 -0
  83. package/dist/commands/object-disk-info.d.ts.map +1 -0
  84. package/dist/commands/octopus-merge.d.ts +3 -3
  85. package/dist/commands/octopus-merge.d.ts.map +1 -1
  86. package/dist/commands/promisor-remote.d.ts.map +1 -1
  87. package/dist/commands/pull-command.d.ts +55 -7
  88. package/dist/commands/pull-command.d.ts.map +1 -1
  89. package/dist/commands/push-command.d.ts +18 -1
  90. package/dist/commands/push-command.d.ts.map +1 -1
  91. package/dist/commands/range-diff/range-diff-command.d.ts +37 -1
  92. package/dist/commands/range-diff/range-diff-command.d.ts.map +1 -1
  93. package/dist/commands/rebase-command.d.ts +13 -1
  94. package/dist/commands/rebase-command.d.ts.map +1 -1
  95. package/dist/commands/ref-filter/for-each-ref-command.d.ts +3 -2
  96. package/dist/commands/ref-filter/for-each-ref-command.d.ts.map +1 -1
  97. package/dist/commands/ref-filter/ref-filter.d.ts.map +1 -1
  98. package/dist/commands/ref-filter/ref-format.d.ts +26 -1
  99. package/dist/commands/ref-filter/ref-format.d.ts.map +1 -1
  100. package/dist/commands/ref-filter/ref-listing-command.d.ts +9 -0
  101. package/dist/commands/ref-filter/ref-listing-command.d.ts.map +1 -1
  102. package/dist/commands/remote-transport.d.ts +27 -0
  103. package/dist/commands/remote-transport.d.ts.map +1 -1
  104. package/dist/commands/repack-command.d.ts +18 -2
  105. package/dist/commands/repack-command.d.ts.map +1 -1
  106. package/dist/commands/repo-command.d.ts +2 -7
  107. package/dist/commands/repo-command.d.ts.map +1 -1
  108. package/dist/commands/reset-command.d.ts +4 -1
  109. package/dist/commands/reset-command.d.ts.map +1 -1
  110. package/dist/commands/restore-command.d.ts.map +1 -1
  111. package/dist/commands/rev-list-command.d.ts +65 -0
  112. package/dist/commands/rev-list-command.d.ts.map +1 -1
  113. package/dist/commands/revert-command.d.ts +3 -0
  114. package/dist/commands/revert-command.d.ts.map +1 -1
  115. package/dist/commands/revision-filenames.d.ts.map +1 -1
  116. package/dist/commands/revision-range.d.ts +17 -0
  117. package/dist/commands/revision-range.d.ts.map +1 -1
  118. package/dist/commands/revision-resolver.d.ts +12 -0
  119. package/dist/commands/revision-resolver.d.ts.map +1 -1
  120. package/dist/commands/serve-repository.d.ts +17 -1
  121. package/dist/commands/serve-repository.d.ts.map +1 -1
  122. package/dist/commands/served-lazy-fetch.d.ts +61 -0
  123. package/dist/commands/served-lazy-fetch.d.ts.map +1 -0
  124. package/dist/commands/signing.d.ts +10 -4
  125. package/dist/commands/signing.d.ts.map +1 -1
  126. package/dist/commands/status-color-config.d.ts +33 -0
  127. package/dist/commands/status-color-config.d.ts.map +1 -0
  128. package/dist/commands/status-command.d.ts +15 -0
  129. package/dist/commands/status-command.d.ts.map +1 -1
  130. package/dist/commands/status-format.d.ts +46 -4
  131. package/dist/commands/status-format.d.ts.map +1 -1
  132. package/dist/commands/tag-command.d.ts +15 -1
  133. package/dist/commands/tag-command.d.ts.map +1 -1
  134. package/dist/commands/tree-restore.d.ts +14 -0
  135. package/dist/commands/tree-restore.d.ts.map +1 -1
  136. package/dist/commands/verify-command.d.ts +22 -2
  137. package/dist/commands/verify-command.d.ts.map +1 -1
  138. package/dist/commands/worktree-add-command.d.ts.map +1 -1
  139. package/dist/commands/worktree-overwrite-checks.d.ts +31 -6
  140. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  141. package/dist/{commands-C9M78Chn.js → commands-DT3VEv50.js} +14879 -16703
  142. package/dist/errors/commit-errors.d.ts +23 -3
  143. package/dist/errors/commit-errors.d.ts.map +1 -1
  144. package/dist/errors/git-api-error.d.ts +6 -0
  145. package/dist/errors/git-api-error.d.ts.map +1 -1
  146. package/dist/errors/index.js +30 -4
  147. package/dist/{fsck-C4US3l0B.js → fsck-BZ508Elg.js} +1 -1
  148. package/dist/git-command.d.ts +33 -1
  149. package/dist/git-command.d.ts.map +1 -1
  150. package/dist/git.d.ts +104 -1
  151. package/dist/git.d.ts.map +1 -1
  152. package/dist/index.js +8 -7
  153. package/dist/{remote-transport-C43eykfK.js → local-transport-D98U6p4d.js} +184 -683
  154. package/dist/{maintenance-run-command-CoJFKr2p.js → maintenance-run-command-DZFnbnbo.js} +2285 -79
  155. package/dist/remote-config/remote-config-store.d.ts +6 -0
  156. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  157. package/dist/remote-transport-zvSqwpOB.js +4865 -0
  158. package/dist/results/cherry-pick-result.d.ts +4 -3
  159. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  160. package/dist/results/diff-output.d.ts +7 -0
  161. package/dist/results/diff-output.d.ts.map +1 -1
  162. package/dist/results/diff-words.d.ts +14 -3
  163. package/dist/results/diff-words.d.ts.map +1 -1
  164. package/dist/results/index.js +1 -1
  165. package/dist/results/line-prefix-sink.d.ts +50 -0
  166. package/dist/results/line-prefix-sink.d.ts.map +1 -0
  167. package/dist/results/merge-result.d.ts +4 -3
  168. package/dist/results/merge-result.d.ts.map +1 -1
  169. package/dist/results/rebase-result.d.ts +5 -0
  170. package/dist/results/rebase-result.d.ts.map +1 -1
  171. package/dist/results/revert-result.d.ts +4 -3
  172. package/dist/results/revert-result.d.ts.map +1 -1
  173. package/dist/{results-B0CWLCAp.js → results-rF81cQse.js} +1425 -202
  174. package/dist/transport-command.d.ts +10 -0
  175. package/dist/transport-command.d.ts.map +1 -1
  176. package/package.json +12 -12
  177. package/src/commands/add-command.ts +15 -2
  178. package/src/commands/add-patch/patch-backend.ts +6 -44
  179. package/src/commands/archive/remote-archive-command.ts +10 -3
  180. package/src/commands/branch-command.ts +57 -4
  181. package/src/commands/cat-file/batch-format.ts +17 -18
  182. package/src/commands/cat-file/cat-file-command.ts +181 -15
  183. package/src/commands/check-ignore-command.ts +61 -17
  184. package/src/commands/checkout-command.ts +149 -21
  185. package/src/commands/checkout-index-command.ts +2 -1
  186. package/src/commands/checkout-paths.ts +13 -0
  187. package/src/commands/cherry-pick-command.ts +9 -0
  188. package/src/commands/clean-interactive.ts +20 -74
  189. package/src/commands/clone-command.ts +13 -0
  190. package/src/commands/column/column-config.ts +63 -0
  191. package/src/commands/column/column-layout.ts +396 -0
  192. package/src/commands/column/index.ts +2 -0
  193. package/src/commands/column-command.ts +171 -0
  194. package/src/commands/comment-char-config.ts +42 -0
  195. package/src/commands/commit-command.ts +61 -21
  196. package/src/commands/config-command.ts +28 -0
  197. package/src/commands/credential-helper.ts +807 -0
  198. package/src/commands/default-branch.ts +38 -0
  199. package/src/commands/diff-color-config.ts +23 -10
  200. package/src/commands/diff-command.ts +25 -2
  201. package/src/commands/fast-export/fast-export-command.ts +661 -35
  202. package/src/commands/fast-export/fast-import-command.ts +694 -94
  203. package/src/commands/fast-export/fast-stream-support.ts +18 -1
  204. package/src/commands/fetch-command.ts +103 -14
  205. package/src/commands/git-hooks.ts +85 -0
  206. package/src/commands/history-command.ts +952 -20
  207. package/src/commands/index-host.ts +51 -0
  208. package/src/commands/index-refresh.ts +121 -0
  209. package/src/commands/index.ts +9 -0
  210. package/src/commands/init-command.ts +34 -1
  211. package/src/commands/legacy-remotes.ts +4 -20
  212. package/src/commands/local-transport.ts +130 -9
  213. package/src/commands/log-command.ts +39 -1
  214. package/src/commands/log-output.ts +31 -4
  215. package/src/commands/maintenance-schedule-command.ts +418 -0
  216. package/src/commands/merge-command.ts +10 -0
  217. package/src/commands/merge-index-command.ts +202 -0
  218. package/src/commands/merge-one-file.ts +451 -0
  219. package/src/commands/merge-support.ts +127 -11
  220. package/src/commands/object-disk-info.ts +169 -0
  221. package/src/commands/octopus-merge.ts +37 -128
  222. package/src/commands/promisor-remote.ts +14 -3
  223. package/src/commands/pull-command.ts +173 -27
  224. package/src/commands/push-command.ts +50 -5
  225. package/src/commands/range-diff/range-diff-command.ts +86 -3
  226. package/src/commands/rebase-command.ts +46 -1
  227. package/src/commands/ref-filter/for-each-ref-command.ts +4 -3
  228. package/src/commands/ref-filter/ref-filter.ts +59 -4
  229. package/src/commands/ref-filter/ref-format.ts +83 -10
  230. package/src/commands/ref-filter/ref-listing-command.ts +30 -0
  231. package/src/commands/remote-command.ts +2 -2
  232. package/src/commands/remote-transport.ts +66 -3
  233. package/src/commands/repack-command.ts +75 -9
  234. package/src/commands/repo-command.ts +6 -70
  235. package/src/commands/reset-command.ts +11 -1
  236. package/src/commands/restore-command.ts +1 -0
  237. package/src/commands/rev-list-command.ts +205 -3
  238. package/src/commands/revert-command.ts +9 -0
  239. package/src/commands/revision-filenames.ts +32 -4
  240. package/src/commands/revision-range.ts +2 -2
  241. package/src/commands/revision-resolver.ts +21 -1
  242. package/src/commands/serve-repository.ts +34 -8
  243. package/src/commands/served-lazy-fetch.ts +164 -0
  244. package/src/commands/signing.ts +18 -10
  245. package/src/commands/status-color-config.ts +92 -0
  246. package/src/commands/status-command.ts +50 -2
  247. package/src/commands/status-format.ts +198 -50
  248. package/src/commands/tag-command.ts +57 -2
  249. package/src/commands/tree-restore.ts +17 -0
  250. package/src/commands/verify-command.ts +84 -12
  251. package/src/commands/worktree-add-command.ts +2 -0
  252. package/src/commands/worktree-overwrite-checks.ts +75 -14
  253. package/src/errors/commit-errors.ts +31 -3
  254. package/src/errors/git-api-error.ts +7 -0
  255. package/src/git-command.ts +105 -4
  256. package/src/git.ts +153 -0
  257. package/src/remote-config/remote-config-store.ts +16 -0
  258. package/src/results/cherry-pick-result.ts +4 -3
  259. package/src/results/diff-output.ts +8 -0
  260. package/src/results/diff-words.ts +160 -32
  261. package/src/results/line-prefix-sink.ts +102 -0
  262. package/src/results/merge-result.ts +4 -3
  263. package/src/results/rebase-result.ts +5 -0
  264. package/src/results/revert-result.ts +4 -3
  265. package/src/transport-command.ts +48 -2
@@ -1,15 +1,16 @@
1
- import { I as __exportAll, p as fetchFsckOf, x as checkSubmoduleName } from "./fsck-C4US3l0B.js";
1
+ import { I as __exportAll, p as fetchFsckOf, x as checkSubmoduleName } from "./fsck-BZ508Elg.js";
2
2
  import { FetchIntoCheckedOutBranchError, GitApiError, IncompatibleOptionsError, InvalidArgumentError, InvalidConfigError, InvalidPathError, InvalidRefNameError, InvalidRemoteError, MissingArgumentError, NoHeadError, NotACommitError, RefAlreadyExistsError, RefFilterError, RefNotFoundError, RevisionError, SwitchRefusedError, TransportError as TransportError$1 } from "./errors/index.js";
3
- import { $t as SubmoduleUnpack, Ao as rerereGcLocation, Bl as runPostCheckoutHook, C as patchRevisionOf, Cl as markIndexUpdate, Co as unknownRevisionMessage, Ct as matchArgValue, El as commonGitFileOf, Ft as removeBranchState, Hr as appendTrailers, Jl as coreBool, Jt as checkFlaggedEntries, M as DiffCommand, Ml as hookHostInGitDir, Ot as sanitizedSubject, Qt as restoreWorktreeHard, Sl as worktreePathRules, So as parseRevisionArgs, T as runPatchSelection, Tt as parseColorSpec, Tu as approxidateCareful$1, Ut as StashCreateCommand, Vo as ortConfigOptions, Wc as SparseUnpack, Xl as worktreeModeTrust, Xt as recordWrittenStat, Yo as stageZeroClashes, Yt as fsmonitorKeptEntries, Zt as restoreKeptEntries, _l as restoreCaseOptions, _n as shortBranchName, ai as matchPathspecSeen, al as overwriteMessage, an as STASH_REF, bi as parseDateMode, cl as removeDirectoryIfEmpty, co as installTracking, cu as configBool$2, dc as registerPartialClone, do as trackableStart, en as recursesIntoSubmodules, fa as rewriteIndex, fl as worktreeDiffers, gc as httpClientSettingsOf, gl as planTreeRestore, hc as resetPromisorAcceptance, hn as repositoryPlaceOf, ia as flatTree, ii as matchPathspec, il as flaggedEntryDiffers, in as StashApplyCommand, io as autoSetupRebase, jl as gitFileOf, jn as isSubmoduleIgnoreMode, ju as RemoteConfigStore, kt as wrapText, ku as deleteRefs, lc as promisorOf, li as pathspecErrors, lo as planTracking, lr as PathspecAttributes, lu as configValue, mc as promisorRemoteReplyOf, mn as refuseIfCheckedOut, nl as entryNotUptodate, oc as createPromisorFetcher, oi as parsePathspec, ol as pruneEmptyParents, or as MergeBaseGraph, pc as promisorAutoFilter, q as formatTrackingInfo, qc as pushSparseWarnings, qo as addLeadingDirs, rl as findInTheWay, rn as PathspecFile, sc as hasPromisorRemote, sn as LogCommand, so as guessRemoteBranch, sr as commitsBaseSource, su as bareAttributesResolver, ta as OperationState, tc as reflogMessages, ti as globalPathspecMagic, tt as revisionMergeBases, uc as promisorRemotes, un as shortenUnambiguousRef, uu as conflictStyleOf, va as updateIndexCacheTree, vl as writeTreeRestorePlan, vo as parseRevisionAndPathArgs, vt as expandStringArg, w as pathPatchMode, wt as matchBoolArg, xi as showDate, xl as withTreePathRefusal, xn as worktreeUsingBranch, xo as handleRevisionArg, yl as firstInvalidPath, yt as formatCommitPretty, yu as hostEnvironmentOf, za as GitCommand, zo as lowLevelMerge } from "./results-B0CWLCAp.js";
4
- import { C as WorktreePruneCommand, D as openBundle, E as bundleBytes, M as listBundleRefs, N as parseBundleHeader, O as verifyBundleIn, S as GarbageCollectCommand, a as protocolVersionOf, c as resolveRemote, d as withRemoteUploadPack, i as prepareRemote, j as encodeBundleHeader, n as httpSessionSettings, o as remoteContextOf, r as openResolvedRemote, t as bundleRemoteOf } from "./remote-transport-C43eykfK.js";
5
- import { FileMode, ObjectFilterError, PromisorFetchError, RefTransactionAbortedError, historyWithoutLazyFetch, isSymbolicRef, isValidBranchName, isValidRefName, objectFormatOf, parseCoreAbbrev, parseObjectFilter, writePack } from "@statewalker/vcs-core";
6
- import { compareGitPaths, decodeGitPath, encodeGitPath, parseGitBool } from "@statewalker/vcs-utils/encoding";
7
- import { AttributesMemo, attributesIndexOf, attributesSourceSetting, cacheTreeOfTree, collectChunks, entryStatOf, isIndexUnborn, wildmatch } from "@statewalker/vcs-working-tree";
8
- import { approxidateCareful, compareGitPaths as compareGitPaths$1, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, gitStrWidth as gitStrWidth$1, nullObjectIdLike, parseGitBool as parseGitBool$1, startProgress } from "@statewalker/vcs-utils";
3
+ import { $l as firstInvalidPath, $o as unknownRevisionMessage, $t as matchBoolArg, Aa as OperationState, Ai as globalPathspecMagic, Au as worktreeModeTrust, Bc as promisorRemotes, Bo as trackableStart, C as patchRevisionOf, Cn as checkFlaggedEntries, Cs as addLeadingDirs, Dn as restoreWorktreeHard, En as restoreKeptEntries, Fi as parsePathspec, Fl as findInTheWay, Fr as MergeBaseGraph, Fu as wsBlankLine, Gc as resetPromisorAcceptance, Gu as conflictStyleOf, Hu as bareAttributesResolver, Ic as createPromisorFetcher, Il as flaggedEntryDiffers, In as LogCommand, Io as guessRemoteBranch, Ir as commitsBaseSource, Iu as wsCheckEmit, Jt as formatCommitPretty, Kc as httpClientSettingsOf, Kl as worktreeDiffers, Kn as shortBranchName, Lc as hasPromisorRemote, Ll as leadingFileOf, Lo as installTracking, Lt as readDiffColorSettings, M as applyIndexStatUpdates, Mn as PathspecFile, Mu as WS_DEFAULT_RULE, N as refreshIndexEntries, Na as flatTree, Ni as matchPathspec, Nl as belowRefused, Nn as StashApplyCommand, No as autoSetupRebase, Nu as checkBlankAtEof, On as SubmoduleUnpack, Ot as revisionMergeBases, Ou as coreBool, P as DiffCommand, Pi as matchPathspecSeen, Pl as entryNotUptodate, Pn as STASH_REF, Pu as isGitSpace, Ql as writeTreeRestorePlan, Qo as parseRevisionArgs, Qs as formatStat, Qt as matchArgValue, Ri as pathspecErrors, Rl as overwriteMessage, Ro as planTracking, Rr as PathspecAttributes, T as runPatchSelection, Tn as recordWrittenStat, Ts as stageZeroClashes, Uc as promisorAutoFilter, Un as refuseIfCheckedOut, Uu as configBool$2, Va as rewriteIndex, Vc as registerPartialClone, Vl as removeDirectoryIfEmpty, Wc as promisorRemoteReplyOf, Wl as takeCleanSubdirectory, Wn as repositoryPlaceOf, Wu as configValue, Xi as showDate, Xl as planTreeRestore, Xn as worktreeUsingBranch, Y as formatTrackingInfo, Yi as parseDateMode, Zl as restoreCaseOptions, Zo as handleRevisionArg, _i as appendTrailers, _s as ortConfigOptions, aa as ApplyParser, bu as runPostCheckoutHook, ca as latin1ToBytes, du as gitFileOf, ed as hostEnvironmentOf, en as parseColorSpec, fd as RemoteConfigStore, fu as hookHostInGitDir, hs as lowLevelMerge, in as wrapText, iu as HookSession, jc as reflogMessages, kn as recursesIntoSubmodules, mo as GitCommand, mu as hookRunnerOf, nu as worktreePathRules, oa as bytesToLatin1, od as approxidateCareful$1, or as isSubmoduleIgnoreMode, os as rerereGcLocation, ou as commonGitFileOf, pa as newFilePatch, pi as mergesMode, qa as updateIndexCacheTree, qo as parseRevisionAndPathArgs, qt as expandStringArg, rn as sanitizedSubject, ru as markIndexUpdate, tu as withTreePathRefusal, ud as deleteRefs, un as removeBranchState, vn as StashCreateCommand, w as pathPatchMode, wl as pushSparseWarnings, wn as fsmonitorKeptEntries, xl as SparseUnpack, zc as promisorOf, zl as pruneEmptyParents, zn as shortenUnambiguousRef } from "./results-rF81cQse.js";
4
+ import { D as parseBundleHeader, E as listBundleRefs, S as verifyBundleIn, T as encodeBundleHeader, a as prepareRemote, b as bundleBytes, f as withRemoteUploadPack, i as openResolvedRemote, l as resolveRemote, n as httpSessionSettings, o as protocolVersionOf, r as localLazyFetchOf, s as remoteContextOf, t as bundleRemoteOf, x as openBundle } from "./remote-transport-zvSqwpOB.js";
5
+ import { _ as WorktreePruneCommand, c as remoteHookSession, g as GarbageCollectCommand } from "./local-transport-D98U6p4d.js";
6
+ import { FileMode, ObjectFilterError, PromisorFetchError, RefTransactionAbortedError, historyWithoutLazyFetch, isSymbolicRef, isValidBranchName, isValidRefName, joinPath, listObjects, objectFormatOf, packNameOf, parseCoreAbbrev, parseObjectFilter, resolveObjectFilter, writePack } from "@statewalker/vcs-core";
7
+ import { compareGitPaths, decodeGitPath, encodeGitPath, parseGitBool, parseGitInt } from "@statewalker/vcs-utils/encoding";
8
+ import { AttributesMemo, attributesIndexOf, attributesSourceSetting, cacheTreeOfTree, collectChunks, entryStatOf, isIndexUnborn, sparseFilterMatcher, wildmatch } from "@statewalker/vcs-working-tree";
9
+ import { approxidateCareful, compareGitPaths as compareGitPaths$1, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, formatHunkHeader, funcnameFindFunction, gitStrWidth as gitStrWidth$1, isUrlNormalizeError, normalizeUrl, nullObjectIdLike, parseGitBool as parseGitBool$1, startProgress, unifiedDiffHunks, urlMatchedEntries } from "@statewalker/vcs-utils";
9
10
  import { atomicFilesOver } from "@statewalker/vcs-utils/files";
10
11
  import { nullObjectIdLike as nullObjectIdLike$1 } from "@statewalker/vcs-utils/hash";
11
- import { ConfigParseError, FileRawStorage, GitWorkingCopyConfig, ReflogExpiryAbortedError, ReflogExpiryConfigError, configFilesApiOf, dropReflogs, expireReflogs, geometricSplit, multiPackIndexExpire, multiPackIndexRepack, multiPackIndexWrite, packDeltaSearch, parseExpiryDate, prunePacked, readPackWriteSettings, readRepositoryFormat, repack, rerereGc, rerereGcNeeded, writeCommitGraph, writeReflogEntry } from "@statewalker/vcs-store-files";
12
- import { FetchCheckError, GitTransportRegistry, NegotiateOnlyUnsupportedError, ObjectFormatMismatchError, ReceivedObjects, SmartHttpClient, TransportError, anonymizeUrl, checkReceivedPack, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, fetchFromConnection, fetchRefcolWidth, fetchUpdateDisplay, formatFetchDisplay, formatFetchHead, matchDestination, matchSource, negotiateOnly, negotiationAlgorithmOf, parseGitUrl, parseRefSpec, processSessionId, transportSummaryWidth, unpackLimitOf } from "@statewalker/vcs-transport";
12
+ import { ConfigParseError, FileRawStorage, GitWorkingCopyConfig, IncrementalMidxError, ReflogExpiryAbortedError, ReflogExpiryConfigError, configFilesApiOf, dropReflogs, expireReflogs, geometricSplit, multiPackIndexExpire, multiPackIndexRepack, multiPackIndexWrite, packDeltaSearch, parseExpiryDate, prunePacked, readPackWriteSettings, readRepositoryFormat, repack, rerereGc, rerereGcNeeded, writeCommitGraph, writeReflogEntry } from "@statewalker/vcs-store-files";
13
+ import { FetchCheckError, GitTransportRegistry, NegotiateOnlyUnsupportedError, ObjectFormatMismatchError, ReceivedObjects, SmartHttpClient, TransportError, anonymizeUrl, checkReceivedPack, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, fetchFromConnection, fetchRefcolWidth, fetchResultOf, fetchUpdateDisplay, formatFetchDisplay, formatFetchHead, matchDestination, matchSource, negotiateOnly, negotiationAlgorithmOf, parseGitUrl, parseRefSpec, processSessionId, refusedRefOf, transportSummaryWidth, unpackLimitOf } from "@statewalker/vcs-transport";
13
14
  import { collect } from "@statewalker/vcs-utils/streams";
14
15
  //#region src/commands/checkout-paths.ts
15
16
  /**
@@ -62,6 +63,7 @@ async function runPathCheckout(ctx, req) {
62
63
  "--merge"
63
64
  ], "fatal: git checkout: --ours/--theirs, --force and --merge are incompatible when\nchecking out of the index.");
64
65
  let sourceTree;
66
+ let sourceMetadata;
65
67
  if (from !== void 0) {
66
68
  let resolved;
67
69
  try {
@@ -72,6 +74,7 @@ async function runPathCheckout(ctx, req) {
72
74
  }
73
75
  if (!resolved.tree) throw new RefNotFoundError(from, `fatal: unable to read tree (${resolved.id})`);
74
76
  sourceTree = resolved.tree;
77
+ sourceMetadata = await ctx.checkoutRefOf?.(from === "@" ? "HEAD" : from, resolved.id);
75
78
  }
76
79
  if (ignoreUnmerged && req.merge) throw fail([isRestore ? "--ignore-unmerged" : "--force", "-m"], `fatal: options '${isRestore ? "--ignore-unmerged" : "--force"}' and '-m' cannot be used together`);
77
80
  if (!checkoutWorktree && !checkoutIndex) throw fail(["--staged", "--worktree"], "fatal: neither '--staged' or '--worktree' is specified");
@@ -98,6 +101,7 @@ async function runPathCheckout(ctx, req) {
98
101
  originals,
99
102
  reportUnmatched: !req.allPaths,
100
103
  ...sourceTree ? { sourceTree } : {},
104
+ ...sourceMetadata ? { sourceMetadata } : {},
101
105
  checkoutIndex,
102
106
  checkoutWorktree,
103
107
  overlay: req.overlay ?? !isRestore,
@@ -424,7 +428,11 @@ async function checkoutWorktree(ctx, o, ordered, out, changed) {
424
428
  ...written !== mode ? { raw: true } : {},
425
429
  createParents: true,
426
430
  replaceInTheWay: true,
427
- discardUntracked: true
431
+ discardUntracked: true,
432
+ metadata: {
433
+ ...o.sourceMetadata,
434
+ blob: objectId
435
+ }
428
436
  });
429
437
  return true;
430
438
  };
@@ -647,6 +655,14 @@ let CheckoutStatus = /* @__PURE__ */ function(CheckoutStatus) {
647
655
  }({});
648
656
  const sameSide = (a, b) => a === void 0 || b === void 0 ? a === b : a.objectId === b.objectId && a.mode === b.mode;
649
657
  /**
658
+ * The revision a switch was given as git's `setup_branch_path` reads it (`@` for HEAD, `-`
659
+ * for `@{-1}`): the start point of a branch created, else the name checked out.
660
+ */
661
+ function switchArgument(plan, name) {
662
+ const arg = plan.kind === "create" ? plan.startName : name;
663
+ return arg === "@" ? "HEAD" : arg === "-" ? "@{-1}" : arg;
664
+ }
665
+ /**
650
666
  * Command to checkout branches, commits, or paths.
651
667
  *
652
668
  * Based on JGit's CheckoutCommand. Supports both branch checkout
@@ -849,6 +865,11 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
849
865
  this.onlyMergeOnSwitchingBranches = only;
850
866
  return this;
851
867
  }
868
+ /** The index's file system monitor state for a refresh, when the monitor is on. */
869
+ async fsmonitorOf() {
870
+ const run = await this.fsmonitorRefresh(this.staging);
871
+ return run ? { fsmonitor: run.state } : {};
872
+ }
852
873
  /** Whether this switch skips merge_working_tree (see {@link setOnlyMergeOnSwitchingBranches}). */
853
874
  skipsMergeWorkingTree() {
854
875
  if (!this.onlyMergeOnSwitchingBranches || this.orphan) return false;
@@ -1290,7 +1311,7 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1290
1311
  blobs: this.blobs,
1291
1312
  workingCopy: this.workingCopy,
1292
1313
  worktree
1293
- }, treeId, trackedBefore, keptOut, sparse, void 0, new Set(fsmKept.keys()));
1314
+ }, treeId, trackedBefore, keptOut, sparse, void 0, new Set(fsmKept.keys()), { treeish: headId });
1294
1315
  await recordWrittenStat(this.staging, worktree, written);
1295
1316
  await this.staging.write();
1296
1317
  await sparse?.finish({
@@ -1307,10 +1328,12 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1307
1328
  * checkout do before the write).
1308
1329
  */
1309
1330
  async writeSwitchedIndex() {
1310
- await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
1331
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat, (lines) => this.cacheTreeLines.push(...lines, ...lines));
1311
1332
  markIndexUpdate(this.staging, { workdir: true });
1312
1333
  await this.staging.write();
1313
1334
  }
1335
+ /** verify_cache's lines of the switch's index write (stderr, after the sparse lines) */
1336
+ cacheTreeLines = [];
1314
1337
  /** The switch an autostash switch makes again: its caller runs post-checkout once. */
1315
1338
  noPostCheckout = false;
1316
1339
  withoutPostCheckout() {
@@ -1365,7 +1388,8 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1365
1388
  blobs: this.blobs,
1366
1389
  worktree: this.worktreeAccess,
1367
1390
  abbreviate: (id) => this.abbreviateObjectId(id),
1368
- resolveTree: (rev) => this.resolveSourceTree(rev)
1391
+ resolveTree: (rev) => this.resolveSourceTree(rev),
1392
+ checkoutRefOf: (rev, id) => this.checkoutRefOf(rev, id)
1369
1393
  };
1370
1394
  }
1371
1395
  /** git's `get_global_magic` from the host environment (`GIT_LITERAL_PATHSPECS`, ...). */
@@ -1445,13 +1469,18 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1445
1469
  const invalid = firstInvalidPath(target, index, pathRules);
1446
1470
  if (invalid !== void 0) throw new InvalidPathError(invalid);
1447
1471
  const keepAll = this.orphan && !this.orphanFromEmptyTree && !orphanCheckout && orphanStart === void 0;
1448
- if (!this.force && !keepAll && unmerged.size > 0) return {
1472
+ const refresh = !this.force && worktree ? await refreshIndexEntries(this.staging, worktree, {
1473
+ trust: worktreeModeTrust(this.workingCopy, worktree),
1474
+ ...await this.fsmonitorOf()
1475
+ }) : void 0;
1476
+ if (!this.force && unmerged.size > 0) return {
1449
1477
  status: "CONFLICTS",
1450
1478
  updated: [],
1451
1479
  removed: [],
1452
1480
  conflicts: [...unmerged].sort(),
1453
1481
  ref: null,
1454
- message: "error: you need to resolve your current index first"
1482
+ message: "error: you need to resolve your current index first",
1483
+ ...refresh && refresh.unmerged.length > 0 ? { output: refresh.unmerged.map((path) => `${path}: needs merge`) } : {}
1455
1484
  };
1456
1485
  const switched = [];
1457
1486
  const local = [];
@@ -1463,6 +1492,47 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1463
1492
  const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : void 0;
1464
1493
  const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
1465
1494
  const initial = unborn && !keepAll;
1495
+ const indexTime = this.staging.getUpdateTime();
1496
+ /**
1497
+ * Index entries verify_clean_subdirectory took out (see {@link takeCleanSubdirectory}):
1498
+ * removed, their own paths merged as if the index lacked them
1499
+ */
1500
+ const consumed = /* @__PURE__ */ new Set();
1501
+ /** Directories deleted_entry's verify_absent checks for untracked files */
1502
+ const absentDirs = [];
1503
+ /** Paths whose merge failed: git's traverse_trees enters no subtree of theirs */
1504
+ const refused = /* @__PURE__ */ new Set();
1505
+ /** The paths each refusal list holds (a path is listed once) */
1506
+ const listed = /* @__PURE__ */ new Map();
1507
+ const refuse = (list, path, at = path) => {
1508
+ let seen = listed.get(list);
1509
+ if (!seen) {
1510
+ seen = new Set(list);
1511
+ listed.set(list, seen);
1512
+ }
1513
+ if (!seen.has(at)) {
1514
+ seen.add(at);
1515
+ list.push(at);
1516
+ }
1517
+ refused.add(path);
1518
+ };
1519
+ /** `switched` as a set: a path verify_clean_subdirectory took out may come up again */
1520
+ const changing = /* @__PURE__ */ new Set();
1521
+ const change = (path) => {
1522
+ if (changing.has(path)) return;
1523
+ changing.add(path);
1524
+ switched.push(path);
1525
+ };
1526
+ /** Whether the switch so far removes the index entry at `path` (CE_REMOVE in its result) */
1527
+ const removesPath = (path) => changing.has(path) && !target.has(path);
1528
+ /** verify_absent's directory check of `path`; whether it passed */
1529
+ const cleanSubdirectory = async (wt, path) => {
1530
+ const result = await takeCleanSubdirectory(wt, path, index, consumed, trust, indexTime);
1531
+ for (const p of result.taken) change(p);
1532
+ if (result.notUptodate === void 0) return true;
1533
+ refuse(local, path, result.notUptodate);
1534
+ return false;
1535
+ };
1466
1536
  const paths = [.../* @__PURE__ */ new Set([...head.keys(), ...target.keys()])].sort();
1467
1537
  for (const path of keepAll ? [] : paths) {
1468
1538
  const h = head.get(path);
@@ -1477,7 +1547,8 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1477
1547
  continue;
1478
1548
  }
1479
1549
  if (!this.force && sameSide(h, t)) continue;
1480
- const i = index.get(path);
1550
+ if (!this.force && belowRefused(path, refused)) continue;
1551
+ const i = consumed.has(path) ? void 0 : index.get(path);
1481
1552
  if (this.force) {
1482
1553
  if (i?.skipWorktree && sameSide(i, t)) continue;
1483
1554
  if (fsmKept.has(path) && sameSide(i, t)) continue;
@@ -1487,25 +1558,35 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1487
1558
  continue;
1488
1559
  }
1489
1560
  if (sameSide(i, t)) {
1490
- if (h && !i && !t && worktree && await this.untrackedFileAt(worktree, path)) untrackedRemoved.push(path);
1561
+ if (h && !i && !t && worktree && !quiet(path)) {
1562
+ const there = await worktree.getEntry(path);
1563
+ if (there?.isDirectory) {
1564
+ if (h.mode !== FileMode.GITLINK && await cleanSubdirectory(worktree, path)) absentDirs.push(path);
1565
+ } else if (there) {
1566
+ if (!consumed.has(path) && await this.untrackedFileAt(worktree, path)) refuse(untrackedRemoved, path);
1567
+ } else {
1568
+ const leading = await leadingFileOf(worktree, path);
1569
+ if (leading !== void 0 && !(index.has(leading) && (consumed.has(leading) || removesPath(leading))) && !await worktree.isIgnored(leading)) refuse(untrackedRemoved, path, leading);
1570
+ }
1571
+ }
1491
1572
  continue;
1492
1573
  }
1493
1574
  if (!sameSide(i, h)) {
1494
- if (i !== void 0 || t !== void 0) local.push(path);
1575
+ if (i !== void 0 || t !== void 0) refuse(local, path);
1495
1576
  continue;
1496
1577
  }
1497
1578
  if (subs && worktree && !quiet(path)) {
1498
1579
  if (i !== void 0 && i.mode === FileMode.GITLINK) {
1499
1580
  if (!t && await subs.isSubmodule(path, i) && await subs.exists(path)) await subs.refuses(path, (h ?? i).objectId, null);
1500
- const refused = await subs.notUptodate(path, i);
1501
- if (refused) {
1502
- local.push(path);
1581
+ const notUptodate = await subs.notUptodate(path, i);
1582
+ if (notUptodate) {
1583
+ refuse(local, path);
1503
1584
  continue;
1504
1585
  }
1505
- if (refused === false) {
1586
+ if (notUptodate === false) {
1506
1587
  if (t && t.mode !== FileMode.GITLINK) await subs.fileReplacesRefuses(path, i);
1507
1588
  if (t) await subs.mergedRefuses(path, i, t);
1508
- switched.push(path);
1589
+ change(path);
1509
1590
  continue;
1510
1591
  }
1511
1592
  } else if (i === void 0 && t) {
@@ -1514,17 +1595,20 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1514
1595
  if (!absent) await subs.mergedRefuses(path, void 0, t);
1515
1596
  }
1516
1597
  }
1517
- if (i !== void 0 && worktree && !quiet(path) && await entryNotUptodate(worktree, path, i, trust, this.staging.getUpdateTime())) {
1518
- local.push(path);
1598
+ if (i !== void 0 && worktree && !quiet(path) && await entryNotUptodate(worktree, path, i, trust, indexTime)) {
1599
+ refuse(local, path);
1519
1600
  continue;
1520
1601
  }
1521
1602
  if (subs && i !== void 0 && t && !quiet(path)) await subs.mergedRefuses(path, i, t);
1522
- switched.push(path);
1603
+ if (i === void 0 && t && worktree && !quiet(path) && t.mode !== FileMode.GITLINK) {
1604
+ if ((await worktree.getEntry(path))?.isDirectory && !await cleanSubdirectory(worktree, path)) continue;
1605
+ }
1606
+ change(path);
1523
1607
  }
1524
1608
  if (worktree && !this.force) {
1525
1609
  const found = await findInTheWay(worktree, {
1526
- writes: switched.filter((p) => target.has(p) && writes(p) && !submodulePaths.has(p)),
1527
- removes: new Set(switched.filter((p) => !target.has(p))),
1610
+ writes: [...switched.filter((p) => target.has(p) && writes(p) && !submodulePaths.has(p)), ...absentDirs],
1611
+ removes: /* @__PURE__ */ new Set([...switched.filter((p) => !target.has(p)), ...consumed]),
1528
1612
  index,
1529
1613
  ...await restoreCaseOptions(worktree, ignoreCase),
1530
1614
  caseVariantsExpendable: true
@@ -1574,12 +1658,12 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1574
1658
  };
1575
1659
  }
1576
1660
  }
1577
- const refused = local.length + untracked.length + untrackedRemoved.length + lostDirs.length;
1578
- if (this.merge && headId && refused > 0 && this.patchCompatibility === "2.43") {
1661
+ const refusals = local.length + untracked.length + untrackedRemoved.length + lostDirs.length;
1662
+ if (this.merge && headId && refusals > 0 && this.patchCompatibility === "2.43") {
1579
1663
  const staged = [.../* @__PURE__ */ new Set([...index.keys(), ...head.keys()])].filter((p) => !sameSide(index.get(p), head.get(p))).sort(compareGitPaths);
1580
1664
  if (staged.length > 0) throw new SwitchRefusedError(`fatal: cannot continue with staged changes in the following files:\n${staged.join(" ")}`);
1581
1665
  }
1582
- if (this.merge && headId && refused > 0) {
1666
+ if (this.merge && headId && refusals > 0) {
1583
1667
  const left = await this.getCurrentBranch();
1584
1668
  this.autostashSwitch = {
1585
1669
  label: autostashLabel(switchTo),
@@ -1680,7 +1764,8 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1680
1764
  direction: "checkout",
1681
1765
  index: attributesIndexOf(result)
1682
1766
  },
1683
- progress
1767
+ progress,
1768
+ ...targetId ? { metadata: await this.checkoutRefOf(switchArgument(switchTo, this.name), targetId) } : {}
1684
1769
  });
1685
1770
  updated.push(...only.entries.map((e) => e.path));
1686
1771
  for (const e of [...only.entries, ...only.gitlinks]) written.add(e.path);
@@ -1692,6 +1777,7 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1692
1777
  progress.stop();
1693
1778
  }
1694
1779
  this.staging.clearResolveUndo?.();
1780
+ if (refresh) await applyIndexStatUpdates(this.staging, refresh.updates.filter((update) => !switching.has(update.path)));
1695
1781
  if (targetTreeId && this.force) {
1696
1782
  await this.staging.readTree(this.trees, targetTreeId, { keepMatching: "flags" });
1697
1783
  await restoreKeptEntries(this.staging, fsmKept);
@@ -1736,6 +1822,7 @@ var CheckoutCommand = class CheckoutCommand extends GitCommand {
1736
1822
  });
1737
1823
  pushSparseWarnings(sparseWarnings, sparse, outcome, true);
1738
1824
  }
1825
+ sparseWarnings.push(...this.cacheTreeLines.splice(0));
1739
1826
  return this.updateRefsForSwitch(switchTo, updated, removed, sparseWarnings);
1740
1827
  }
1741
1828
  /**
@@ -2467,7 +2554,7 @@ function estimateBisectSteps(all) {
2467
2554
  //#region src/commands/bisect/bisect-checkout.ts
2468
2555
  /** git's ORPHAN_CUTOFF */
2469
2556
  const ORPHAN_CUTOFF = 4;
2470
- const bool = (value, fallback) => {
2557
+ const bool$1 = (value, fallback) => {
2471
2558
  if (value === void 0) return fallback;
2472
2559
  const v = value.toLowerCase();
2473
2560
  if (v === "" || v === "true" || v === "yes" || v === "on" || v === "1") return true;
@@ -2498,7 +2585,7 @@ async function gitCheckout(host, name, options) {
2498
2585
  if (!old.path && old.id && now.id !== old.id) stderr += await orphanedCommitWarning(host, old.id, now.id);
2499
2586
  const describe = (msg, id) => describeDetachedHead(host, msg, id);
2500
2587
  if (name === "HEAD" && !now.path) {} else if (!now.path) {
2501
- if (old.path && bool(host.config("advice.detachedHead"), true)) stderr += detachAdvice(name);
2588
+ if (old.path && bool$1(host.config("advice.detachedHead"), true)) stderr += detachAdvice(name);
2502
2589
  if (now.id) stderr += await describe("HEAD is now at", now.id);
2503
2590
  } else if (old.path && old.path === now.path) stderr += `Already on '${name}'\n`;
2504
2591
  else stderr += `Switched to branch '${name}'\n`;
@@ -2568,7 +2655,7 @@ async function orphanedCommitWarning(host, oldId, newId) {
2568
2655
  }
2569
2656
  const one = lost.length === 1;
2570
2657
  let out = `Warning: you are leaving ${lost.length} ${one ? "commit" : "commits"} behind, not connected to\nany of your branches:\n\n${sb}\n`;
2571
- if (bool(host.config("advice.detachedHead"), true)) out += `If you want to keep ${one ? "it" : "them"} by creating a new branch, this may be a good time\nto do so with:\n\n git branch <new-branch-name> ${await host.abbreviate(oldId)}\n\n`;
2658
+ if (bool$1(host.config("advice.detachedHead"), true)) out += `If you want to keep ${one ? "it" : "them"} by creating a new branch, this may be a good time\nto do so with:\n\n git branch <new-branch-name> ${await host.abbreviate(oldId)}\n\n`;
2572
2659
  return out;
2573
2660
  }
2574
2661
  /** The commits `from` reaches that `not` does not (a limited walk of `from ^not`). */
@@ -2605,7 +2692,7 @@ async function reportTracking(host, path) {
2605
2692
  }, path, {
2606
2693
  quick: false,
2607
2694
  divergenceAdvice: true,
2608
- hints: bool(host.config("advice.statusHints"), true)
2695
+ hints: bool$1(host.config("advice.statusHints"), true)
2609
2696
  });
2610
2697
  return {
2611
2698
  stdout: report.text,
@@ -4168,8 +4255,1163 @@ var BisectRunCommand = class extends BisectCommand {
4168
4255
  }
4169
4256
  };
4170
4257
  //#endregion
4258
+ //#region src/commands/object-disk-info.ts
4259
+ /**
4260
+ * What an object takes on disk, as git's `odb_read_object_info_extended` reports it through
4261
+ * `disk_sizep`: a packed object's entry (from its offset to the next entry's, or to the pack's
4262
+ * trailer for the last), else its loose file's size. Packs are asked first (the repository's
4263
+ * own in the pack set's lookup order, then its alternates'), then the loose files (its own,
4264
+ * then its alternates'), as git's `oid_object_info_extended` looks objects up.
4265
+ *
4266
+ * `git repo structure` (its disk sizes), `git rev-list --disk-usage`, and the
4267
+ * `%(objectsize:disk)`/`%(deltabase)` atoms of `cat-file` and the ref filter share it.
4268
+ */
4269
+ /**
4270
+ * The on-disk measures of the objects of `workingCopy`'s object directory and its alternates.
4271
+ *
4272
+ * @example
4273
+ * ```typescript
4274
+ * const info = await objectDiskInfoOf(workingCopy);
4275
+ * const bytes = (await info.diskSize(id)) ?? 0;
4276
+ * ```
4277
+ */
4278
+ async function objectDiskInfoOf(workingCopy) {
4279
+ const objectsFile = await commonGitFileOf(workingCopy, "objects");
4280
+ const packSet = workingCopy.history.packs;
4281
+ const packs = [];
4282
+ /** The objects directory of each pack and of each loose source, own first */
4283
+ const packDirs = /* @__PURE__ */ new Map();
4284
+ const looseDirs = [];
4285
+ /**
4286
+ * Reads the pack lists (again): a lazy fetch of a partial clone installs a new pack while a
4287
+ * command runs, as git's `reprepare_packed_git` after a miss.
4288
+ */
4289
+ const loadPacks = async (rescan = false) => {
4290
+ const add = (pack, dir) => {
4291
+ if (packDirs.has(pack)) return;
4292
+ packs.push(pack);
4293
+ packDirs.set(pack, dir);
4294
+ };
4295
+ if (!objectsFile) return;
4296
+ if (rescan) await packSet?.refresh().catch(() => false);
4297
+ for (const pack of await packSet?.packs().catch(() => []) ?? []) add(pack, objectsFile.path);
4298
+ const alternates = await workingCopy.history.objects?.alternates?.list().catch(() => []) ?? [];
4299
+ for (const alternate of alternates) {
4300
+ if (rescan) await alternate.packs.refresh().catch(() => false);
4301
+ for (const pack of await alternate.packs.packs().catch(() => []) ?? []) add(pack, alternate.objectsDir);
4302
+ if (!looseDirs.includes(alternate.objectsDir)) looseDirs.push(alternate.objectsDir);
4303
+ }
4304
+ };
4305
+ if (objectsFile) looseDirs.push(objectsFile.path);
4306
+ await loadPacks();
4307
+ const format = objectFormatOf(workingCopy.history.objects);
4308
+ const trailer = format.rawLength;
4309
+ const sorted = /* @__PURE__ */ new Map();
4310
+ const packSizes = /* @__PURE__ */ new Map();
4311
+ const offsetsOf = (pack) => {
4312
+ let offsets = sorted.get(pack);
4313
+ if (!offsets) {
4314
+ offsets = new Float64Array(pack.count);
4315
+ for (let i = 0; i < pack.count; i++) offsets[i] = pack.offsetAt?.(i) ?? 0;
4316
+ offsets.sort();
4317
+ sorted.set(pack, offsets);
4318
+ }
4319
+ return offsets;
4320
+ };
4321
+ const packSizeOf = async (pack) => {
4322
+ let size = packSizes.get(pack);
4323
+ if (size === void 0) {
4324
+ size = 0;
4325
+ const dir = packDirs.get(pack);
4326
+ if (objectsFile && dir !== void 0) {
4327
+ const path = joinPath(dir, "pack", `${packNameOf(pack)}.pack`);
4328
+ size = (await objectsFile.files.stats(path))?.size ?? 0;
4329
+ }
4330
+ packSizes.set(pack, size);
4331
+ }
4332
+ return size;
4333
+ };
4334
+ /** The pack holding `id` (the first in lookup order) and the entry's offset. */
4335
+ const packedIn = (id) => {
4336
+ for (const pack of packs) {
4337
+ if (!pack.has(id) || !pack.indexOf || !pack.offsetAt) continue;
4338
+ const index = pack.indexOf(id);
4339
+ if (index < 0) continue;
4340
+ return {
4341
+ pack,
4342
+ offset: pack.offsetAt(index)
4343
+ };
4344
+ }
4345
+ };
4346
+ const looseSize = async (id) => {
4347
+ for (const dir of looseDirs) {
4348
+ const path = joinPath(dir, id.slice(0, 2), id.slice(2));
4349
+ const stats = await objectsFile?.files.stats(path).catch(() => void 0);
4350
+ if (stats?.kind === "file") return stats.size;
4351
+ }
4352
+ };
4353
+ /** Where `id` is stored: packs first, then loose files, the pack lists reread on a miss. */
4354
+ const locate = async (id) => {
4355
+ for (let pass = 0; pass < 2; pass++) {
4356
+ const packed = packedIn(id);
4357
+ if (packed) return { packed };
4358
+ const loose = await looseSize(id);
4359
+ if (loose !== void 0) return { loose };
4360
+ if (pass === 0) await loadPacks(true);
4361
+ }
4362
+ };
4363
+ return {
4364
+ async diskSize(id) {
4365
+ const where = await locate(id);
4366
+ if (!where) return void 0;
4367
+ if ("loose" in where) return where.loose;
4368
+ const { pack, offset } = where.packed;
4369
+ const offsets = offsetsOf(pack);
4370
+ let lo = 0;
4371
+ let hi = offsets.length;
4372
+ while (lo < hi) {
4373
+ const mid = lo + hi >> 1;
4374
+ if (offsets[mid] <= offset) lo = mid + 1;
4375
+ else hi = mid;
4376
+ }
4377
+ return (lo < offsets.length ? offsets[lo] : await packSizeOf(pack) - trailer) - offset;
4378
+ },
4379
+ async deltaBase(id) {
4380
+ const where = await locate(id);
4381
+ if (!where) return void 0;
4382
+ if ("packed" in where) {
4383
+ const entry = await where.packed.pack.entry(id);
4384
+ if (entry && (entry.kind === 6 || entry.kind === 7)) return entry.baseId;
4385
+ }
4386
+ return format.nullId;
4387
+ }
4388
+ };
4389
+ }
4390
+ //#endregion
4391
+ //#region src/commands/range-diff/linear-assignment.ts
4392
+ /**
4393
+ * git's linear-assignment.c: the Jonker-Volgenant shortest augmenting path solver of the
4394
+ * linear assignment problem (Jonker, R., & Volgenant, A. (1987). A shortest augmenting path
4395
+ * algorithm for dense and sparse linear assignment problems. Computing, 38(4), 325-340),
4396
+ * step for step as git runs it, so that ties end in git's pairing.
4397
+ *
4398
+ * @example
4399
+ * ```typescript
4400
+ * // two columns, two rows: column 0 costs 1 in row 0 and 2 in row 1
4401
+ * const { columnToRow } = computeAssignment(2, 2, [1, 5, 2, 1]);
4402
+ * // columnToRow: [0, 1]
4403
+ * ```
4404
+ */
4405
+ /** git's `INT_MAX` */
4406
+ const INT_MAX = 2147483647;
4407
+ /**
4408
+ * `compute_assignment`: the assignment of columns to rows of least total cost. `cost` is the
4409
+ * cost matrix, the cost of assigning column `j` to row `i` at `cost[j + columnCount * i]`.
4410
+ * With fewer than two columns every column and row is paired with 0, as git leaves them.
4411
+ *
4412
+ * @throws Error where git hits its `BUG("negative j")`
4413
+ */
4414
+ function computeAssignment(columnCount, rowCount, cost) {
4415
+ const column2row = new Int32Array(columnCount);
4416
+ const row2column = new Int32Array(rowCount);
4417
+ if (columnCount < 2) return {
4418
+ columnToRow: column2row,
4419
+ rowToColumn: row2column
4420
+ };
4421
+ const COST = (column, row) => cost[column + columnCount * row];
4422
+ column2row.fill(-1);
4423
+ row2column.fill(-1);
4424
+ const v = new Int32Array(columnCount);
4425
+ for (let j = columnCount - 1; j >= 0; j--) {
4426
+ let i1 = 0;
4427
+ for (let i = 1; i < rowCount; i++) if (COST(j, i1) > COST(j, i)) i1 = i;
4428
+ v[j] = COST(j, i1);
4429
+ if (row2column[i1] === -1) {
4430
+ row2column[i1] = j;
4431
+ column2row[j] = i1;
4432
+ } else {
4433
+ if (row2column[i1] >= 0) row2column[i1] = -2 - row2column[i1];
4434
+ column2row[j] = -1;
4435
+ }
4436
+ }
4437
+ const freeRow = new Int32Array(rowCount);
4438
+ let freeCount = 0;
4439
+ for (let i = 0; i < rowCount; i++) {
4440
+ const j1 = row2column[i];
4441
+ if (j1 === -1) freeRow[freeCount++] = i;
4442
+ else if (j1 < -1) row2column[i] = -2 - j1;
4443
+ else {
4444
+ const other = j1 === 0 ? 1 : 0;
4445
+ let min = COST(other, i) - v[other];
4446
+ for (let j = 1; j < columnCount; j++) if (j !== j1 && min > COST(j, i) - v[j]) min = COST(j, i) - v[j];
4447
+ v[j1] = v[j1] - min;
4448
+ }
4449
+ }
4450
+ if (freeCount === (columnCount < rowCount ? rowCount - columnCount : 0)) return {
4451
+ columnToRow: column2row,
4452
+ rowToColumn: row2column
4453
+ };
4454
+ for (let phase = 0; phase < 2; phase++) {
4455
+ let k = 0;
4456
+ const savedFreeCount = freeCount;
4457
+ freeCount = 0;
4458
+ while (k < savedFreeCount) {
4459
+ let j1 = 0;
4460
+ const i = freeRow[k++];
4461
+ let u1 = COST(j1, i) - v[j1];
4462
+ let j2 = -1;
4463
+ let u2 = INT_MAX;
4464
+ for (let j = 1; j < columnCount; j++) {
4465
+ const c = COST(j, i) - v[j];
4466
+ if (u2 > c) {
4467
+ if (u1 < c) {
4468
+ u2 = c;
4469
+ j2 = j;
4470
+ } else {
4471
+ u2 = u1;
4472
+ u1 = c;
4473
+ j2 = j1;
4474
+ j1 = j;
4475
+ }
4476
+ }
4477
+ }
4478
+ if (j2 < 0) {
4479
+ j2 = j1;
4480
+ u2 = u1;
4481
+ }
4482
+ let i0 = column2row[j1];
4483
+ if (u1 < u2) v[j1] = v[j1] - (u2 - u1);
4484
+ else if (i0 >= 0) {
4485
+ j1 = j2;
4486
+ i0 = column2row[j1];
4487
+ }
4488
+ if (i0 >= 0) {
4489
+ if (u1 < u2) freeRow[--k] = i0;
4490
+ else freeRow[freeCount++] = i0;
4491
+ }
4492
+ row2column[i] = j1;
4493
+ column2row[j1] = i;
4494
+ }
4495
+ }
4496
+ const savedFreeCount = freeCount;
4497
+ const d = new Int32Array(columnCount);
4498
+ const pred = new Int32Array(columnCount);
4499
+ const col = new Int32Array(columnCount);
4500
+ for (freeCount = 0; freeCount < savedFreeCount; freeCount++) {
4501
+ const i1 = freeRow[freeCount];
4502
+ let low = 0;
4503
+ let up = 0;
4504
+ let last = 0;
4505
+ let min = 0;
4506
+ let i = 0;
4507
+ for (let j = 0; j < columnCount; j++) {
4508
+ d[j] = COST(j, i1) - v[j];
4509
+ pred[j] = i1;
4510
+ col[j] = j;
4511
+ }
4512
+ let j = -1;
4513
+ update: do {
4514
+ last = low;
4515
+ min = d[col[up++]];
4516
+ for (let k = up; k < columnCount; k++) {
4517
+ j = col[k];
4518
+ const c = d[j];
4519
+ if (c <= min) {
4520
+ if (c < min) {
4521
+ up = low;
4522
+ min = c;
4523
+ }
4524
+ col[k] = col[up];
4525
+ col[up++] = j;
4526
+ }
4527
+ }
4528
+ for (let k = low; k < up; k++) if (column2row[col[k]] === -1) break update;
4529
+ do {
4530
+ const j1 = col[low++];
4531
+ i = column2row[j1];
4532
+ const u1 = COST(j1, i) - v[j1] - min;
4533
+ for (let k = up; k < columnCount; k++) {
4534
+ j = col[k];
4535
+ const c = COST(j, i) - v[j] - u1;
4536
+ if (c < d[j]) {
4537
+ d[j] = c;
4538
+ pred[j] = i;
4539
+ if (c === min) {
4540
+ if (column2row[j] === -1) break update;
4541
+ col[k] = col[up];
4542
+ col[up++] = j;
4543
+ }
4544
+ }
4545
+ }
4546
+ } while (low !== up);
4547
+ } while (low === up);
4548
+ for (let k = 0; k < last; k++) {
4549
+ const j1 = col[k];
4550
+ v[j1] = v[j1] + d[j1] - min;
4551
+ }
4552
+ do {
4553
+ if (j < 0) throw new Error(`BUG: negative j: ${j}`);
4554
+ i = pred[j];
4555
+ column2row[j] = i;
4556
+ const swap = row2column[i];
4557
+ row2column[i] = j;
4558
+ j = swap;
4559
+ } while (i1 !== i);
4560
+ }
4561
+ return {
4562
+ columnToRow: column2row,
4563
+ rowToColumn: row2column
4564
+ };
4565
+ }
4566
+ //#endregion
4567
+ //#region src/commands/range-diff/range-diff.ts
4568
+ /** range-diff.h's RANGE_DIFF_CREATION_FACTOR_DEFAULT */
4569
+ const RANGE_DIFF_CREATION_FACTOR_DEFAULT = 60;
4570
+ /** range-diff.h's CREATION_FACTOR_FOR_THE_SAME_SERIES (format-patch from 2.46 on) */
4571
+ const CREATION_FACTOR_FOR_THE_SAME_SERIES = 999;
4572
+ /**
4573
+ * range-diff.h's RANGE_DIFF_MAX_MEMORY_DEFAULT on 64-bit hosts: the largest cost matrix
4574
+ * (`4 * n * n` bytes) range-diff builds, 4 GiB. git 2.52 added it with `--max-memory`;
4575
+ * ours applies it whatever the version, so that a huge pair of ranges is refused rather than
4576
+ * trying to allocate gigabytes.
4577
+ */
4578
+ const RANGE_DIFF_MAX_MEMORY_DEFAULT = 4n * 1024n * 1024n * 1024n;
4579
+ /** The largest value git's `git_parse_unsigned` takes for a `size_t` (SIZE_MAX, 64-bit) */
4580
+ const SIZE_MAX = (1n << 64n) - 1n;
4581
+ /**
4582
+ * builtin/range-diff.c's `parse_max_memory` (`git_parse_unsigned` up to SIZE_MAX): a number
4583
+ * (decimal, `0x` hex or `0` octal, as strtoumax reads it) with an optional `k`, `m` or `g`
4584
+ * unit (any case); undefined for what git refuses (`invalid max-memory value`).
4585
+ */
4586
+ function parseRangeDiffMaxMemory(value) {
4587
+ if (!value || value.includes("-")) return void 0;
4588
+ const m = /^[ \t\n\v\f\r]*\+?(?:0[xX]([0-9a-fA-F]+)|(0[0-7]*)|([1-9][0-9]*))(.*)$/s.exec(value);
4589
+ if (!m) return void 0;
4590
+ let val;
4591
+ if (m[1] !== void 0) val = BigInt(`0x${m[1]}`);
4592
+ else if (m[2] !== void 0) val = BigInt(`0o${m[2] === "0" ? "0" : m[2].slice(1)}`);
4593
+ else val = BigInt(m[3]);
4594
+ if (val > SIZE_MAX) return void 0;
4595
+ const unit = m[4].toLowerCase();
4596
+ const factor = unit === "" ? 1n : unit === "k" ? 1024n : unit === "m" ? 1n << 20n : unit === "g" ? 1n << 30n : 0n;
4597
+ if (factor === 0n || factor * val > SIZE_MAX) return void 0;
4598
+ return factor * val;
4599
+ }
4600
+ /** strbuf.c's `humanise_bytes` (not compact): `4.00 GiB`, `1.50 MiB`, `12 bytes`. */
4601
+ function humaniseBytes(bytes) {
4602
+ const two = (n) => n.toString().padStart(2, "0");
4603
+ if (bytes > 1n << 30n) return `${bytes >> 30n & 4294967295n}.${two((bytes & (1n << 30n) - 1n) / 10737419n)} GiB`;
4604
+ if (bytes > 1n << 20n) {
4605
+ const x = bytes + 5243n & 4294967295n;
4606
+ return `${x >> 20n}.${two((x & (1n << 20n) - 1n) * 100n >> 20n)} MiB`;
4607
+ }
4608
+ if (bytes > 1n << 10n) {
4609
+ const x = bytes + 5n & 4294967295n;
4610
+ return `${x >> 10n}.${two((x & (1n << 10n) - 1n) * 100n >> 10n)} KiB`;
4611
+ }
4612
+ return `${bytes} ${bytes === 1n ? "byte" : "bytes"}`;
4613
+ }
4614
+ /** Thrown where range-diff dies over the cost matrix's size (exit 128). */
4615
+ var RangeDiffMemoryError = class extends Error {};
4616
+ /** linear-assignment.h's COST_MAX */
4617
+ const COST_MAX = 65536;
4618
+ /** Thrown where range-diff's reading fails (`error(...)`; the command then exits 1). */
4619
+ var RangeDiffError = class extends Error {};
4620
+ const diffOf = (p) => p.patch.slice(p.diffOffset);
4621
+ /**
4622
+ * `read_patches`: the patches of a `git log --no-color -p --reverse --date-order
4623
+ * --decorate=no --no-prefix --submodule=short --no-abbrev-commit --pretty=medium` output
4624
+ * (as a binary string, ordinary `+`/`-`/` ` indicators), each commit's section headers
4625
+ * (` ## Metadata ##`, ` ## Commit message ##`, ` ## Notes ##`, ` ## <file> ##`) and hunk
4626
+ * lines rewritten as git rewrites them.
4627
+ */
4628
+ function readRangeDiffPatches(log, includeMerges = false) {
4629
+ const list = [];
4630
+ let buf = "";
4631
+ let util;
4632
+ let inHeader = true;
4633
+ let currentFilename;
4634
+ const parser = new ApplyParser();
4635
+ parser.pValue = 0;
4636
+ parser.verbosity = -1;
4637
+ const push = () => {
4638
+ if (util) {
4639
+ util.patch = buf;
4640
+ list.push(util);
4641
+ }
4642
+ };
4643
+ let at = 0;
4644
+ let size = log.length;
4645
+ while (size > 0) {
4646
+ const nl = log.indexOf("\n", at);
4647
+ const hasEol = nl >= 0 && nl < at + size;
4648
+ let len = hasEol ? nl + 1 - at : size;
4649
+ const line = log.slice(at, hasEol ? nl : at + size);
4650
+ if (line.startsWith("commit ")) {
4651
+ push();
4652
+ buf = "";
4653
+ let p = line.slice(7);
4654
+ const from = includeMerges ? p.indexOf(" (from ") : -1;
4655
+ if (from >= 0) p = p.slice(0, from);
4656
+ if (!/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(p)) throw new RangeDiffError(`could not parse commit '${p}'`);
4657
+ util = {
4658
+ oid: p,
4659
+ patch: "",
4660
+ diffOffset: 0,
4661
+ diffsize: 0,
4662
+ i: 0,
4663
+ matching: -1,
4664
+ shown: false
4665
+ };
4666
+ inHeader = true;
4667
+ size -= len;
4668
+ at += len;
4669
+ continue;
4670
+ }
4671
+ if (!util) throw new RangeDiffError(`could not parse first line of \`log\` output: did not start with 'commit ': '${line}'`);
4672
+ if (line.startsWith("diff --git")) {
4673
+ inHeader = false;
4674
+ buf += "\n";
4675
+ if (!util.diffOffset) util.diffOffset = buf.length;
4676
+ const patch = newFilePatch();
4677
+ const origLen = len;
4678
+ parser.linenr = 0;
4679
+ len = parser.readGitDiffHeader(log, at, len, size, patch);
4680
+ if (len < 0) throw new RangeDiffError(`could not parse git header '${log.slice(at, at + origLen)}'`);
4681
+ buf += " ## ";
4682
+ if (patch.isNew > 0) buf += `${patch.newName} (new)`;
4683
+ else if (patch.isDelete > 0) buf += `${patch.oldName} (deleted)`;
4684
+ else if (patch.isRename) buf += `${patch.oldName} => ${patch.newName}`;
4685
+ else buf += patch.newName ?? "";
4686
+ currentFilename = (patch.isDelete > 0 ? patch.oldName : patch.newName) ?? void 0;
4687
+ if (patch.newMode && patch.oldMode && patch.oldMode !== patch.newMode) {
4688
+ const o = (m) => m.toString(8).padStart(6, "0");
4689
+ buf += ` (mode change ${o(patch.oldMode)} => ${o(patch.newMode)})`;
4690
+ }
4691
+ buf += " ##";
4692
+ } else if (inHeader) {
4693
+ if (line.startsWith("Author: ")) buf += ` ## Metadata ##\n${line}\n\n ## Commit message ##\n`;
4694
+ else if (line.startsWith("Notes") && line.endsWith(":")) buf += `\n\n ## ${line.slice(0, -1)} ##\n`;
4695
+ else if (line.startsWith(" ")) {
4696
+ let p = len - 2;
4697
+ while (p >= 0 && isGitSpace(log.charCodeAt(at + p))) p--;
4698
+ buf += `${log.slice(at, at + p + 1)}\n`;
4699
+ }
4700
+ size -= len;
4701
+ at += len;
4702
+ continue;
4703
+ } else if (line.startsWith("@@ ")) {
4704
+ const rest = line.slice(3);
4705
+ const p = rest.indexOf("@@");
4706
+ buf += "@@";
4707
+ if (p >= 0) {
4708
+ const after = rest.slice(p + 2);
4709
+ if (currentFilename !== void 0 && after.length > 0) buf += ` ${currentFilename}:`;
4710
+ buf += after;
4711
+ }
4712
+ } else if (line.length === 0) {
4713
+ size -= len;
4714
+ at += len;
4715
+ continue;
4716
+ } else if (line[0] === "+") buf += `+${line.slice(1)}`;
4717
+ else if (line[0] === "-") buf += `-${line.slice(1)}`;
4718
+ else if (line[0] === " ") buf += ` ${line.slice(1)}`;
4719
+ else buf += ` ${line}`;
4720
+ buf += "\n";
4721
+ util.diffsize++;
4722
+ size -= len;
4723
+ at += len;
4724
+ }
4725
+ push();
4726
+ for (const [i, p] of list.entries()) p.i = i;
4727
+ return list;
4728
+ }
4729
+ /**
4730
+ * `find_exact_matches`: the patches whose diffs are identical paired (several identical ones
4731
+ * in `a`: the last one first, as git's hashmap returns them).
4732
+ */
4733
+ function findExactMatches(a, b) {
4734
+ const map = /* @__PURE__ */ new Map();
4735
+ for (const [i, util] of a.entries()) {
4736
+ util.i = i;
4737
+ const key = diffOf(util);
4738
+ const list = map.get(key);
4739
+ if (list) list.push(util);
4740
+ else map.set(key, [util]);
4741
+ }
4742
+ for (const [i, util] of b.entries()) {
4743
+ util.i = i;
4744
+ const other = map.get(diffOf(util))?.pop();
4745
+ if (other) {
4746
+ if (other.matching >= 0) throw new Error("BUG: already assigned!");
4747
+ other.matching = i;
4748
+ util.matching = other.i;
4749
+ }
4750
+ }
4751
+ }
4752
+ /** `diffsize`: the lines (hunk headers included) of the diff of two texts, three of context. */
4753
+ function diffsize(a, b) {
4754
+ const result = unifiedDiffHunks(latin1ToBytes(a), latin1ToBytes(b), { context: 3 });
4755
+ let count = 0;
4756
+ for (const hunk of result.hunks) count += 1 + hunk.lines.length;
4757
+ return count;
4758
+ }
4759
+ /**
4760
+ * `get_correspondences`: the patches not matched exactly paired by the least total cost (the
4761
+ * size of the diff between two patches; creating or dropping a patch costs its size times
4762
+ * `creationFactor` percent).
4763
+ */
4764
+ function getCorrespondences(a, b, creationFactor, maxMemory = RANGE_DIFF_MAX_MEMORY_DEFAULT) {
4765
+ const n = a.length + b.length;
4766
+ const costBytes = 4n * BigInt(n) * BigInt(n);
4767
+ if (costBytes >= maxMemory) throw new RangeDiffMemoryError(`range-diff: unable to compute the range-diff, since it exceeds the maximum memory for the cost matrix: ${humaniseBytes(costBytes)} (${costBytes} bytes) needed, limited to ${humaniseBytes(maxMemory)} (${maxMemory} bytes)`);
4768
+ const cost = new Int32Array(n * n);
4769
+ const scaled = (size) => Math.trunc(size * creationFactor / 100);
4770
+ for (let i = 0; i < a.length; i++) {
4771
+ const aUtil = a[i];
4772
+ for (let j = 0; j < b.length; j++) {
4773
+ const bUtil = b[j];
4774
+ let c;
4775
+ if (aUtil.matching === j) c = 0;
4776
+ else if (aUtil.matching < 0 && bUtil.matching < 0) c = diffsize(diffOf(aUtil), diffOf(bUtil));
4777
+ else c = COST_MAX;
4778
+ cost[i + n * j] = c;
4779
+ }
4780
+ const c = aUtil.matching < 0 ? scaled(aUtil.diffsize) : COST_MAX;
4781
+ for (let j = b.length; j < n; j++) cost[i + n * j] = c;
4782
+ }
4783
+ for (let j = 0; j < b.length; j++) {
4784
+ const util = b[j];
4785
+ const c = util.matching < 0 ? scaled(util.diffsize) : COST_MAX;
4786
+ for (let i = a.length; i < n; i++) cost[i + n * j] = c;
4787
+ }
4788
+ const { columnToRow: a2b } = computeAssignment(n, n, cost);
4789
+ for (let i = 0; i < a.length; i++) {
4790
+ const j = a2b[i];
4791
+ if (j >= 0 && j < b.length) {
4792
+ a[i].matching = j;
4793
+ b[j].matching = i;
4794
+ }
4795
+ }
4796
+ }
4797
+ /** range-diff.c's `section_headers` driver */
4798
+ let sectionHeaders;
4799
+ function sectionHeaderFunction() {
4800
+ sectionHeaders ??= funcnameFindFunction({ pattern: "^ ## (.*) ##$\n^.?@@ (.*)$" });
4801
+ return sectionHeaders;
4802
+ }
4803
+ const PREFIX = " ";
4804
+ const REVERSE = "\x1B[7m";
4805
+ /**
4806
+ * `output`: the pairs in the order of the second range, each dropped patch of the first
4807
+ * once its predecessors were shown, each pair's header (`n: <id> = n: <id> <subject>`, `!`
4808
+ * when the patches differ, `<`/`>` for a patch on one side only) and the diff of its
4809
+ * patches, four spaces in. The result is a binary string.
4810
+ */
4811
+ async function writeRangeDiff(a, b, options) {
4812
+ let out = "";
4813
+ const width = String(1 + Math.max(a.length, b.length)).length;
4814
+ let dashes = "";
4815
+ const c = options.colors;
4816
+ const color = (slot) => c ? c[slot] : "";
4817
+ const shows = !options.noPatch && (options.stat || showsPatch(options));
4818
+ const header = async (aUtil, bUtil) => {
4819
+ const oid = aUtil ?? bUtil;
4820
+ if (!dashes) dashes = "-".repeat((await options.abbrev(oid.oid)).length);
4821
+ const reset = color("reset");
4822
+ const old = color("old");
4823
+ const nw = color("new");
4824
+ const commit = color("commit");
4825
+ let status;
4826
+ let col;
4827
+ if (!bUtil) {
4828
+ col = old;
4829
+ status = "<";
4830
+ } else if (!aUtil) {
4831
+ col = nw;
4832
+ status = ">";
4833
+ } else if (aUtil.patch !== bUtil.patch) {
4834
+ col = commit;
4835
+ status = "!";
4836
+ } else {
4837
+ col = commit;
4838
+ status = "=";
4839
+ }
4840
+ let line = status === "!" ? old : col;
4841
+ line += aUtil ? `${String(aUtil.i + 1).padStart(width)}: ${await options.abbrev(aUtil.oid)} ` : `${"-".padStart(width)}: ${dashes} `;
4842
+ if (status === "!") line += reset + col;
4843
+ line += status;
4844
+ if (status === "!") line += reset + nw;
4845
+ line += bUtil ? ` ${String(bUtil.i + 1).padStart(width)}: ${await options.abbrev(bUtil.oid)}` : ` ${"-".padStart(width)}: ${dashes}`;
4846
+ if (status === "!") line += reset + col;
4847
+ line += ` ${await options.subject(oid.oid)}`;
4848
+ out += `${line}${reset}\n`;
4849
+ };
4850
+ let i = 0;
4851
+ let j = 0;
4852
+ while (i < a.length || j < b.length) {
4853
+ while (i < a.length && a[i].shown) i++;
4854
+ if (i < a.length && a[i].matching < 0) {
4855
+ if (!options.rightOnly) await header(a[i], void 0);
4856
+ i++;
4857
+ continue;
4858
+ }
4859
+ while (j < b.length && b[j].matching < 0) {
4860
+ if (!options.leftOnly) await header(void 0, b[j]);
4861
+ j++;
4862
+ }
4863
+ if (j < b.length) {
4864
+ const bUtil = b[j];
4865
+ const aUtil = a[bUtil.matching];
4866
+ await header(aUtil, bUtil);
4867
+ if (shows) out += patchDiff(aUtil.patch, bUtil.patch, options);
4868
+ aUtil.shown = true;
4869
+ j++;
4870
+ }
4871
+ }
4872
+ return out;
4873
+ }
4874
+ /** Whether the output format holds the patch (the default when no other is asked for) */
4875
+ const showsPatch = (o) => !o.noPatch && (!!o.patch || !o.stat);
4876
+ /** `patch_diff`: the diff of two patches (files "a" and "b", no diff headers, four in). */
4877
+ function patchDiff(a, b, options) {
4878
+ const showPatch = showsPatch(options);
4879
+ const oldBytes = latin1ToBytes(a);
4880
+ const newBytes = latin1ToBytes(b);
4881
+ const result = unifiedDiffHunks(oldBytes, newBytes, {
4882
+ context: 3,
4883
+ indentHeuristic: true,
4884
+ findFunction: sectionHeaderFunction()
4885
+ });
4886
+ let out = "";
4887
+ if (result.hunks.length === 0) return out;
4888
+ const c = options.colors;
4889
+ const dual = options.dualColor !== false;
4890
+ if (options.stat) {
4891
+ let added = 0;
4892
+ let deleted = 0;
4893
+ for (const hunk of result.hunks) for (const line of hunk.lines) if (line.kind === "+") added++;
4894
+ else if (line.kind === "-") deleted++;
4895
+ const stat = formatStat([{
4896
+ fromName: "a",
4897
+ name: "b",
4898
+ isRenamed: true,
4899
+ isBinary: false,
4900
+ added,
4901
+ deleted
4902
+ }], c ? { colors: c } : {});
4903
+ for (const line of stat.split("\n").slice(0, -1)) out += `${PREFIX}${line}\n`;
4904
+ if (showPatch) out += `${PREFIX}\n`;
4905
+ }
4906
+ if (!showPatch) return out;
4907
+ const color = (slot) => c ? c[slot] : "";
4908
+ const reset = color("reset");
4909
+ const emit = (setSign, set, reverse, sign, text) => {
4910
+ let line = PREFIX;
4911
+ let body = text;
4912
+ let eol = "";
4913
+ if (body.endsWith("\n")) {
4914
+ body = body.slice(0, -1);
4915
+ eol = "\n";
4916
+ }
4917
+ let cr = "";
4918
+ if (body.endsWith("\r")) {
4919
+ body = body.slice(0, -1);
4920
+ cr = "\r";
4921
+ }
4922
+ let needsReset = false;
4923
+ if (body.length > 0 || sign) {
4924
+ if (reverse && c) {
4925
+ line += REVERSE;
4926
+ needsReset = true;
4927
+ }
4928
+ if (setSign !== void 0) {
4929
+ line += setSign;
4930
+ needsReset = true;
4931
+ }
4932
+ line += sign;
4933
+ if (body.length > 0) {
4934
+ if (set !== void 0) {
4935
+ if (setSign !== void 0) line += reset;
4936
+ line += set;
4937
+ needsReset = true;
4938
+ }
4939
+ line += body;
4940
+ needsReset = true;
4941
+ }
4942
+ }
4943
+ if (needsReset) line += reset;
4944
+ return `${line}${cr}${eol}`;
4945
+ };
4946
+ const wsRule = WS_DEFAULT_RULE;
4947
+ let blankPre = 0;
4948
+ let blankPost = 0;
4949
+ if (c && !dual && wsRule & 1024) {
4950
+ const at = checkBlankAtEof(oldBytes, newBytes);
4951
+ blankPre = at.preimage;
4952
+ blankPost = at.postimage;
4953
+ }
4954
+ for (const hunk of result.hunks) {
4955
+ const full = bytesToLatin1(formatHunkHeader(hunk));
4956
+ const ep = full.indexOf("@@", 2) + 2;
4957
+ let rest = full.slice(ep);
4958
+ if (rest.endsWith("\n")) rest = rest.slice(0, -1);
4959
+ let headerLine = `${dual && c ? REVERSE : ""}${color("frag")}@@${reset}`;
4960
+ let k = 0;
4961
+ while (k < rest.length && (rest[k] === " " || rest[k] === " ")) k++;
4962
+ if (k > 0) headerLine += `${color("context")}${rest.slice(0, k)}${reset}`;
4963
+ if (k < rest.length) headerLine += `${color("func")}${rest.slice(k)}${reset}`;
4964
+ out += `${PREFIX}${headerLine}\n`;
4965
+ let lnoPre = hunk.oldStart;
4966
+ let lnoPost = hunk.newStart;
4967
+ for (const line of hunk.lines) {
4968
+ const lines = line.kind === "-" ? result.old : result.new;
4969
+ const text = bytesToLatin1(lines.line(line.index));
4970
+ const first = text[0];
4971
+ if (line.kind === " ") {
4972
+ lnoPre++;
4973
+ lnoPost++;
4974
+ let set = color("context");
4975
+ if (dual) {
4976
+ if (first === "+") set = color("new");
4977
+ else if (first === "@") set = color("frag");
4978
+ else if (first === "-") set = color("old");
4979
+ }
4980
+ out += emit(set, void 0, false, " ", text);
4981
+ } else if (line.kind === "+") {
4982
+ lnoPost++;
4983
+ if (dual) {
4984
+ const sign = color("new");
4985
+ let set;
4986
+ if (first === "-") set = color("oldBold");
4987
+ else if (first === "@") set = color("frag");
4988
+ else if (first === "+") set = color("newBold");
4989
+ else set = color("contextBold");
4990
+ out += emit(sign, set, true, "+", text);
4991
+ } else if (c?.whitespace) {
4992
+ const bytes = lines.line(line.index);
4993
+ if (blankPre > 0 && blankPost > 0 && blankPre <= lnoPre && blankPost <= lnoPost && wsBlankLine(bytes, 0, bytes.length)) out += emit(c.whitespace, void 0, false, "+", text);
4994
+ else {
4995
+ let marked = `${PREFIX}${c.new}+${reset}`;
4996
+ const parts = [];
4997
+ wsCheckEmit(bytes, wsRule, {
4998
+ str: (s) => parts.push(s),
4999
+ bytes: (bb) => parts.push(bytesToLatin1(bb))
5000
+ }, c.new, reset, c.whitespace);
5001
+ marked += parts.join("");
5002
+ out += marked;
5003
+ }
5004
+ } else out += emit(color("new"), void 0, false, "+", text);
5005
+ } else {
5006
+ lnoPre++;
5007
+ if (dual) {
5008
+ const sign = color("old");
5009
+ let set;
5010
+ if (first === "+") set = color("newDimmed");
5011
+ else if (first === "@") set = color("frag");
5012
+ else if (first === "-") set = color("oldDimmed");
5013
+ else set = color("contextDimmed");
5014
+ out += emit(sign, set, true, "-", text);
5015
+ } else out += emit(color("old"), void 0, false, "-", text);
5016
+ }
5017
+ }
5018
+ }
5019
+ return out;
5020
+ }
5021
+ //#endregion
5022
+ //#region src/commands/range-diff/range-diff-command.ts
5023
+ const USAGE$1 = [
5024
+ "usage: git range-diff [<options>] <old-base>..<old-tip> <new-base>..<new-tip>",
5025
+ " or: git range-diff [<options>] <old-tip>...<new-tip>",
5026
+ " or: git range-diff [<options>] <base> <old-tip> <new-tip>"
5027
+ ].join("\n");
5028
+ /** git's MINIMUM_ABBREV */
5029
+ const MINIMUM_ABBREV = 4;
5030
+ /**
5031
+ * What the `git log` reading a range is told of notes (`--show-notes-by-default` and the
5032
+ * notes options after it, revision.c's display_notes_opt).
5033
+ */
5034
+ function rangeDiffNotesOptions(given) {
5035
+ let show = false;
5036
+ let useDefault = -1;
5037
+ let refs = [];
5038
+ for (const value of given) if (value === true) {
5039
+ show = true;
5040
+ useDefault = 1;
5041
+ } else if (value === false) {
5042
+ show = false;
5043
+ useDefault = -1;
5044
+ refs = [];
5045
+ } else {
5046
+ show = true;
5047
+ refs.push(value);
5048
+ }
5049
+ if (given.length === 0) return { notes: true };
5050
+ if (!show) return { notes: false };
5051
+ if (useDefault > 0 || useDefault === -1 && refs.length === 0) return {
5052
+ notes: true,
5053
+ notesRefs: refs
5054
+ };
5055
+ return { notesRefs: refs };
5056
+ }
5057
+ /**
5058
+ * What the `git log` reading a range is told of merges by range-diff's `--diff-merges` and
5059
+ * `--remerge-diff` (git 2.48, passed through in order): diff-merges.c's `func_by_opt` over each
5060
+ * value, the last one winning (`m`/`on` is `-m`, which follows `log.diffMerges`, given as
5061
+ * `configured`). `fullHistory` is whether any value turned `simplify_history` off
5062
+ * (`set_separate` and `set_remerge_diff`, which no later value turns back on). Undefined for
5063
+ * none given (merges left out); a value git refuses throws the log's death.
5064
+ */
5065
+ function rangeDiffMergesOptions(given, configured) {
5066
+ let log;
5067
+ let fullHistory = false;
5068
+ for (const value of given) {
5069
+ const byDefault = value === "m" || value === "on";
5070
+ const mode = byDefault ? configured ? mergesMode(configured) : "separate" : mergesMode(value);
5071
+ if (mode === void 0 && !byDefault) throw new GitApiError(`fatal: invalid value for '--diff-merges': '${value}'`, { exitCode: 128 });
5072
+ if (mode === "separate" || mode === "first-parent" || mode === "remerge") fullHistory = true;
5073
+ log = byDefault ? { m: true } : { diffMerges: mode };
5074
+ }
5075
+ return log ? {
5076
+ log,
5077
+ fullHistory
5078
+ } : void 0;
5079
+ }
5080
+ /**
5081
+ * The base of commands printing range-diffs (`show_range_diff`): `git range-diff` and
5082
+ * format-patch's `--range-diff`.
5083
+ */
5084
+ var RangeDiffBase = class extends GitCommand {
5085
+ /** `show_range_diff`: the output for two ranges, as bytes. */
5086
+ async showRangeDiff(range1, range2, run) {
5087
+ if (run.leftOnly && run.rightOnly) throw new GitApiError("error: options '--left-only' and '--right-only' cannot be used together", { exitCode: 255 });
5088
+ const a = await this.readPatches(range1, run);
5089
+ const b = await this.readPatches(range2, run);
5090
+ findExactMatches(a, b);
5091
+ try {
5092
+ getCorrespondences(a, b, run.creationFactor, run.maxMemory);
5093
+ } catch (error) {
5094
+ if (error instanceof RangeDiffMemoryError) throw new GitApiError(`fatal: ${error.message}`, { exitCode: 128 });
5095
+ throw error;
5096
+ }
5097
+ const colors = run.color === false ? void 0 : readDiffColorSettings(this.workingCopy, run.color ? { color: true } : {}).colors;
5098
+ const text = await writeRangeDiff(a, b, {
5099
+ ...colors ? { colors } : {},
5100
+ dualColor: run.dualColor,
5101
+ leftOnly: !!run.leftOnly,
5102
+ rightOnly: !!run.rightOnly,
5103
+ patch: !!run.patch,
5104
+ stat: !!run.stat,
5105
+ noPatch: !!run.noPatch,
5106
+ abbrev: (id) => this.shortId(id, run.abbrev),
5107
+ subject: (id) => this.subjectOf(id)
5108
+ });
5109
+ return latin1ToBytes(text);
5110
+ }
5111
+ async readPatches(range, run) {
5112
+ const includeMerges = (run.diffMerges?.length ?? 0) > 0;
5113
+ const log = new RevListCommand(this._workingCopy).setNoMerges(!includeMerges).setOrder("date").setReverse(true).setDiffOptions({
5114
+ color: false,
5115
+ noPrefix: true,
5116
+ submoduleFormat: "short"
5117
+ });
5118
+ log.addArgument(range);
5119
+ for (const arg of run.logArgs ?? []) log.addArgument(arg);
5120
+ let bytes;
5121
+ try {
5122
+ const merges = includeMerges ? rangeDiffMergesOptions(run.diffMerges ?? [], RemoteConfigStore.from(this._workingCopy).value("log.diffMerges")) : void 0;
5123
+ if (merges?.fullHistory) log.setFullHistory(true);
5124
+ bytes = await log.callLogBytes({
5125
+ ...merges?.log,
5126
+ patch: true,
5127
+ pretty: "medium",
5128
+ decorate: "no",
5129
+ abbrevCommit: false,
5130
+ ...rangeDiffNotesOptions(run.notes)
5131
+ });
5132
+ } catch (error) {
5133
+ const message = error instanceof Error ? error.message : String(error);
5134
+ throw new GitApiError(`${message}\nerror: could not parse log for '${range}'`, { exitCode: 255 });
5135
+ }
5136
+ try {
5137
+ return readRangeDiffPatches(bytesToLatin1(bytes), includeMerges);
5138
+ } catch (error) {
5139
+ if (error instanceof RangeDiffError) throw new GitApiError(`error: ${error.message}\nerror: could not parse log for '${range}'`, { exitCode: 255 });
5140
+ throw error;
5141
+ }
5142
+ }
5143
+ /** `find_unique_abbrev(oid, abbrev)` */
5144
+ async shortId(id, abbrev) {
5145
+ if (abbrev === void 0) return this.abbreviateObjectId(id);
5146
+ if (abbrev >= id.length) return id;
5147
+ const lengths = await this.idAbbreviator().lengths([id], abbrev);
5148
+ return id.slice(0, lengths.get(id) ?? abbrev);
5149
+ }
5150
+ /** `pp_commit_easy(CMIT_FMT_ONELINE)` as a binary string. */
5151
+ async subjectOf(id) {
5152
+ const commit = await this.commits.load(id);
5153
+ if (!commit) return "";
5154
+ const subject = await formatCommitPretty("%s", commit, id);
5155
+ return bytesToLatin1(new TextEncoder().encode(subject));
5156
+ }
5157
+ /** `is_range_diff_range`: a revision argument with both a positive and a negative side. */
5158
+ async isRangeDiffRange(arg) {
5159
+ let entries;
5160
+ try {
5161
+ ({entries} = await new RevListCommand(this._workingCopy).addRevision(arg).resolve());
5162
+ } catch {
5163
+ throw new GitApiError(`fatal: bad revision '${arg}'`, { exitCode: 128 });
5164
+ }
5165
+ const negative = new Set(entries.filter((e) => e.exclude).map((e) => e.id));
5166
+ return negative.size > 0 && entries.some((e) => !negative.has(e.id));
5167
+ }
5168
+ /** `repo_get_oid_committish` succeeds */
5169
+ async isCommittish(arg) {
5170
+ const resolver = this.revisionResolver();
5171
+ const id = await resolver.resolve(arg).catch(() => void 0);
5172
+ if (id === void 0) return false;
5173
+ return await resolver.commitReference(id).catch(() => void 0) !== void 0;
5174
+ }
5175
+ };
5176
+ /** `git range-diff`. */
5177
+ var RangeDiffCommand = class extends RangeDiffBase {
5178
+ args = [];
5179
+ creationFactor = 60;
5180
+ /** `--no-dual-color` (1), `--dual-color` (0), neither (-1) */
5181
+ simpleColor = -1;
5182
+ color;
5183
+ leftOnly = false;
5184
+ rightOnly = false;
5185
+ notes = [];
5186
+ noPatch = false;
5187
+ stat = false;
5188
+ patch = false;
5189
+ abbrev;
5190
+ maxMemory;
5191
+ /** `--diff-merges=<v>` (`--remerge-diff` as `remerge`) and the option as written */
5192
+ diffMerges = [];
5193
+ compatibility;
5194
+ /**
5195
+ * A positional argument as git takes it: a range, a commit, `--`, or what follows the
5196
+ * ranges (paths after `--`).
5197
+ */
5198
+ addArgument(arg) {
5199
+ this.checkCallable();
5200
+ this.args.push(arg);
5201
+ return this;
5202
+ }
5203
+ /** A path the ranges' logs are limited to (after a `--`, added when not there yet). */
5204
+ addPath(path) {
5205
+ this.checkCallable();
5206
+ if (!this.args.includes("--")) this.args.push("--");
5207
+ this.args.push(path);
5208
+ return this;
5209
+ }
5210
+ /** `--creation-factor=<percent>` (default 60). */
5211
+ setCreationFactor(factor) {
5212
+ this.checkCallable();
5213
+ this.creationFactor = factor;
5214
+ return this;
5215
+ }
5216
+ /** `--dual-color` (true: also forces colors) / `--no-dual-color` (false). */
5217
+ setDualColor(dual) {
5218
+ this.checkCallable();
5219
+ this.simpleColor = dual ? 0 : 1;
5220
+ return this;
5221
+ }
5222
+ /** `--color` / `--no-color` (unset: `color.diff`/`color.ui`, `auto` is none). */
5223
+ setColor(color) {
5224
+ this.checkCallable();
5225
+ this.color = color;
5226
+ return this;
5227
+ }
5228
+ /** `--left-only`: only what concerns the first range. */
5229
+ setLeftOnly(value) {
5230
+ this.checkCallable();
5231
+ this.leftOnly = value;
5232
+ return this;
5233
+ }
5234
+ /** `--right-only`: only what concerns the second range. */
5235
+ setRightOnly(value) {
5236
+ this.checkCallable();
5237
+ this.rightOnly = value;
5238
+ return this;
5239
+ }
5240
+ /** `--notes` (true), `--notes=<ref>`, `--no-notes` (false), in order. */
5241
+ addNotes(value) {
5242
+ this.checkCallable();
5243
+ this.notes.push(value);
5244
+ return this;
5245
+ }
5246
+ /** `-s` / `--no-patch`: only the pairs. */
5247
+ setNoPatch(value) {
5248
+ this.checkCallable();
5249
+ this.noPatch = value;
5250
+ return this;
5251
+ }
5252
+ /** `--stat`: the diffstat of each changed pair's patches. */
5253
+ setStat(value) {
5254
+ this.checkCallable();
5255
+ this.stat = value;
5256
+ return this;
5257
+ }
5258
+ /** `-p`: the patches' diff too (with `--stat`). */
5259
+ setPatch(value) {
5260
+ this.checkCallable();
5261
+ this.patch = value;
5262
+ return this;
5263
+ }
5264
+ /** `--abbrev[=<n>]` of the commit ids (true: the default length). */
5265
+ setAbbrev(abbrev) {
5266
+ this.checkCallable();
5267
+ this.abbrev = abbrev === true ? void 0 : Math.max(abbrev, MINIMUM_ABBREV);
5268
+ return this;
5269
+ }
5270
+ /**
5271
+ * `--max-memory=<size>` (git 2.52): the largest cost matrix built, in bytes or with a `k`,
5272
+ * `m` or `g` unit (default 4 GiB, which ours applies whatever the version). A value git
5273
+ * refuses fails the call with its `invalid max-memory value` and the usage (exit 129).
5274
+ */
5275
+ setMaxMemory(size) {
5276
+ this.checkCallable();
5277
+ this.maxMemory = typeof size === "number" ? BigInt(size) : size;
5278
+ return this;
5279
+ }
5280
+ /**
5281
+ * `--diff-merges=<format>` (git 2.48): merge commits of both ranges are read too, each
5282
+ * diffed as `git log --diff-merges=<format>` diffs it (`first-parent`/`1`, `separate`,
5283
+ * `combined`/`c`, `dense-combined`/`cc`, `remerge`/`r`, `off`/`none`, `m`/`on`), and paired
5284
+ * like the other commits. Several calls are passed on in order, the last winning; a value
5285
+ * git refuses fails the call as git's log dies (exit 255). Refused under 2.43, which lacks
5286
+ * the option.
5287
+ */
5288
+ setDiffMerges(format) {
5289
+ this.checkCallable();
5290
+ this.diffMerges.push({
5291
+ value: format,
5292
+ option: `diff-merges=${format}`
5293
+ });
5294
+ return this;
5295
+ }
5296
+ /** `--remerge-diff` (git 2.48): `--diff-merges=remerge`. */
5297
+ setRemergeDiff(value) {
5298
+ this.checkCallable();
5299
+ if (value) this.diffMerges.push({
5300
+ value: "remerge",
5301
+ option: "remerge-diff"
5302
+ });
5303
+ return this;
5304
+ }
5305
+ /**
5306
+ * The git version whose options this follows (default the hook runner's): 2.43 has no
5307
+ * `--diff-merges` or `--remerge-diff`.
5308
+ */
5309
+ setCompatibility(version) {
5310
+ this.checkCallable();
5311
+ this.compatibility = version;
5312
+ return this;
5313
+ }
5314
+ /** The output as bytes. */
5315
+ async call() {
5316
+ this.checkCallable();
5317
+ this.setCallable(false);
5318
+ if (this.diffMerges.length > 0 && (this.compatibility ?? this.gitCompatibility()) === "2.43") throw new GitApiError(`error: unknown option \`${this.diffMerges[0]?.option}'`, { exitCode: 129 });
5319
+ let maxMemory;
5320
+ if (typeof this.maxMemory === "string") {
5321
+ maxMemory = parseRangeDiffMaxMemory(this.maxMemory);
5322
+ if (maxMemory === void 0) throw new GitApiError(`error: invalid max-memory value: ${this.maxMemory}\n\n${USAGE$1}`, { exitCode: 129 });
5323
+ } else maxMemory = this.maxMemory;
5324
+ const { range1, range2, logArgs } = await this.ranges();
5325
+ const color = this.simpleColor === 0 ? true : this.color;
5326
+ return this.showRangeDiff(range1, range2, {
5327
+ creationFactor: this.creationFactor,
5328
+ notes: this.notes,
5329
+ diffMerges: this.diffMerges.map((d) => d.value),
5330
+ logArgs,
5331
+ dualColor: this.simpleColor < 1,
5332
+ ...color !== void 0 ? { color } : {},
5333
+ leftOnly: this.leftOnly,
5334
+ rightOnly: this.rightOnly,
5335
+ patch: this.patch,
5336
+ stat: this.stat,
5337
+ noPatch: this.noPatch,
5338
+ ...this.abbrev !== void 0 ? { abbrev: this.abbrev } : {},
5339
+ ...maxMemory !== void 0 ? { maxMemory } : {}
5340
+ });
5341
+ }
5342
+ /** {@link call} as bytes. */
5343
+ callBytes() {
5344
+ return this.call();
5345
+ }
5346
+ /** {@link call} as text (UTF-8). */
5347
+ async callText() {
5348
+ return new TextDecoder().decode(await this.call());
5349
+ }
5350
+ /** cmd_range_diff's reading of the arguments. */
5351
+ async ranges() {
5352
+ const argv = this.args;
5353
+ const dashDash = argv.indexOf("--");
5354
+ const usage = (message) => new GitApiError(`fatal: ${message}\n\n${USAGE$1}`, { exitCode: 129 });
5355
+ const argc = argv.length;
5356
+ const arg = (k) => argv[k];
5357
+ if (dashDash === 3 || dashDash < 0 && argc > 2 && await this.isCommittish(arg(0)) && await this.isCommittish(arg(1)) && await this.isCommittish(arg(2))) {
5358
+ if (dashDash >= 0) {
5359
+ for (const k of [
5360
+ 0,
5361
+ 1,
5362
+ 2
5363
+ ]) if (!await this.isCommittish(arg(k))) throw usage(`not a revision: '${arg(k)}'`);
5364
+ }
5365
+ return {
5366
+ range1: `${arg(0)}..${arg(1)}`,
5367
+ range2: `${arg(0)}..${arg(2)}`,
5368
+ logArgs: argv.slice(dashDash < 0 ? 3 : dashDash)
5369
+ };
5370
+ }
5371
+ if (dashDash === 2 || dashDash < 0 && argc > 1 && await this.isRangeDiffRange(arg(0)) && await this.isRangeDiffRange(arg(1))) {
5372
+ if (dashDash >= 0) {
5373
+ for (const k of [0, 1]) if (!await this.isRangeDiffRange(arg(k))) throw usage(`not a commit range: '${arg(k)}'`);
5374
+ }
5375
+ return {
5376
+ range1: arg(0),
5377
+ range2: arg(1),
5378
+ logArgs: argv.slice(dashDash < 0 ? 2 : dashDash)
5379
+ };
5380
+ }
5381
+ if (dashDash === 1 || dashDash < 0 && argc > 0 && arg(0).includes("...")) {
5382
+ const dots = arg(0).indexOf("...");
5383
+ if (dots < 0) throw usage(`not a symmetric range: '${arg(0)}'`);
5384
+ const a = dots === 0 ? "HEAD" : arg(0).slice(0, dots);
5385
+ const b = arg(0).slice(dots + 3) || "HEAD";
5386
+ return {
5387
+ range1: `${b}..${a}`,
5388
+ range2: `${a}..${b}`,
5389
+ logArgs: argv.slice(dashDash < 0 ? 1 : dashDash)
5390
+ };
5391
+ }
5392
+ throw usage("need two commit ranges");
5393
+ }
5394
+ };
5395
+ //#endregion
4171
5396
  //#region src/commands/rev-list-command.ts
4172
5397
  /**
5398
+ * RevListCommand - `git log` / `git rev-list` over revision arguments: ranges (`a..b`,
5399
+ * `a...b`), exclusions (`^a`, `--not`) and parent shorthands (`x^@`, `x^!`, `x^-<n>`),
5400
+ * read as git's `handle_revision_arg` reads them (see `revision-range.ts`), walked by
5401
+ * {@link LogCommand}.
5402
+ *
5403
+ * @example
5404
+ * ```typescript
5405
+ * // git log --format=%H main...feat
5406
+ * for await (const commit of await git.revList().addRevision("main...feat").call()) {
5407
+ * console.log(commit.id);
5408
+ * }
5409
+ * // git rev-list v1.0..HEAD --not release
5410
+ * const range = git.revList().addRevision("v1.0..HEAD").addRevision("--not").addRevision("release");
5411
+ * const { entries } = await range.resolve(); // what was included and excluded
5412
+ * ```
5413
+ */
5414
+ /**
4173
5415
  * Commits reachable from the included revisions and not from the excluded ones, the set
4174
5416
  * `git log <revisions> --` lists. It reads its arguments as `git log` does, not as
4175
5417
  * `git rev-list` does: without revisions (or with nothing but `--not`, which names none) it
@@ -4212,6 +5454,16 @@ var RevListCommand = class extends GitCommand {
4212
5454
  printParents = false;
4213
5455
  /** `--ancestry-path=<commit>` revisions, resolved when called */
4214
5456
  ancestryPaths = [];
5457
+ /** `--objects` */
5458
+ objects = false;
5459
+ /** `--disk-usage` (true) or `--disk-usage=<format>` (its format, checked when called) */
5460
+ diskUsage = false;
5461
+ /** `--filter=<spec>` */
5462
+ filterSpec;
5463
+ /** `--use-bitmap-index` */
5464
+ useBitmapIndex = false;
5465
+ /** Whether an option changing which commits the walk shows was given */
5466
+ walkLimited = false;
4215
5467
  /** What git prints while reading replace refs and grafts (see GitCommand). */
4216
5468
  async replacementMessages() {
4217
5469
  const own = await super.replacementMessages();
@@ -4256,7 +5508,9 @@ var RevListCommand = class extends GitCommand {
4256
5508
  }
4257
5509
  /** The git version to follow where versions differ (see `LogCommand.setCompatibility`). */
4258
5510
  setCompatibility(version) {
4259
- return this.configured((log) => log.setCompatibility(version));
5511
+ this.checkCallable();
5512
+ this.configure.push((log) => log.setCompatibility(version));
5513
+ return this;
4260
5514
  }
4261
5515
  /** `--grep-reflog=<pattern>` (see `LogCommand.addGrepReflog`). */
4262
5516
  addGrepReflog(pattern) {
@@ -4377,9 +5631,57 @@ var RevListCommand = class extends GitCommand {
4377
5631
  * // "2\t3\n"
4378
5632
  * ```
4379
5633
  */
4380
- setCount(count) {
5634
+ setCount(count) {
5635
+ this.checkCallable();
5636
+ this.count = count;
5637
+ return this;
5638
+ }
5639
+ /**
5640
+ * `--objects`: the trees, blobs and tags the walk reaches count too. Supported with
5641
+ * {@link setDiskUsage} only, and there with revisions alone (no paths or options limiting
5642
+ * the commits): the listing itself refuses it.
5643
+ */
5644
+ setObjects(objects) {
5645
+ this.checkCallable();
5646
+ this.objects = objects;
5647
+ return this;
5648
+ }
5649
+ /**
5650
+ * `--disk-usage` (`true`) or `--disk-usage=<format>` (its format): {@link callText} prints,
5651
+ * instead of the list, the bytes on disk of the objects the walk shows (the commits, and
5652
+ * with {@link setObjects} every listed object; each counted once, as a pack entry or a loose
5653
+ * file), as `<n>`, or with `"human"` in git's units (`1.50 KiB`, `12 bytes`). Any other
5654
+ * format dies as git's option parsing does.
5655
+ *
5656
+ * @example
5657
+ * ```typescript
5658
+ * // git rev-list --disk-usage=human --objects --all
5659
+ * await git.revList().addRevision("--all").setObjects(true).setDiskUsage("human").callText();
5660
+ * // "3.04 KiB\n"
5661
+ * ```
5662
+ */
5663
+ setDiskUsage(diskUsage) {
5664
+ this.checkCallable();
5665
+ this.diskUsage = diskUsage;
5666
+ return this;
5667
+ }
5668
+ /**
5669
+ * `--filter=<spec>` (`--no-filter` with undefined): a partial clone filter of the objects
5670
+ * {@link setObjects} counts (list-objects-filter.c); git dies without `--objects`.
5671
+ */
5672
+ setFilter(spec) {
5673
+ this.checkCallable();
5674
+ this.filterSpec = spec;
5675
+ return this;
5676
+ }
5677
+ /**
5678
+ * `--use-bitmap-index`: {@link setObjects}' objects come from the reachability bitmap when
5679
+ * the walk allows it, which counts exactly what the wants reach and the haves do not (the
5680
+ * plain walk may count more of a range's trees and blobs, as git's does).
5681
+ */
5682
+ setUseBitmapIndex(use) {
4381
5683
  this.checkCallable();
4382
- this.count = count;
5684
+ this.useBitmapIndex = use;
4383
5685
  return this;
4384
5686
  }
4385
5687
  /** `--full-history` (see `LogCommand.setFullHistory`). */
@@ -4561,6 +5863,7 @@ var RevListCommand = class extends GitCommand {
4561
5863
  configured(step) {
4562
5864
  this.checkCallable();
4563
5865
  this.configure.push(step);
5866
+ this.walkLimited = true;
4564
5867
  return this;
4565
5868
  }
4566
5869
  /**
@@ -4590,7 +5893,7 @@ var RevListCommand = class extends GitCommand {
4590
5893
  return {
4591
5894
  entries: [...parsed.entries, ...more.entries],
4592
5895
  warnings: resolver.warnings,
4593
- inputGiven: !!parsed.inputGiven || more.entries.length > 0,
5896
+ inputGiven: !!parsed.inputGiven || !!more.inputGiven,
4594
5897
  paths: [...stdinPaths, ...more.paths]
4595
5898
  };
4596
5899
  }
@@ -4624,6 +5927,10 @@ var RevListCommand = class extends GitCommand {
4624
5927
  * `--cherry-mark`. With {@link setCount}, the counts instead.
4625
5928
  */
4626
5929
  async callText() {
5930
+ const human = this.checkDiskUsage();
5931
+ if (this.filterSpec !== void 0 && !this.objects) throw new GitApiError("fatal: object filtering requires --objects", { exitCode: 128 });
5932
+ if (this.diskUsage !== false) return this.diskUsageText(human);
5933
+ if (this.objects) throw new GitApiError("rev-list --objects is supported with --disk-usage only");
4627
5934
  let out = "";
4628
5935
  const log = await this.prepare(false);
4629
5936
  if (this.bisect) return this.bisectText(log !== void 0);
@@ -4646,6 +5953,92 @@ var RevListCommand = class extends GitCommand {
4646
5953
  if (this.cherryMark) return `${left + right}\t${same}\n`;
4647
5954
  return `${left + right}\n`;
4648
5955
  }
5956
+ /** `--disk-usage=<format>` as builtin/rev-list.c reads it: whether it asks for `human`. */
5957
+ checkDiskUsage() {
5958
+ if (typeof this.diskUsage !== "string") return false;
5959
+ if (this.diskUsage === "human") return true;
5960
+ throw new GitApiError(`fatal: invalid value for '--disk-usage=<format>': '${this.diskUsage}', the only allowed format is 'human'`, { exitCode: 128 });
5961
+ }
5962
+ /**
5963
+ * `--disk-usage`: the bytes on disk of what the walk shows (show_commit and show_object's
5964
+ * get_object_disk_usage), printed by print_disk_usage.
5965
+ */
5966
+ async diskUsageText(human) {
5967
+ const info = await objectDiskInfoOf(this._workingCopy);
5968
+ let total = 0;
5969
+ const add = async (id) => {
5970
+ const size = await info.diskSize(id);
5971
+ if (size === void 0) throw new GitApiError(`fatal: unable to get disk usage of ${id}`, { exitCode: 128 });
5972
+ total += size;
5973
+ };
5974
+ if (this.objects) for (const id of await this.listedObjects()) await add(id);
5975
+ else {
5976
+ const log = await this.prepare(false);
5977
+ if (log) for await (const commit of await log.call()) await add(commit.id);
5978
+ }
5979
+ return `${human ? humaniseBytes(BigInt(total)) : total}\n`;
5980
+ }
5981
+ /**
5982
+ * `--objects`' walk (list-objects.c over the revisions: the commits shown, then the tags,
5983
+ * trees and blobs), through the bitmap under {@link setUseBitmapIndex} where git's
5984
+ * prepare_bitmap_walk would answer.
5985
+ */
5986
+ async listedObjects() {
5987
+ this.checkCallable();
5988
+ this.setCallable(false);
5989
+ const objects = this._workingCopy.history.objects;
5990
+ if (!objects) throw new GitApiError("rev-list --objects needs the object store");
5991
+ if (this.walkLimited || this.mixed.length > 0 || this.walkReflogs) throw new GitApiError("rev-list --objects --disk-usage is supported with revisions alone (no paths or walk options)");
5992
+ const { entries, warnings } = await this.resolve();
5993
+ this.warnings = [...warnings];
5994
+ const wants = [];
5995
+ const haves = [];
5996
+ for (const entry of entries) (entry.exclude ? haves : wants).push(entry.id);
5997
+ if (wants.length === 0) return [];
5998
+ const filter = await this.resolvedFilter();
5999
+ const bitmap = this.useBitmapIndex ? await this._workingCopy.history.packs?.bitmap?.().catch(() => void 0) : void 0;
6000
+ const ids = [];
6001
+ for await (const o of listObjects(objects, {
6002
+ wants,
6003
+ haves,
6004
+ ...filter ? { filter } : {},
6005
+ ...bitmap ? { bitmap } : {}
6006
+ })) ids.push(o.id);
6007
+ return ids;
6008
+ }
6009
+ /** `--filter=<spec>` parsed, a `sparse:oid` blob read (git dies on a bad one). */
6010
+ async resolvedFilter() {
6011
+ if (this.filterSpec === void 0) return void 0;
6012
+ let parsed;
6013
+ try {
6014
+ parsed = parseObjectFilter(this.filterSpec);
6015
+ } catch (error) {
6016
+ if (error instanceof ObjectFilterError) throw new GitApiError(`fatal: ${error.message}`, { exitCode: 128 });
6017
+ throw error;
6018
+ }
6019
+ return resolveObjectFilter(parsed, async (name) => {
6020
+ const id = await this.revisionResolver().resolve(name).catch(() => void 0);
6021
+ const object = id !== void 0 ? await this.loadBlobText(id) : void 0;
6022
+ if (object === void 0) throw new GitApiError(`fatal: unable to access sparse blob in '${name}'`, { exitCode: 128 });
6023
+ return sparseFilterMatcher(object);
6024
+ });
6025
+ }
6026
+ /** A blob's content as text, undefined when `id` names no blob. */
6027
+ async loadBlobText(id) {
6028
+ const blobs = this._workingCopy.history.blobs;
6029
+ if (!await blobs.has(id).catch(() => false)) return void 0;
6030
+ const chunks = [];
6031
+ for await (const chunk of await blobs.load(id) ?? []) chunks.push(chunk);
6032
+ let length = 0;
6033
+ for (const c of chunks) length += c.length;
6034
+ const bytes = new Uint8Array(length);
6035
+ let at = 0;
6036
+ for (const c of chunks) {
6037
+ bytes.set(c, at);
6038
+ at += c.length;
6039
+ }
6040
+ return new TextDecoder().decode(bytes);
6041
+ }
4649
6042
  /** revision.c's get_revision_mark for rev-list (no graph). */
4650
6043
  revisionMark(commit) {
4651
6044
  if (commit.boundary) return "-";
@@ -4718,6 +6111,13 @@ var RevListCommand = class extends GitCommand {
4718
6111
  ""
4719
6112
  ].join("\n");
4720
6113
  }
6114
+ /**
6115
+ * fast-export.c's rewrite_commit over the walk {@link call} made (see
6116
+ * `LogCommand.rewriteCommit`): `id` itself before a walk.
6117
+ */
6118
+ rewriteCommit(id) {
6119
+ return this.log ? this.log.rewriteCommit(id) : id;
6120
+ }
4721
6121
  /** The log walking the revisions; undefined when they name nothing to walk. */
4722
6122
  async prepare(defaultHead = true) {
4723
6123
  this.checkCallable();
@@ -5608,9 +7008,13 @@ var RefFormat = class {
5608
7008
  quoteStyle;
5609
7009
  useColor;
5610
7010
  peelNested;
7011
+ /** The git version followed (see {@link RefFormatOptions.compatibility}) */
7012
+ compatibility;
5611
7013
  headTarget;
5612
7014
  mailmapLoad;
5613
7015
  dateModes = /* @__PURE__ */ new Map();
7016
+ /** What the signature checks printed on stderr (`error: cannot run gpg: ...`), in order */
7017
+ messages = [];
5614
7018
  /**
5615
7019
  * `format` verified as git's verify_ref_format does (atoms parsed, `%(rest)` refused,
5616
7020
  * `%(raw)` refused with `--shell`/`--python`/`--tcl`).
@@ -5622,6 +7026,7 @@ var RefFormat = class {
5622
7026
  this.quoteStyle = options.quoteStyle ?? "none";
5623
7027
  this.useColor = options.useColor ?? false;
5624
7028
  this.peelNested = options.compatibility !== "2.43";
7029
+ this.compatibility = options.compatibility ?? "2.56";
5625
7030
  let cp = 0;
5626
7031
  for (;;) {
5627
7032
  const sp = findNext(format, cp);
@@ -5932,6 +7337,13 @@ var RefFormat = class {
5932
7337
  default: return id;
5933
7338
  }
5934
7339
  }
7340
+ /** `disk_sizep` and `delta_base_oid` of get_object's object info. */
7341
+ async onDisk(id, atom, refname) {
7342
+ if (!this.source.objectOnDisk) throw fatal(`%(${atom.name}) is not supported: this store does not keep objects on disk`);
7343
+ const found = await this.source.objectOnDisk(id);
7344
+ if (!found) throw fatal(`missing object ${id} for ${refname}`);
7345
+ return found;
7346
+ }
5935
7347
  /** grab_values (and grab_common_values) of one object, the ref's own or the peeled one. */
5936
7348
  async grabValues(values, deref, id, object, refname) {
5937
7349
  const mine = values.filter((v) => v.atom.deref === deref);
@@ -5941,10 +7353,15 @@ var RefFormat = class {
5941
7353
  const atom = v.atom;
5942
7354
  if (atom.type === "objecttype") v.s = object.type;
5943
7355
  else if (atom.type === "objectsize") {
5944
- if (atom.objectsize === "disk") throw fatal(`%(${atom.name}) is not supported: object disk sizes are not available`);
7356
+ if (atom.objectsize === "disk") {
7357
+ const { diskSize } = await this.onDisk(id, atom, refname);
7358
+ v.value = diskSize;
7359
+ v.s = String(diskSize);
7360
+ continue;
7361
+ }
5945
7362
  v.value = object.bytes.length;
5946
7363
  v.s = String(object.bytes.length);
5947
- } else if (atom.type === "deltabase") throw fatal(`%(${atom.name}) is not supported: delta bases are not available`);
7364
+ } else if (atom.type === "deltabase") v.s = (await this.onDisk(id, atom, refname)).deltaBase;
5948
7365
  else if (atom.type === "objectname" && deref) v.s = await this.oidText(id, atom);
5949
7366
  }
5950
7367
  if (object.type === "tag") {
@@ -5973,7 +7390,7 @@ var RefFormat = class {
5973
7390
  await this.grabContents(mine, object, buf);
5974
7391
  await this.grabPerson("author", mine, buf);
5975
7392
  await this.grabPerson("committer", mine, buf);
5976
- this.grabSignature(mine, buf);
7393
+ await this.grabSignature(mine, object.bytes, buf);
5977
7394
  await this.grabDescribe(mine, id, object);
5978
7395
  } else await this.grabContents(mine, object, buf);
5979
7396
  }
@@ -6098,15 +7515,50 @@ var RefFormat = class {
6098
7515
  v.s = showDate(timestamp, tzText, mode, this.source.dateContext);
6099
7516
  v.value = timestamp;
6100
7517
  }
6101
- /** grab_signature for an unsigned commit; a signed one cannot be verified here. */
6102
- grabSignature(values, buf) {
7518
+ /**
7519
+ * grab_signature: the commit's signature checked once (check_commit_signature) and each
7520
+ * `%(signature...)` atom given its field; an unsigned commit is `N`, trust `undefined`.
7521
+ */
7522
+ async grabSignature(values, bytes, buf) {
6103
7523
  const atoms = values.filter((v) => v.atom.type === "signature");
6104
7524
  if (atoms.length === 0) return;
6105
- const header = buf.slice(0, Math.max(buf.indexOf("\n\n"), 0));
6106
- if (/(^|\n)gpgsig(-sha256)? /.test(header)) throw fatal("%(signature) is not supported: signatures cannot be verified");
6107
- for (const v of atoms) {
6108
- const option = v.atom.signature;
6109
- v.s = option === "grade" ? "N" : option === "trustlevel" ? "undefined" : "";
7525
+ let check;
7526
+ if (this.source.commitSignature) {
7527
+ check = await this.source.commitSignature(bytes);
7528
+ for (const line of check.messages) this.messages.push(line);
7529
+ } else {
7530
+ const header = buf.slice(0, Math.max(buf.indexOf("\n\n"), 0));
7531
+ if (/(^|\n)gpgsig(-sha256)? /.test(header)) throw fatal("%(signature) is not supported: signatures cannot be verified");
7532
+ check = {
7533
+ result: "N",
7534
+ trustLevel: "undefined",
7535
+ failed: true,
7536
+ messages: []
7537
+ };
7538
+ }
7539
+ for (const v of atoms) switch (v.atom.signature) {
7540
+ case "":
7541
+ v.s = check.output ?? "";
7542
+ break;
7543
+ case "signer":
7544
+ v.s = check.signer ?? "";
7545
+ break;
7546
+ case "grade":
7547
+ v.s = check.result === "G" ? check.trustLevel === "undefined" || check.trustLevel === "never" ? "U" : "G" : check.result;
7548
+ break;
7549
+ case "key":
7550
+ v.s = check.key ?? "";
7551
+ break;
7552
+ case "fingerprint":
7553
+ v.s = check.fingerprint ?? "";
7554
+ break;
7555
+ case "primarykeyfingerprint":
7556
+ v.s = check.primaryKeyFingerprint ?? "";
7557
+ break;
7558
+ case "trustlevel":
7559
+ v.s = check.trustLevel;
7560
+ break;
7561
+ default: v.s = "";
6110
7562
  }
6111
7563
  }
6112
7564
  async grabDescribe(values, id, object) {
@@ -6574,7 +8026,6 @@ function versionSuffixes(source, warnings) {
6574
8026
  */
6575
8027
  async function sortRefs(items, sorting, format, source, warnings = []) {
6576
8028
  if (sorting.length === 0) return;
6577
- for (const item of items) for (const key of sorting) await format.value(item, key.atom);
6578
8029
  let suffixes;
6579
8030
  const compareKey = (key, a, b) => {
6580
8031
  const va = a.values[key.atom];
@@ -6596,13 +8047,52 @@ async function sortRefs(items, sorting, format, source, warnings = []) {
6596
8047
  return key.reverse && !detached ? -cmp : cmp;
6597
8048
  };
6598
8049
  const first = sorting[0];
6599
- items.sort((a, b) => {
8050
+ const compare = async (a, b) => {
6600
8051
  for (const key of sorting) {
8052
+ await format.value(a, key.atom);
8053
+ await format.value(b, key.atom);
6601
8054
  const cmp = compareKey(key, a, b);
6602
8055
  if (cmp) return cmp;
6603
8056
  }
6604
8057
  return first.icase ? compareBytesIcase(a.refname, b.refname) : compareBytes$1(a.refname, b.refname);
6605
- });
8058
+ };
8059
+ const sorted = await mergeSort(items, compare);
8060
+ for (let i = 0; i < sorted.length; i++) items[i] = sorted[i];
8061
+ }
8062
+ /**
8063
+ * compat/qsort_s.c's msort_with_tmp (git's QSORT_S on platforms without an ISO qsort_s):
8064
+ * a stable merge sort comparing in the order git does, the left half sorted first.
8065
+ */
8066
+ async function mergeSort(items, compare) {
8067
+ if (items.length <= 1) return [...items];
8068
+ const n1 = Math.floor(items.length / 2);
8069
+ const left = await mergeSort(items.slice(0, n1), compare);
8070
+ const right = await mergeSort(items.slice(n1), compare);
8071
+ const out = [];
8072
+ let i = 0;
8073
+ let j = 0;
8074
+ while (i < left.length && j < right.length) if (await compare(left[i], right[j]) <= 0) out.push(left[i++]);
8075
+ else out.push(right[j++]);
8076
+ while (i < left.length) out.push(left[i++]);
8077
+ while (j < right.length) out.push(right[j++]);
8078
+ return out;
8079
+ }
8080
+ /**
8081
+ * can_do_iterative_format (git 2.47+): refs sorted by `refname` alone (any of its forms, no
8082
+ * flag), no `%(ahead-behind)` or `%(is-base)` and no `--[no-]merged` are formatted in the
8083
+ * order the ref backends list them (full names, byte order), never sorted by the key, each
8084
+ * ref's values computed in that order.
8085
+ */
8086
+ function formatsIteratively(sorting, format, filter) {
8087
+ if (format.compatibility === "2.43") return false;
8088
+ if (sorting.length > 1) return false;
8089
+ const key = sorting[0];
8090
+ if (key) {
8091
+ if (key.reverse || key.version || key.icase || key.detachedHeadFirst) return false;
8092
+ if (format.atoms[key.atom]?.type !== "refname") return false;
8093
+ }
8094
+ if (format.atoms.some((a) => a.type === "ahead-behind" || a.type === "is-base")) return false;
8095
+ return !filter.merged?.length && !filter.noMerged?.length;
6606
8096
  }
6607
8097
  /**
6608
8098
  * filter_ahead_behind: each `%(ahead-behind:<base>)` count of every ref that names a
@@ -6743,7 +8233,8 @@ async function filterAndFormatRefs(source, filter, sorting, format, options = {}
6743
8233
  const { items, warnings } = await filterRefs(source, filter);
6744
8234
  await fillAheadBehind(items, options.aheadBehindBases ?? [], source, warnings);
6745
8235
  await fillIsBase(items, options.isBaseTips ?? [], source);
6746
- await sortRefs(items, sorting, format, source, warnings);
8236
+ if (formatsIteratively(sorting, format, filter)) items.sort((a, b) => compareBytes$1(a.refname, b.refname));
8237
+ else await sortRefs(items, sorting, format, source, warnings);
6747
8238
  const total = options.count && options.count < items.length ? options.count : items.length;
6748
8239
  const shown = items.slice(0, total);
6749
8240
  const lines = [];
@@ -8793,6 +10284,591 @@ async function objectExists(history, id) {
8793
10284
  return false;
8794
10285
  }
8795
10286
  //#endregion
10287
+ //#region src/commands/credential-helper.ts
10288
+ /** git's `CREDENTIAL_INIT`. */
10289
+ function newCredential() {
10290
+ return {
10291
+ ephemeral: false,
10292
+ wwwauth: [],
10293
+ stateHeaders: [],
10294
+ stateHeadersToSend: [],
10295
+ multistage: false,
10296
+ quit: false,
10297
+ approved: false,
10298
+ configured: false,
10299
+ useHttpPath: false,
10300
+ usernameFromProto: false,
10301
+ sanitizePrompt: true,
10302
+ protectProtocol: true,
10303
+ helpers: [],
10304
+ capaAuthtype: {
10305
+ requestInitial: false,
10306
+ requestHelper: false,
10307
+ response: false
10308
+ },
10309
+ capaState: {
10310
+ requestInitial: false,
10311
+ requestHelper: false,
10312
+ response: false
10313
+ }
10314
+ };
10315
+ }
10316
+ /** A death of git's credential code (`die()`): its `fatal:` line. */
10317
+ var CredentialError = class extends Error {
10318
+ constructor(message) {
10319
+ super(`fatal: ${message}`);
10320
+ this.name = "CredentialError";
10321
+ }
10322
+ };
10323
+ function setCapability(capa, op) {
10324
+ if (op === "initial") capa.requestInitial = true;
10325
+ else if (op === "helper") capa.requestHelper = true;
10326
+ else capa.response = true;
10327
+ }
10328
+ /** `credential_set_all_capabilities` */
10329
+ function setAllCapabilities(c, op) {
10330
+ setCapability(c.capaAuthtype, op);
10331
+ setCapability(c.capaState, op);
10332
+ }
10333
+ function hasCapability(capa, op) {
10334
+ if (op === "helper") return capa.requestInitial;
10335
+ if (op === "response") return capa.requestInitial && capa.requestHelper;
10336
+ return false;
10337
+ }
10338
+ function clearSecrets(c) {
10339
+ delete c.password;
10340
+ delete c.credential;
10341
+ }
10342
+ /** `credential_next_state`: the `state[]` a helper gave become the ones sent next. */
10343
+ function nextState(c) {
10344
+ c.stateHeadersToSend = c.stateHeaders;
10345
+ c.stateHeaders = [];
10346
+ }
10347
+ /** git_config_bool without a key to die for: a bad value reads as false here. */
10348
+ function bool(value) {
10349
+ return parseGitBool(value) ?? false;
10350
+ }
10351
+ /**
10352
+ * `credential_read`: applies the key=value lines of `text` up to an empty line (or its end)
10353
+ * to `c`. A line without `=` stops the reading with git's warning (false is returned); keys
10354
+ * git does not know are ignored. Under 2.43 the keys 2.46 added are unknown too.
10355
+ */
10356
+ function readCredential(c, text, op, compatibility = "2.56", warn = () => {}) {
10357
+ const modern = compatibility !== "2.43";
10358
+ const lines = text.split("\n");
10359
+ if (lines[lines.length - 1] === "") lines.pop();
10360
+ for (const raw of lines) {
10361
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
10362
+ if (line === "") break;
10363
+ const eq = line.indexOf("=");
10364
+ if (eq < 0) {
10365
+ warn(`warning: invalid credential line: ${line}\n`);
10366
+ return false;
10367
+ }
10368
+ const key = line.slice(0, eq);
10369
+ const value = line.slice(eq + 1);
10370
+ switch (key) {
10371
+ case "username":
10372
+ c.username = value;
10373
+ c.usernameFromProto = true;
10374
+ break;
10375
+ case "password":
10376
+ c.password = value;
10377
+ break;
10378
+ case "protocol":
10379
+ c.protocol = value;
10380
+ break;
10381
+ case "host":
10382
+ c.host = value;
10383
+ break;
10384
+ case "path":
10385
+ c.path = value;
10386
+ break;
10387
+ case "wwwauth[]":
10388
+ c.wwwauth.push(value);
10389
+ break;
10390
+ case "password_expiry_utc": {
10391
+ const expiry = parseTimestamp(value);
10392
+ c.passwordExpiryUtc = expiry === 0 || expiry === void 0 ? void 0 : expiry;
10393
+ break;
10394
+ }
10395
+ case "oauth_refresh_token":
10396
+ c.oauthRefreshToken = value;
10397
+ break;
10398
+ case "url":
10399
+ credentialFromUrl(c, value, warn);
10400
+ break;
10401
+ case "quit":
10402
+ c.quit = bool(value);
10403
+ break;
10404
+ default:
10405
+ if (!modern) break;
10406
+ switch (key) {
10407
+ case "credential":
10408
+ c.credential = value;
10409
+ break;
10410
+ case "ephemeral":
10411
+ c.ephemeral = bool(value);
10412
+ break;
10413
+ case "state[]":
10414
+ c.stateHeaders.push(value);
10415
+ break;
10416
+ case "capability[]":
10417
+ if (value === "authtype") setCapability(c.capaAuthtype, op);
10418
+ else if (value === "state") setCapability(c.capaState, op);
10419
+ break;
10420
+ case "continue":
10421
+ c.multistage = bool(value);
10422
+ break;
10423
+ case "authtype": c.authtype = value;
10424
+ }
10425
+ }
10426
+ }
10427
+ return true;
10428
+ }
10429
+ /** parse_timestamp (strtoumax, base 10): leading digits; undefined (ERANGE) when too large. */
10430
+ function parseTimestamp(value) {
10431
+ const digits = /^\s*\+?(\d*)/.exec(value)?.[1] ?? "";
10432
+ if (digits === "") return 0;
10433
+ const n = Number(digits);
10434
+ return Number.isSafeInteger(n) ? n : void 0;
10435
+ }
10436
+ /**
10437
+ * `credential_write`: the lines git hands a helper (`helper`: `get`) or hands back
10438
+ * (`response`: `store`, `erase`, and `git credential`'s output).
10439
+ *
10440
+ * @throws CredentialError for a value holding a newline (or, 2.46+, a carriage return under
10441
+ * `credential.protectProtocol`)
10442
+ */
10443
+ function writeCredential(c, op, compatibility = "2.56") {
10444
+ const modern = compatibility !== "2.43";
10445
+ let out = "";
10446
+ const item = (key, value) => {
10447
+ if (value === void 0) return;
10448
+ if (value.includes("\n")) throw new CredentialError(`credential value for ${key} contains newline`);
10449
+ if (modern && c.protectProtocol && value.includes("\r")) throw new CredentialError(`credential value for ${key} contains carriage return\nIf this is intended, set \`credential.protectProtocol=false\``);
10450
+ out += `${key}=${value}\n`;
10451
+ };
10452
+ const authtype = modern && hasCapability(c.capaAuthtype, op);
10453
+ const state = modern && hasCapability(c.capaState, op);
10454
+ if (authtype) item("capability[]", "authtype");
10455
+ if (state) item("capability[]", "state");
10456
+ if (authtype) {
10457
+ item("authtype", c.authtype);
10458
+ item("credential", c.credential);
10459
+ if (c.ephemeral) item("ephemeral", "1");
10460
+ }
10461
+ item("protocol", c.protocol ?? "");
10462
+ item("host", c.host ?? "");
10463
+ item("path", c.path);
10464
+ item("username", c.username);
10465
+ item("password", c.password);
10466
+ item("oauth_refresh_token", c.oauthRefreshToken);
10467
+ if (c.passwordExpiryUtc !== void 0) item("password_expiry_utc", String(c.passwordExpiryUtc));
10468
+ for (const header of c.wwwauth) item("wwwauth[]", header);
10469
+ if (state) {
10470
+ if (c.multistage) item("continue", "1");
10471
+ for (const header of c.stateHeadersToSend) item("state[]", header);
10472
+ }
10473
+ return out;
10474
+ }
10475
+ const encoder = new TextEncoder();
10476
+ const decoder = new TextDecoder();
10477
+ /** url_decode_mem: `%XX` escapes decoded (no `+`), bytes read as UTF-8. */
10478
+ function urlDecode(text) {
10479
+ const bytes = encoder.encode(text);
10480
+ const out = [];
10481
+ const hex = (b) => {
10482
+ if (b === void 0) return -1;
10483
+ if (b >= 48 && b <= 57) return b - 48;
10484
+ if (b >= 65 && b <= 70) return b - 55;
10485
+ if (b >= 97 && b <= 102) return b - 87;
10486
+ return -1;
10487
+ };
10488
+ for (let i = 0; i < bytes.length; i++) {
10489
+ const b = bytes[i];
10490
+ if (b === 37 && bytes.length - i >= 3) {
10491
+ const hi = hex(bytes[i + 1]);
10492
+ const lo = hex(bytes[i + 2]);
10493
+ const val = hi < 0 || lo < 0 ? -1 : hi << 4 | lo;
10494
+ if (val > 0) {
10495
+ out.push(val);
10496
+ i += 2;
10497
+ continue;
10498
+ }
10499
+ }
10500
+ out.push(b);
10501
+ }
10502
+ return decoder.decode(new Uint8Array(out));
10503
+ }
10504
+ /**
10505
+ * `credential_from_url_1`: `c` cleared, then filled from `url` (`proto://[user[:pass]@]host/path`,
10506
+ * slashes around the path trimmed). A partial URL may lack any part.
10507
+ *
10508
+ * @returns git's warning when the URL cannot be used (no scheme, a newline in a part)
10509
+ */
10510
+ function credentialFromUrlGently(c, url, allowPartial) {
10511
+ Object.assign(c, newCredential());
10512
+ for (const key of [
10513
+ "protocol",
10514
+ "host",
10515
+ "path",
10516
+ "username",
10517
+ "password",
10518
+ "credential",
10519
+ "authtype",
10520
+ "oauthRefreshToken",
10521
+ "passwordExpiryUtc"
10522
+ ]) delete c[key];
10523
+ const protoEnd = url.indexOf("://");
10524
+ if (!allowPartial && protoEnd <= 0) return `warning: url has no scheme: ${url}\n`;
10525
+ const cp = protoEnd >= 0 ? protoEnd + 3 : 0;
10526
+ const rest = url.slice(cp);
10527
+ const atRel = rest.indexOf("@");
10528
+ const colonRel = rest.indexOf(":");
10529
+ let slashRel = rest.search(/[/?#]/);
10530
+ if (slashRel < 0) slashRel = rest.length;
10531
+ let hostRel;
10532
+ if (atRel < 0 || slashRel <= atRel) hostRel = 0;
10533
+ else if (colonRel < 0 || atRel <= colonRel) {
10534
+ c.username = urlDecode(rest.slice(0, atRel));
10535
+ if (c.username) c.usernameFromProto = true;
10536
+ hostRel = atRel + 1;
10537
+ } else {
10538
+ c.username = urlDecode(rest.slice(0, colonRel));
10539
+ if (c.username) c.usernameFromProto = true;
10540
+ c.password = urlDecode(rest.slice(colonRel + 1, atRel));
10541
+ hostRel = atRel + 1;
10542
+ }
10543
+ if (protoEnd > 0) c.protocol = url.slice(0, protoEnd);
10544
+ if (!allowPartial || slashRel - hostRel > 0) c.host = urlDecode(rest.slice(hostRel, slashRel));
10545
+ let p = slashRel;
10546
+ while (rest[p] === "/") p++;
10547
+ if (p < rest.length) {
10548
+ let path = urlDecode(rest.slice(p));
10549
+ let end = path.length;
10550
+ while (end > 1 && path[end - 1] === "/") end--;
10551
+ path = path.slice(0, end);
10552
+ c.path = path;
10553
+ }
10554
+ for (const key of [
10555
+ "username",
10556
+ "password",
10557
+ "protocol",
10558
+ "host",
10559
+ "path"
10560
+ ]) if (c[key]?.includes("\n")) return `warning: url contains a newline in its ${key} component: ${url}\n`;
10561
+ }
10562
+ /**
10563
+ * `credential_from_url`: `c` from a full URL.
10564
+ *
10565
+ * @throws CredentialError when git dies on it (`credential url cannot be parsed: <url>`),
10566
+ * after handing its warning to `warn`
10567
+ */
10568
+ function credentialFromUrl(c, url, warn = () => {}) {
10569
+ const warning = credentialFromUrlGently(c, url, false);
10570
+ if (warning !== void 0) {
10571
+ warn(warning);
10572
+ throw new CredentialError(`credential url cannot be parsed: ${url}`);
10573
+ }
10574
+ }
10575
+ /**
10576
+ * The remote as git's prompt names it (`Username for '<this>': `): `credential_format`
10577
+ * (2.46+'s `credential.sanitizePrompt`, on by default) or `credential_describe`.
10578
+ */
10579
+ function describeCredential(c, compatibility = "2.56") {
10580
+ if (compatibility !== "2.43" && c.sanitizePrompt) return credentialFormat(c, compatibility);
10581
+ if (c.protocol === void 0) return "";
10582
+ let out = `${c.protocol}://`;
10583
+ if (c.username) out += `${c.username}@`;
10584
+ if (c.host !== void 0) out += c.host;
10585
+ if (c.path !== void 0) out += `/${c.path}`;
10586
+ return out;
10587
+ }
10588
+ /** `credential_match` (without the secrets) */
10589
+ function credentialMatch(want, have) {
10590
+ const check = (key) => want[key] === void 0 || have[key] !== void 0 && want[key] === have[key];
10591
+ return check("protocol") && check("host") && check("path") && check("username");
10592
+ }
10593
+ const URL_UNSAFE_CHARS = " <>\"%{}|\\^`:?#[]@!$&'()*+,;=";
10594
+ /** strbuf_add_percentencode over the UTF-8 bytes of `text`. */
10595
+ function percentEncode(text, flags) {
10596
+ let out = "";
10597
+ for (const ch of encoder.encode(text)) {
10598
+ const c = String.fromCharCode(ch);
10599
+ const encode = ch <= 31 || ch >= 127 || c === "/" && flags.slash === true || (flags.hostAndPort ? !/[A-Za-z0-9]/.test(c) && !"-.:[]".includes(c) : URL_UNSAFE_CHARS.includes(c));
10600
+ out += encode ? `%${ch.toString(16).toUpperCase().padStart(2, "0")}` : c;
10601
+ }
10602
+ return out;
10603
+ }
10604
+ /** `credential_format`: the URL the configuration is matched against. */
10605
+ function credentialFormat(c, compatibility) {
10606
+ if (c.protocol === void 0) return "";
10607
+ let out = `${c.protocol}://`;
10608
+ if (c.username) out += `${percentEncode(c.username, { slash: true })}@`;
10609
+ if (c.host !== void 0) out += compatibility === "2.43" ? c.host : percentEncode(c.host, { hostAndPort: true });
10610
+ if (c.path !== void 0) out += `/${percentEncode(c.path, {})}`;
10611
+ return out;
10612
+ }
10613
+ /** The `credential.*` entries matching a URL `url_normalize` refuses (see `applyConfig`). */
10614
+ function* unnormalizedMatches(entries, fallbackMatch) {
10615
+ for (const entry of entries) {
10616
+ if (!entry.key.startsWith("credential.")) continue;
10617
+ const rest = entry.key.slice(11);
10618
+ const dot = rest.lastIndexOf(".");
10619
+ if (dot < 0) {
10620
+ yield {
10621
+ name: rest,
10622
+ entry
10623
+ };
10624
+ continue;
10625
+ }
10626
+ const configUrl = rest.slice(0, dot);
10627
+ if (!isUrlNormalizeError(normalizeUrl(configUrl, { allowGlobs: true }))) continue;
10628
+ if (fallbackMatch(configUrl)) yield {
10629
+ name: rest.slice(dot + 1),
10630
+ entry
10631
+ };
10632
+ }
10633
+ }
10634
+ /**
10635
+ * credential.c's helper sequence over a {@link GitCredential}: `credential_fill`,
10636
+ * `credential_approve`, `credential_reject`.
10637
+ *
10638
+ * @example
10639
+ * ```ts
10640
+ * const c = newCredential();
10641
+ * credentialFromUrl(c, "https://example.com/repo.git");
10642
+ * if (await helpers.fill(c, true)) use(c.username, c.password);
10643
+ * ```
10644
+ */
10645
+ var CredentialHelpers = class {
10646
+ options;
10647
+ compatibility;
10648
+ constructor(options) {
10649
+ this.options = options;
10650
+ this.compatibility = options.compatibility ?? "2.56";
10651
+ }
10652
+ stderr(text) {
10653
+ if (text) this.options.onStderr?.(text);
10654
+ }
10655
+ nowSeconds() {
10656
+ return Math.floor((this.options.now ?? Date.now)() / 1e3);
10657
+ }
10658
+ /**
10659
+ * `credential_apply_config`: the helpers, `credential.username` and `useHttpPath` of every
10660
+ * `credential.*` / `credential.<url>.*` entry matching `c`, in config order; once per
10661
+ * credential. The path is dropped for http(s) unless `useHttpPath`.
10662
+ *
10663
+ * @throws CredentialError without a host or a protocol
10664
+ * @throws InvalidConfigError for a valueless entry (`config_error_nonbool`)
10665
+ */
10666
+ applyConfig(c) {
10667
+ if (c.host === void 0) throw new CredentialError("refusing to work with credential missing host field");
10668
+ if (c.protocol === void 0) throw new CredentialError("refusing to work with credential missing protocol field");
10669
+ if (c.configured) return;
10670
+ const normalized = normalizeUrl(credentialFormat(c, this.compatibility));
10671
+ const entries = this.options.entries();
10672
+ const fallbackMatch = (configUrl) => {
10673
+ const want = newCredential();
10674
+ const warning = credentialFromUrlGently(want, configUrl, true);
10675
+ if (warning !== void 0) {
10676
+ this.stderr(warning);
10677
+ this.stderr(`warning: skipping credential lookup for key: credential.${configUrl}\n`);
10678
+ return false;
10679
+ }
10680
+ return credentialMatch(want, c);
10681
+ };
10682
+ const matched = isUrlNormalizeError(normalized) ? unnormalizedMatches(entries, fallbackMatch) : urlMatchedEntries(entries, "credential", normalized, void 0, {
10683
+ selectAll: true,
10684
+ fallbackMatch
10685
+ });
10686
+ for (const { name, entry } of matched) {
10687
+ const value = entry.value;
10688
+ const key = `credential.${name}`;
10689
+ if (value === void 0) throw new InvalidConfigError(key, `error: missing value for '${entry.key}'`);
10690
+ if (name === "helper") {
10691
+ if (value) c.helpers.push(value);
10692
+ else c.helpers = [];
10693
+ } else if (name === "username") {
10694
+ if (!c.usernameFromProto) c.username = value;
10695
+ } else if (name === "usehttppath") c.useHttpPath = bool(value);
10696
+ else if (this.compatibility !== "2.43") {
10697
+ if (name === "sanitizeprompt") c.sanitizePrompt = bool(value);
10698
+ else if (name === "protectprotocol") c.protectProtocol = bool(value);
10699
+ }
10700
+ }
10701
+ c.configured = true;
10702
+ if (!c.useHttpPath && (c.protocol === "http" || c.protocol === "https")) delete c.path;
10703
+ }
10704
+ /** `credential_do` + `run_credential_helper` */
10705
+ async runHelper(c, helper, operation) {
10706
+ const program = helper.startsWith("!") ? helper.slice(1) : helper.startsWith("/") ? helper : `git credential-${helper}`;
10707
+ const wantOutput = operation === "get";
10708
+ const stdin = writeCredential(c, wantOutput ? "helper" : "response", this.compatibility);
10709
+ const run = await this.options.run(`${program} ${operation}`, stdin);
10710
+ if (!run) return;
10711
+ this.stderr(decoder.decode(run.stderr));
10712
+ if (wantOutput) readCredential(c, decoder.decode(run.stdout), "helper", this.compatibility, (line) => this.stderr(line));
10713
+ }
10714
+ /** A username and a password, or (2.46+) a `credential`: nothing more to ask for. */
10715
+ full(c) {
10716
+ return c.username !== void 0 && c.password !== void 0 || this.compatibility !== "2.43" && c.credential !== void 0;
10717
+ }
10718
+ /**
10719
+ * `credential_fill` up to the prompt: asks the helpers in order until one completes the
10720
+ * credential (a username and a password, 2.46+ also a `credential`).
10721
+ *
10722
+ * @param allCapabilities the caller takes every capability (http.c: true; 2.46+ only)
10723
+ * @returns whether the credential is complete (false: git would prompt)
10724
+ * @throws CredentialError when a helper said `quit` (`credential helper '<h>' told us to quit`)
10725
+ */
10726
+ async fill(c, allCapabilities = false) {
10727
+ if (this.full(c)) return true;
10728
+ const modern = this.compatibility !== "2.43";
10729
+ if (modern) {
10730
+ nextState(c);
10731
+ c.multistage = false;
10732
+ }
10733
+ this.applyConfig(c);
10734
+ if (modern && allCapabilities) setAllCapabilities(c, "initial");
10735
+ for (let i = 0; i < c.helpers.length; i++) {
10736
+ const helper = c.helpers[i];
10737
+ await this.runHelper(c, helper, "get");
10738
+ if (c.passwordExpiryUtc !== void 0 && c.passwordExpiryUtc < this.nowSeconds()) {
10739
+ if (modern) clearSecrets(c);
10740
+ else delete c.password;
10741
+ c.passwordExpiryUtc = void 0;
10742
+ }
10743
+ if (this.full(c)) {
10744
+ if (modern) c.wwwauth = [];
10745
+ return true;
10746
+ }
10747
+ if (c.quit) throw new CredentialError(`credential helper '${helper}' told us to quit`);
10748
+ }
10749
+ return false;
10750
+ }
10751
+ /** `credential_approve`: a complete, unexpired credential stored to every helper (`store`). */
10752
+ async approve(c) {
10753
+ if (c.approved) return;
10754
+ if (!this.full(c)) return;
10755
+ if (c.passwordExpiryUtc !== void 0 && c.passwordExpiryUtc < this.nowSeconds()) return;
10756
+ if (this.compatibility !== "2.43") nextState(c);
10757
+ this.applyConfig(c);
10758
+ for (let i = 0; i < c.helpers.length; i++) await this.runHelper(c, c.helpers[i], "store");
10759
+ c.approved = true;
10760
+ }
10761
+ /** `credential_reject`: the credential erased from every helper (`erase`), then forgotten. */
10762
+ async reject(c) {
10763
+ if (this.compatibility !== "2.43") nextState(c);
10764
+ this.applyConfig(c);
10765
+ for (let i = 0; i < c.helpers.length; i++) await this.runHelper(c, c.helpers[i], "erase");
10766
+ clearSecrets(c);
10767
+ delete c.username;
10768
+ delete c.oauthRefreshToken;
10769
+ c.passwordExpiryUtc = void 0;
10770
+ c.approved = false;
10771
+ }
10772
+ };
10773
+ /**
10774
+ * An `HttpCredentialHelper` speaking git's helper protocol (`credential.helper`), as http.c
10775
+ * drives its `http_auth`: a 401 starts a credential from the request's URL (its user, its
10776
+ * `WWW-Authenticate` challenges) and fills it through the helpers (every capability, 2.46+);
10777
+ * `approve` stores it, `reject` erases it, both with what the helpers said during the fill.
10778
+ */
10779
+ function createConfigCredentialHelper(options) {
10780
+ const helpers = new CredentialHelpers(options);
10781
+ const modern = (options.compatibility ?? "2.56") !== "2.43";
10782
+ /** The credential of each base URL, as the last fill left it */
10783
+ const states = /* @__PURE__ */ new Map();
10784
+ const fresh = (request) => {
10785
+ const c = newCredential();
10786
+ credentialFromUrl(c, request.url);
10787
+ if (request.username !== void 0 && c.username === void 0) {
10788
+ c.username = request.username;
10789
+ if (request.username) c.usernameFromProto = true;
10790
+ }
10791
+ c.wwwauth = [...request.wwwAuthenticate];
10792
+ return c;
10793
+ };
10794
+ const withSecrets = (c, credentials) => {
10795
+ if (credentials.username !== void 0) c.username = credentials.username;
10796
+ if (credentials.password !== void 0) c.password = credentials.password;
10797
+ if (credentials.token !== void 0 && c.password === void 0) {
10798
+ c.password = credentials.token;
10799
+ c.username ??= "x-access-token";
10800
+ }
10801
+ if (modern && credentials.authtype !== void 0) c.authtype = credentials.authtype;
10802
+ if (modern && credentials.credential !== void 0) c.credential = credentials.credential;
10803
+ return c;
10804
+ };
10805
+ return {
10806
+ async fill(request) {
10807
+ const c = fresh(request);
10808
+ states.set(request.url, c);
10809
+ if (!await helpers.fill(c, true)) return void 0;
10810
+ return {
10811
+ ...c.username !== void 0 ? { username: c.username } : {},
10812
+ ...c.password !== void 0 ? { password: c.password } : {},
10813
+ ...modern && c.authtype !== void 0 && c.credential !== void 0 ? {
10814
+ authtype: c.authtype,
10815
+ credential: c.credential
10816
+ } : {}
10817
+ };
10818
+ },
10819
+ async approve(credentials, request) {
10820
+ const c = states.get(request.url) ?? withSecrets(fresh(request), credentials);
10821
+ c.wwwauth = [];
10822
+ await helpers.approve(c);
10823
+ },
10824
+ async reject(credentials, request) {
10825
+ const c = states.get(request.url) ?? withSecrets(fresh(request), credentials);
10826
+ states.delete(request.url);
10827
+ c.wwwauth = [...request.wwwAuthenticate];
10828
+ await helpers.reject(c);
10829
+ }
10830
+ };
10831
+ }
10832
+ /**
10833
+ * How {@link CredentialHelpers} reach a repository: its configuration's `credential.*`
10834
+ * entries (command line included), its helpers run through the host's hook runner in the
10835
+ * worktree's top (no runner: none runs), the protocol of the runner's compatibility.
10836
+ */
10837
+ function credentialHelpersOptionsOf(workingCopy, options = {}) {
10838
+ const hooks = options.hooks ?? new HookSession(workingCopy);
10839
+ return {
10840
+ entries: () => RemoteConfigStore.from(workingCopy).entriesWithPrefix("credential.") ?? [],
10841
+ run: (command, stdin) => hooks.runCredentialHelper(command, stdin),
10842
+ onStderr: options.onStderr ?? ((text) => hooks.append(text)),
10843
+ compatibility: hookRunnerOf(workingCopy)?.compatibility ?? "2.56",
10844
+ ...options.now ? { now: options.now } : {}
10845
+ };
10846
+ }
10847
+ /** git's credential.c over a repository (see {@link credentialHelpersOptionsOf}). */
10848
+ function credentialHelpersOf(workingCopy, options = {}) {
10849
+ return new CredentialHelpers(credentialHelpersOptionsOf(workingCopy, options));
10850
+ }
10851
+ /**
10852
+ * The credential helper git builds from a repository's configuration (`credential.helper`,
10853
+ * `credential.<url>.*`, command line included): see {@link credentialHelpersOptionsOf} and
10854
+ * {@link createConfigCredentialHelper}.
10855
+ *
10856
+ * @example
10857
+ * ```ts
10858
+ * await git.push().setCredentialHelper(credentialHelperOf(workingCopy)).call();
10859
+ * ```
10860
+ */
10861
+ function credentialHelperOf(workingCopy, options = {}) {
10862
+ return createConfigCredentialHelper(credentialHelpersOptionsOf(workingCopy, options));
10863
+ }
10864
+ /**
10865
+ * Whether the configuration names any credential helper (`credential.helper` or
10866
+ * `credential.<url>.helper`, empty resets included).
10867
+ */
10868
+ function configuresCredentialHelper(workingCopy) {
10869
+ return (RemoteConfigStore.from(workingCopy).entriesWithPrefix("credential.") ?? []).some((e) => e.key === "credential.helper" || e.key.endsWith(".helper"));
10870
+ }
10871
+ //#endregion
8796
10872
  //#region src/transport-command.ts
8797
10873
  /**
8798
10874
  * Base class for commands that require network transport.
@@ -8821,6 +10897,8 @@ var TransportCommand = class extends GitCommand {
8821
10897
  credentialHelper;
8822
10898
  /** git's `warning:` lines of the HTTP client */
8823
10899
  warningCallback;
10900
+ /** The helper built from `credential.helper` for this command (see {@link httpCredentialHelper}) */
10901
+ configCredentialHelper;
8824
10902
  constructor(workingCopy) {
8825
10903
  super(workingCopy);
8826
10904
  this.aroundEntryPoints(() => {
@@ -8953,6 +11031,18 @@ var TransportCommand = class extends GitCommand {
8953
11031
  return this;
8954
11032
  }
8955
11033
  /**
11034
+ * The credential helper this command's HTTP requests ask: the one given to
11035
+ * {@link setCredentialHelper}, else, when the configuration names a `credential.helper`
11036
+ * and the host has a hook runner, git's helpers of that configuration (credential.c through
11037
+ * {@link credentialHelperOf}: their stderr in the hook output), as git's transports read
11038
+ * them; else none.
11039
+ */
11040
+ httpCredentialHelper() {
11041
+ if (this.credentialHelper) return this.credentialHelper;
11042
+ if (this.configCredentialHelper === void 0) this.configCredentialHelper = hookRunnerOf(this._workingCopy) && configuresCredentialHelper(this._workingCopy) ? credentialHelperOf(this._workingCopy, { hooks: this.hooks }) : null;
11043
+ return this.configCredentialHelper ?? void 0;
11044
+ }
11045
+ /**
8956
11046
  * Receives the `warning:` lines git's HTTP client prints on stderr (`rate limited, waiting
8957
11047
  * <n> seconds before retry`).
8958
11048
  */
@@ -9065,8 +11155,19 @@ var TransportCommand = class extends GitCommand {
9065
11155
  ...this.gzipRequests !== void 0 ? { gzipRequests: this.gzipRequests } : {},
9066
11156
  protocolVersion: protocolVersionOf(RemoteConfigStore.from(this._workingCopy)),
9067
11157
  httpSettings: (url) => this.httpSettingsFor(url),
9068
- ...this.credentialHelper ? { credentialHelper: this.credentialHelper } : {},
9069
- ...httpSessionSettings(this._workingCopy)
11158
+ ...credentialHelperOption(this.httpCredentialHelper()),
11159
+ ...httpSessionSettings(this._workingCopy),
11160
+ localHooks: (remote) => remoteHookSession(this._workingCopy, remote, { localPush: true }),
11161
+ ...(() => {
11162
+ const namespace = hostEnvironmentOf(this._workingCopy)?.namespace;
11163
+ return namespace ? { namespace } : {};
11164
+ })(),
11165
+ ...localLazyFetchOf(hostEnvironmentOf(this._workingCopy), {
11166
+ transports: this.getTransports(),
11167
+ ...this.credentialHelper ? { credentialHelper: this.credentialHelper } : {},
11168
+ ...this.timeout !== void 0 ? { timeout: this.timeout } : {},
11169
+ ...this.warningCallback ? { warningCallback: this.warningCallback } : {}
11170
+ })
9070
11171
  };
9071
11172
  }
9072
11173
  /**
@@ -9111,7 +11212,7 @@ var TransportCommand = class extends GitCommand {
9111
11212
  return createBundleUriHost({
9112
11213
  ...options.objectFormat ? { objectFormat: options.objectFormat } : {},
9113
11214
  ...options.compatibility !== "2.43" ? { fsckObjects: async () => {
9114
- const { fetchFsckOf } = await import("./fsck-C4US3l0B.js").then((n) => n.t);
11215
+ const { fetchFsckOf } = await import("./fsck-BZ508Elg.js").then((n) => n.t);
9115
11216
  return fetchFsckOf({
9116
11217
  value: (key) => /^fetch\.fsck\./i.test(key) ? void 0 : store.value(key),
9117
11218
  compatibility: options.compatibility,
@@ -9130,7 +11231,7 @@ var TransportCommand = class extends GitCommand {
9130
11231
  ...options.remoteUrl !== void 0 ? { remoteUrl: options.remoteUrl } : {},
9131
11232
  ...this.credentials ? { credentials: this.credentials } : {},
9132
11233
  ...this.headers ? { headers: this.headers } : {},
9133
- ...this.credentialHelper ? { credentialHelper: this.credentialHelper } : {},
11234
+ ...credentialHelperOption(this.httpCredentialHelper()),
9134
11235
  httpSettings: (url) => this.httpSettingsFor(url),
9135
11236
  configValue: (key) => store.value(key),
9136
11237
  setConfigValue: options.setConfigValue ?? (async (key, value) => {
@@ -9183,6 +11284,10 @@ var TransportCommand = class extends GitCommand {
9183
11284
  };
9184
11285
  }
9185
11286
  };
11287
+ /** The `credentialHelper` option of a session or host, when there is one. */
11288
+ function credentialHelperOption(helper) {
11289
+ return helper ? { credentialHelper: helper } : {};
11290
+ }
9186
11291
  //#endregion
9187
11292
  //#region src/commands/plumbing-command.ts
9188
11293
  /**
@@ -10278,6 +12383,7 @@ var FetchCommand = class FetchCommand extends TransportCommand {
10278
12383
  refetch = false;
10279
12384
  /** `--negotiation-tip=<revision>` (a revision, or a ref glob), in order */
10280
12385
  negotiationTips = [];
12386
+ negotiationIncludes = [];
10281
12387
  negotiateOnlyMode = false;
10282
12388
  setUpstream = false;
10283
12389
  /** `--[no-]recurse-submodules[=<mode>]`; unset: the configuration's */
@@ -10560,6 +12666,19 @@ var FetchCommand = class FetchCommand extends TransportCommand {
10560
12666
  return this;
10561
12667
  }
10562
12668
  /**
12669
+ * git 2.56's `git fetch --negotiation-include=<revision>`: these commits (a revision, or a
12670
+ * glob of refs) are sent as `have` lines whatever the negotiator chooses, before its own;
12671
+ * without any, the remote's `remote.<name>.negotiationInclude` values (an empty value
12672
+ * clears the earlier ones). A revision naming nothing is skipped; a glob matching no ref is
12673
+ * ignored with git's warning. git 2.43 has no such option: under its compatibility the call
12674
+ * dies as git's option parser does (`unknown option`, exit 129).
12675
+ */
12676
+ setNegotiationIncludes(...revisions) {
12677
+ this.checkCallable();
12678
+ this.negotiationIncludes = [...revisions];
12679
+ return this;
12680
+ }
12681
+ /**
10563
12682
  * `git fetch --negotiate-only`: negotiates with the remote from {@link setNegotiationTips}
10564
12683
  * (protocol v2, a server with `wait-for-done`) and fetches nothing; the commits the server
10565
12684
  * acknowledged come back as {@link FetchResult.negotiatedCommits} (git prints them on
@@ -10888,6 +13007,7 @@ var FetchCommand = class FetchCommand extends TransportCommand {
10888
13007
  async call() {
10889
13008
  this.checkCallable();
10890
13009
  this.setCallable(false);
13010
+ if (this.negotiationIncludes.length > 0 && this.negotiationCompatibility() === "2.43") throw new GitApiError(`error: unknown option \`negotiation-include=${this.negotiationIncludes[0]}'`, { exitCode: 129 });
10891
13011
  if (this.negotiateOnlyMode) {
10892
13012
  if (this.recurseSubmodules === "yes" || this.recurseSubmodules === "on-demand") throw new GitApiError("fatal: options '--negotiate-only' and '--recurse-submodules' cannot be used together", { exitCode: 128 });
10893
13013
  if (this.negotiationTips.length === 0 && this.negotiationCompatibility() === "2.43") throw new GitApiError("fatal: --negotiate-only needs one or more --negotiation-tip=*", { exitCode: 128 });
@@ -10960,6 +13080,8 @@ var FetchCommand = class FetchCommand extends TransportCommand {
10960
13080
  const sessionId = clientSessionIdOf(this.workingCopy);
10961
13081
  const tipsGiven = this.negotiationTipsGiven();
10962
13082
  const negotiationTips = tipsGiven.length > 0 ? await this.resolveNegotiationTips(messages, tipsGiven) : void 0;
13083
+ const includesGiven = this.negotiationIncludesGiven();
13084
+ const negotiationIncludes = includesGiven.length > 0 ? await this.resolveNegotiationTips(messages, includesGiven, "--negotiation-include") : void 0;
10963
13085
  const unpackLimit = unpackLimitOf({ getAll: (key) => store.values(key) }, "fetch");
10964
13086
  resetPromisorAcceptance(this.workingCopy);
10965
13087
  const fetchOptions = {
@@ -11017,6 +13139,7 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11017
13139
  ...this.refetch ? { refetch: true } : {},
11018
13140
  ...negotiationAlgorithm !== "consecutive" ? { negotiationAlgorithm } : {},
11019
13141
  ...negotiationTips ? { negotiationTips } : {},
13142
+ ...negotiationIncludes?.length ? { negotiationIncludes } : {},
11020
13143
  onWarning: (line) => messages.push(line),
11021
13144
  promisorRemote: promisorRemoteReplyOf(this.workingCopy, (line) => messages.push(line)),
11022
13145
  autoFilter: () => promisorAutoFilter(this.workingCopy, (line) => messages.push(line))
@@ -11026,7 +13149,27 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11026
13149
  ...this.remoteSessionOptions(),
11027
13150
  ...uploadPack !== void 0 ? { program: uploadPack } : {}
11028
13151
  };
11029
- const result = await withRemoteUploadPack(remote, sessionOptions, (connection) => fetchFromConnection(connection, fetchOptions)).catch((error) => {
13152
+ const markedOf = (result) => this.fetchHeadEntries(result, {
13153
+ given: given.length,
13154
+ merge: mergeRefs,
13155
+ explicit: !useConfig,
13156
+ firstIsExact: given.length > 0 && !parseRefSpec(given[0]).wildcard,
13157
+ hasMerge: upstream !== void 0
13158
+ });
13159
+ const result = await withRemoteUploadPack(remote, sessionOptions, (connection) => fetchFromConnection(connection, fetchOptions)).catch(async (error) => {
13160
+ const partial = error instanceof RefTransactionAbortedError ? fetchResultOf(error) : void 0;
13161
+ if (partial && writesFetchHead && !this.atomic && checkout?.writeFetchHead) {
13162
+ const kept = (await markedOf(partial)).filter((e) => !e.shallowRejected);
13163
+ const marked = [...kept.filter((e) => !e.notForMerge), ...kept.filter((e) => e.notForMerge)];
13164
+ const refusedRef = refusedRefOf(error);
13165
+ const at = refusedRef === void 0 ? -1 : marked.findIndex((e) => e.localRef === refusedRef);
13166
+ const written = at < 0 ? marked : marked.slice(0, at + 1);
13167
+ await checkout.writeFetchHead(formatFetchHead(written.map(({ oid, remoteRef, notForMerge }) => ({
13168
+ oid,
13169
+ remoteRef,
13170
+ notForMerge
13171
+ })), remoteUrl), { append: true });
13172
+ }
11030
13173
  const message = error instanceof Error ? error.message : "";
11031
13174
  if (message.startsWith("couldn't find remote ref ")) throw new TransportError$1(`fatal: ${message}`, void 0, { cause: error });
11032
13175
  if (error instanceof ObjectFormatMismatchError) throw new TransportError$1(`fatal: ${message}`, void 0, { cause: error });
@@ -11046,13 +13189,7 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11046
13189
  for (const ref of result.remoteRefs) if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
11047
13190
  trackingUpdates.push(...result.refUpdates.map(toTrackingRefUpdate));
11048
13191
  if (result.refTransactionError !== void 0) errors.push(result.refTransactionError);
11049
- const marked = await this.fetchHeadEntries(result, {
11050
- given: given.length,
11051
- merge: mergeRefs,
11052
- explicit: !useConfig,
11053
- firstIsExact: given.length > 0 && !parseRefSpec(given[0]).wildcard,
11054
- hasMerge: upstream !== void 0
11055
- });
13192
+ const marked = await markedOf(result);
11056
13193
  for (const e of marked) if (e.shallowRejected && !e.notForMerge) messages.push(`warning: rejected ${e.localRef ?? e.remoteRef} because shallow roots are not allowed to be updated`);
11057
13194
  const entries = marked.filter((e) => !e.shallowRejected).map(({ oid, remoteRef, notForMerge }) => ({
11058
13195
  oid,
@@ -11125,18 +13262,36 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11125
13262
  */
11126
13263
  negotiationTipsGiven() {
11127
13264
  if (this.negotiationTips.length > 0 || this.negotiationCompatibility() === "2.43") return this.negotiationTips;
11128
- const store = RemoteConfigStore.from(this.workingCopy);
11129
- if (!store.isConfigured(this.remote)) return [];
11130
- return store.values(`remote.${this.remote}.negotiationRestrict`).filter((v) => v !== "");
13265
+ return this.remoteTransportOption("negotiationRestrict");
13266
+ }
13267
+ /**
13268
+ * The `--negotiation-include` revisions given, else the remote's
13269
+ * `remote.<name>.negotiationInclude` values; none under git 2.43, which has neither.
13270
+ */
13271
+ negotiationIncludesGiven() {
13272
+ if (this.negotiationCompatibility() === "2.43") return [];
13273
+ if (this.negotiationIncludes.length > 0) return this.negotiationIncludes;
13274
+ return this.remoteTransportOption("negotiationInclude");
13275
+ }
13276
+ /**
13277
+ * A multi-valued `remote.<name>.<key>` as transport.c's parse_transport_option keeps it:
13278
+ * each value appended, an empty one clearing the list. git reads it for the remote named
13279
+ * as given, a URL or path too (remote_get makes a remote of that name).
13280
+ */
13281
+ remoteTransportOption(key) {
13282
+ const list = [];
13283
+ for (const value of RemoteConfigStore.from(this.workingCopy).values(`remote.${this.remote}.${key}`)) if (value === "") list.length = 0;
13284
+ else list.push(value);
13285
+ return list;
11131
13286
  }
11132
13287
  /**
11133
13288
  * add_negotiation_tips: a revision (no glob characters) must name an object here, else git
11134
13289
  * dies (git 2.5x skips a name that resolves to nothing); a glob adds every ref it matches
11135
13290
  * (`refs/` put before a pattern without it), with git's warning when it matches none.
11136
13291
  */
11137
- async resolveNegotiationTips(messages, given = this.negotiationTips) {
13292
+ async resolveNegotiationTips(messages, given = this.negotiationTips, optionName) {
11138
13293
  const legacy = this.negotiationCompatibility() === "2.43";
11139
- const option = legacy ? "--negotiation-tip" : "--negotiation-restrict";
13294
+ const option = optionName ?? (legacy ? "--negotiation-tip" : "--negotiation-restrict");
11140
13295
  const tips = [];
11141
13296
  const glob = (text) => /[*?[\\]/.test(text);
11142
13297
  const refs = given.some(glob) ? await createTransportRefStore(this._workingCopy.history.refs).listAll() : [];
@@ -11175,6 +13330,8 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11175
13330
  const messages = [...legacyMessages];
11176
13331
  const given = this.negotiationTipsGiven();
11177
13332
  const tips = await this.resolveNegotiationTips(messages, given);
13333
+ const includesGiven = this.negotiationIncludesGiven();
13334
+ const includes = includesGiven.length > 0 ? await this.resolveNegotiationTips(messages, includesGiven, "--negotiation-include") : [];
11178
13335
  const remote = await this.prepareRemote(remoteUrl);
11179
13336
  if (given.length === 0) throw new GitApiError("fatal: --negotiate-only needs one or more --negotiation-restrict=*", { exitCode: 128 });
11180
13337
  const uploadPack = this.uploadPack ?? this.remoteProgram(this.remote, "uploadpack");
@@ -11198,6 +13355,7 @@ var FetchCommand = class FetchCommand extends TransportCommand {
11198
13355
  result.negotiatedCommits = await withRemoteUploadPack(remote, sessionOptions, (connection) => negotiateOnly(connection, {
11199
13356
  repository: createRepositoryFacade({ history: historyWithoutLazyFetch(history) }),
11200
13357
  tips,
13358
+ ...includes.length > 0 ? { includes } : {},
11201
13359
  negotiationAlgorithm: algorithm,
11202
13360
  shallow,
11203
13361
  ...sessionId !== void 0 ? { sessionId } : {}
@@ -12537,6 +14695,7 @@ var RepackCommand = class extends GitCommand {
12537
14695
  _reuseObjects = true;
12538
14696
  _writeBitmaps;
12539
14697
  _writeMidx = false;
14698
+ _compatibility;
12540
14699
  _geometric;
12541
14700
  _filter;
12542
14701
  _keepPacks = [];
@@ -12624,12 +14783,37 @@ var RepackCommand = class extends GitCommand {
12624
14783
  this._writeBitmaps = write;
12625
14784
  return this;
12626
14785
  }
12627
- /** `-m` (`--write-midx`): a multi-pack-index over the packs that stay. */
12628
- setWriteMidx(write) {
14786
+ /**
14787
+ * `-m` (`--write-midx[=<mode>]`): a multi-pack-index over the packs that stay (`true` or
14788
+ * `""`), or (`"incremental"`, git 2.55+) the incremental chain rebuilt with a new layer on top,
14789
+ * its layers compacted by `repack.midxSplitFactor` under `--geometric`. Any other value is
14790
+ * git's `error: unknown value for write-midx` (exit 129); under 2.43 compatibility every value
14791
+ * is (`option `write-midx' takes no value`).
14792
+ */
14793
+ setWriteMidx(mode) {
14794
+ this.checkCallable();
14795
+ this._writeMidx = mode;
14796
+ return this;
14797
+ }
14798
+ /**
14799
+ * The git version followed where versions differ: "2.43", "2.56" (2.55 and 2.56 alike), or
14800
+ * "2.57" (git master after 2.56, whose incremental midx layer also takes the packs its bitmap
14801
+ * needs: kept packs, packs that stay, cruft packs). Default: the hooks' compatibility (2.43 or
14802
+ * 2.56).
14803
+ */
14804
+ setCompatibility(compatibility) {
12629
14805
  this.checkCallable();
12630
- this._writeMidx = write;
14806
+ this._compatibility = compatibility;
12631
14807
  return this;
12632
14808
  }
14809
+ /** git_config_int of the configuration: `fallback` when unset, git's death on a bad unit. */
14810
+ configInt(key, fallback) {
14811
+ const value = RemoteConfigStore.from(this.workingCopy).value(key);
14812
+ if (value === void 0) return fallback;
14813
+ const n = parseGitInt(value);
14814
+ if (n === void 0) throw new GitApiError(`fatal: bad numeric config value '${value}' for '${key.toLowerCase()}': invalid unit`);
14815
+ return n;
14816
+ }
12633
14817
  /** `--geometric=<factor>` (`-g`): roll small packs up into a geometric progression. */
12634
14818
  setGeometric(factor) {
12635
14819
  this.checkCallable();
@@ -12738,13 +14922,22 @@ var RepackCommand = class extends GitCommand {
12738
14922
  async call() {
12739
14923
  this.checkCallable();
12740
14924
  this.setCallable(false);
14925
+ const compatibility = this._compatibility ?? this.hooks.compatibility;
14926
+ const legacy = compatibility === "2.43";
14927
+ const midxSplitFactor = legacy ? 2 : this.configInt("repack.midxSplitFactor", 2);
14928
+ const midxNewLayerThreshold = legacy ? 8 : this.configInt("repack.midxNewLayerThreshold", 8);
14929
+ let writeMidx = false;
14930
+ if (typeof this._writeMidx === "string" && legacy) throw new GitApiError("error: option `write-midx' takes no value", { exitCode: 129 });
14931
+ if (this._writeMidx === true || this._writeMidx === "") writeMidx = true;
14932
+ else if (this._writeMidx === "incremental") writeMidx = "incremental";
14933
+ else if (typeof this._writeMidx === "string") throw new GitApiError(`error: unknown value for write-midx: ${this._writeMidx}`, { exitCode: 129 });
12741
14934
  const loosenAsked = this._loosen || this._unpackUnreachable !== void 0;
12742
14935
  const incompatible = [
12743
14936
  ...loosenAsked ? ["-A"] : [],
12744
14937
  ...this._keepUnreachable ? ["-k/--keep-unreachable"] : [],
12745
14938
  ...this._cruft ? ["--cruft"] : []
12746
14939
  ];
12747
- if (this.hooks.compatibility === "2.43") {
14940
+ if (legacy) {
12748
14941
  const pair = (x, y) => new GitApiError(`fatal: options '${x}' and '${y}' cannot be used together`);
12749
14942
  if (this._keepUnreachable && loosenAsked) throw pair("--keep-unreachable", "-A");
12750
14943
  if (this._cruft && loosenAsked) throw pair("--cruft", "-A");
@@ -12753,6 +14946,8 @@ var RepackCommand = class extends GitCommand {
12753
14946
  if (incompatible.length === 3) throw new GitApiError("fatal: options '-A', '-k/--keep-unreachable', and '--cruft' cannot be used together");
12754
14947
  if (incompatible.length === 2) throw new GitApiError(`fatal: options '${incompatible[0]}' and '${incompatible[1]}' cannot be used together`);
12755
14948
  const all = this._all || this._loosen || this._cruft;
14949
+ if (midxSplitFactor < 2) throw new GitApiError(`fatal: invalid value for --midx-split-factor: ${midxSplitFactor}`);
14950
+ if (midxNewLayerThreshold < 1) throw new GitApiError(`fatal: invalid value for --midx-new-layer-threshold: ${midxNewLayerThreshold}`);
12756
14951
  const geometric = this._geometric ? this._geometric : void 0;
12757
14952
  if (geometric !== void 0 && all) throw new GitApiError("fatal: options '--geometric' and '-A/-a' cannot be used together");
12758
14953
  const repository = await this.filesRepository();
@@ -12782,7 +14977,8 @@ var RepackCommand = class extends GitCommand {
12782
14977
  files,
12783
14978
  gitDir,
12784
14979
  ...environment ? { environment } : {},
12785
- compatibility: this.hooks.compatibility,
14980
+ compatibility: legacy ? "2.43" : "2.56",
14981
+ ...compatibility === "2.57" ? { incrementalMidxClosure: true } : {},
12786
14982
  ...this.progress && !this._quiet ? { progress: this.progress } : {},
12787
14983
  all,
12788
14984
  deleteRedundant: this._delete,
@@ -12801,7 +14997,11 @@ var RepackCommand = class extends GitCommand {
12801
14997
  ...this._maxCruftSize !== void 0 ? { maxCruftSize: this._maxCruftSize } : {}
12802
14998
  } : {},
12803
14999
  ...this._writeBitmaps !== void 0 ? { writeBitmaps: this._writeBitmaps } : {},
12804
- ...this._writeMidx ? { writeMidx: true } : {},
15000
+ ...writeMidx ? {
15001
+ writeMidx,
15002
+ midxSplitFactor,
15003
+ midxNewLayerThreshold
15004
+ } : {},
12805
15005
  ...geometric !== void 0 ? { geometric } : {},
12806
15006
  ...this._filter !== void 0 ? { filter: this._filter } : {},
12807
15007
  ...this._keepPacks.length ? { keepPacks: this._keepPacks } : {},
@@ -12811,7 +15011,13 @@ var RepackCommand = class extends GitCommand {
12811
15011
  ...noDelta ? { noDelta } : {},
12812
15012
  onWarning: (line) => geometricWarnings.push(line)
12813
15013
  });
12814
- const result = noDelta && worktree?.batch ? await worktree.batch(run) : await run();
15014
+ let result;
15015
+ try {
15016
+ result = noDelta && worktree?.batch ? await worktree.batch(run) : await run();
15017
+ } catch (e) {
15018
+ if (e instanceof IncrementalMidxError) throw new GitApiError(e.lines.join("\n"), { exitCode: e.lines[0]?.startsWith("fatal:") ? 128 : 255 });
15019
+ throw e;
15020
+ }
12815
15021
  const output = [];
12816
15022
  if ((!result || result.nothingNew) && !this._quiet) output.push("Nothing new to pack.");
12817
15023
  return {
@@ -13619,4 +15825,4 @@ function midxNames(bytes) {
13619
15825
  return [];
13620
15826
  }
13621
15827
  //#endregion
13622
- export { relativeFilesPath as $, BisectResetCommand as $t, fetchBundleUri as A, nonCommitSwitchError as An, isRootRef$1 as At, stripFileFromPath as B, signatureStart as Bt, strictUrlOrigin as C, findBisection as Cn, shortlogIdent as Ct, TransportCommand as D, CheckoutCommand as Dn, fillIsBase as Dt, PlumbingError as E, skipAwayIndex as En, fillAheadBehind as Et, BundleCommandBase as F, RefFormat as Ft, defaultRemoteOf as G, atomSource as Gt, Gitmodules as H, trimTrailingSpaces as Ht, BundleList as I, RefKind as It, lstatKind as J, RevListCommand as Jt, isRelativeSubmoduleUrl as K, parseAtom as Kt, parseBundleListConfig as L, lstripRef as Lt, BundleListHeadsCommand as M, checkoutPaths as Mn, refKindOf as Mt, BundleUnbundleCommand as N, runPathCheckout as Nn, sortRefs as Nt, createBundleUriHost as O, CheckoutStage as On, filterAndFormatRefs as Ot, BundleVerifyCommand as P, versionCompare as Pt, physicalFilesPath as Q, BisectReplayCommand as Qt, parseBundleListLine as R, rstripRef as Rt, guardSubmoduleTransports as S, estimateBisectSteps as Sn, readShortlogInput as St, PlumbingCommand as T, skipAway as Tn, compareBytes$1 as Tt, SubmoduleGitDirError as U, quoteRefValue as Ut, updateBundleList as V, tagHeader as Vt, SubmoduleModel as W, ATOM_NAMES as Wt, parentIsDirectory as X, BisectLogCommand as Xt, openConfigFile as Y, BisectCommand as Yt, parseSubmoduleUpdateStrategy as Z, BisectNextCommand as Zt, SubmoduleFetchRepository as _, FIND_BISECTION_ALL as _n, formatSubject as _t, ReflogCommand as a, BISECT_USAGE as an, setInConfigFile as at, submoduleTouchesInRange as b, TREESAME as bn, parseShortlogGroup as bt, GuardedTransportCommand as c, isBisectSuccess as cn, upPathOf as ct, fetchOutputText as d, sqQuoteArgv as dn, validateSubmodulePath as dt, BisectRunCommand as en, relativeUrl as et, fetchSucceeded as f, strbufRtrim as fn, worktreeHostPath as ft, uriProtocolsOption as g, BisectNode as gn, commitSubject as gt, toTrackingRefUpdate as h, BisectGraph as hn, Shortlog as ht, RepackCommand as i, BisectTermsCommand as in, safeCreateLeadingDirectories as it, isBundle as j, pathCheckoutResult as jn, parseRefSorting as jt, fetchBundleList as k, CheckoutStatus as kn, filterRefs as kt, FetchCommand as l, sqDequoteToArgv as ln, urlIsLocalNotSsh as lt, toTagMode as m, BisectDie as mn, SHORTLOG_DEFAULT_WRAP as mt, MaintenanceRunCommand as n, BisectStartCommand as nn, resolveFilesLinks as nt, inLinkedWorktree as o, BisectCode as on, submodulePathConfigOf as ot, prefetchRefspecs as p, strbufTrim as pn, BundleCreateCommand as pt, joinFilesPath as q, MAX_REF_FILTER_PEEL_DEPTH as qt, maintenance_run_command_exports as r, BisectStateCommand as rn, resolveRelativeUrl as rt, objectsDirectoryDisplay as s, BisectEngine as sn, submoduleUpdateTypeName as st, MAINTENANCE_TASKS as t, BisectSkipCommand as tn, remoteFromUrl as tt, TagOption as u, sqQuote as un, validateSubmoduleGitDir as ut, findUnpushedSubmodules as v, FIND_BISECTION_FIRST_PARENT_ONLY as vn, inputLines as vt, clientSessionIdOf as w, managedSkipped as wn, splitIdent as wt, createSubmoduleAuthPolicy as x, UNINTERESTING as xn, parseShortlogWrap as xt, parseFetchRecurseSubmodules as y, PRN_MODULO as yn, outputEncoderFor as yt, printBundleList as z, shortenRefName as zt };
15828
+ export { printBundleList as $, estimateBisectSteps as $n, shortenRefName as $t, configuresCredentialHelper as A, BisectResetCommand as An, commitSubject as At, setAllCapabilities as B, sqDequoteToArgv as Bn, fillAheadBehind as Bt, strictUrlOrigin as C, writeRangeDiff as Cn, urlIsLocalNotSsh as Ct, TransportCommand as D, BisectLogCommand as Dn, BundleCreateCommand as Dt, PlumbingError as E, BisectCommand as En, worktreeHostPath as Et, credentialHelpersOptionsOf as F, BisectTermsCommand as Fn, parseShortlogWrap as Ft, isBundle as G, BisectDie as Gn, parseRefSorting as Gt, createBundleUriHost as H, sqQuoteArgv as Hn, filterAndFormatRefs as Ht, describeCredential as I, BISECT_USAGE as In, readShortlogInput as It, BundleVerifyCommand as J, FIND_BISECTION_ALL as Jn, versionCompare as Jt, BundleListHeadsCommand as K, BisectGraph as Kn, refKindOf as Kt, newCredential as L, BisectCode as Ln, shortlogIdent as Lt, credentialFromUrl as M, BisectSkipCommand as Mn, inputLines as Mt, credentialHelperOf as N, BisectStartCommand as Nn, outputEncoderFor as Nt, CredentialError as O, BisectNextCommand as On, SHORTLOG_DEFAULT_WRAP as Ot, credentialHelpersOf as P, BisectStateCommand as Pn, parseShortlogGroup as Pt, parseBundleListLine as Q, UNINTERESTING as Qn, rstripRef as Qt, nextState as R, BisectEngine as Rn, splitIdent as Rt, guardSubmoduleTransports as S, readRangeDiffPatches as Sn, upPathOf as St, PlumbingCommand as T, objectDiskInfoOf as Tn, validateSubmodulePath as Tt, fetchBundleList as U, strbufRtrim as Un, filterRefs as Ut, writeCredential as V, sqQuote as Vn, fillIsBase as Vt, fetchBundleUri as W, strbufTrim as Wn, isRootRef$1 as Wt, BundleList as X, PRN_MODULO as Xn, RefKind as Xt, BundleCommandBase as Y, FIND_BISECTION_FIRST_PARENT_ONLY as Yn, RefFormat as Yt, parseBundleListConfig as Z, TREESAME as Zn, lstripRef as Zt, SubmoduleFetchRepository as _, RangeDiffMemoryError as _n, resolveRelativeUrl as _t, ReflogCommand as a, atomSource as an, CheckoutStage as ar, defaultRemoteOf as at, submoduleTouchesInRange as b, humaniseBytes as bn, submodulePathConfigOf as bt, GuardedTransportCommand as c, RevListCommand as cn, pathCheckoutResult as cr, lstatKind as ct, fetchOutputText as d, rangeDiffMergesOptions as dn, parseSubmoduleUpdateStrategy as dt, signatureStart as en, findBisection as er, stripFileFromPath as et, fetchSucceeded as f, rangeDiffNotesOptions as fn, physicalFilesPath as ft, uriProtocolsOption as g, RangeDiffError as gn, resolveFilesLinks as gt, toTrackingRefUpdate as h, RANGE_DIFF_MAX_MEMORY_DEFAULT as hn, remoteFromUrl as ht, RepackCommand as i, ATOM_NAMES as in, CheckoutCommand as ir, SubmoduleModel as it, createConfigCredentialHelper as j, BisectRunCommand as jn, formatSubject as jt, CredentialHelpers as k, BisectReplayCommand as kn, Shortlog as kt, FetchCommand as l, RangeDiffBase as ln, checkoutPaths as lr, openConfigFile as lt, toTagMode as m, RANGE_DIFF_CREATION_FACTOR_DEFAULT as mn, relativeUrl as mt, MaintenanceRunCommand as n, trimTrailingSpaces as nn, skipAway as nr, Gitmodules as nt, inLinkedWorktree as o, parseAtom as on, CheckoutStatus as or, isRelativeSubmoduleUrl as ot, prefetchRefspecs as p, CREATION_FACTOR_FOR_THE_SAME_SERIES as pn, relativeFilesPath as pt, BundleUnbundleCommand as q, BisectNode as qn, sortRefs as qt, maintenance_run_command_exports as r, quoteRefValue as rn, skipAwayIndex as rr, SubmoduleGitDirError as rt, objectsDirectoryDisplay as s, MAX_REF_FILTER_PEEL_DEPTH as sn, nonCommitSwitchError as sr, joinFilesPath as st, MAINTENANCE_TASKS as t, tagHeader as tn, managedSkipped as tr, updateBundleList as tt, TagOption as u, RangeDiffCommand as un, runPathCheckout as ur, parentIsDirectory as ut, findUnpushedSubmodules as v, findExactMatches as vn, safeCreateLeadingDirectories as vt, clientSessionIdOf as w, computeAssignment as wn, validateSubmoduleGitDir as wt, createSubmoduleAuthPolicy as x, parseRangeDiffMaxMemory as xn, submoduleUpdateTypeName as xt, parseFetchRecurseSubmodules as y, getCorrespondences as yn, setInConfigFile as yt, readCredential as z, isBisectSuccess as zn, compareBytes$1 as zt };