@statewalker/vcs-commands 0.13.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 (304) 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/archive-command.d.ts +6 -2
  5. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  6. package/dist/commands/archive/remote-archive-command.d.ts +27 -2
  7. package/dist/commands/archive/remote-archive-command.d.ts.map +1 -1
  8. package/dist/commands/archive/upload-archive-writer.d.ts +11 -5
  9. package/dist/commands/archive/upload-archive-writer.d.ts.map +1 -1
  10. package/dist/commands/branch-command.d.ts +14 -2
  11. package/dist/commands/branch-command.d.ts.map +1 -1
  12. package/dist/commands/bundle/bundle-format.d.ts +6 -1
  13. package/dist/commands/bundle/bundle-format.d.ts.map +1 -1
  14. package/dist/commands/bundle/bundle-uri-host.d.ts +12 -1
  15. package/dist/commands/bundle/bundle-uri-host.d.ts.map +1 -1
  16. package/dist/commands/bundle/bundle-uri.d.ts +7 -1
  17. package/dist/commands/bundle/bundle-uri.d.ts.map +1 -1
  18. package/dist/commands/bundle/bundle-verify.d.ts +4 -1
  19. package/dist/commands/bundle/bundle-verify.d.ts.map +1 -1
  20. package/dist/commands/cat-file/batch-format.d.ts +8 -12
  21. package/dist/commands/cat-file/batch-format.d.ts.map +1 -1
  22. package/dist/commands/cat-file/cat-file-command.d.ts +39 -5
  23. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  24. package/dist/commands/check-ignore-command.d.ts.map +1 -1
  25. package/dist/commands/checkout-command.d.ts +4 -0
  26. package/dist/commands/checkout-command.d.ts.map +1 -1
  27. package/dist/commands/checkout-paths.d.ts +9 -0
  28. package/dist/commands/checkout-paths.d.ts.map +1 -1
  29. package/dist/commands/cherry-pick-command.d.ts +3 -0
  30. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  31. package/dist/commands/clean-interactive.d.ts +0 -9
  32. package/dist/commands/clean-interactive.d.ts.map +1 -1
  33. package/dist/commands/clone-command.d.ts +17 -0
  34. package/dist/commands/clone-command.d.ts.map +1 -1
  35. package/dist/commands/column/column-config.d.ts +23 -0
  36. package/dist/commands/column/column-config.d.ts.map +1 -0
  37. package/dist/commands/column/column-layout.d.ts +129 -0
  38. package/dist/commands/column/column-layout.d.ts.map +1 -0
  39. package/dist/commands/column/index.d.ts +3 -0
  40. package/dist/commands/column/index.d.ts.map +1 -0
  41. package/dist/commands/column-command.d.ts +59 -0
  42. package/dist/commands/column-command.d.ts.map +1 -0
  43. package/dist/commands/comment-char-config.d.ts +15 -0
  44. package/dist/commands/comment-char-config.d.ts.map +1 -1
  45. package/dist/commands/commit-command.d.ts +30 -2
  46. package/dist/commands/commit-command.d.ts.map +1 -1
  47. package/dist/commands/config-command.d.ts +12 -0
  48. package/dist/commands/config-command.d.ts.map +1 -1
  49. package/dist/commands/credential-helper.d.ts +214 -0
  50. package/dist/commands/credential-helper.d.ts.map +1 -0
  51. package/dist/commands/default-branch.d.ts +33 -3
  52. package/dist/commands/default-branch.d.ts.map +1 -1
  53. package/dist/commands/diff-color-config.d.ts +4 -0
  54. package/dist/commands/diff-color-config.d.ts.map +1 -1
  55. package/dist/commands/diff-command.d.ts +12 -0
  56. package/dist/commands/diff-command.d.ts.map +1 -1
  57. package/dist/commands/fast-export/fast-export-command.d.ts +89 -2
  58. package/dist/commands/fast-export/fast-export-command.d.ts.map +1 -1
  59. package/dist/commands/fast-export/fast-import-command.d.ts +113 -8
  60. package/dist/commands/fast-export/fast-import-command.d.ts.map +1 -1
  61. package/dist/commands/fast-export/fast-stream-support.d.ts +0 -9
  62. package/dist/commands/fast-export/fast-stream-support.d.ts.map +1 -1
  63. package/dist/commands/fetch-command.d.ts +23 -1
  64. package/dist/commands/fetch-command.d.ts.map +1 -1
  65. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -1
  66. package/dist/commands/git-hooks.d.ts +31 -3
  67. package/dist/commands/git-hooks.d.ts.map +1 -1
  68. package/dist/commands/history-command.d.ts +173 -7
  69. package/dist/commands/history-command.d.ts.map +1 -1
  70. package/dist/commands/index-host.d.ts +19 -0
  71. package/dist/commands/index-host.d.ts.map +1 -1
  72. package/dist/commands/index-refresh.d.ts +36 -0
  73. package/dist/commands/index-refresh.d.ts.map +1 -0
  74. package/dist/commands/index.d.ts +9 -0
  75. package/dist/commands/index.d.ts.map +1 -1
  76. package/dist/commands/index.js +7 -6
  77. package/dist/commands/init-command.d.ts +20 -0
  78. package/dist/commands/init-command.d.ts.map +1 -1
  79. package/dist/commands/local-transport.d.ts +40 -2
  80. package/dist/commands/local-transport.d.ts.map +1 -1
  81. package/dist/commands/log-command.d.ts +7 -0
  82. package/dist/commands/log-command.d.ts.map +1 -1
  83. package/dist/commands/log-output.d.ts +11 -0
  84. package/dist/commands/log-output.d.ts.map +1 -1
  85. package/dist/commands/ls-tree-command.d.ts +10 -0
  86. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  87. package/dist/commands/maintenance-schedule-command.d.ts +122 -0
  88. package/dist/commands/maintenance-schedule-command.d.ts.map +1 -0
  89. package/dist/commands/merge-command.d.ts +13 -1
  90. package/dist/commands/merge-command.d.ts.map +1 -1
  91. package/dist/commands/merge-index-command.d.ts +42 -0
  92. package/dist/commands/merge-index-command.d.ts.map +1 -0
  93. package/dist/commands/merge-one-file.d.ts +129 -0
  94. package/dist/commands/merge-one-file.d.ts.map +1 -0
  95. package/dist/commands/merge-support.d.ts +40 -4
  96. package/dist/commands/merge-support.d.ts.map +1 -1
  97. package/dist/commands/object-disk-info.d.ts +35 -0
  98. package/dist/commands/object-disk-info.d.ts.map +1 -0
  99. package/dist/commands/octopus-merge.d.ts +3 -3
  100. package/dist/commands/octopus-merge.d.ts.map +1 -1
  101. package/dist/commands/plumbing-input.d.ts.map +1 -1
  102. package/dist/commands/promisor-remote-reply.d.ts +31 -4
  103. package/dist/commands/promisor-remote-reply.d.ts.map +1 -1
  104. package/dist/commands/promisor-remote.d.ts +8 -1
  105. package/dist/commands/promisor-remote.d.ts.map +1 -1
  106. package/dist/commands/pull-command.d.ts +55 -7
  107. package/dist/commands/pull-command.d.ts.map +1 -1
  108. package/dist/commands/push-command.d.ts +18 -1
  109. package/dist/commands/push-command.d.ts.map +1 -1
  110. package/dist/commands/range-diff/range-diff-command.d.ts +37 -1
  111. package/dist/commands/range-diff/range-diff-command.d.ts.map +1 -1
  112. package/dist/commands/rebase-command.d.ts +13 -1
  113. package/dist/commands/rebase-command.d.ts.map +1 -1
  114. package/dist/commands/ref-filter/for-each-ref-command.d.ts +3 -2
  115. package/dist/commands/ref-filter/for-each-ref-command.d.ts.map +1 -1
  116. package/dist/commands/ref-filter/index.d.ts +1 -0
  117. package/dist/commands/ref-filter/index.d.ts.map +1 -1
  118. package/dist/commands/ref-filter/peel-limit.d.ts +8 -0
  119. package/dist/commands/ref-filter/peel-limit.d.ts.map +1 -0
  120. package/dist/commands/ref-filter/ref-filter.d.ts.map +1 -1
  121. package/dist/commands/ref-filter/ref-format.d.ts +26 -1
  122. package/dist/commands/ref-filter/ref-format.d.ts.map +1 -1
  123. package/dist/commands/ref-filter/ref-listing-command.d.ts +9 -0
  124. package/dist/commands/ref-filter/ref-listing-command.d.ts.map +1 -1
  125. package/dist/commands/remote-transport.d.ts +27 -0
  126. package/dist/commands/remote-transport.d.ts.map +1 -1
  127. package/dist/commands/repack-command.d.ts +18 -2
  128. package/dist/commands/repack-command.d.ts.map +1 -1
  129. package/dist/commands/repo-command.d.ts +2 -7
  130. package/dist/commands/repo-command.d.ts.map +1 -1
  131. package/dist/commands/reset-command.d.ts +4 -1
  132. package/dist/commands/reset-command.d.ts.map +1 -1
  133. package/dist/commands/restore-command.d.ts.map +1 -1
  134. package/dist/commands/rev-list-command.d.ts +65 -0
  135. package/dist/commands/rev-list-command.d.ts.map +1 -1
  136. package/dist/commands/revert-command.d.ts +3 -0
  137. package/dist/commands/revert-command.d.ts.map +1 -1
  138. package/dist/commands/revision-filenames.d.ts.map +1 -1
  139. package/dist/commands/revision-range.d.ts +17 -0
  140. package/dist/commands/revision-range.d.ts.map +1 -1
  141. package/dist/commands/revision-resolver.d.ts +12 -0
  142. package/dist/commands/revision-resolver.d.ts.map +1 -1
  143. package/dist/commands/serve-repository.d.ts +21 -4
  144. package/dist/commands/serve-repository.d.ts.map +1 -1
  145. package/dist/commands/served-lazy-fetch.d.ts +61 -0
  146. package/dist/commands/served-lazy-fetch.d.ts.map +1 -0
  147. package/dist/commands/signing.d.ts +37 -4
  148. package/dist/commands/signing.d.ts.map +1 -1
  149. package/dist/commands/split-cmdline.d.ts +6 -0
  150. package/dist/commands/split-cmdline.d.ts.map +1 -0
  151. package/dist/commands/status-color-config.d.ts +33 -0
  152. package/dist/commands/status-color-config.d.ts.map +1 -0
  153. package/dist/commands/status-command.d.ts +15 -0
  154. package/dist/commands/status-command.d.ts.map +1 -1
  155. package/dist/commands/status-format.d.ts +46 -4
  156. package/dist/commands/status-format.d.ts.map +1 -1
  157. package/dist/commands/tag-command.d.ts +15 -1
  158. package/dist/commands/tag-command.d.ts.map +1 -1
  159. package/dist/commands/tree-restore.d.ts +14 -0
  160. package/dist/commands/tree-restore.d.ts.map +1 -1
  161. package/dist/commands/verify-command.d.ts +22 -2
  162. package/dist/commands/verify-command.d.ts.map +1 -1
  163. package/dist/commands/worktree-add-command.d.ts.map +1 -1
  164. package/dist/commands/worktree-overwrite-checks.d.ts +31 -6
  165. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  166. package/dist/{commands-CPceUCP2.js → commands-DT3VEv50.js} +15168 -16842
  167. package/dist/errors/commit-errors.d.ts +37 -1
  168. package/dist/errors/commit-errors.d.ts.map +1 -1
  169. package/dist/errors/git-api-error.d.ts +6 -0
  170. package/dist/errors/git-api-error.d.ts.map +1 -1
  171. package/dist/errors/index.js +44 -3
  172. package/dist/{fsck-tbrPZX2q.js → fsck-BZ508Elg.js} +2 -2
  173. package/dist/git-command.d.ts +33 -1
  174. package/dist/git-command.d.ts.map +1 -1
  175. package/dist/git.d.ts +104 -1
  176. package/dist/git.d.ts.map +1 -1
  177. package/dist/index.js +8 -7
  178. package/dist/{remote-transport-C0OSJtor.js → local-transport-D98U6p4d.js} +228 -692
  179. package/dist/{maintenance-run-command-UiSIaeP8.js → maintenance-run-command-DZFnbnbo.js} +2366 -108
  180. package/dist/remote-config/remote-config-store.d.ts +6 -0
  181. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  182. package/dist/remote-transport-zvSqwpOB.js +4865 -0
  183. package/dist/results/cherry-pick-result.d.ts +4 -3
  184. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  185. package/dist/results/diff-output.d.ts +7 -0
  186. package/dist/results/diff-output.d.ts.map +1 -1
  187. package/dist/results/diff-words.d.ts +14 -3
  188. package/dist/results/diff-words.d.ts.map +1 -1
  189. package/dist/results/index.js +1 -1
  190. package/dist/results/line-prefix-sink.d.ts +50 -0
  191. package/dist/results/line-prefix-sink.d.ts.map +1 -0
  192. package/dist/results/merge-result.d.ts +4 -3
  193. package/dist/results/merge-result.d.ts.map +1 -1
  194. package/dist/results/rebase-result.d.ts +5 -0
  195. package/dist/results/rebase-result.d.ts.map +1 -1
  196. package/dist/results/revert-result.d.ts +4 -3
  197. package/dist/results/revert-result.d.ts.map +1 -1
  198. package/dist/{results-CkS1p1CH.js → results-rF81cQse.js} +1788 -247
  199. package/dist/transport-command.d.ts +13 -0
  200. package/dist/transport-command.d.ts.map +1 -1
  201. package/package.json +21 -13
  202. package/src/commands/add-command.ts +15 -2
  203. package/src/commands/add-patch/patch-backend.ts +6 -44
  204. package/src/commands/archive/archive-command.ts +7 -3
  205. package/src/commands/archive/remote-archive-command.ts +45 -4
  206. package/src/commands/archive/upload-archive-writer.ts +34 -22
  207. package/src/commands/branch-command.ts +57 -4
  208. package/src/commands/bundle/bundle-format.ts +10 -2
  209. package/src/commands/bundle/bundle-uri-host.ts +71 -11
  210. package/src/commands/bundle/bundle-uri.ts +11 -4
  211. package/src/commands/bundle/bundle-verify.ts +4 -1
  212. package/src/commands/cat-file/batch-format.ts +17 -18
  213. package/src/commands/cat-file/cat-file-command.ts +182 -48
  214. package/src/commands/check-ignore-command.ts +110 -21
  215. package/src/commands/checkout-command.ts +149 -21
  216. package/src/commands/checkout-index-command.ts +2 -1
  217. package/src/commands/checkout-paths.ts +13 -0
  218. package/src/commands/cherry-pick-command.ts +9 -0
  219. package/src/commands/clean-interactive.ts +20 -74
  220. package/src/commands/clone-command.ts +102 -11
  221. package/src/commands/column/column-config.ts +63 -0
  222. package/src/commands/column/column-layout.ts +396 -0
  223. package/src/commands/column/index.ts +2 -0
  224. package/src/commands/column-command.ts +171 -0
  225. package/src/commands/comment-char-config.ts +42 -0
  226. package/src/commands/commit-command.ts +93 -18
  227. package/src/commands/config-command.ts +28 -0
  228. package/src/commands/credential-helper.ts +807 -0
  229. package/src/commands/default-branch.ts +57 -5
  230. package/src/commands/diff-color-config.ts +23 -10
  231. package/src/commands/diff-command.ts +25 -2
  232. package/src/commands/fast-export/fast-export-command.ts +661 -35
  233. package/src/commands/fast-export/fast-import-command.ts +694 -94
  234. package/src/commands/fast-export/fast-stream-support.ts +18 -1
  235. package/src/commands/fetch-command.ts +116 -16
  236. package/src/commands/fsck/fsck-object-checks.ts +3 -1
  237. package/src/commands/git-hooks.ts +96 -5
  238. package/src/commands/history-command.ts +952 -20
  239. package/src/commands/index-host.ts +51 -0
  240. package/src/commands/index-refresh.ts +121 -0
  241. package/src/commands/index.ts +9 -0
  242. package/src/commands/init-command.ts +57 -4
  243. package/src/commands/legacy-remotes.ts +4 -20
  244. package/src/commands/local-transport.ts +183 -18
  245. package/src/commands/log-command.ts +39 -1
  246. package/src/commands/log-output.ts +31 -4
  247. package/src/commands/ls-tree-command.ts +20 -12
  248. package/src/commands/maintenance-schedule-command.ts +418 -0
  249. package/src/commands/merge-command.ts +42 -8
  250. package/src/commands/merge-index-command.ts +202 -0
  251. package/src/commands/merge-one-file.ts +451 -0
  252. package/src/commands/merge-support.ts +169 -15
  253. package/src/commands/object-disk-info.ts +169 -0
  254. package/src/commands/octopus-merge.ts +37 -128
  255. package/src/commands/plumbing-input.ts +3 -1
  256. package/src/commands/promisor-remote-reply.ts +338 -56
  257. package/src/commands/promisor-remote.ts +39 -6
  258. package/src/commands/pull-command.ts +173 -27
  259. package/src/commands/push-command.ts +55 -6
  260. package/src/commands/range-diff/range-diff-command.ts +86 -3
  261. package/src/commands/read-tree-command.ts +2 -2
  262. package/src/commands/rebase-command.ts +46 -1
  263. package/src/commands/ref-filter/for-each-ref-command.ts +4 -3
  264. package/src/commands/ref-filter/index.ts +1 -0
  265. package/src/commands/ref-filter/peel-limit.ts +7 -0
  266. package/src/commands/ref-filter/ref-filter.ts +68 -7
  267. package/src/commands/ref-filter/ref-format.ts +85 -11
  268. package/src/commands/ref-filter/ref-listing-command.ts +30 -0
  269. package/src/commands/remote-command.ts +2 -2
  270. package/src/commands/remote-transport.ts +66 -3
  271. package/src/commands/repack-command.ts +75 -9
  272. package/src/commands/repo-command.ts +6 -70
  273. package/src/commands/reset-command.ts +11 -1
  274. package/src/commands/restore-command.ts +1 -0
  275. package/src/commands/rev-list-command.ts +205 -3
  276. package/src/commands/revert-command.ts +9 -0
  277. package/src/commands/revision-filenames.ts +32 -4
  278. package/src/commands/revision-range.ts +2 -2
  279. package/src/commands/revision-resolver.ts +21 -1
  280. package/src/commands/serve-repository.ts +42 -11
  281. package/src/commands/served-lazy-fetch.ts +164 -0
  282. package/src/commands/signing.ts +103 -12
  283. package/src/commands/split-cmdline.ts +32 -0
  284. package/src/commands/status-color-config.ts +92 -0
  285. package/src/commands/status-command.ts +50 -2
  286. package/src/commands/status-format.ts +198 -50
  287. package/src/commands/tag-command.ts +57 -2
  288. package/src/commands/tree-restore.ts +17 -0
  289. package/src/commands/verify-command.ts +84 -12
  290. package/src/commands/worktree-add-command.ts +2 -0
  291. package/src/commands/worktree-overwrite-checks.ts +75 -14
  292. package/src/errors/commit-errors.ts +52 -2
  293. package/src/errors/git-api-error.ts +7 -0
  294. package/src/git-command.ts +105 -4
  295. package/src/git.ts +153 -0
  296. package/src/remote-config/remote-config-store.ts +16 -0
  297. package/src/results/cherry-pick-result.ts +4 -3
  298. package/src/results/diff-output.ts +8 -0
  299. package/src/results/diff-words.ts +160 -32
  300. package/src/results/line-prefix-sink.ts +102 -0
  301. package/src/results/merge-result.ts +4 -3
  302. package/src/results/rebase-result.ts +5 -0
  303. package/src/results/revert-result.ts +4 -3
  304. package/src/transport-command.ts +79 -3
@@ -0,0 +1,4865 @@
1
+ import { I as __exportAll } from "./fsck-BZ508Elg.js";
2
+ import { GitApiError, InvalidConfigError, InvalidPathError, RevisionError, TransportError as TransportError$1 } from "./errors/index.js";
3
+ import { At as textconvRunnerOf, Dr as GrepPatternError, Fi as parsePathspec, Gt as parseGitColor, Hu as bareAttributesResolver, Jo as verifyFilename, Jt as formatCommitPretty, Ni as matchPathspec, Wn as repositoryPlaceOf, Wu as configValue, Yn as worktreeAdminWorkingCopy, Yo as verifyNonFilename, ca as latin1ToBytes, da as pathToLatin1, ed as hostEnvironmentOf, eu as treePathRefusal, fd as RemoteConfigStore, ku as createIdAbbreviator, la as latin1ToPath, mo as GitCommand, nu as worktreePathRules, sa as cUnquote, sc as quotePath, tu as withTreePathRefusal, z as TextconvCaches } from "./results-rF81cQse.js";
4
+ import { d as withLocalReceivePack, f as withLocalUploadPack, i as openLocalRemote, l as servedMaxTreeDepth, m as uploadPackHistory, n as httpBackendEnv, o as receiveFsckSettingsOf, p as withReceiveTransactionHook, s as receivePackSettingsOf, t as createDuplexPair, u as servedUseBitmaps } from "./local-transport-D98U6p4d.js";
5
+ import { FileMode, historyWithoutLazyFetch } from "@statewalker/vcs-core";
6
+ import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
7
+ import { FilterDriverError, FilterDriverRunError, attributesIndexOfTree, collectChunks, convAttrsOf, crlfToWorktree, identToWorktree, readConversionSettings, reencode, smudgeContent, sparseFilterMatcher } from "@statewalker/vcs-working-tree";
8
+ import { PosixRegexError, approxidateCareful, compilePosixRegex, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1, parseGitUlong } from "@statewalker/vcs-utils";
9
+ import { SHA1_OBJECT_FORMAT as SHA1_OBJECT_FORMAT$1, objectFormatByName as objectFormatByName$1 } from "@statewalker/vcs-utils/hash";
10
+ import { readProtectedConfig } from "@statewalker/vcs-store-files";
11
+ import { connectivityErrors, createByteQueue, createRepositoryFacade, createTransportRefStore, isGitUrl, openDuplexConnection, openReceivePack, openUploadPack, packObjectsHookArgs, parseGitUrl, protocolVersionFor, serveOverDuplex, servedGitFilesOf } from "@statewalker/vcs-transport";
12
+ import { createDeflater, deflateSync } from "@statewalker/vcs-utils/compression";
13
+ import { CRC32, crc32 } from "@statewalker/vcs-utils/hash/crc32";
14
+ import { userdiffFindFunction as userdiffFindFunction$1 } from "@statewalker/vcs-utils/diff";
15
+ //#region src/commands/git-describe.ts
16
+ /** A failure where git describe dies: its message (without `fatal: `). */
17
+ var DescribeDeath = class extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "DescribeDeath";
21
+ }
22
+ };
23
+ /** A simple wildmatch: `*` (any run), `?` (one character), `[...]` classes. */
24
+ function globMatch(pattern, text) {
25
+ let re = "";
26
+ for (let i = 0; i < pattern.length; i++) {
27
+ const c = pattern[i];
28
+ if (c === "*") re += ".*";
29
+ else if (c === "?") re += ".";
30
+ else if (c === "[") {
31
+ const end = pattern.indexOf("]", i + 2);
32
+ if (end < 0) re += "\\[";
33
+ else {
34
+ let cls = pattern.slice(i + 1, end);
35
+ if (cls.startsWith("!")) cls = `^${cls.slice(1)}`;
36
+ re += `[${cls.replace(/\\/g, "\\\\")}]`;
37
+ i = end;
38
+ }
39
+ } else re += c.replace(/[.+^${}()|\\/]/g, "\\$&");
40
+ }
41
+ return new RegExp(`^${re}$`, "s").test(text);
42
+ }
43
+ /** describe.c's MAX_TAGS (FLAG_BITS - 1) */
44
+ const DESCRIBE_MAX_TAGS = 28;
45
+ const DEFAULT_CANDIDATES = 10;
46
+ const PRIO_NAMES = [
47
+ "head",
48
+ "lightweight",
49
+ "annotated"
50
+ ];
51
+ const LABEL_WIDTH = Math.max(...PRIO_NAMES.map((n) => n.length));
52
+ /** prio_queue by commit date, newest first, ties in insertion order. */
53
+ var DateQueue = class {
54
+ items = [];
55
+ counter = 0;
56
+ get size() {
57
+ return this.items.length;
58
+ }
59
+ put(node) {
60
+ const entry = {
61
+ node,
62
+ ctr: this.counter++
63
+ };
64
+ let lo = 0;
65
+ let hi = this.items.length;
66
+ while (lo < hi) {
67
+ const mid = lo + hi >> 1;
68
+ const m = this.items[mid];
69
+ if (m.node.date > node.date || m.node.date === node.date && m.ctr < entry.ctr) lo = mid + 1;
70
+ else hi = mid;
71
+ }
72
+ this.items.splice(lo, 0, entry);
73
+ }
74
+ get() {
75
+ return this.items.shift()?.node;
76
+ }
77
+ nodes() {
78
+ return this.items.map((e) => e.node);
79
+ }
80
+ };
81
+ /**
82
+ * builtin/describe.c over one repository: the names read once ({@link load}), then any
83
+ * number of commits or blobs described, with git's stderr lines (warnings, `--debug`) in
84
+ * {@link stderr}.
85
+ */
86
+ var Describer = class {
87
+ source;
88
+ options;
89
+ /** The lines git prints on stderr, in order */
90
+ stderr = [];
91
+ /** The name and depth the last {@link describeCommit} found (none: `--always`'s id) */
92
+ lastMatch;
93
+ names = /* @__PURE__ */ new Map();
94
+ match;
95
+ maxCandidates;
96
+ constructor(source, options = {}) {
97
+ this.source = source;
98
+ this.options = options;
99
+ this.match = source.wildmatch ?? globMatch;
100
+ const candidates = options.candidates ?? DEFAULT_CANDIDATES;
101
+ this.maxCandidates = Math.min(Math.max(candidates, 0), 28);
102
+ }
103
+ /** How many names were found (git dies without any unless `--always`). */
104
+ get nameCount() {
105
+ return this.names.size;
106
+ }
107
+ /** describe.c's get_name over refs/tags/ (refs/ with `--all`). */
108
+ async load() {
109
+ const { source, options } = this;
110
+ const refs = [];
111
+ const prefix = options.all ? "refs/" : "refs/tags/";
112
+ for await (const ref of source.refs.list(prefix)) if (ref.name.startsWith(prefix)) refs.push(ref);
113
+ refs.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
114
+ const names = /* @__PURE__ */ new Map();
115
+ const filtered = !!(options.exclude?.length || options.match?.length);
116
+ for (const ref of refs) {
117
+ const isTag = ref.name.startsWith("refs/tags/");
118
+ let matched = isTag ? ref.name.slice(10) : void 0;
119
+ if (!isTag && filtered) {
120
+ for (const kind of ["refs/heads/", "refs/remotes/"]) if (ref.name.startsWith(kind)) matched = ref.name.slice(kind.length);
121
+ if (matched === void 0) continue;
122
+ }
123
+ if (matched !== void 0) {
124
+ const text = matched;
125
+ if ((options.exclude ?? []).some((p) => this.match(p, text))) continue;
126
+ if (options.match?.length && !options.match.some((p) => this.match(p, text))) continue;
127
+ }
128
+ const path = options.all ? ref.name.slice(5) : matched;
129
+ const oid = ref.objectId && ref.target === void 0 ? ref.objectId : (await source.refs.resolve(ref.name).catch(() => void 0))?.objectId;
130
+ if (!oid) continue;
131
+ let peeled = oid;
132
+ let first;
133
+ for (let depth = 0; depth < 32 && source.tags && await isTagObject(source, peeled); depth++) {
134
+ const tag = await source.tags.load(peeled).catch(() => void 0);
135
+ if (!tag) break;
136
+ first ??= {
137
+ name: tag.tag,
138
+ date: tag.tagger?.timestamp ?? 0,
139
+ object: tag.object
140
+ };
141
+ peeled = tag.object;
142
+ }
143
+ const prio = peeled !== oid ? 2 : isTag ? 1 : 0;
144
+ const known = names.get(peeled);
145
+ let replace = !known || known.prio < prio;
146
+ if (known && known.prio === 2 && prio === 2) replace = (known.tag?.date ?? 0) < (first?.date ?? 0);
147
+ if (replace) names.set(peeled, {
148
+ peeled,
149
+ prio,
150
+ oid,
151
+ path,
152
+ ...prio === 2 && first ? { tag: first } : {}
153
+ });
154
+ }
155
+ this.names = names;
156
+ }
157
+ /** append_name: an annotated tag by its own name (another ref name is "misnamed"). */
158
+ appendName(n) {
159
+ const all = !!this.options.all;
160
+ if (n.tag && !n.nameChecked) {
161
+ if (n.tag.name !== (all ? n.path.slice(5) : n.path)) {
162
+ this.stderr.push(`warning: tag '${n.path}' is externally known as '${n.tag.name}'`);
163
+ n.misnamed = true;
164
+ }
165
+ n.nameChecked = true;
166
+ }
167
+ if (n.tag) return `${all ? "tags/" : ""}${n.tag.name}`;
168
+ return n.path;
169
+ }
170
+ async suffix(depth, oid) {
171
+ return `-${depth}-g${await this.source.abbreviate(oid, this.options.abbrev)}`;
172
+ }
173
+ /**
174
+ * describe_commit of `commit` (`named`: the object the revision named, which 2.43
175
+ * suffixes a lightweight exact match with: an annotated tag's own id).
176
+ *
177
+ * @throws DescribeDeath where git dies
178
+ */
179
+ async describeCommit(commit, named = commit) {
180
+ const { options, source } = this;
181
+ const legacy = options.compatibility === "2.43";
182
+ const all = !!options.all;
183
+ const tags = !!options.tags || all;
184
+ const self = legacy ? named : commit;
185
+ this.lastMatch = void 0;
186
+ const exact = this.names.get(commit);
187
+ if (exact && (tags || exact.prio === 2)) {
188
+ const text = this.appendName(exact);
189
+ this.lastMatch = {
190
+ tag: text,
191
+ depth: 0
192
+ };
193
+ if (exact.misnamed || options.long) return text + await this.suffix(0, exact.tag ? exact.tag.object : self);
194
+ return text;
195
+ }
196
+ if (!this.maxCandidates) throw new DescribeDeath(`no tag exactly matches '${commit}'`);
197
+ if (options.debug) this.stderr.push("No exact match on refs or tags, searching to describe");
198
+ const nodes = /* @__PURE__ */ new Map();
199
+ const node = async (oid) => {
200
+ let n = nodes.get(oid);
201
+ if (n === void 0) {
202
+ const c = await source.commits.load(oid).catch(() => void 0);
203
+ n = c ? {
204
+ id: oid,
205
+ date: c.committer.timestamp,
206
+ flags: 0,
207
+ seen: false,
208
+ parents: c.parents,
209
+ ...c.tree ? { tree: c.tree } : {}
210
+ } : null;
211
+ nodes.set(oid, n);
212
+ }
213
+ return n ?? void 0;
214
+ };
215
+ const queue = new DateQueue();
216
+ const start = await node(commit);
217
+ if (!start) throw new DescribeDeath(`${commit} is neither a commit nor blob`);
218
+ start.seen = true;
219
+ queue.put(start);
220
+ const matches = [];
221
+ let annotated = 0;
222
+ let unannotated = 0;
223
+ let seenCommits = 0;
224
+ let gaveUpOn;
225
+ for (let c = queue.get(); c; c = queue.get()) {
226
+ seenCommits++;
227
+ if (!legacy && (matches.length === this.maxCandidates || matches.length === this.names.size)) {
228
+ gaveUpOn = c;
229
+ break;
230
+ }
231
+ const n = this.names.get(c.id);
232
+ if (n) {
233
+ if (!tags && n.prio < 2) unannotated++;
234
+ else if (matches.length < this.maxCandidates) {
235
+ const order = matches.length + 1;
236
+ const t = {
237
+ name: n,
238
+ depth: seenCommits - 1,
239
+ flagWithin: 2 ** order,
240
+ foundOrder: order
241
+ };
242
+ matches.push(t);
243
+ c.flags |= t.flagWithin;
244
+ if (n.prio === 2) annotated++;
245
+ } else {
246
+ gaveUpOn = c;
247
+ break;
248
+ }
249
+ }
250
+ for (const t of matches) if (!(c.flags & t.flagWithin)) t.depth++;
251
+ if (annotated && queue.size === 0) {
252
+ let bestDepth = Number.MAX_SAFE_INTEGER;
253
+ let bestWithin = 0;
254
+ for (const t of matches) if (t.depth < bestDepth) {
255
+ bestDepth = t.depth;
256
+ bestWithin = t.flagWithin;
257
+ } else if (t.depth === bestDepth) bestWithin |= t.flagWithin;
258
+ if ((c.flags & bestWithin) === bestWithin) {
259
+ if (options.debug) this.stderr.push(`finished search at ${c.id}`);
260
+ break;
261
+ }
262
+ }
263
+ for (const pid of c.parents) {
264
+ const p = await node(pid);
265
+ if (p) {
266
+ if (!p.seen) {
267
+ p.seen = true;
268
+ queue.put(p);
269
+ }
270
+ p.flags |= c.flags;
271
+ }
272
+ if (options.firstParent) break;
273
+ }
274
+ }
275
+ if (matches.length === 0) {
276
+ if (options.always) return source.abbreviate(commit, options.abbrev);
277
+ if (unannotated) throw new DescribeDeath(`No annotated tags can describe '${commit}'.\nHowever, there were unannotated tags: try --tags.`);
278
+ throw new DescribeDeath(`No tags can describe '${commit}'.\nTry --always, or create some tags.`);
279
+ }
280
+ matches.sort((a, b) => a.depth - b.depth || a.foundOrder - b.foundOrder);
281
+ const best = matches[0];
282
+ if (gaveUpOn) {
283
+ queue.put(gaveUpOn);
284
+ seenCommits--;
285
+ }
286
+ seenCommits += await this.finishDepth(queue, best, node);
287
+ if (options.debug) {
288
+ for (const t of matches) {
289
+ const label = PRIO_NAMES[t.name.prio];
290
+ this.stderr.push(` ${label.padEnd(LABEL_WIDTH)} ${String(t.depth).padStart(8)} ${t.name.path}`);
291
+ }
292
+ this.stderr.push(`traversed ${seenCommits} commits`);
293
+ if (gaveUpOn) {
294
+ if (legacy) this.stderr.push(`more than ${this.maxCandidates} tags found; listed ${this.maxCandidates} most recent`, `gave up search at ${gaveUpOn.id}`);
295
+ else this.stderr.push(`found ${this.maxCandidates} tags; gave up search at ${gaveUpOn.id}`);
296
+ }
297
+ }
298
+ const text = this.appendName(best.name);
299
+ this.lastMatch = {
300
+ tag: text,
301
+ depth: best.depth
302
+ };
303
+ if (best.name.misnamed || options.abbrev !== 0) return text + await this.suffix(best.depth, commit);
304
+ return text;
305
+ }
306
+ /** finish_depth_computation: the commits the best candidate does not reach. */
307
+ async finishDepth(queue, best, node) {
308
+ let seenCommits = 0;
309
+ const unflagged = /* @__PURE__ */ new Set();
310
+ for (const n of queue.nodes()) if (!(n.flags & best.flagWithin)) unflagged.add(n.id);
311
+ for (let c = queue.get(); c; c = queue.get()) {
312
+ seenCommits++;
313
+ if (c.flags & best.flagWithin) {
314
+ if (unflagged.size === 0) break;
315
+ } else {
316
+ unflagged.delete(c.id);
317
+ best.depth++;
318
+ }
319
+ for (const pid of c.parents) {
320
+ const p = await node(pid);
321
+ if (!p) continue;
322
+ const seen = p.seen;
323
+ if (!seen) {
324
+ p.seen = true;
325
+ queue.put(p);
326
+ }
327
+ const before = p.flags & best.flagWithin;
328
+ p.flags |= c.flags;
329
+ const after = p.flags & best.flagWithin;
330
+ if (!seen && !after) unflagged.add(p.id);
331
+ if (seen && !before && after) unflagged.delete(p.id);
332
+ }
333
+ }
334
+ return seenCommits;
335
+ }
336
+ /**
337
+ * describe_blob: the first commit (oldest first, in `rev-list --objects --reverse HEAD`'s
338
+ * order) whose tree holds the blob, described, and the blob's path in it.
339
+ *
340
+ * @throws DescribeDeath when HEAD does not reach it (2.43: an empty description)
341
+ */
342
+ async describeBlob(blob, head) {
343
+ const legacy = this.options.compatibility === "2.43";
344
+ if (head === void 0) throw new DescribeDeath(`cannot search for blob '${blob}' on an unborn branch`);
345
+ const { source } = this;
346
+ const order = [];
347
+ const nodes = /* @__PURE__ */ new Map();
348
+ const queue = new DateQueue();
349
+ const load = async (oid) => {
350
+ const c = await source.commits.load(oid).catch(() => void 0);
351
+ if (!c) return void 0;
352
+ const n = {
353
+ id: oid,
354
+ date: c.committer.timestamp,
355
+ flags: 0,
356
+ seen: true,
357
+ parents: c.parents,
358
+ ...c.tree ? { tree: c.tree } : {}
359
+ };
360
+ nodes.set(oid, n);
361
+ return n;
362
+ };
363
+ const first = await load(head);
364
+ if (first) queue.put(first);
365
+ for (let c = queue.get(); c; c = queue.get()) {
366
+ order.push(c);
367
+ for (const pid of c.parents) {
368
+ if (nodes.has(pid)) continue;
369
+ const p = await load(pid);
370
+ if (p) queue.put(p);
371
+ }
372
+ }
373
+ order.reverse();
374
+ const seenTrees = /* @__PURE__ */ new Set();
375
+ const find = async (tree, base) => {
376
+ if (seenTrees.has(tree)) return void 0;
377
+ seenTrees.add(tree);
378
+ const entries = await source.trees?.load(tree).catch(() => void 0);
379
+ if (!entries) return void 0;
380
+ for await (const e of entries) {
381
+ const path = base + e.name;
382
+ if ((e.mode & 61440) === 16384) {
383
+ const found = await find(e.id, `${path}/`);
384
+ if (found !== void 0) return found;
385
+ } else if ((e.mode & 61440) === 57344) {} else if (e.id === blob) return path;
386
+ }
387
+ };
388
+ for (const c of order) {
389
+ if (!c.tree) continue;
390
+ const path = await find(c.tree, "");
391
+ if (path !== void 0) return `${await this.describeCommit(c.id)}:${path}`;
392
+ }
393
+ if (legacy) return "";
394
+ throw new DescribeDeath(`blob '${blob}' not reachable from HEAD`);
395
+ }
396
+ };
397
+ async function isTagObject(source, id) {
398
+ return await source.tags?.has(id).catch(() => false) ?? false;
399
+ }
400
+ /**
401
+ * A `git describe <commit>` of the source's refs: the description, or an empty string where
402
+ * git describe fails (no tag can describe the commit), as `%(describe)` shows it.
403
+ */
404
+ function createDescriber(source) {
405
+ return async (id, options = {}) => {
406
+ const describer = new Describer(source, options);
407
+ await describer.load();
408
+ if (describer.nameCount === 0 && !options.always) return "";
409
+ return describer.describeCommit(id).catch((e) => {
410
+ if (e instanceof DescribeDeath) return "";
411
+ throw e;
412
+ });
413
+ };
414
+ }
415
+ //#endregion
416
+ //#region src/commands/archive/archive-entry.ts
417
+ /** The size of the chunks a writer sends to its output. */
418
+ const OUTPUT_CHUNK = 65536;
419
+ /**
420
+ * The bytes a writer has written: kept whole, or sent to an {@link ArchiveOutput} in chunks
421
+ * of about {@link OUTPUT_CHUNK}.
422
+ */
423
+ var ArchiveSink = class {
424
+ output;
425
+ buffer;
426
+ /** The bytes sent to the output so far */
427
+ sent = 0;
428
+ constructor(output, capacity = 16384) {
429
+ this.output = output;
430
+ this.buffer = new ByteBuffer(output ? OUTPUT_CHUNK * 2 : capacity);
431
+ }
432
+ /** The archive's length so far (sent and held). */
433
+ get position() {
434
+ return this.sent + this.buffer.length;
435
+ }
436
+ /** Sends what is held once it reaches a chunk (`force`: whatever is held). */
437
+ async flush(force = false) {
438
+ if (!this.output || this.buffer.length === 0) return;
439
+ if (!force && this.buffer.length < 65536) return;
440
+ const chunk = this.buffer.bytes().slice();
441
+ this.sent += chunk.length;
442
+ this.buffer.clear();
443
+ await this.output(chunk);
444
+ }
445
+ /** Writes a large piece (a streamed blob's chunk), sent as it is when there is an output. */
446
+ async write(bytes) {
447
+ if (!this.output) {
448
+ this.buffer.push(bytes);
449
+ return;
450
+ }
451
+ if (this.buffer.length + bytes.length < 65536) {
452
+ this.buffer.push(bytes);
453
+ return;
454
+ }
455
+ await this.flush(true);
456
+ this.sent += bytes.length;
457
+ await this.output(bytes.slice());
458
+ }
459
+ /** The bytes held whole (no output), or empty once everything was sent. */
460
+ async finish() {
461
+ if (!this.output) return this.buffer.bytes();
462
+ await this.flush(true);
463
+ return /* @__PURE__ */ new Uint8Array(0);
464
+ }
465
+ };
466
+ /** A growing byte buffer. */
467
+ var ByteBuffer = class {
468
+ buf;
469
+ length = 0;
470
+ constructor(capacity = 16384) {
471
+ this.buf = new Uint8Array(capacity);
472
+ }
473
+ reserve(n) {
474
+ if (this.length + n <= this.buf.length) return;
475
+ let size = this.buf.length * 2;
476
+ while (size < this.length + n) size *= 2;
477
+ const next = new Uint8Array(size);
478
+ next.set(this.buf.subarray(0, this.length));
479
+ this.buf = next;
480
+ }
481
+ push(bytes) {
482
+ this.reserve(bytes.length);
483
+ this.buf.set(bytes, this.length);
484
+ this.length += bytes.length;
485
+ }
486
+ zeros(n) {
487
+ this.reserve(n);
488
+ this.buf.fill(0, this.length, this.length + n);
489
+ this.length += n;
490
+ }
491
+ /** Forgets the bytes written (the capacity kept). */
492
+ clear() {
493
+ this.length = 0;
494
+ }
495
+ /** The bytes written (a view: copy before writing more). */
496
+ bytes() {
497
+ return this.buf.subarray(0, this.length);
498
+ }
499
+ };
500
+ const ascii = new TextEncoder();
501
+ /** ASCII text as bytes. */
502
+ function asciiBytes(text) {
503
+ return ascii.encode(text);
504
+ }
505
+ /** git's `S_ISDIR`, `S_ISGITLINK`, `S_ISLNK`, `S_ISREG` on a mode. */
506
+ const isDirMode = (mode) => (mode & 61440) === 16384;
507
+ const isGitlinkMode = (mode) => (mode & 61440) === 57344;
508
+ const isLinkMode = (mode) => (mode & 61440) === 40960;
509
+ const isRegMode = (mode) => (mode & 61440) === 32768;
510
+ //#endregion
511
+ //#region src/commands/archive/tar-archive.ts
512
+ /**
513
+ * git's tar writer (archive-tar.c): ustar headers with a pax global header carrying the
514
+ * commit id (`comment`), pax extended headers for paths and link targets that do not fit,
515
+ * records of 512 bytes written in blocks of 20 records, and the trailer that ends the
516
+ * archive with at least two zero records and fills its last block.
517
+ */
518
+ const RECORDSIZE = 512;
519
+ const BLOCKSIZE = RECORDSIZE * 20;
520
+ /** The largest size and mtime a ustar header holds (11 octal digits). */
521
+ const USTAR_MAX = 8589934591;
522
+ const TYPEFLAG_REG = 48;
523
+ const TYPEFLAG_LNK = 50;
524
+ const TYPEFLAG_DIR = 53;
525
+ const TYPEFLAG_GLOBAL_HEADER = 103;
526
+ const TYPEFLAG_EXT_HEADER = 120;
527
+ /** Field offsets and sizes of `struct ustar_header`. */
528
+ const NAME = 0;
529
+ const NAME_SIZE = 100;
530
+ const MODE = 100;
531
+ const UID = 108;
532
+ const GID = 116;
533
+ const SIZE = 124;
534
+ const MTIME = 136;
535
+ const CHKSUM = 148;
536
+ const TYPEFLAG = 156;
537
+ const LINKNAME = 157;
538
+ const LINKNAME_SIZE = 100;
539
+ const MAGIC = 257;
540
+ const VERSION = 263;
541
+ const UNAME = 265;
542
+ const GNAME = 297;
543
+ const DEVMAJOR = 329;
544
+ const DEVMINOR = 337;
545
+ const PREFIX = 345;
546
+ const PREFIX_SIZE = 155;
547
+ /** `xsnprintf(field, size, "%0<size-1>o", value)`: octal digits and a NUL. */
548
+ function octal(header, at, size, value) {
549
+ const digits = value.toString(8).padStart(size - 1, "0");
550
+ header.set(asciiBytes(digits.slice(-(size - 1))), at);
551
+ header[at + size - 1] = 0;
552
+ }
553
+ /** `strbuf_append_ext_header`: one pax record, `"%u %s=%s\n"`. */
554
+ function extRecord(out, keyword, value) {
555
+ let len = 2 + keyword.length + 1 + value.length + 1;
556
+ for (let tmp = 1; Math.floor(len / 10) >= tmp; tmp *= 10) len++;
557
+ out.push(asciiBytes(`${len} ${keyword}=`));
558
+ out.push(value);
559
+ out.push(asciiBytes("\n"));
560
+ }
561
+ /** `get_path_prefix`: where a long path is split between the prefix and name fields. */
562
+ function pathPrefix(path, maxlen) {
563
+ let i = path.length;
564
+ if (i > 1 && path[i - 1] === 47) i--;
565
+ if (i > maxlen) i = maxlen;
566
+ do
567
+ i--;
568
+ while (i > 0 && path[i] !== 47);
569
+ return i;
570
+ }
571
+ /** Writes git's tar archive (`git archive --format=tar`). */
572
+ var TarArchiveWriter = class {
573
+ settings;
574
+ sink;
575
+ out;
576
+ umask;
577
+ time;
578
+ constructor(settings) {
579
+ this.settings = settings;
580
+ this.sink = new ArchiveSink(settings.output, BLOCKSIZE);
581
+ this.out = this.sink.buffer;
582
+ this.umask = settings.umask ?? 2;
583
+ this.time = settings.time;
584
+ this.writeGlobalExtendedHeader();
585
+ }
586
+ /** `write_blocked`: data padded to a whole record. */
587
+ writeBlocked(data) {
588
+ this.out.push(data);
589
+ const tail = data.length % RECORDSIZE;
590
+ if (tail) this.out.zeros(RECORDSIZE - tail);
591
+ }
592
+ /** `stream_blocked`: a streamed blob's bytes, padded to a whole record; false when short. */
593
+ async streamBlocked(stream, size) {
594
+ let total = 0;
595
+ try {
596
+ for await (const chunk of stream) {
597
+ if (total + chunk.length > size) return false;
598
+ total += chunk.length;
599
+ await this.sink.write(chunk);
600
+ }
601
+ } catch {
602
+ return false;
603
+ }
604
+ if (total !== size) return false;
605
+ const tail = size % RECORDSIZE;
606
+ if (tail) this.out.zeros(RECORDSIZE - tail);
607
+ return true;
608
+ }
609
+ /** `prepare_header`: the numeric fields, owner, magic and checksum. */
610
+ prepareHeader(header, mode, size) {
611
+ octal(header, MODE, 8, mode & 4095);
612
+ octal(header, SIZE, 12, isRegMode(mode) ? size : 0);
613
+ octal(header, MTIME, 12, this.time);
614
+ octal(header, UID, 8, 0);
615
+ octal(header, GID, 8, 0);
616
+ header.set(asciiBytes("root"), UNAME);
617
+ header.set(asciiBytes("root"), GNAME);
618
+ octal(header, DEVMAJOR, 8, 0);
619
+ octal(header, DEVMINOR, 8, 0);
620
+ header.set(asciiBytes("ustar\0"), MAGIC);
621
+ header.set(asciiBytes("00"), VERSION);
622
+ let sum = 256;
623
+ for (let i = 0; i < RECORDSIZE; i++) if (i < CHKSUM || i >= 156) sum += header[i];
624
+ octal(header, CHKSUM, 8, sum);
625
+ }
626
+ writeGlobalExtendedHeader() {
627
+ const ext = new ByteBuffer(256);
628
+ if (this.settings.commitId) extRecord(ext, "comment", asciiBytes(this.settings.commitId));
629
+ if (this.time > USTAR_MAX) {
630
+ extRecord(ext, "mtime", asciiBytes(String(this.time)));
631
+ this.time = USTAR_MAX;
632
+ }
633
+ if (!ext.length) return;
634
+ const header = new Uint8Array(RECORDSIZE);
635
+ header[TYPEFLAG] = TYPEFLAG_GLOBAL_HEADER;
636
+ header.set(asciiBytes("pax_global_header"), NAME);
637
+ this.prepareHeader(header, 33206, ext.length);
638
+ this.writeBlocked(header);
639
+ this.writeBlocked(ext.bytes());
640
+ }
641
+ writeExtendedHeader(id, ext) {
642
+ const header = new Uint8Array(RECORDSIZE);
643
+ header[TYPEFLAG] = TYPEFLAG_EXT_HEADER;
644
+ header.set(asciiBytes(`${id}.paxheader`.slice(0, 99)), NAME);
645
+ this.prepareHeader(header, 33206, ext.length);
646
+ this.writeBlocked(header);
647
+ this.writeBlocked(ext);
648
+ }
649
+ /** `write_tar_entry`. */
650
+ async entry(entry) {
651
+ const { path, id, content } = entry;
652
+ const stream = isRegMode(entry.mode) ? entry.stream : void 0;
653
+ const size = stream ? entry.size ?? 0 : content.length;
654
+ let mode = entry.mode;
655
+ const header = new Uint8Array(RECORDSIZE);
656
+ const ext = new ByteBuffer(256);
657
+ if (isDirMode(mode) || isGitlinkMode(mode)) {
658
+ header[TYPEFLAG] = TYPEFLAG_DIR;
659
+ mode = (mode | 511) & ~this.umask;
660
+ } else if (isLinkMode(mode)) {
661
+ header[TYPEFLAG] = TYPEFLAG_LNK;
662
+ mode |= 511;
663
+ } else if (isRegMode(mode)) {
664
+ header[TYPEFLAG] = TYPEFLAG_REG;
665
+ mode = (mode | (mode & 64 ? 511 : 438)) & ~this.umask;
666
+ } else return `unsupported file mode: 0${mode.toString(8)} (SHA1: ${id})`;
667
+ if (path.length > NAME_SIZE) {
668
+ const plen = pathPrefix(path, PREFIX_SIZE);
669
+ const rest = path.length - plen - 1;
670
+ if (plen > 0 && rest <= NAME_SIZE) {
671
+ header.set(path.subarray(0, plen), PREFIX);
672
+ header.set(path.subarray(plen + 1), NAME);
673
+ } else {
674
+ header.set(asciiBytes(`${id}.data`.slice(0, 99)), NAME);
675
+ extRecord(ext, "path", path);
676
+ }
677
+ } else header.set(path, NAME);
678
+ if (isLinkMode(mode)) {
679
+ if (content.length > LINKNAME_SIZE) {
680
+ header.set(asciiBytes(`see ${id}.paxheader`.slice(0, 99)), LINKNAME);
681
+ extRecord(ext, "linkpath", content);
682
+ } else header.set(content, LINKNAME);
683
+ }
684
+ let sizeInHeader = size;
685
+ if (isRegMode(mode) && size > USTAR_MAX) {
686
+ sizeInHeader = 0;
687
+ extRecord(ext, "size", asciiBytes(String(size)));
688
+ }
689
+ this.prepareHeader(header, mode, sizeInHeader);
690
+ if (ext.length > 0) this.writeExtendedHeader(id, ext.bytes());
691
+ this.writeBlocked(header);
692
+ if (stream) {
693
+ if (!await this.streamBlocked(stream, size)) return `cannot stream blob ${id}`;
694
+ } else if (isRegMode(mode) && content.length > 0) {
695
+ await this.sink.write(content);
696
+ const tail = content.length % RECORDSIZE;
697
+ if (tail) this.out.zeros(RECORDSIZE - tail);
698
+ }
699
+ await this.sink.flush();
700
+ }
701
+ /** `write_trailer`: the last block filled, another one when fewer than two records remain. */
702
+ async finish() {
703
+ const offset = this.sink.position % BLOCKSIZE;
704
+ const tail = BLOCKSIZE - offset;
705
+ this.out.zeros(tail);
706
+ if (tail < 2 * RECORDSIZE) this.out.zeros(BLOCKSIZE);
707
+ return this.sink.finish();
708
+ }
709
+ };
710
+ //#endregion
711
+ //#region src/commands/grep/grep-engine.ts
712
+ /**
713
+ * git's grep matcher and printer (`grep.c`): the patterns compiled as `compile_grep_patterns`
714
+ * compiles them, each line of a source matched as `grep_source_1` matches it, and the output
715
+ * written as `show_line`, `show_pre_context` and `show_funcname_line` write it.
716
+ *
717
+ * @example
718
+ * ```ts
719
+ * const engine = new GrepEngine([grepPattern("foo")], { lineNumber: true });
720
+ * engine.grepSource({ name: encode("file"), content: encode("a foo\nb\n") });
721
+ * new TextDecoder().decode(engine.output()); // "file:1:a foo\n"
722
+ * ```
723
+ *
724
+ * What git does, kept here:
725
+ * - A pattern with newlines is one pattern per line. Patterns are basic POSIX regexes by
726
+ * default (`extended`, `fixed`, `perl`), compiled with `REG_NEWLINE`, `-i` as `REG_ICASE`;
727
+ * one without a regex character (`$()*+.?[\^{|`) is a literal, as with `-F`. A pattern
728
+ * holding a NUL byte dies unless it is `-P`. `-P` is a git built without PCRE: a literal
729
+ * `-P` pattern matches, any other dies.
730
+ * - `-w` takes a match only between non-word characters (or the line's ends), and retries
731
+ * from after the next non-word character as `headerless_match_one_pattern` does.
732
+ * - `--and`, `--not`, `(`, `)` (and `--all-match`) build git's expression tree; `--or` is the
733
+ * default between patterns. `--column` evaluates every branch, a `--not` swapping the
734
+ * column of a match and of an inverted one.
735
+ * - Context (`-A`, `-B`), function lines (`-p`) and function bodies (`-W`) through the
736
+ * source's funcname pattern, or git's default (a line starting with a letter, `_` or `$`).
737
+ * - Several sources print as git's threaded grep prints them (its default): each source's
738
+ * output starts with a hunk mark (`--`, or an empty line with `--break`), and the first line
739
+ * of the first output is dropped. {@link GrepEngineOptions.threads} `1` prints as git's
740
+ * single-threaded grep (`--threads=1`).
741
+ *
742
+ * @module
743
+ */
744
+ const encoder$1 = new TextEncoder();
745
+ /** A pattern token (`-e <pattern>`), its origin `-e option` unless given. */
746
+ function grepPattern(pattern, origin = "-e option", no = 0) {
747
+ return {
748
+ kind: "pattern",
749
+ pattern: typeof pattern === "string" ? encoder$1.encode(pattern) : pattern,
750
+ origin,
751
+ no
752
+ };
753
+ }
754
+ /**
755
+ * The patterns of a `-f` file (builtin/grep.c `file_callback`): one per line (a CR before
756
+ * the newline dropped), empty lines skipped, each numbered by the non-empty lines before it.
757
+ */
758
+ function grepPatternFile(content, name) {
759
+ const bytes = typeof content === "string" ? encoder$1.encode(content) : content;
760
+ const out = [];
761
+ let lno = 0;
762
+ let pos = 0;
763
+ while (pos < bytes.length) {
764
+ let end = bytes.indexOf(10, pos);
765
+ const next = end < 0 ? bytes.length : end + 1;
766
+ if (end < 0) end = bytes.length;
767
+ let stop = end;
768
+ if (end < bytes.length && stop > pos && bytes[stop - 1] === 13) stop--;
769
+ if (stop > pos) out.push(grepPattern(bytes.slice(pos, stop), name, ++lno));
770
+ pos = next;
771
+ }
772
+ return out;
773
+ }
774
+ /** git's die() of grep (an expression or option it refuses): exit status 128. */
775
+ var GrepError = class extends GitApiError {
776
+ /** git's lines */
777
+ lines;
778
+ constructor(line) {
779
+ super(line, { exitCode: 128 });
780
+ this.name = "GrepError";
781
+ this.lines = [line];
782
+ }
783
+ };
784
+ /** git's default grep colors (`GREP_OPT_INIT`). */
785
+ const DEFAULT_GREP_COLORS = {
786
+ context: "",
787
+ filename: "\x1B[35m",
788
+ function: "",
789
+ lineNumber: "\x1B[32m",
790
+ column: "\x1B[32m",
791
+ matchContext: "\x1B[1;31m",
792
+ matchSelected: "\x1B[1;31m",
793
+ selected: "",
794
+ separator: "\x1B[36m"
795
+ };
796
+ /** Characters that make a pattern a regex (git's `is_regex_special`) */
797
+ const REGEX_SPECIAL = /* @__PURE__ */ new Uint8Array(256);
798
+ for (const c of "$()*+.?[\\^{|") REGEX_SPECIAL[c.charCodeAt(0)] = 1;
799
+ const isAlpha = (b) => b >= 65 && b <= 90 || b >= 97 && b <= 122;
800
+ const isDigit = (b) => b >= 48 && b <= 57;
801
+ /** grep.c's word_char: git's ASCII isalnum, or `_` */
802
+ const wordChar = (b) => b !== void 0 && (isAlpha(b) || isDigit(b) || b === 95);
803
+ /** git's isspace: space, tab, LF, CR */
804
+ const isSpace = (b) => b === 32 || b === 9 || b === 10 || b === 13;
805
+ const lowerAscii = (b) => b >= 65 && b <= 90 ? b + 32 : b;
806
+ /** A C string: the bytes up to the first NUL, as `%s` prints them */
807
+ function cString(bytes) {
808
+ const nul = bytes.indexOf(0);
809
+ return new TextDecoder("latin1").decode(nul < 0 ? bytes : bytes.subarray(0, nul));
810
+ }
811
+ /** A literal pattern (compile_fixed_regexp: the pattern quoted, `REG_ICASE` for `-i`) */
812
+ function literalMatcher(needle, ignoreCase) {
813
+ const n = ignoreCase ? needle.map(lowerAscii) : needle;
814
+ return (buf, bol, eol) => {
815
+ const last = eol - n.length;
816
+ outer: for (let i = bol; i <= last; i++) {
817
+ for (let k = 0; k < n.length; k++) {
818
+ const b = buf[i + k];
819
+ if ((ignoreCase ? lowerAscii(b) : b) !== n[k]) continue outer;
820
+ }
821
+ return [i - bol, i - bol + n.length];
822
+ }
823
+ };
824
+ }
825
+ /** grep.c's compile_regexp of one pattern (a git built without PCRE) */
826
+ function compilePattern(token, type, ignoreCase) {
827
+ const bytes = token.pattern;
828
+ const where = token.no ? `In '${token.origin}' at ${token.no}, ` : token.origin ? `${token.origin}, ` : "";
829
+ const text = cString(bytes);
830
+ if (type !== "perl" && bytes.includes(0)) throw new GrepPatternError(text, "fatal: given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2");
831
+ const isFixed = !bytes.some((b) => REGEX_SPECIAL[b] === 1);
832
+ if (type === "fixed" || isFixed) return literalMatcher(encodeLatin1(text), ignoreCase);
833
+ if (type === "perl") throw new GrepPatternError(text, "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
834
+ try {
835
+ const re = compilePosixRegex(bytes, {
836
+ extended: type === "extended",
837
+ icase: ignoreCase,
838
+ newline: true
839
+ });
840
+ return (buf, bol, eol, notbol) => {
841
+ const m = re.exec(buf.subarray(bol, eol), eol - bol, 1, notbol);
842
+ return m ? [m.start, m.end] : void 0;
843
+ };
844
+ } catch (e) {
845
+ if (e instanceof PosixRegexError) throw new GrepPatternError(text, `fatal: ${where}'${text}': ${e.message}`);
846
+ throw e;
847
+ }
848
+ }
849
+ function encodeLatin1(s) {
850
+ const out = new Uint8Array(s.length);
851
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
852
+ return out;
853
+ }
854
+ /** The text git prints for a token (`p->pattern`) */
855
+ function tokenText(t) {
856
+ switch (t.kind) {
857
+ case "pattern": return cString(t.pattern);
858
+ case "and": return "--and";
859
+ case "not": return "--not";
860
+ case "open": return "(";
861
+ case "close": return ")";
862
+ }
863
+ }
864
+ /** grep.c's compile_pattern_or and friends over the token list */
865
+ var ExpressionParser = class {
866
+ tokens;
867
+ patterns;
868
+ legacy;
869
+ pos = 0;
870
+ constructor(tokens, patterns, legacy = false) {
871
+ this.tokens = tokens;
872
+ this.patterns = patterns;
873
+ this.legacy = legacy;
874
+ }
875
+ die(message) {
876
+ throw new GrepError(`fatal: ${message}`);
877
+ }
878
+ get cur() {
879
+ return this.tokens[this.pos];
880
+ }
881
+ atom() {
882
+ const p = this.cur;
883
+ if (!p) return void 0;
884
+ if (p.kind === "pattern") {
885
+ this.pos++;
886
+ return {
887
+ k: "atom",
888
+ p: this.patterns.get(p),
889
+ hit: false
890
+ };
891
+ }
892
+ if (p.kind === "open") {
893
+ this.pos++;
894
+ const x = this.or();
895
+ if (this.cur?.kind !== "close") this.die(this.legacy ? "unmatched parenthesis" : "unmatched ( for expression group");
896
+ this.pos++;
897
+ return x;
898
+ }
899
+ }
900
+ not() {
901
+ const p = this.cur;
902
+ if (!p) return void 0;
903
+ if (p.kind === "not") {
904
+ if (this.pos + 1 >= this.tokens.length) this.die("--not not followed by pattern expression");
905
+ this.pos++;
906
+ const x = this.not();
907
+ if (!x) this.die("--not followed by non pattern expression");
908
+ return {
909
+ k: "not",
910
+ x,
911
+ hit: false
912
+ };
913
+ }
914
+ return this.atom();
915
+ }
916
+ and() {
917
+ const x = this.not();
918
+ const p = this.cur;
919
+ if (p && p.kind === "and") {
920
+ if (!x) this.die("--and not preceded by pattern expression");
921
+ if (this.pos + 1 >= this.tokens.length) this.die("--and not followed by pattern expression");
922
+ this.pos++;
923
+ const y = this.and();
924
+ if (!y) this.die("--and not followed by pattern expression");
925
+ return {
926
+ k: "and",
927
+ l: x,
928
+ r: y,
929
+ hit: false
930
+ };
931
+ }
932
+ return x;
933
+ }
934
+ or() {
935
+ const x = this.and();
936
+ const p = this.cur;
937
+ if (x && p && p.kind !== "close") {
938
+ const y = this.or();
939
+ if (!y) this.die(`not a pattern expression ${tokenText(p)}`);
940
+ return {
941
+ k: "or",
942
+ l: x,
943
+ r: y,
944
+ hit: false
945
+ };
946
+ }
947
+ return x;
948
+ }
949
+ };
950
+ /** A growing byte buffer */
951
+ var Out = class {
952
+ chunks = [];
953
+ length = 0;
954
+ push(bytes) {
955
+ if (bytes.length === 0) return;
956
+ this.chunks.push(bytes);
957
+ this.length += bytes.length;
958
+ }
959
+ bytes() {
960
+ const out = new Uint8Array(this.length);
961
+ let at = 0;
962
+ for (const c of this.chunks) {
963
+ out.set(c, at);
964
+ at += c.length;
965
+ }
966
+ return out;
967
+ }
968
+ };
969
+ const NL = new Uint8Array([10]);
970
+ const NUL = new Uint8Array([0]);
971
+ const HUNK = encoder$1.encode("--");
972
+ const RESET = encoder$1.encode("\x1B[m");
973
+ const FIRST_FEW_BYTES = 8e3;
974
+ /** `buffer_is_binary`: a NUL among the first 8000 bytes */
975
+ function bufferIsBinary(content) {
976
+ const end = Math.min(content.length, FIRST_FEW_BYTES);
977
+ for (let i = 0; i < end; i++) if (content[i] === 0) return true;
978
+ return false;
979
+ }
980
+ /**
981
+ * Matches sources and collects git grep's output. Create one per `git grep` run (its hunk
982
+ * marks depend on what earlier sources printed); {@link output} gives what was printed.
983
+ *
984
+ * @throws GrepPatternError, GrepError (from the constructor) where git dies compiling
985
+ */
986
+ var GrepEngine = class {
987
+ patterns = [];
988
+ expr;
989
+ allMatch;
990
+ o;
991
+ colors;
992
+ threaded;
993
+ /** git 2.43 compatibility */
994
+ legacy;
995
+ skipFirstLineSetting;
996
+ skipFirstLine;
997
+ lastShown = 0;
998
+ showHunkMark = false;
999
+ out = new Out();
1000
+ cur = new Out();
1001
+ /** The current source's funcname matcher: undefined not asked yet, null the default rule */
1002
+ findFunc;
1003
+ source;
1004
+ buf = /* @__PURE__ */ new Uint8Array(0);
1005
+ constructor(tokens, options = {}) {
1006
+ const type = options.patternType ?? "basic";
1007
+ this.legacy = options.compatibility === "2.43";
1008
+ const ignoreCase = !!options.ignoreCase;
1009
+ const word = !!options.wordRegexp;
1010
+ const list = [];
1011
+ for (const t of tokens) {
1012
+ if (t.kind !== "pattern" || !t.pattern.includes(10)) {
1013
+ list.push(t);
1014
+ continue;
1015
+ }
1016
+ let pos = 0;
1017
+ for (;;) {
1018
+ const nl = t.pattern.indexOf(10, pos);
1019
+ const end = nl < 0 ? t.pattern.length : nl;
1020
+ list.push({
1021
+ ...t,
1022
+ pattern: t.pattern.slice(pos, end)
1023
+ });
1024
+ if (nl < 0) break;
1025
+ pos = nl + 1;
1026
+ }
1027
+ }
1028
+ if (list.length === 0) throw new GrepError("fatal: no pattern given");
1029
+ const byToken = /* @__PURE__ */ new Map();
1030
+ let extended = false;
1031
+ for (const t of list) {
1032
+ if (t.kind !== "pattern") {
1033
+ extended = true;
1034
+ continue;
1035
+ }
1036
+ const p = {
1037
+ token: t,
1038
+ exec: compilePattern(t, type, ignoreCase),
1039
+ word
1040
+ };
1041
+ this.patterns.push(p);
1042
+ byToken.set(t, p);
1043
+ }
1044
+ if (options.allMatch) extended = true;
1045
+ if (extended) {
1046
+ const parser = new ExpressionParser(list, byToken, this.legacy);
1047
+ this.expr = parser.or();
1048
+ const left = list[parser.pos];
1049
+ if (left) throw new GrepError(`fatal: ${this.legacy ? "incomplete pattern expression" : "incomplete pattern expression group"}: ${tokenText(left)}`);
1050
+ }
1051
+ this.allMatch = !!options.allMatch && this.expr !== void 0;
1052
+ const invert = !!options.invert;
1053
+ this.o = {
1054
+ ignoreCase,
1055
+ wordRegexp: word,
1056
+ invert,
1057
+ allMatch: !!options.allMatch,
1058
+ lineNumber: !!options.lineNumber,
1059
+ column: !!options.column,
1060
+ pathname: options.pathname ?? true,
1061
+ nullFollowingName: !!options.nullFollowingName,
1062
+ onlyMatching: !invert && !!options.onlyMatching,
1063
+ count: !!options.count,
1064
+ nameOnly: !!options.nameOnly,
1065
+ unmatchNameOnly: !!options.unmatchNameOnly,
1066
+ statusOnly: !!options.statusOnly,
1067
+ fileBreak: !!options.fileBreak,
1068
+ heading: !!options.heading,
1069
+ preContext: Math.max(0, options.preContext ?? 0),
1070
+ postContext: Math.max(0, options.postContext ?? 0),
1071
+ funcname: !!options.funcname,
1072
+ funcbody: !!options.funcbody,
1073
+ maxCount: options.maxCount ?? -1,
1074
+ binary: options.binary ?? "default"
1075
+ };
1076
+ this.colors = options.colors;
1077
+ this.threaded = options.threads === void 0 || options.threads > 1;
1078
+ const o = this.o;
1079
+ this.skipFirstLineSetting = this.threaded && !(o.nameOnly || o.unmatchNameOnly || o.count) && (o.preContext > 0 || o.postContext > 0 || o.fileBreak || o.funcbody);
1080
+ this.skipFirstLine = this.skipFirstLineSetting;
1081
+ }
1082
+ /** Everything printed so far */
1083
+ output() {
1084
+ return this.out.bytes();
1085
+ }
1086
+ /** Searches one source (grep.c's `grep_source`); returns whether it hit. */
1087
+ grepSource(source) {
1088
+ this.source = source;
1089
+ this.cur = new Out();
1090
+ let hit;
1091
+ if (!this.allMatch) hit = this.grepSource1(source, false);
1092
+ else {
1093
+ const expr = this.expr;
1094
+ clearHitMarkers(expr);
1095
+ this.grepSource1(source, true);
1096
+ hit = checkHitMarkers(expr) ? this.grepSource1(source, false) : false;
1097
+ }
1098
+ this.workDone();
1099
+ this.source = void 0;
1100
+ return hit;
1101
+ }
1102
+ /** builtin/grep.c's work_done: the source's output, the first line of all dropped when threaded */
1103
+ workDone() {
1104
+ if (this.cur.length === 0) return;
1105
+ let bytes = this.cur.bytes();
1106
+ if (this.skipFirstLine) {
1107
+ const nl = bytes.indexOf(10);
1108
+ bytes = nl < 0 ? /* @__PURE__ */ new Uint8Array(0) : bytes.subarray(nl + 1);
1109
+ this.skipFirstLine = false;
1110
+ }
1111
+ this.out.push(bytes);
1112
+ }
1113
+ emit(bytes) {
1114
+ this.cur.push(bytes);
1115
+ }
1116
+ emitColor(bytes, color) {
1117
+ if (this.colors && color) {
1118
+ this.emit(encoder$1.encode(color));
1119
+ this.emit(bytes);
1120
+ this.emit(RESET);
1121
+ } else this.emit(bytes);
1122
+ }
1123
+ emitSep(sign) {
1124
+ if (this.o.nullFollowingName) this.emit(NUL);
1125
+ else this.emitColor(new Uint8Array([sign]), this.colors?.separator);
1126
+ }
1127
+ showName(name) {
1128
+ this.emitColor(name, this.colors?.filename);
1129
+ this.emit(this.o.nullFollowingName ? NUL : NL);
1130
+ }
1131
+ /** headerless_match_one_pattern: `[so, eo]` from `bol` */
1132
+ matchOne(p, bol, eol, notbolIn) {
1133
+ const buf = this.buf;
1134
+ const start = bol;
1135
+ let notbol = notbolIn;
1136
+ for (;;) {
1137
+ const m = p.exec(buf, bol, eol, notbol);
1138
+ let hit = m !== void 0;
1139
+ if (m && p.word) {
1140
+ const [so, eo] = m;
1141
+ const okStart = so === 0 || !wordChar(buf[bol + so - 1]);
1142
+ const okEnd = eo === eol - bol || !wordChar(buf[bol + eo]);
1143
+ if (!(okStart && okEnd)) hit = false;
1144
+ if (so === eo) hit = false;
1145
+ if (!hit && bol + so + 1 < eol) {
1146
+ bol = bol + so + 1;
1147
+ while (wordChar(buf[bol - 1]) && bol < eol) bol++;
1148
+ notbol = true;
1149
+ if (bol < eol) continue;
1150
+ }
1151
+ }
1152
+ if (!hit || !m) return void 0;
1153
+ return [m[0] + bol - start, m[1] + bol - start];
1154
+ }
1155
+ }
1156
+ /** match_expr_eval; `col` and `icol` are the earliest match and inverted match columns */
1157
+ evaluate(x, bol, eol, col, icol, collect) {
1158
+ let h = false;
1159
+ switch (x.k) {
1160
+ case "atom": {
1161
+ const m = this.matchOne(x.p, bol, eol, false);
1162
+ h = m !== void 0;
1163
+ if (m && (col.v < 0 || m[0] < col.v)) col.v = m[0];
1164
+ break;
1165
+ }
1166
+ case "not":
1167
+ h = !this.evaluate(x.x, bol, eol, icol, col, false);
1168
+ break;
1169
+ case "and":
1170
+ h = this.evaluate(x.l, bol, eol, col, icol, false);
1171
+ if (h || this.o.column) h = this.evaluate(x.r, bol, eol, col, icol, false) && h;
1172
+ break;
1173
+ case "or":
1174
+ if (!(collect || this.o.column)) return this.evaluate(x.l, bol, eol, col, icol, false) || this.evaluate(x.r, bol, eol, col, icol, false);
1175
+ h = this.evaluate(x.l, bol, eol, col, icol, false);
1176
+ if (collect) x.l.hit ||= h;
1177
+ h = this.evaluate(x.r, bol, eol, col, icol, collect) || h;
1178
+ }
1179
+ if (collect) x.hit ||= h;
1180
+ return h;
1181
+ }
1182
+ /** match_line */
1183
+ matchLine(bol, eol, col, icol, collect) {
1184
+ if (this.expr) return this.evaluate(this.expr, bol, eol, col, icol, collect);
1185
+ let hit = false;
1186
+ for (const p of this.patterns) {
1187
+ const m = this.matchOne(p, bol, eol, false);
1188
+ if (!m) continue;
1189
+ hit = true;
1190
+ if (!this.o.column) break;
1191
+ if (col.v < 0 || m[0] < col.v) col.v = m[0];
1192
+ }
1193
+ return hit;
1194
+ }
1195
+ /** grep_next_match over every pattern: the earliest match (the longest of those) */
1196
+ nextMatch(bol, eol, notbol) {
1197
+ let best;
1198
+ if (bol >= eol) return void 0;
1199
+ for (const p of this.patterns) {
1200
+ const m = this.matchOne(p, bol, eol, notbol);
1201
+ if (!m) continue;
1202
+ if (best && (m[0] > best[0] || m[0] === best[0] && m[1] < best[1])) continue;
1203
+ best = m;
1204
+ }
1205
+ return best;
1206
+ }
1207
+ showLineHeader(name, lno, cno, sign) {
1208
+ const o = this.o;
1209
+ if (o.heading && this.lastShown === 0) {
1210
+ this.emitColor(name, this.colors?.filename);
1211
+ this.emit(NL);
1212
+ }
1213
+ this.lastShown = lno;
1214
+ if (!o.heading && o.pathname) {
1215
+ this.emitColor(name, this.colors?.filename);
1216
+ this.emitSep(sign);
1217
+ }
1218
+ if (o.lineNumber) {
1219
+ this.emitColor(encoder$1.encode(String(lno)), this.colors?.lineNumber);
1220
+ this.emitSep(sign);
1221
+ }
1222
+ if (o.column && cno) {
1223
+ this.emitColor(encoder$1.encode(String(cno)), this.colors?.column);
1224
+ this.emitSep(sign);
1225
+ }
1226
+ }
1227
+ /** show_line */
1228
+ showLine(bol, eol, lno, cnoIn, sign) {
1229
+ const o = this.o;
1230
+ const buf = this.buf;
1231
+ const name = this.source.name;
1232
+ let cno = cnoIn;
1233
+ if (o.fileBreak && this.lastShown === 0) {
1234
+ if (this.showHunkMark) this.emit(NL);
1235
+ } else if (o.preContext || o.postContext || o.funcbody) {
1236
+ if (this.lastShown === 0) {
1237
+ if (this.showHunkMark) {
1238
+ this.emitColor(HUNK, this.colors?.separator);
1239
+ this.emit(NL);
1240
+ }
1241
+ } else if (lno > this.lastShown + 1) {
1242
+ this.emitColor(HUNK, this.colors?.separator);
1243
+ this.emit(NL);
1244
+ }
1245
+ }
1246
+ if (!o.onlyMatching) this.showLineHeader(name, lno, cno, sign);
1247
+ let at = bol;
1248
+ if (this.colors || o.onlyMatching) {
1249
+ let matchColor;
1250
+ let lineColor;
1251
+ if (this.colors) {
1252
+ matchColor = sign === 58 ? this.colors.matchSelected : this.colors.matchContext;
1253
+ if (sign === 58) lineColor = this.colors.selected;
1254
+ else if (sign === 45) lineColor = this.colors.context;
1255
+ else if (sign === 61) lineColor = this.colors.function;
1256
+ }
1257
+ let notbol = false;
1258
+ for (;;) {
1259
+ const m = this.nextMatch(at, eol, notbol);
1260
+ if (!m || m[0] === m[1]) break;
1261
+ if (!this.legacy) cno = at - bol + m[0] + 1;
1262
+ if (o.onlyMatching) this.showLineHeader(name, lno, cno, sign);
1263
+ else this.emitColor(buf.subarray(at, at + m[0]), lineColor);
1264
+ this.emitColor(buf.subarray(at + m[0], at + m[1]), matchColor);
1265
+ if (o.onlyMatching) this.emit(NL);
1266
+ at += m[1];
1267
+ if (this.legacy) cno += m[1];
1268
+ notbol = true;
1269
+ }
1270
+ if (!o.onlyMatching) {
1271
+ this.emitColor(buf.subarray(at, eol), lineColor);
1272
+ this.emit(NL);
1273
+ }
1274
+ return;
1275
+ }
1276
+ this.emit(buf.subarray(at, eol));
1277
+ this.emit(NL);
1278
+ }
1279
+ /** match_funcname */
1280
+ matchFuncname(bol, eol) {
1281
+ if (this.findFunc === void 0) this.findFunc = this.source?.findFunction?.() ?? null;
1282
+ if (this.findFunc) return this.findFunc(this.buf.subarray(bol, eol)) !== void 0;
1283
+ if (bol === eol) return false;
1284
+ const c = this.buf[bol] ?? 0;
1285
+ return isAlpha(c) || c === 95 || c === 36;
1286
+ }
1287
+ isEmptyLine(bol, eol) {
1288
+ let at = bol;
1289
+ while (at < eol && at < this.buf.length && isSpace(this.buf[at])) at++;
1290
+ return at === eol;
1291
+ }
1292
+ /** show_funcname_line */
1293
+ showFuncnameLine(bolIn, lnoIn) {
1294
+ const buf = this.buf;
1295
+ let bol = bolIn;
1296
+ let lno = lnoIn;
1297
+ while (bol > 0) {
1298
+ const eol = --bol;
1299
+ while (bol > 0 && buf[bol - 1] !== 10) bol--;
1300
+ lno--;
1301
+ if (lno <= this.lastShown) break;
1302
+ if (this.matchFuncname(bol, eol)) {
1303
+ this.showLine(bol, eol, lno, 0, 61);
1304
+ break;
1305
+ }
1306
+ }
1307
+ }
1308
+ /** show_pre_context */
1309
+ showPreContext(bolIn, end, lno) {
1310
+ const o = this.o;
1311
+ const buf = this.buf;
1312
+ let bol = bolIn;
1313
+ let cur = lno;
1314
+ let from = 1;
1315
+ let funcnameLno = 0;
1316
+ let funcnameNeeded = o.funcname;
1317
+ let commentNeeded = false;
1318
+ if (o.preContext < lno) from = lno - o.preContext;
1319
+ if (from <= this.lastShown) from = this.lastShown + 1;
1320
+ const origFrom = from;
1321
+ if (o.funcbody) {
1322
+ if (this.matchFuncname(bol, end)) commentNeeded = true;
1323
+ else funcnameNeeded = true;
1324
+ from = this.lastShown + 1;
1325
+ }
1326
+ while (bol > 0 && cur > from) {
1327
+ const nextBol = bol;
1328
+ const eol = --bol;
1329
+ while (bol > 0 && buf[bol - 1] !== 10) bol--;
1330
+ cur--;
1331
+ if (commentNeeded && (this.isEmptyLine(bol, eol) || this.matchFuncname(bol, eol))) {
1332
+ commentNeeded = false;
1333
+ from = origFrom;
1334
+ if (cur < from) {
1335
+ cur++;
1336
+ bol = nextBol;
1337
+ break;
1338
+ }
1339
+ }
1340
+ if (funcnameNeeded && this.matchFuncname(bol, eol)) {
1341
+ funcnameLno = cur;
1342
+ funcnameNeeded = false;
1343
+ if (o.funcbody) commentNeeded = true;
1344
+ else from = origFrom;
1345
+ }
1346
+ }
1347
+ if (o.funcname && funcnameNeeded) this.showFuncnameLine(bol, cur);
1348
+ while (cur < lno) {
1349
+ let eol = bol;
1350
+ while (buf[eol] !== 10) eol++;
1351
+ this.showLine(bol, eol, cur, 0, cur === funcnameLno ? 61 : 45);
1352
+ bol = eol + 1;
1353
+ cur++;
1354
+ }
1355
+ }
1356
+ /** grep_source_1 */
1357
+ grepSource1(source, collect) {
1358
+ const o = this.o;
1359
+ if (o.preContext || o.postContext || o.fileBreak || o.funcbody) {
1360
+ if (this.lastShown) this.showHunkMark = true;
1361
+ if (this.threaded) this.showHunkMark = true;
1362
+ }
1363
+ this.lastShown = 0;
1364
+ let binaryMatchOnly = false;
1365
+ if (!source.textconv) {
1366
+ const binary = source.binary ?? (source.content ? bufferIsBinary(source.content) : false);
1367
+ if (o.binary === "default" && binary) binaryMatchOnly = true;
1368
+ else if (o.binary === "nomatch" && binary) return false;
1369
+ }
1370
+ this.findFunc = void 0;
1371
+ const buf = source.content;
1372
+ if (!buf) return false;
1373
+ this.buf = buf;
1374
+ const size = buf.length;
1375
+ let bol = 0;
1376
+ let left = size;
1377
+ let lno = 1;
1378
+ let lastHit = 0;
1379
+ let count = 0;
1380
+ let showFunction = false;
1381
+ let peekBol = -1;
1382
+ const tryLookahead = !this.expr && !o.invert;
1383
+ while (left) {
1384
+ if (tryLookahead && !(lastHit && (showFunction || lno <= lastHit + o.postContext))) {
1385
+ let earliest = -1;
1386
+ for (const p of this.patterns) {
1387
+ const m = p.exec(buf, bol, size, false);
1388
+ if (m && (earliest < 0 || m[0] < earliest)) earliest = m[0];
1389
+ }
1390
+ if (earliest < 0) break;
1391
+ let sp = bol + earliest;
1392
+ while (sp > bol && buf[sp - 1] !== 10) sp--;
1393
+ for (let at = buf.indexOf(10, bol); at >= 0 && at < sp; at = buf.indexOf(10, at + 1)) lno++;
1394
+ left -= sp - bol;
1395
+ bol = sp;
1396
+ }
1397
+ let eol = buf.indexOf(10, bol);
1398
+ if (eol < 0) eol = size;
1399
+ left = size - eol;
1400
+ const col = { v: -1 };
1401
+ const icol = { v: -1 };
1402
+ let hit = this.matchLine(bol, eol, col, icol, collect);
1403
+ if (!collect) {
1404
+ if (o.invert) hit = !hit;
1405
+ if (o.unmatchNameOnly) {
1406
+ if (hit) return false;
1407
+ } else if (hit && (o.maxCount < 0 || count < o.maxCount)) {
1408
+ count++;
1409
+ if (o.statusOnly) return true;
1410
+ if (o.nameOnly) {
1411
+ this.showName(source.name);
1412
+ return true;
1413
+ }
1414
+ if (!o.count) {
1415
+ if (binaryMatchOnly) {
1416
+ this.emit(encoder$1.encode("Binary file "));
1417
+ this.emitColor(source.name, this.colors?.filename);
1418
+ this.emit(encoder$1.encode(" matches\n"));
1419
+ return true;
1420
+ }
1421
+ if (o.preContext || o.funcbody) this.showPreContext(bol, eol, lno);
1422
+ else if (o.funcname) this.showFuncnameLine(bol, lno);
1423
+ let cno = o.invert ? icol.v : col.v;
1424
+ if (cno < 0) cno = 0;
1425
+ this.showLine(bol, eol, lno, cno + 1, 58);
1426
+ lastHit = lno;
1427
+ if (o.funcbody) showFunction = true;
1428
+ }
1429
+ } else {
1430
+ if (showFunction && (peekBol < 0 || peekBol < bol)) {
1431
+ let peekLeft = left;
1432
+ let peekEol = eol;
1433
+ peekBol = bol;
1434
+ while (this.isEmptyLine(peekBol, peekEol)) {
1435
+ peekBol = peekEol + 1;
1436
+ let e = peekBol;
1437
+ while (peekLeft && (e < size ? buf[e] : 0) !== 10) {
1438
+ peekLeft--;
1439
+ e++;
1440
+ }
1441
+ peekEol = e;
1442
+ }
1443
+ if (!this.legacy && peekBol >= size || this.matchFuncname(peekBol, peekEol)) showFunction = false;
1444
+ }
1445
+ if (showFunction || lastHit && lno <= lastHit + o.postContext) this.showLine(bol, eol, lno, col.v + 1, 45);
1446
+ }
1447
+ }
1448
+ bol = eol + 1;
1449
+ if (!left) break;
1450
+ left--;
1451
+ lno++;
1452
+ }
1453
+ if (collect) return false;
1454
+ if (o.statusOnly) return o.unmatchNameOnly;
1455
+ if (o.unmatchNameOnly) {
1456
+ this.showName(source.name);
1457
+ return true;
1458
+ }
1459
+ if (o.count && count) {
1460
+ if (o.pathname) {
1461
+ this.emitColor(source.name, this.colors?.filename);
1462
+ this.emitSep(58);
1463
+ }
1464
+ this.emit(encoder$1.encode(`${count}\n`));
1465
+ return true;
1466
+ }
1467
+ return lastHit !== 0;
1468
+ }
1469
+ };
1470
+ /** clr_hit_marker: the top-level or chain's markers */
1471
+ function clearHitMarkers(xIn) {
1472
+ let x = xIn;
1473
+ for (;;) {
1474
+ x.hit = false;
1475
+ if (x.k !== "or") return;
1476
+ x.l.hit = false;
1477
+ x = x.r;
1478
+ }
1479
+ }
1480
+ /** chk_hit_marker: every term of the top-level or chain hit some line */
1481
+ function checkHitMarkers(xIn) {
1482
+ let x = xIn;
1483
+ for (;;) {
1484
+ if (x.k !== "or") return x.hit;
1485
+ if (!x.l.hit) return false;
1486
+ x = x.r;
1487
+ }
1488
+ }
1489
+ //#endregion
1490
+ //#region src/commands/grep/grep-command.ts
1491
+ /**
1492
+ * `git grep` (builtin/grep.c over grep.c): lines matching patterns in the worktree's tracked
1493
+ * files, the index (`--cached`), untracked files too (`--untracked`), a directory outside
1494
+ * git's control (`--no-index`), or trees and revisions.
1495
+ *
1496
+ * @example
1497
+ * ```typescript
1498
+ * // git grep -n -e foo --and --not -e bar HEAD -- src
1499
+ * const result = await git
1500
+ * .grep()
1501
+ * .addPattern("foo")
1502
+ * .and()
1503
+ * .not()
1504
+ * .addPattern("bar")
1505
+ * .setLineNumber(true)
1506
+ * .setArguments(["HEAD", "--", "src"])
1507
+ * .call();
1508
+ * process.stdout.write(result.output); // HEAD:src/a.c:12:foo()
1509
+ * result.exitCode; // 0 when something matched, else 1
1510
+ * ```
1511
+ *
1512
+ * What it searches, as git does:
1513
+ * - The worktree: every regular file of the index (stage 0 once per unmerged path, skip-worktree
1514
+ * entries left out), read from disk, or from the index when the entry is assume-unchanged
1515
+ * (an intent-to-add or unmerged one then skipped).
1516
+ * - `--cached`: the index's blobs. Trees and revisions (`setArguments`, `addRevision`): their
1517
+ * files named `<rev>:<path>` (a blob given as `<rev>:<path>` by that name alone); the diff
1518
+ * attributes of a commit's files come from the worktree and index, a tree's files have none.
1519
+ * - `--untracked` and `--no-index`: the files of the directory (`.git` never entered), ignored
1520
+ * ones left out unless `--no-exclude-standard` (the default of `--no-index`); `--no-index`
1521
+ * enters nested repositories. Without a repository, {@link grepNoIndex}.
1522
+ *
1523
+ * Names are relative to the current directory ({@link GrepCommand.setPrefix}) unless
1524
+ * `--full-name`/`grep.fullName`, quoted as `core.quotePath` says (not with `-z`). Binary files
1525
+ * (a NUL in their first 8000 bytes, or the `diff` attribute's driver) report `Binary file x
1526
+ * matches`; `--textconv` runs `diff.<driver>.textconv` through the runner the host installs
1527
+ * (`installTextconvRunner`), a blob of a tree or the index through the driver's notes cache
1528
+ * (`diff.<driver>.cachetextconv`, as git's fill_textconv). `-p`/`-W` use the driver's funcname pattern. Configuration:
1529
+ * `grep.lineNumber`, `grep.column`, `grep.fullName`, `grep.patternType`,
1530
+ * `grep.extendedRegexp`, `grep.threads`, `color.grep`, `color.grep.<slot>`.
1531
+ *
1532
+ * Output follows git's threaded grep (its default, `GrepEngine`): with context, every source's
1533
+ * output after the first starts with `--`. `--recurse-submodules` (or `submodule.recurse`)
1534
+ * is refused; `-O`/`--open-files-in-pager` is not offered.
1535
+ *
1536
+ * @module
1537
+ */
1538
+ const S_IFMT = 61440;
1539
+ const S_IFREG = 32768;
1540
+ const isRegular = (mode) => (mode & S_IFMT) === S_IFREG;
1541
+ /** An index without in-tree attributes files */
1542
+ const NO_INDEX = { attributesBlob: () => void 0 };
1543
+ function die(message) {
1544
+ throw new GrepError(`fatal: ${message}`);
1545
+ }
1546
+ /** git's `relative_path(in, prefix)` for two paths from the top (prefix ends with `/`). */
1547
+ function relativePath(path, prefix) {
1548
+ if (!prefix) return path;
1549
+ const a = path.split("/");
1550
+ const b = prefix.split("/").filter((p) => p !== "");
1551
+ let k = 0;
1552
+ while (k < a.length - 1 && k < b.length && a[k] === b[k]) k++;
1553
+ return [...b.slice(k).map(() => ".."), ...a.slice(k)].join("/");
1554
+ }
1555
+ const SHORT_MAGIC = /* @__PURE__ */ new Set([..."!\"#%&',-;<=>@_`~^/"]);
1556
+ /** The pathspec argument read against the prefix (`:(top)` and `:/` from the top). */
1557
+ function prefixedArg(arg, prefix) {
1558
+ if (!prefix) return arg;
1559
+ if (arg.startsWith(":(")) {
1560
+ const close = arg.indexOf(")");
1561
+ if (close < 0) return arg;
1562
+ if (arg.slice(2, close).split(",").map((w) => w.trim()).includes("top")) return arg;
1563
+ return arg.slice(0, close + 1) + prefix + arg.slice(close + 1);
1564
+ }
1565
+ if (arg.startsWith(":")) {
1566
+ let i = 1;
1567
+ while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC.has(arg[i])) i++;
1568
+ const magic = arg.slice(1, i);
1569
+ if (arg[i] === ":") i++;
1570
+ if (magic.includes("/")) return arg;
1571
+ return arg.slice(0, i) + prefix + arg.slice(i);
1572
+ }
1573
+ return prefix + arg;
1574
+ }
1575
+ /** The part of an argument after its magic (git's `copyfrom`) */
1576
+ function afterMagic(arg) {
1577
+ if (arg.startsWith(":(")) {
1578
+ const close = arg.indexOf(")");
1579
+ return close < 0 ? arg : arg.slice(close + 1);
1580
+ }
1581
+ if (arg.startsWith(":")) {
1582
+ let i = 1;
1583
+ while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC.has(arg[i])) i++;
1584
+ if (arg[i] === ":") i++;
1585
+ return arg.slice(i);
1586
+ }
1587
+ return arg;
1588
+ }
1589
+ /** dir.c's within_depth */
1590
+ function withinDepth(name, depthIn, maxDepth) {
1591
+ let depth = depthIn;
1592
+ for (let i = 0; i < name.length; i++) {
1593
+ if (name.charCodeAt(i) !== 47) continue;
1594
+ depth++;
1595
+ if (depth > maxDepth) return false;
1596
+ }
1597
+ return depth <= maxDepth;
1598
+ }
1599
+ /** match_pathspec with `--max-depth` (git's PATHSPEC_MAXDEPTH, recursive) */
1600
+ function pathMatches(items, path, maxDepth) {
1601
+ if (maxDepth < 0) return matchPathspec(items, path, 0) !== 0;
1602
+ if (items.length === 0) return withinDepth(path, 0, maxDepth);
1603
+ const name = latin1$3(path);
1604
+ let positive = 0;
1605
+ for (const item of items) {
1606
+ if (item.exclude) continue;
1607
+ let how = matchPathspec([item], path, 0);
1608
+ if (how && how !== 3) {
1609
+ let len = item.match.length;
1610
+ if (name[len] === "/") len++;
1611
+ how = withinDepth(name.slice(len), 0, maxDepth) ? how : 0;
1612
+ }
1613
+ positive = Math.max(positive, how);
1614
+ }
1615
+ if (!positive) return false;
1616
+ return !items.some((i) => i.exclude) || matchPathspec(items, path, 0) !== 0;
1617
+ }
1618
+ /** A path as one character per byte (pathspec items hold bytes) */
1619
+ function latin1$3(path) {
1620
+ let ascii = true;
1621
+ for (let i = 0; i < path.length; i++) if (path.charCodeAt(i) > 127) ascii = false;
1622
+ if (ascii) return path;
1623
+ let out = "";
1624
+ for (const b of encodeGitPath(path)) out += String.fromCharCode(b);
1625
+ return out;
1626
+ }
1627
+ /** One search of `git grep` over a context. */
1628
+ var GrepRun = class {
1629
+ ctx;
1630
+ o;
1631
+ engine;
1632
+ items = [];
1633
+ relative = true;
1634
+ quoteFully = true;
1635
+ drivers = /* @__PURE__ */ new Map();
1636
+ prefix;
1637
+ constructor(ctx, o) {
1638
+ this.ctx = ctx;
1639
+ this.o = o;
1640
+ this.prefix = o.prefix ?? "";
1641
+ }
1642
+ async run() {
1643
+ const ctx = this.ctx;
1644
+ const o = this.o;
1645
+ const get = (key) => ctx.config(key);
1646
+ const bool = (key) => {
1647
+ const v = get(key);
1648
+ return v === void 0 ? void 0 : parseGitBool$1(v) ?? true;
1649
+ };
1650
+ let configured;
1651
+ const typeValue = get("grep.patternType");
1652
+ if (typeValue !== void 0) {
1653
+ if (typeValue === "basic" || typeValue === "extended" || typeValue === "fixed") configured = typeValue;
1654
+ else if (typeValue === "perl") configured = "perl";
1655
+ else if (typeValue !== "default") die(`bad grep.patterntype argument: ${typeValue}`);
1656
+ }
1657
+ const threadsValue = get("grep.threads");
1658
+ let threads = o.threads ?? (threadsValue !== void 0 ? Number(threadsValue) : 0);
1659
+ if (threadsValue !== void 0 && Number(threadsValue) < 0) die(`invalid number of threads specified (${threadsValue}) for grep.threads`);
1660
+ this.relative = o.fullName !== void 0 ? !o.fullName : !(bool("grep.fullName") ?? false);
1661
+ this.quoteFully = bool("core.quotePath") ?? true;
1662
+ const useIndex = !o.noIndex && ctx.repository;
1663
+ if ((o.recurseSubmodules ?? bool("submodule.recurse") ?? false) && useIndex) die("--recurse-submodules is not supported by this implementation of git grep");
1664
+ const tokens = o.tokens;
1665
+ if (tokens.length === 0) die("no pattern given");
1666
+ const { objects, paths } = await this.readArguments(useIndex);
1667
+ this.items = this.parsePaths(paths);
1668
+ if (o.maxCount === 0) return {
1669
+ exitCode: 1,
1670
+ matched: false,
1671
+ output: /* @__PURE__ */ new Uint8Array(0)
1672
+ };
1673
+ if (threads < 0) die(`invalid number of threads specified (${threads})`);
1674
+ if (threads === 0) threads = 8;
1675
+ let patternType = o.patternType ?? configured;
1676
+ if (patternType === void 0) patternType = bool("grep.extendedRegexp") ? "extended" : "basic";
1677
+ this.engine = new GrepEngine(tokens, {
1678
+ ...o,
1679
+ patternType,
1680
+ lineNumber: o.lineNumber ?? bool("grep.lineNumber") ?? false,
1681
+ column: o.column ?? bool("grep.column") ?? false,
1682
+ threads,
1683
+ ...this.colorOn() ? { colors: this.colors() } : {}
1684
+ });
1685
+ const incompatible = [
1686
+ [!useIndex && !!o.noIndex, "--no-index"],
1687
+ [!!o.untracked, "--untracked"],
1688
+ [!!o.cached, "--cached"]
1689
+ ].filter(([on]) => on);
1690
+ if (incompatible.length === 3) die("options '--no-index', '--untracked', and '--cached' cannot be used together");
1691
+ if (incompatible.length === 2) die(`options '${incompatible[0]?.[1]}' and '${incompatible[1]?.[1]}' cannot be used together`);
1692
+ let hit;
1693
+ if (!useIndex || o.untracked) {
1694
+ const exclude = o.excludeStandard ?? useIndex;
1695
+ hit = await ctx.inOneOperation(() => this.grepDirectory(exclude, useIndex));
1696
+ } else if (o.excludeStandard !== void 0) die("--[no-]exclude-standard cannot be used for tracked contents");
1697
+ else if (objects.length === 0) hit = await ctx.inOneOperation(() => this.grepCache(!!o.cached));
1698
+ else {
1699
+ if (o.cached) die("both --cached and trees are given");
1700
+ hit = await ctx.inOneOperation(() => this.grepObjects(objects));
1701
+ }
1702
+ return {
1703
+ exitCode: hit ? 0 : 1,
1704
+ matched: hit,
1705
+ output: this.engine.output()
1706
+ };
1707
+ }
1708
+ colorOn() {
1709
+ if (this.o.color !== void 0) return this.o.color;
1710
+ const value = this.ctx.config("color.grep") ?? this.ctx.config("color.ui");
1711
+ if (value === void 0) return false;
1712
+ if (value === "always") return true;
1713
+ if (value === "auto" || value === "never") return false;
1714
+ return false;
1715
+ }
1716
+ colors() {
1717
+ const colors = { ...DEFAULT_GREP_COLORS };
1718
+ for (const [slot, key] of [
1719
+ ["context", "context"],
1720
+ ["filename", "filename"],
1721
+ ["function", "function"],
1722
+ ["lineNumber", "lineNumber"],
1723
+ ["column", "column"],
1724
+ ["selected", "selected"],
1725
+ ["separator", "separator"],
1726
+ ["matchContext", "match"],
1727
+ ["matchSelected", "match"],
1728
+ ["matchContext", "matchContext"],
1729
+ ["matchSelected", "matchSelected"]
1730
+ ]) {
1731
+ const value = this.ctx.config(`color.grep.${key}`);
1732
+ if (value === void 0) continue;
1733
+ const color = parseGitColor(value);
1734
+ if (color !== void 0) colors[slot] = color;
1735
+ }
1736
+ return colors;
1737
+ }
1738
+ /** cmd_grep's revision loop and verify_filename */
1739
+ async readArguments(useIndex) {
1740
+ const ctx = this.ctx;
1741
+ const args = this.o.args ?? [];
1742
+ const seenDashdash = args.includes("--");
1743
+ const allowRevs = useIndex && !this.o.untracked;
1744
+ const objects = [];
1745
+ let i = 0;
1746
+ const resolver = allowRevs ? ctx.resolver?.() : void 0;
1747
+ if (resolver) resolver.cwdPrefix = this.prefix;
1748
+ const files = ctx.argumentFiles?.(this.prefix);
1749
+ for (; i < args.length; i++) {
1750
+ const arg = args[i];
1751
+ if (arg === "--") {
1752
+ i++;
1753
+ break;
1754
+ }
1755
+ if (!allowRevs || !resolver) {
1756
+ if (seenDashdash) die("--no-index or --untracked cannot be used with revs");
1757
+ break;
1758
+ }
1759
+ const id = await resolver.resolve(arg).catch((e) => {
1760
+ if (e instanceof RevisionError) throw e;
1761
+ });
1762
+ if (id === void 0) {
1763
+ if (seenDashdash) die(`unable to resolve revision: ${arg}`);
1764
+ break;
1765
+ }
1766
+ if (!seenDashdash && files) {
1767
+ const message = await verifyNonFilename(files, arg);
1768
+ if (message) throw new RevisionError(arg, message);
1769
+ }
1770
+ objects.push({
1771
+ name: arg,
1772
+ id,
1773
+ ...this.objectPath(arg)
1774
+ });
1775
+ }
1776
+ if (!seenDashdash && files && resolver) for (let j = i; j < args.length; j++) await verifyFilename(files, resolver, args[j], j === i && allowRevs);
1777
+ else if (!seenDashdash && files) {
1778
+ const quiet = ctx.resolver?.() ?? { warnings: [] };
1779
+ for (let j = i; j < args.length; j++) await verifyFilename(files, quiet, args[j], false);
1780
+ }
1781
+ return {
1782
+ objects,
1783
+ paths: args.slice(i)
1784
+ };
1785
+ }
1786
+ /** The path GET_OID_RECORD_PATH records for `<rev>:<path>` or `:<n>:<path>` */
1787
+ objectPath(arg) {
1788
+ let at = -1;
1789
+ if (arg.startsWith(":")) at = /^:[0-3]:/.test(arg) ? 2 : 0;
1790
+ else {
1791
+ let depth = 0;
1792
+ for (let i = 0; i < arg.length; i++) {
1793
+ const c = arg[i];
1794
+ if ((c === "@" || c === "^") && arg[i + 1] === "{") {
1795
+ i++;
1796
+ depth++;
1797
+ } else if (depth > 0 && c === "}") depth--;
1798
+ else if (depth === 0 && c === ":") {
1799
+ at = i;
1800
+ break;
1801
+ }
1802
+ }
1803
+ }
1804
+ if (at < 0) return {};
1805
+ let path = arg.slice(at + 1);
1806
+ if (path.startsWith("./") || path.startsWith("../") || path === "." || path === "..") {
1807
+ const out = [];
1808
+ for (const part of `${this.prefix}${path}`.split("/")) {
1809
+ if (part === "" || part === ".") continue;
1810
+ if (part === "..") out.pop();
1811
+ else out.push(part);
1812
+ }
1813
+ path = out.join("/");
1814
+ }
1815
+ return { path };
1816
+ }
1817
+ /** parse_pathspec with PATHSPEC_PREFER_CWD */
1818
+ parsePaths(paths) {
1819
+ const prefix = this.prefix;
1820
+ const args = paths.length === 0 && prefix ? ["."] : paths;
1821
+ return parsePathspec(args.map((arg) => {
1822
+ const prefixed = prefixedArg(arg, prefix);
1823
+ try {
1824
+ parsePathspec([prefixed]);
1825
+ } catch (e) {
1826
+ if (e instanceof Error && /is outside repository/.test(e.message)) {
1827
+ const copy = afterMagic(arg);
1828
+ if (!this.ctx.repository) die(`'${copy}' is outside the directory tree`);
1829
+ die(`${arg}: '${copy}' is outside repository at '${this.ctx.hostTop ?? ""}'`);
1830
+ }
1831
+ if (e instanceof Error) die(e.message);
1832
+ throw e;
1833
+ }
1834
+ return prefixed;
1835
+ }));
1836
+ }
1837
+ matches(path) {
1838
+ return pathMatches(this.items, path, this.o.maxDepth ?? -1);
1839
+ }
1840
+ /** grep_source_name: the name printed for `path` (after a tree's `<rev>:`) */
1841
+ sourceName(path, treeName = "") {
1842
+ const rel = this.relative && this.prefix ? relativePath(path, this.prefix) : path;
1843
+ if (this.o.nullFollowingName) return encodeGitPath(treeName + rel);
1844
+ return encodeGitPath(treeName + quotePath(rel, this.quoteFully));
1845
+ }
1846
+ /** userdiff_find_by_path: the `diff` attribute's driver */
1847
+ driver(path, withIndex) {
1848
+ if (path === void 0) return Promise.resolve(void 0);
1849
+ const key = `${withIndex ? "i" : "w"}:${path}`;
1850
+ let found = this.drivers.get(key);
1851
+ if (!found) {
1852
+ found = this.loadDriver(path, withIndex);
1853
+ this.drivers.set(key, found);
1854
+ }
1855
+ return found;
1856
+ }
1857
+ async loadDriver(path, withIndex) {
1858
+ const filter = this.ctx.worktree?.contentFilter;
1859
+ if (!filter?.attributes) return void 0;
1860
+ const value = (await filter.attributes(path, ["diff"], withIndex ? void 0 : {
1861
+ direction: "checkin",
1862
+ index: NO_INDEX
1863
+ })).get("diff");
1864
+ if (value === true) return {
1865
+ binary: false,
1866
+ findFunction: () => void 0
1867
+ };
1868
+ if (value === false) return {
1869
+ binary: true,
1870
+ findFunction: () => void 0
1871
+ };
1872
+ if (typeof value !== "string") return void 0;
1873
+ const get = (key) => this.ctx.config(key);
1874
+ const binaryValue = get(`diff.${value}.binary`);
1875
+ const binary = binaryValue === void 0 ? void 0 : parseGitBool$1(binaryValue);
1876
+ const command = get(`diff.${value}.textconv`);
1877
+ let find = null;
1878
+ return {
1879
+ ...binary !== void 0 ? { binary } : {},
1880
+ ...command !== void 0 ? { textconv: {
1881
+ name: value,
1882
+ command,
1883
+ cache: parseGitBool$1(get(`diff.${value}.cachetextconv`)) ?? false
1884
+ } } : {},
1885
+ findFunction: () => {
1886
+ if (find === null) try {
1887
+ find = userdiffFindFunction$1(value, get);
1888
+ } catch (e) {
1889
+ die(e.message);
1890
+ }
1891
+ return find;
1892
+ }
1893
+ };
1894
+ }
1895
+ /** grep_source for one file or blob */
1896
+ async grepOne(name, path, withIndex, read, textconvInput, id) {
1897
+ const o = this.o;
1898
+ const driver = await this.driver(path, withIndex);
1899
+ let content = await read();
1900
+ let textconv = false;
1901
+ if (o.textconv && driver?.textconv && this.ctx.textconv && content !== void 0) {
1902
+ const tc = driver.textconv;
1903
+ content = await this.ctx.textconv({
1904
+ driver: tc.name,
1905
+ command: tc.command,
1906
+ path: path ?? "",
1907
+ content: await textconvInput(content),
1908
+ cache: tc.cache
1909
+ }, id);
1910
+ textconv = true;
1911
+ }
1912
+ return this.engine.grepSource({
1913
+ name,
1914
+ content,
1915
+ textconv,
1916
+ ...driver?.binary !== void 0 ? { binary: driver.binary } : {},
1917
+ findFunction: () => driver?.findFunction()
1918
+ });
1919
+ }
1920
+ async readFile(path) {
1921
+ const worktree = this.ctx.worktree;
1922
+ if (!worktree) return void 0;
1923
+ const entry = await worktree.getEntry(path);
1924
+ if (!entry || entry.isDirectory || !isRegular(entry.mode)) return void 0;
1925
+ try {
1926
+ return await collectChunks(worktree.readContent(path));
1927
+ } catch {
1928
+ return;
1929
+ }
1930
+ }
1931
+ grepFile(path, withIndex) {
1932
+ return this.grepOne(this.sourceName(path), path, withIndex, () => this.readFile(path), async (c) => c);
1933
+ }
1934
+ grepBlob(id, name, path, mode = FileMode.REGULAR_FILE) {
1935
+ const read = () => this.ctx.readBlob?.(id) ?? Promise.resolve(void 0);
1936
+ return this.grepOne(name, path, true, read, async (content) => collectChunks(await smudgeContent(this.ctx.worktree?.contentFilter, path ?? "", content, mode)), id);
1937
+ }
1938
+ /** grep_cache */
1939
+ async grepCache(cached) {
1940
+ const entries = await this.ctx.entries?.() ?? [];
1941
+ let hit = false;
1942
+ for (let nr = 0; nr < entries.length; nr++) {
1943
+ const ce = entries[nr];
1944
+ if (!cached && ce.skipWorktree) continue;
1945
+ if (isRegular(ce.mode) && this.matches(ce.path)) {
1946
+ if (cached || ce.assumeValid) {
1947
+ if (ce.stage || ce.intentToAdd) continue;
1948
+ hit = await this.grepBlob(ce.objectId, this.sourceName(ce.path), ce.path, ce.mode) || hit;
1949
+ } else hit = await this.grepFile(ce.path, true) || hit;
1950
+ } else continue;
1951
+ if (ce.stage) while (nr + 1 < entries.length && entries[nr + 1]?.path === ce.path) nr++;
1952
+ if (hit && this.o.statusOnly) break;
1953
+ }
1954
+ return hit;
1955
+ }
1956
+ /** grep_objects */
1957
+ async grepObjects(objects) {
1958
+ const resolver = this.ctx.resolver?.();
1959
+ const work = [];
1960
+ const wanted = [];
1961
+ for (const object of objects) {
1962
+ const peeled = await resolver.peelTags(object.id).catch(() => void 0);
1963
+ if (!peeled || peeled.type === void 0) die(`invalid object '${object.name}' given.`);
1964
+ const { id, type } = peeled;
1965
+ if (type === "blob") {
1966
+ work.push(() => this.grepBlob(id, this.blobName(object.name), object.path));
1967
+ continue;
1968
+ }
1969
+ if (type !== "commit" && type !== "tree") die(`unable to grep from object of type ${type}`);
1970
+ const tree = await resolver.peelToType(id, "tree");
1971
+ if (!tree) die(`unable to read tree (${id})`);
1972
+ const files = [];
1973
+ await this.listTree(tree, "", files);
1974
+ const base = object.name ? `${object.name}:` : "";
1975
+ for (const f of files) wanted.push(f.id);
1976
+ work.push(async () => {
1977
+ let hit = false;
1978
+ for (const f of files) {
1979
+ hit = await this.grepBlob(f.id, this.sourceName(f.path, base), type === "commit" ? f.path : void 0, f.mode) || hit;
1980
+ if (hit && this.o.statusOnly) break;
1981
+ }
1982
+ return hit;
1983
+ });
1984
+ }
1985
+ if (wanted.length > 0) await this.ctx.prefetch?.(wanted);
1986
+ let hit = false;
1987
+ for (const w of work) if (await w()) {
1988
+ hit = true;
1989
+ if (this.o.statusOnly) break;
1990
+ }
1991
+ return hit;
1992
+ }
1993
+ /**
1994
+ * The name of a blob given on the command line: git's grep_oid names it as a path, so it is
1995
+ * relative to the prefix too (`../HEAD:./v` from `t/`)
1996
+ */
1997
+ blobName(name) {
1998
+ return this.sourceName(name);
1999
+ }
2000
+ /** grep_tree's walk: the regular files in tree order that the pathspec takes */
2001
+ async listTree(id, base, out) {
2002
+ const entries = await this.ctx.treeEntries?.(id) ?? [];
2003
+ for (const e of entries) {
2004
+ const path = base + e.name;
2005
+ if ((e.mode & S_IFMT) === 16384) await this.listTree(e.id, `${path}/`, out);
2006
+ else if (isRegular(e.mode) && this.matches(path)) out.push({
2007
+ path,
2008
+ id: e.id,
2009
+ mode: e.mode
2010
+ });
2011
+ }
2012
+ }
2013
+ /** grep_directory: fill_directory's files (index unread), sorted */
2014
+ async grepDirectory(exclude, useIndex) {
2015
+ const worktree = this.ctx.worktree;
2016
+ if (!worktree) return false;
2017
+ const files = [];
2018
+ const host = await worktree.untrackedScanHost?.();
2019
+ if (host) {
2020
+ const walk = async (dir) => {
2021
+ if (exclude) await host.loadIgnoreFile(dir);
2022
+ let listed;
2023
+ try {
2024
+ listed = await host.listDirectory(dir, false);
2025
+ } catch {
2026
+ return;
2027
+ }
2028
+ for (const entry of listed) {
2029
+ if (entry.name === ".git" || entry.name === "." || entry.name === "..") continue;
2030
+ const path = dir ? `${dir}/${entry.name}` : entry.name;
2031
+ const kind = entry.kind ?? (await host.lstat(path))?.kind;
2032
+ if (kind === "directory") {
2033
+ if (exclude && host.isExcluded(path, true)) continue;
2034
+ if (useIndex && await host.isNestedRepository(path)) continue;
2035
+ await walk(path);
2036
+ } else if (kind === "file" || kind === "symlink") {
2037
+ if (exclude && host.isExcluded(path, false)) continue;
2038
+ if (this.matches(path)) files.push(path);
2039
+ }
2040
+ }
2041
+ };
2042
+ await walk("");
2043
+ } else for await (const entry of worktree.walk({ includeIgnored: !exclude })) if (!entry.isDirectory && this.matches(entry.path)) files.push(entry.path);
2044
+ files.sort((a, b) => compareBytes(encodeGitPath(a), encodeGitPath(b)));
2045
+ let hit = false;
2046
+ for (const path of files) {
2047
+ hit = await this.grepFile(path, false) || hit;
2048
+ if (hit && this.o.statusOnly) break;
2049
+ }
2050
+ return hit;
2051
+ }
2052
+ };
2053
+ function compareBytes(a, b) {
2054
+ const n = Math.min(a.length, b.length);
2055
+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];
2056
+ return a.length - b.length;
2057
+ }
2058
+ /** The options a {@link GrepCommand} or {@link grepNoIndex} run starts from. */
2059
+ function emptyOptions() {
2060
+ return { tokens: [] };
2061
+ }
2062
+ /**
2063
+ * `git grep`. Patterns: {@link addPattern} (`-e`), {@link addPatternFile} (`-f`), with
2064
+ * {@link and}, {@link not}, {@link open}, {@link close} between them (`--or` is the default).
2065
+ * Where to search: {@link setArguments} (`[<rev>...] [[--] <path>...]` as git reads them),
2066
+ * {@link setCached}, {@link setUntracked}, {@link setNoIndex}. {@link call} resolves with
2067
+ * git's stdout and exit status, or throws `GrepError`/`GrepPatternError`/`RevisionError` with
2068
+ * git's line where it dies (exit status 128).
2069
+ */
2070
+ var GrepCommand = class extends GitCommand {
2071
+ options = emptyOptions();
2072
+ set(key, value) {
2073
+ this.checkCallable();
2074
+ this.options[key] = value;
2075
+ return this;
2076
+ }
2077
+ /** `-e <pattern>` (a string is taken as UTF-8) */
2078
+ addPattern(pattern, origin = "-e option") {
2079
+ this.checkCallable();
2080
+ this.options.tokens.push(grepPattern(pattern, origin));
2081
+ return this;
2082
+ }
2083
+ /** `-f <file>`: the file's content, one pattern per non-empty line; `name` as given */
2084
+ addPatternFile(content, name) {
2085
+ this.checkCallable();
2086
+ this.options.tokens.push(...grepPatternFile(content, name));
2087
+ return this;
2088
+ }
2089
+ /** `--and` */
2090
+ and() {
2091
+ return this.token({ kind: "and" });
2092
+ }
2093
+ /** `--not` */
2094
+ not() {
2095
+ return this.token({ kind: "not" });
2096
+ }
2097
+ /** `(` */
2098
+ open() {
2099
+ return this.token({ kind: "open" });
2100
+ }
2101
+ /** `)` */
2102
+ close() {
2103
+ return this.token({ kind: "close" });
2104
+ }
2105
+ token(t) {
2106
+ this.checkCallable();
2107
+ this.options.tokens.push(t);
2108
+ return this;
2109
+ }
2110
+ /** `--all-match` */
2111
+ setAllMatch(on) {
2112
+ return this.set("allMatch", on);
2113
+ }
2114
+ /** `-E` (`extended`), `-F` (`fixed`), `-G` (`basic`), `-P` (`perl`) */
2115
+ setPatternType(type) {
2116
+ return this.set("patternType", type);
2117
+ }
2118
+ /** `-i` */
2119
+ setIgnoreCase(on) {
2120
+ return this.set("ignoreCase", on);
2121
+ }
2122
+ /** `-w` */
2123
+ setWordRegexp(on) {
2124
+ return this.set("wordRegexp", on);
2125
+ }
2126
+ /** `-v` */
2127
+ setInvertMatch(on) {
2128
+ return this.set("invert", on);
2129
+ }
2130
+ /** `--cached` */
2131
+ setCached(on) {
2132
+ return this.set("cached", on);
2133
+ }
2134
+ /** `--untracked` */
2135
+ setUntracked(on) {
2136
+ return this.set("untracked", on);
2137
+ }
2138
+ /** `--no-index` */
2139
+ setNoIndex(on) {
2140
+ return this.set("noIndex", on);
2141
+ }
2142
+ /** `--exclude-standard` (true) / `--no-exclude-standard` (false) */
2143
+ setExcludeStandard(on) {
2144
+ return this.set("excludeStandard", on);
2145
+ }
2146
+ /** `--recurse-submodules`: refused (not supported yet) */
2147
+ setRecurseSubmodules(on) {
2148
+ return this.set("recurseSubmodules", on);
2149
+ }
2150
+ /**
2151
+ * The arguments after the pattern: revisions, then paths (`--` between them), checked as
2152
+ * git checks them (a path must exist without `--`, a revision must not also be a file)
2153
+ */
2154
+ setArguments(args) {
2155
+ return this.set("args", [...args]);
2156
+ }
2157
+ /** A revision or tree to search (`<rev>`, `<rev>:<path>`, a tree id) */
2158
+ addRevision(revision) {
2159
+ const args = this.options.args ?? [];
2160
+ const dd = args.indexOf("--");
2161
+ const revs = dd < 0 ? args : args.slice(0, dd);
2162
+ const paths = dd < 0 ? [] : args.slice(dd + 1);
2163
+ return this.set("args", [
2164
+ ...revs,
2165
+ revision,
2166
+ "--",
2167
+ ...paths
2168
+ ]);
2169
+ }
2170
+ /** Pathspecs (`-- <path>...`) */
2171
+ addPath(...paths) {
2172
+ const args = this.options.args ?? [];
2173
+ return this.set("args", args.includes("--") ? [...args, ...paths] : [
2174
+ ...args,
2175
+ "--",
2176
+ ...paths
2177
+ ]);
2178
+ }
2179
+ /** The current directory below the top (`sub/` or `sub`): names are relative to it */
2180
+ setPrefix(prefix) {
2181
+ const p = prefix.replace(/^\/+|\/+$/g, "");
2182
+ return this.set("prefix", p ? `${p}/` : "");
2183
+ }
2184
+ /** `--max-depth <n>` (-1: none) */
2185
+ setMaxDepth(depth) {
2186
+ return this.set("maxDepth", depth);
2187
+ }
2188
+ /** `-n` / `--no-line-number` (undefined: `grep.lineNumber`) */
2189
+ setLineNumber(on) {
2190
+ return this.set("lineNumber", on);
2191
+ }
2192
+ /** `--column` (undefined: `grep.column`) */
2193
+ setColumn(on) {
2194
+ return this.set("column", on);
2195
+ }
2196
+ /** `-H` (true) / `-h` (false) */
2197
+ setShowFilename(on) {
2198
+ return this.set("pathname", on);
2199
+ }
2200
+ /** `--full-name` (undefined: `grep.fullName`) */
2201
+ setFullName(on) {
2202
+ return this.set("fullName", on);
2203
+ }
2204
+ /** `-z` */
2205
+ setNull(on) {
2206
+ return this.set("nullFollowingName", on);
2207
+ }
2208
+ /** `-o` */
2209
+ setOnlyMatching(on) {
2210
+ return this.set("onlyMatching", on);
2211
+ }
2212
+ /** `-c` */
2213
+ setCount(on) {
2214
+ return this.set("count", on);
2215
+ }
2216
+ /** `-l` */
2217
+ setFilesWithMatches(on) {
2218
+ return this.set("nameOnly", on);
2219
+ }
2220
+ /** `-L` */
2221
+ setFilesWithoutMatch(on) {
2222
+ return this.set("unmatchNameOnly", on);
2223
+ }
2224
+ /** `-q` */
2225
+ setQuiet(on) {
2226
+ return this.set("statusOnly", on);
2227
+ }
2228
+ /** `--break` */
2229
+ setBreak(on) {
2230
+ return this.set("fileBreak", on);
2231
+ }
2232
+ /** `--heading` */
2233
+ setHeading(on) {
2234
+ return this.set("heading", on);
2235
+ }
2236
+ /** `-B <n>` */
2237
+ setBeforeContext(n) {
2238
+ return this.set("preContext", n);
2239
+ }
2240
+ /** `-A <n>` */
2241
+ setAfterContext(n) {
2242
+ return this.set("postContext", n);
2243
+ }
2244
+ /** `-C <n>` */
2245
+ setContext(n) {
2246
+ this.set("preContext", n);
2247
+ return this.set("postContext", n);
2248
+ }
2249
+ /** `-p` */
2250
+ setShowFunction(on) {
2251
+ return this.set("funcname", on);
2252
+ }
2253
+ /** `-W` */
2254
+ setFunctionContext(on) {
2255
+ return this.set("funcbody", on);
2256
+ }
2257
+ /** `-m <n>` (negative: no limit) */
2258
+ setMaxCount(n) {
2259
+ return this.set("maxCount", n);
2260
+ }
2261
+ /** `-a` (`text`), `-I` (`nomatch`) */
2262
+ setBinary(mode) {
2263
+ return this.set("binary", mode);
2264
+ }
2265
+ /** `--textconv` / `--no-textconv` */
2266
+ setTextconv(on) {
2267
+ return this.set("textconv", on);
2268
+ }
2269
+ /** `--color=always` (true), `--no-color` (false); undefined: `color.grep`/`color.ui` */
2270
+ setColor(on) {
2271
+ return this.set("color", on);
2272
+ }
2273
+ /**
2274
+ * `--threads <n>`: 1 prints as git's single-threaded grep, more (the default) as its
2275
+ * threaded one (a hunk mark before each file's context, the first output's first line
2276
+ * dropped)
2277
+ */
2278
+ setThreads(n) {
2279
+ return this.set("threads", n);
2280
+ }
2281
+ /** The git version to follow (`2.43` or `2.56`, the default); see `GrepEngineOptions` */
2282
+ setCompatibility(compatibility) {
2283
+ return this.set("compatibility", compatibility);
2284
+ }
2285
+ async call() {
2286
+ this.checkCallable();
2287
+ this.setCallable(false);
2288
+ const wc = this.workingCopy;
2289
+ const worktree = this.worktreeAccess;
2290
+ const get = (key) => configValue(wc, key);
2291
+ const runner = textconvRunnerOf(wc);
2292
+ const caches = new TextconvCaches(() => this.notesContext());
2293
+ return new GrepRun({
2294
+ worktree,
2295
+ config: get,
2296
+ repository: true,
2297
+ hostTop: worktree?.hostPath,
2298
+ entries: async () => {
2299
+ const out = [];
2300
+ for await (const e of this.staging.entries()) out.push(e);
2301
+ return out;
2302
+ },
2303
+ readBlob: async (id) => {
2304
+ const content = await this.blobs.load(id);
2305
+ return content ? collectChunks(content) : void 0;
2306
+ },
2307
+ prefetch: async (ids) => {
2308
+ const promisor = wc.history?.objects?.promisor;
2309
+ if (promisor?.hasPromisorRemote()) await promisor.prefetch(ids);
2310
+ },
2311
+ treeEntries: async (id) => (await this.treeEntries(id)).map((e) => ({
2312
+ name: e.name,
2313
+ mode: e.mode,
2314
+ id: e.id
2315
+ })),
2316
+ resolver: () => this.revisionResolver(),
2317
+ argumentFiles: (prefix) => this.argumentFiles(prefix),
2318
+ ...runner ? { textconv: (request, id) => caches.run(runner, request, id) } : {},
2319
+ inOneOperation: (fn) => this.inOneOperation(fn)
2320
+ }, this.options).run();
2321
+ }
2322
+ };
2323
+ /**
2324
+ * `git grep --no-index` outside a repository: the files of `worktree` (any `Worktree`, a
2325
+ * `FileWorktree` over the directory), read as git reads them without a repository. Options
2326
+ * are {@link GrepOptions} (`prefix` the current directory below `worktree`'s root);
2327
+ * `config` gives configuration values (the global and system files', if any).
2328
+ */
2329
+ async function grepNoIndex(worktree, options, config = () => void 0) {
2330
+ return new GrepRun({
2331
+ worktree,
2332
+ config,
2333
+ repository: false,
2334
+ hostTop: worktree.hostPath,
2335
+ argumentFiles: (prefix) => ({
2336
+ inWorktree: false,
2337
+ prefix,
2338
+ exists: async (path) => {
2339
+ const parts = [];
2340
+ for (const part of path.split("/")) {
2341
+ if (part === "" || part === ".") continue;
2342
+ if (part === "..") {
2343
+ if (parts.length === 0) return true;
2344
+ parts.pop();
2345
+ } else parts.push(part);
2346
+ }
2347
+ if (parts.length === 0) return true;
2348
+ return await worktree.getEntry(parts.join("/")) !== void 0;
2349
+ }
2350
+ }),
2351
+ inOneOperation: (fn) => worktree.batch ? worktree.batch(fn) : fn()
2352
+ }, {
2353
+ ...options,
2354
+ noIndex: true
2355
+ }).run();
2356
+ }
2357
+ //#endregion
2358
+ //#region src/commands/archive/zip-archive.ts
2359
+ /**
2360
+ * git's zip writer (archive-zip.c): a local header with the extended-timestamp extra field
2361
+ * per entry, the content deflated (raw deflate) unless storing it is smaller, streamed blobs
2362
+ * with a data descriptor, zip64 records past the 32-bit limits, the central directory, and
2363
+ * the commit id as the archive's comment.
2364
+ */
2365
+ const ZIP_STREAM = 8;
2366
+ const ZIP_UTF8 = 2048;
2367
+ const METHOD_STORE = 0;
2368
+ const METHOD_DEFLATE = 8;
2369
+ const EXTRA_MTIME_SIZE = 9;
2370
+ const ZIP64_EXTRA_SIZE = 20;
2371
+ const MAX32 = 4294967295;
2372
+ /** archive-zip.c's `STREAM_BUFFER_SIZE`: a streamed blob's reads. */
2373
+ const STREAM_BUFFER_SIZE = 16384;
2374
+ /** Little-endian fields appended to a buffer. */
2375
+ var LeWriter = class {
2376
+ out;
2377
+ constructor(out) {
2378
+ this.out = out;
2379
+ }
2380
+ scratch = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
2381
+ u16(n) {
2382
+ this.scratch.setUint16(0, n & 65535, true);
2383
+ this.out.push(new Uint8Array(this.scratch.buffer, 0, 2));
2384
+ }
2385
+ u32(n) {
2386
+ this.scratch.setUint32(0, n >>> 0, true);
2387
+ this.out.push(new Uint8Array(this.scratch.buffer, 0, 4));
2388
+ }
2389
+ u64(n) {
2390
+ this.scratch.setBigUint64(0, BigInt(n), true);
2391
+ this.out.push(new Uint8Array(this.scratch.buffer, 0, 8));
2392
+ }
2393
+ };
2394
+ const clamp32 = (n) => n < MAX32 ? n : MAX32;
2395
+ /** git's `has_only_ascii`. */
2396
+ function onlyAscii(path) {
2397
+ for (const b of path) if (b >= 128) return false;
2398
+ return true;
2399
+ }
2400
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
2401
+ /** git's `is_utf8`: valid UTF-8 without the noncharacters U+FFFE and U+FFFF. */
2402
+ function isUtf8(path) {
2403
+ let text;
2404
+ try {
2405
+ text = utf8.decode(path);
2406
+ } catch {
2407
+ return false;
2408
+ }
2409
+ return !text.includes("￾") && !text.includes("￿");
2410
+ }
2411
+ /** git's `dos_time`: the DOS date and time of `time` in local time. */
2412
+ function dosTime(time, localTzOffset = (t) => -(/* @__PURE__ */ new Date(t * 1e3)).getTimezoneOffset()) {
2413
+ const local = /* @__PURE__ */ new Date((time + localTzOffset(time) * 60) * 1e3);
2414
+ const date = local.getUTCDate() + (local.getUTCMonth() + 1) * 32 + (local.getUTCFullYear() - 1980) * 512;
2415
+ const dos = Math.floor(local.getUTCSeconds() / 2) + local.getUTCMinutes() * 32 + local.getUTCHours() * 2048;
2416
+ return {
2417
+ date: date & 65535,
2418
+ time: dos & 65535
2419
+ };
2420
+ }
2421
+ /** Writes git's zip archive (`git archive --format=zip`). */
2422
+ var ZipArchiveWriter = class {
2423
+ settings;
2424
+ sink;
2425
+ out;
2426
+ dir = new ByteBuffer(4096);
2427
+ le;
2428
+ dirLe = new LeWriter(this.dir);
2429
+ entries = 0;
2430
+ maxCreatorVersion = 0;
2431
+ dosDate;
2432
+ dosTimeOfDay;
2433
+ constructor(settings) {
2434
+ this.settings = settings;
2435
+ this.sink = new ArchiveSink(settings.output, 65536);
2436
+ this.out = this.sink.buffer;
2437
+ this.le = new LeWriter(this.out);
2438
+ const dos = dosTime(settings.time, settings.localTzOffset);
2439
+ this.dosDate = dos.date;
2440
+ this.dosTimeOfDay = dos.time;
2441
+ }
2442
+ /** `write_zip_entry`. */
2443
+ async entry(entry) {
2444
+ const { path, mode, id } = entry;
2445
+ const offset = this.sink.position;
2446
+ let flags = 0;
2447
+ let crc = 0;
2448
+ let isBinary;
2449
+ let creatorVersion = 0;
2450
+ let versionNeeded = 10;
2451
+ let method;
2452
+ let attr2;
2453
+ let out;
2454
+ let compressedSize;
2455
+ const streamed = entry.streamed === true && isRegMode(mode);
2456
+ const size = streamed && entry.stream ? entry.size ?? 0 : entry.content.length;
2457
+ if (!onlyAscii(path)) {
2458
+ if (isUtf8(path)) flags |= ZIP_UTF8;
2459
+ else this.settings.onWarning?.(`warning: path is not valid UTF-8: ${latin1$2(path)}`);
2460
+ }
2461
+ if (path.length > 65535) return `path too long (${path.length} chars, SHA1: ${id}): ${latin1$2(path)}`;
2462
+ if (isDirMode(mode) || isGitlinkMode(mode)) {
2463
+ method = METHOD_STORE;
2464
+ attr2 = 16;
2465
+ compressedSize = 0;
2466
+ } else if (isRegMode(mode) || isLinkMode(mode)) {
2467
+ method = METHOD_STORE;
2468
+ attr2 = isLinkMode(mode) ? (mode | 511) * 65536 : mode & 73 ? mode * 65536 : 0;
2469
+ if (isLinkMode(mode) || mode & 73) creatorVersion = 791;
2470
+ if (isRegMode(mode) && this.settings.compressionLevel !== 0 && size > 0) method = METHOD_DEFLATE;
2471
+ if (streamed) flags |= ZIP_STREAM;
2472
+ else {
2473
+ crc = crc32(entry.content);
2474
+ isBinary = entry.binary ?? bufferIsBinary(entry.content);
2475
+ out = entry.content;
2476
+ }
2477
+ compressedSize = method === METHOD_STORE ? size : 0;
2478
+ } else return `unsupported file mode: 0${mode.toString(8)} (SHA1: ${id})`;
2479
+ if (creatorVersion > this.maxCreatorVersion) this.maxCreatorVersion = creatorVersion;
2480
+ const level = this.settings.compressionLevel;
2481
+ if (!streamed && method === METHOD_DEFLATE) {
2482
+ const deflated = deflateSync([entry.content], {
2483
+ format: "raw",
2484
+ level
2485
+ });
2486
+ if (deflated.length >= size) {
2487
+ method = METHOD_STORE;
2488
+ compressedSize = size;
2489
+ } else {
2490
+ out = deflated;
2491
+ compressedSize = deflated.length;
2492
+ }
2493
+ }
2494
+ let needZip64 = size > MAX32 || compressedSize > MAX32;
2495
+ if (streamed && size > 2147483647) needZip64 = true;
2496
+ if (needZip64) versionNeeded = 45;
2497
+ const le = this.le;
2498
+ le.u32(67324752);
2499
+ le.u16(versionNeeded);
2500
+ le.u16(flags);
2501
+ le.u16(method);
2502
+ le.u16(this.dosTimeOfDay);
2503
+ le.u16(this.dosDate);
2504
+ le.u32(crc);
2505
+ if (needZip64) {
2506
+ le.u32(MAX32);
2507
+ le.u32(MAX32);
2508
+ } else {
2509
+ le.u32(compressedSize);
2510
+ le.u32(size);
2511
+ }
2512
+ le.u16(path.length);
2513
+ le.u16(EXTRA_MTIME_SIZE + (needZip64 ? ZIP64_EXTRA_SIZE : 0));
2514
+ this.out.push(path);
2515
+ const extra = new ByteBuffer(EXTRA_MTIME_SIZE);
2516
+ const extraLe = new LeWriter(extra);
2517
+ extraLe.u16(21589);
2518
+ extraLe.u16(5);
2519
+ extra.push(new Uint8Array([1]));
2520
+ extraLe.u32(this.settings.time);
2521
+ const extraBytes = extra.bytes().slice();
2522
+ this.out.push(extraBytes);
2523
+ if (needZip64) {
2524
+ le.u16(1);
2525
+ le.u16(16);
2526
+ le.u64(size);
2527
+ le.u64(compressedSize);
2528
+ }
2529
+ if (streamed) {
2530
+ const streamedOut = await this.writeStreamed(entry, size, method === METHOD_STORE, level);
2531
+ if (!streamedOut) return `cannot stream blob ${id}`;
2532
+ crc = streamedOut.crc;
2533
+ isBinary = streamedOut.isBinary;
2534
+ compressedSize = streamedOut.compressedSize;
2535
+ le.u32(134695760);
2536
+ le.u32(crc);
2537
+ if (size >= MAX32 || compressedSize >= MAX32) {
2538
+ le.u64(compressedSize);
2539
+ le.u64(size);
2540
+ } else {
2541
+ le.u32(compressedSize);
2542
+ le.u32(size);
2543
+ }
2544
+ } else if (compressedSize > 0 && out) await this.sink.write(out);
2545
+ let zip64DirPayload = 0;
2546
+ let dirExtraSize = EXTRA_MTIME_SIZE;
2547
+ if (compressedSize > MAX32 || size > MAX32 || offset > MAX32) {
2548
+ if (compressedSize >= MAX32) zip64DirPayload += 8;
2549
+ if (size >= MAX32) zip64DirPayload += 8;
2550
+ if (offset >= MAX32) zip64DirPayload += 8;
2551
+ dirExtraSize += 4 + zip64DirPayload;
2552
+ }
2553
+ const d = this.dirLe;
2554
+ d.u32(33639248);
2555
+ d.u16(creatorVersion);
2556
+ d.u16(versionNeeded);
2557
+ d.u16(flags);
2558
+ d.u16(method);
2559
+ d.u16(this.dosTimeOfDay);
2560
+ d.u16(this.dosDate);
2561
+ d.u32(crc);
2562
+ d.u32(clamp32(compressedSize));
2563
+ d.u32(clamp32(size));
2564
+ d.u16(path.length);
2565
+ d.u16(dirExtraSize);
2566
+ d.u16(0);
2567
+ d.u16(0);
2568
+ d.u16(isBinary === void 0 ? 0 : isBinary ? 0 : 1);
2569
+ d.u32(attr2);
2570
+ d.u32(clamp32(offset));
2571
+ this.dir.push(path);
2572
+ this.dir.push(extraBytes);
2573
+ if (zip64DirPayload) {
2574
+ d.u16(1);
2575
+ d.u16(zip64DirPayload);
2576
+ if (size >= MAX32) d.u64(size);
2577
+ if (compressedSize >= MAX32) d.u64(compressedSize);
2578
+ if (offset >= MAX32) d.u64(offset);
2579
+ }
2580
+ this.entries++;
2581
+ await this.sink.flush();
2582
+ }
2583
+ /**
2584
+ * A streamed blob's data (archive-zip.c's `stream` loops): the CRC-32 and the deflate
2585
+ * computed as it is read, `entry_is_binary` asked of its first read (16 KiB); undefined
2586
+ * when it cannot be read whole.
2587
+ */
2588
+ async writeStreamed(entry, size, store, level) {
2589
+ const crc = new CRC32();
2590
+ const deflater = store ? void 0 : createDeflater({
2591
+ format: "raw",
2592
+ level
2593
+ });
2594
+ const head = new ByteBuffer(STREAM_BUFFER_SIZE);
2595
+ let total = 0;
2596
+ let compressedSize = 0;
2597
+ const emit = async (chunks) => {
2598
+ for (const c of chunks) {
2599
+ compressedSize += c.length;
2600
+ await this.sink.write(c);
2601
+ }
2602
+ };
2603
+ try {
2604
+ for await (const chunk of entry.stream ?? [entry.content]) {
2605
+ if (total + chunk.length > size) return void 0;
2606
+ total += chunk.length;
2607
+ crc.update(chunk);
2608
+ if (head.length < STREAM_BUFFER_SIZE) head.push(chunk.subarray(0, STREAM_BUFFER_SIZE - head.length));
2609
+ if (deflater) await emit(deflater.push(chunk));
2610
+ else {
2611
+ compressedSize += chunk.length;
2612
+ await this.sink.write(chunk);
2613
+ }
2614
+ }
2615
+ } catch {
2616
+ return;
2617
+ }
2618
+ if (total !== size) return void 0;
2619
+ if (deflater) await emit(deflater.finish());
2620
+ return {
2621
+ crc: crc.getValue(),
2622
+ isBinary: entry.binary ?? bufferIsBinary(head.bytes()),
2623
+ compressedSize
2624
+ };
2625
+ }
2626
+ /** `write_zip_trailer`. */
2627
+ async finish() {
2628
+ const zipOffset = this.sink.position;
2629
+ const dirBytes = this.dir.bytes();
2630
+ const clamped = this.entries > 65535 || zipOffset > MAX32;
2631
+ this.out.push(dirBytes);
2632
+ const le = this.le;
2633
+ if (clamped) {
2634
+ le.u32(101075792);
2635
+ le.u64(44);
2636
+ le.u16(this.maxCreatorVersion);
2637
+ le.u16(45);
2638
+ le.u32(0);
2639
+ le.u32(0);
2640
+ le.u64(this.entries);
2641
+ le.u64(this.entries);
2642
+ le.u64(dirBytes.length);
2643
+ le.u64(zipOffset);
2644
+ le.u32(117853008);
2645
+ le.u32(0);
2646
+ le.u64(zipOffset + dirBytes.length);
2647
+ le.u32(1);
2648
+ }
2649
+ const commitId = this.settings.commitId;
2650
+ le.u32(101010256);
2651
+ le.u16(0);
2652
+ le.u16(0);
2653
+ le.u16(Math.min(this.entries, 65535));
2654
+ le.u16(Math.min(this.entries, 65535));
2655
+ le.u32(dirBytes.length);
2656
+ le.u32(clamp32(zipOffset));
2657
+ le.u16(commitId ? this.settings.hexLength ?? commitId.length : 0);
2658
+ if (commitId) this.out.push(asciiBytes(commitId));
2659
+ return this.sink.finish();
2660
+ }
2661
+ };
2662
+ /** Bytes as one character each (git prints paths as their bytes). */
2663
+ function latin1$2(bytes) {
2664
+ let s = "";
2665
+ for (const b of bytes) s += String.fromCharCode(b);
2666
+ return s;
2667
+ }
2668
+ //#endregion
2669
+ //#region src/commands/archive/archive-command.ts
2670
+ /** git's builtin gzip filter (`tar.tgz.command`, `tar.tar.gz.command`). */
2671
+ const INTERNAL_GZIP_COMMAND = "git archive gzip";
2672
+ /** How many bytes {@link ArchiveCommand.callStream} holds before the writer waits. */
2673
+ const STREAM_HIGH_WATER_MARK = 1 << 20;
2674
+ const USAGE = "usage: git archive [<options>] <tree-ish> [<path>...]\n or: git archive --list\n or: git archive --remote <repo> [--exec <cmd>] [<options>] <tree-ish> [<path>...]\n or: git archive --remote <repo> [--exec <cmd>] --list";
2675
+ /** git's default `core.bigFileThreshold` (512 MiB). */
2676
+ const DEFAULT_BIG_FILE_THRESHOLD$1 = 536870912;
2677
+ const EXPORT_ATTRS = ["export-ignore", "export-subst"];
2678
+ /** The attributes convert.c's `convert_attrs` reads. */
2679
+ const CONVERT_ATTRS = [
2680
+ "crlf",
2681
+ "ident",
2682
+ "filter",
2683
+ "eol",
2684
+ "text",
2685
+ "working-tree-encoding"
2686
+ ];
2687
+ /**
2688
+ * `git archive <tree-ish> [<path>...]`: the archive's bytes. Messages git prints on stderr
2689
+ * (`-v`'s paths, warnings) are in {@link getMessages}; where git dies, a {@link GitApiError}
2690
+ * carries its message and exit status.
2691
+ *
2692
+ * Deflated data (zip entries, `tgz`) comes from pako's zlib port, whose bytes differ from
2693
+ * the system zlib git links: the archives match git's byte for byte except for those
2694
+ * compressed streams (`-0` zips and tar archives match whole).
2695
+ */
2696
+ var ArchiveCommand = class extends GitCommand {
2697
+ tree;
2698
+ format;
2699
+ outputName;
2700
+ base = "";
2701
+ paths = [];
2702
+ extraFiles = [];
2703
+ mtime;
2704
+ compressionLevel = -1;
2705
+ verbose = false;
2706
+ worktreeAttributes = false;
2707
+ currentDirectory = "";
2708
+ filterRunner;
2709
+ streamFilterRunner;
2710
+ bigFileThreshold;
2711
+ userUmask = 18;
2712
+ localTzOffset;
2713
+ filterDrivers;
2714
+ compatibility = "2.56";
2715
+ messages = [];
2716
+ /** Run by upload-archive (`write_archive`'s `remote`): `allowUnreachable` its setting */
2717
+ uploadArchive;
2718
+ /** The tree-ish archived (a commit, a tag, a tree). */
2719
+ setTree(name) {
2720
+ this.checkCallable();
2721
+ this.tree = name;
2722
+ return this;
2723
+ }
2724
+ /** `--format=<fmt>`: `tar`, `zip`, `tgz`, `tar.gz` or a configured tar filter. */
2725
+ setFormat(format) {
2726
+ this.checkCallable();
2727
+ this.format = format;
2728
+ return this;
2729
+ }
2730
+ /**
2731
+ * `-o <file>`'s name: the format is inferred from its extension when none is set
2732
+ * (git's `archive_format_from_filename`). Nothing is written: the bytes are returned.
2733
+ */
2734
+ setOutputName(name) {
2735
+ this.checkCallable();
2736
+ this.outputName = name;
2737
+ return this;
2738
+ }
2739
+ /** `--prefix=<prefix>`: the last one prefixes the tree's paths, each one the added files after it. */
2740
+ setPrefix(prefix) {
2741
+ this.checkCallable();
2742
+ this.base = prefix;
2743
+ return this;
2744
+ }
2745
+ /**
2746
+ * `--add-file=<file>`: a file added under the current prefix and its base name, read as
2747
+ * git reads it: an absolute path as it stands, a relative one from the worktree's top (and
2748
+ * {@link setCurrentDirectory}), through the host environment (`GitHostEnvironment`'s
2749
+ * `realPath`/`hostFilesOf`: files outside the repository, symbolic links followed as
2750
+ * `stat` follows them), else from the worktree itself; git's `File not found` and `Not a
2751
+ * regular file` deaths. `content` gives its bytes instead.
2752
+ */
2753
+ addFile(path, content, options = {}) {
2754
+ this.checkCallable();
2755
+ this.extraFiles.push({
2756
+ path,
2757
+ base: this.base,
2758
+ virtual: false,
2759
+ ...content ? { content } : {},
2760
+ ...options.executable ? { executable: true } : {}
2761
+ });
2762
+ return this;
2763
+ }
2764
+ /** `--add-virtual-file=<path>:<content>` (a C-quoted path allowed, as git reads it). */
2765
+ addVirtualFile(spec) {
2766
+ this.checkCallable();
2767
+ const raw = pathToLatin1(spec);
2768
+ let path;
2769
+ let rest;
2770
+ if (raw.startsWith("\"")) {
2771
+ const unquoted = cUnquote(raw);
2772
+ if (!unquoted) throw new GitApiError(`fatal: unclosed quote: '${spec}'`);
2773
+ path = latin1ToPath(unquoted.name);
2774
+ rest = raw.slice(unquoted.end);
2775
+ if (!rest.startsWith(":")) throw new GitApiError(`fatal: missing colon: '${spec}'`);
2776
+ } else {
2777
+ const colon = raw.indexOf(":");
2778
+ if (colon < 0) throw new GitApiError(`fatal: missing colon: '${spec}'`);
2779
+ if (colon === 0) throw new GitApiError(`fatal: empty file name: '${spec}'`);
2780
+ path = latin1ToPath(raw.slice(0, colon));
2781
+ rest = raw.slice(colon);
2782
+ }
2783
+ const content = rest.slice(1).split("\0")[0];
2784
+ this.extraFiles.push({
2785
+ path,
2786
+ base: this.base,
2787
+ content: latin1ToBytes(content),
2788
+ virtual: true
2789
+ });
2790
+ return this;
2791
+ }
2792
+ /** A pathspec element (`git archive <tree-ish> <path>...`). */
2793
+ addPath(path) {
2794
+ this.checkCallable();
2795
+ this.paths.push(path);
2796
+ return this;
2797
+ }
2798
+ /** `--mtime=<time>`: the entries' time (git's approxidate). */
2799
+ setMtime(time) {
2800
+ this.checkCallable();
2801
+ this.mtime = time;
2802
+ return this;
2803
+ }
2804
+ /** `-<n>`: the compression level (zip: 0 to 9, tar filters: any). */
2805
+ setCompressionLevel(level) {
2806
+ this.checkCallable();
2807
+ if (!Number.isInteger(level) || level < 0) throw new RangeError(`bad compression level ${level}`);
2808
+ this.compressionLevel = level;
2809
+ return this;
2810
+ }
2811
+ /** `-v`: each path archived is reported in {@link getMessages}. */
2812
+ setVerbose(verbose) {
2813
+ this.checkCallable();
2814
+ this.verbose = verbose;
2815
+ return this;
2816
+ }
2817
+ /** `--worktree-attributes`: attributes read from the worktree (and the index), not the tree. */
2818
+ setWorktreeAttributes(on) {
2819
+ this.checkCallable();
2820
+ this.worktreeAttributes = on;
2821
+ return this;
2822
+ }
2823
+ /**
2824
+ * The directory git runs in, relative to the worktree's top (`git -C <dir> archive`):
2825
+ * only what lies below it is archived, its paths relative to it.
2826
+ */
2827
+ setCurrentDirectory(dir) {
2828
+ this.checkCallable();
2829
+ const trimmed = dir.replace(/^\/+|\/+$/g, "");
2830
+ this.currentDirectory = trimmed && trimmed !== "." ? `${trimmed}/` : "";
2831
+ return this;
2832
+ }
2833
+ /** Runs the tar filters' commands (git's shell); without it only the builtin gzip works. */
2834
+ setFilterRunner(runner) {
2835
+ this.checkCallable();
2836
+ this.filterRunner = runner;
2837
+ return this;
2838
+ }
2839
+ /**
2840
+ * Runs the tar filters' commands as pipes, the archive streamed through them (git's
2841
+ * `write_tar_filter_archive`); preferred over {@link setFilterRunner}, which is handed the
2842
+ * whole tar archive.
2843
+ */
2844
+ setStreamFilterRunner(runner) {
2845
+ this.checkCallable();
2846
+ this.streamFilterRunner = runner;
2847
+ return this;
2848
+ }
2849
+ /** The umask `tar.umask=user` stands for (default 022). */
2850
+ setUserUmask(umask) {
2851
+ this.checkCallable();
2852
+ this.userUmask = umask;
2853
+ return this;
2854
+ }
2855
+ /** The local time zone (zip's DOS times): its offset east of UTC in minutes at a time. */
2856
+ setLocalTimezone(offset) {
2857
+ this.checkCallable();
2858
+ this.localTzOffset = offset;
2859
+ return this;
2860
+ }
2861
+ /**
2862
+ * The git version whose behaviour to follow (default 2.56): 2.43 ends a tree holding a
2863
+ * path `verify_path` refuses with the `error:` line alone and exit 255, 2.5x adds
2864
+ * `fatal: failed to unpack tree object <tree>` (exit 128).
2865
+ */
2866
+ setCompatibility(version) {
2867
+ this.checkCallable();
2868
+ this.compatibility = version;
2869
+ return this;
2870
+ }
2871
+ /**
2872
+ * What git printed on stderr (`-v`'s paths, warnings), from the `from`th message on: read
2873
+ * while {@link callStream} runs, the messages so far (upload-archive sends them on as they
2874
+ * come).
2875
+ */
2876
+ getMessages(from = 0) {
2877
+ return this.messages.slice(from);
2878
+ }
2879
+ /** `git archive --list`: the formats, as git lists them. */
2880
+ listFormats() {
2881
+ this.checkTarConfig();
2882
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
2883
+ return this.archivers().map((a) => a.name);
2884
+ }
2885
+ /**
2886
+ * Runs the command as git's upload-archive runs it for `git archive --remote` (its
2887
+ * `upload-archive--writer`): only formats served remotely (tar, zip, the tar filters with
2888
+ * `tar.<format>.remote`, by default `tgz` and `tar.gz`), and, unless `allowUnreachable`
2889
+ * (`uploadarchive.allowUnreachable`), only a tree-ish a ref names (`no such ref: <name>`).
2890
+ * See {@link runArchiveWriter}.
2891
+ */
2892
+ setUploadArchive(options) {
2893
+ this.checkCallable();
2894
+ this.uploadArchive = { allowUnreachable: options.allowUnreachable };
2895
+ return this;
2896
+ }
2897
+ /**
2898
+ * The format `name`'s extension names (archive.c's `archive_format_from_filename`: the
2899
+ * archivers of this repository's configuration), or undefined.
2900
+ */
2901
+ formatFromFilename(name) {
2902
+ return this.archivers().find((a) => matchExtension(name, a.name))?.name;
2903
+ }
2904
+ /**
2905
+ * The archivers in git's registration order: tar, the tar filters, zip; upload-archive's
2906
+ * only those served remotely.
2907
+ */
2908
+ archivers() {
2909
+ const filters = /* @__PURE__ */ new Map();
2910
+ const define = (name, command, remote) => {
2911
+ const known = filters.get(name) ?? { name };
2912
+ if (command !== void 0) known.command = command;
2913
+ if (remote !== void 0) known.remote = remote;
2914
+ filters.set(name, known);
2915
+ };
2916
+ define("tgz", INTERNAL_GZIP_COMMAND, true);
2917
+ define("tar.gz", INTERNAL_GZIP_COMMAND, true);
2918
+ for (const { key, value } of this.tarConfig()) {
2919
+ const last = key.lastIndexOf(".");
2920
+ const name = key.slice(4, last);
2921
+ if (last <= 4 || !name) continue;
2922
+ const type = key.slice(last + 1);
2923
+ if (type === "command") {
2924
+ if (value !== void 0) define(name, value);
2925
+ } else if (type === "remote") {
2926
+ const remote = value === void 0 ? true : parseGitBool$1(value);
2927
+ if (remote === void 0) throw new GitApiError(`fatal: bad boolean config value '${value}' for '${key}'`);
2928
+ define(name, void 0, remote);
2929
+ }
2930
+ }
2931
+ const all = [
2932
+ {
2933
+ name: "tar",
2934
+ remote: true
2935
+ },
2936
+ ...[...filters.values()].filter((a) => a.command !== void 0),
2937
+ {
2938
+ name: "zip",
2939
+ remote: true
2940
+ }
2941
+ ];
2942
+ return this.uploadArchive ? all.filter((a) => a.remote) : all;
2943
+ }
2944
+ /** The `tar.*` variables in configuration order, with where each was read. */
2945
+ tarConfig() {
2946
+ return RemoteConfigStore.from(this._workingCopy).entriesWithPrefix("tar.") ?? [];
2947
+ }
2948
+ /**
2949
+ * `init_tar_archiver`'s `git_config(git_tar_config)`, which every `git archive` runs
2950
+ * first (`--list` and zip included): the first variable it refuses, in configuration
2951
+ * order, dies (a `tar.<format>.command` without a value, a `tar.umask` that is no number).
2952
+ */
2953
+ checkTarConfig() {
2954
+ this.tarUmask();
2955
+ }
2956
+ /** `tar.umask`, the tar config's deaths checked on the way. */
2957
+ tarUmask() {
2958
+ let umask = 2;
2959
+ for (const { key, value, file, line } of this.tarConfig()) {
2960
+ const last = key.lastIndexOf(".");
2961
+ if (last > 4 && key.slice(last + 1) === "command" && value === void 0) {
2962
+ const fatal = file !== void 0 && line !== void 0 ? `fatal: bad config variable '${key}' in file '${file}' at line ${line}` : `fatal: unable to parse '${key}' from command-line config`;
2963
+ throw new GitApiError(`error: missing value for '${key}'\n${fatal}`);
2964
+ }
2965
+ if (key !== "tar.umask") continue;
2966
+ if (value === "user") umask = this.userUmask;
2967
+ else {
2968
+ const n = parseGitInt$1(value ?? "");
2969
+ if (n === void 0) {
2970
+ const where = file !== void 0 ? ` in file ${file}` : "";
2971
+ throw new GitApiError(`fatal: bad numeric config value '${value ?? ""}' for 'tar.umask'${where}: invalid unit`);
2972
+ }
2973
+ umask = n;
2974
+ }
2975
+ }
2976
+ return umask;
2977
+ }
2978
+ /**
2979
+ * `core.bigFileThreshold` (git's `unsigned long`, default 512 MiB): git 2.43 reads it with
2980
+ * the core settings when it starts (every value in order, the first it refuses dying), 2.5x
2981
+ * at the first regular file it archives (the last value only).
2982
+ *
2983
+ * @internal
2984
+ */
2985
+ archiveBigFileThreshold() {
2986
+ if (this.bigFileThreshold !== void 0) return this.bigFileThreshold;
2987
+ const key = "core.bigfilethreshold";
2988
+ const values = RemoteConfigStore.from(this._workingCopy).valuesWithOrigin(key);
2989
+ let threshold = DEFAULT_BIG_FILE_THRESHOLD$1;
2990
+ const checked = this.compatibility === "2.43" ? values : values.slice(-1);
2991
+ for (const { text, file } of checked) {
2992
+ const n = parseGitUlong(text);
2993
+ if (typeof n !== "number") {
2994
+ const where = file !== void 0 ? ` in file ${file}` : "";
2995
+ throw new GitApiError(`fatal: bad numeric config value '${text ?? ""}' for '${key}'${where}: ${n}`);
2996
+ }
2997
+ threshold = n;
2998
+ }
2999
+ this.bigFileThreshold = threshold;
3000
+ return threshold;
3001
+ }
3002
+ /** The archive's bytes. */
3003
+ async call() {
3004
+ this.checkCallable();
3005
+ this.setCallable(false);
3006
+ const chunks = [];
3007
+ await this.produce((chunk) => {
3008
+ chunks.push(chunk);
3009
+ });
3010
+ return join(chunks);
3011
+ }
3012
+ /**
3013
+ * The archive's bytes as they are written, in chunks of about 64 KiB, the same bytes
3014
+ * {@link call} returns: blobs above `core.bigFileThreshold` are streamed from the store
3015
+ * and never held whole, and a tar filter (the builtin gzip, or a command through
3016
+ * {@link setStreamFilterRunner}) filters as the archive is written. The writer waits while
3017
+ * a mebibyte is unread. Nothing runs until the iteration starts; where git dies the
3018
+ * iteration throws a {@link GitApiError} (after the bytes git would have written).
3019
+ *
3020
+ * @example
3021
+ * ```typescript
3022
+ * for await (const chunk of git.archive().setFormat("zip").setTree("HEAD").callStream()) {
3023
+ * await sink.write(chunk);
3024
+ * }
3025
+ * ```
3026
+ */
3027
+ callStream() {
3028
+ this.checkCallable();
3029
+ this.setCallable(false);
3030
+ const queue = createByteQueue({
3031
+ highWaterMark: STREAM_HIGH_WATER_MARK,
3032
+ coalesce: 0
3033
+ });
3034
+ let started = false;
3035
+ const start = () => {
3036
+ if (started) return;
3037
+ started = true;
3038
+ this.produce((chunk) => queue.push(chunk)).then(() => queue.end(), (error) => queue.end(error instanceof Error ? error : new Error(String(error))));
3039
+ };
3040
+ return { [Symbol.asyncIterator]() {
3041
+ start();
3042
+ return queue.stream;
3043
+ } };
3044
+ }
3045
+ /** `write_archive`: the archive written to `output`. */
3046
+ async produce(output) {
3047
+ this.checkTarConfig();
3048
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
3049
+ const extras = await this.readExtraFiles();
3050
+ let format = this.format;
3051
+ if (format === void 0 && this.outputName !== void 0) format = this.formatFromFilename(this.outputName);
3052
+ format ??= "tar";
3053
+ if (this.tree === void 0) throw new GitApiError(USAGE, { exitCode: 129 });
3054
+ const archiver = this.archivers().find((a) => a.name === format);
3055
+ if (!archiver) throw new GitApiError(`fatal: Unknown archive format '${format}'`);
3056
+ let level = -1;
3057
+ if (this.compressionLevel !== -1) {
3058
+ const levelsOk = archiver.name !== "tar";
3059
+ const highOk = archiver.command !== void 0;
3060
+ if (levelsOk && (this.compressionLevel <= 9 || highOk)) level = this.compressionLevel;
3061
+ else throw new GitApiError(`fatal: Argument not supported for format '${format}': -${this.compressionLevel}`);
3062
+ }
3063
+ await this.inOneOperation(async () => {
3064
+ const target = await this.resolveTreeish(this.tree);
3065
+ const filter = archiver.command === void 0 ? void 0 : this.openFilter(archiver.command, level, output);
3066
+ const settings = {
3067
+ time: target.time,
3068
+ compressionLevel: level,
3069
+ output: filter?.input ?? output,
3070
+ ...target.commitId ? { commitId: target.commitId } : {}
3071
+ };
3072
+ const writer = archiver.name === "zip" ? new ZipArchiveWriter({
3073
+ ...settings,
3074
+ hexLength: this.objectFormat.hexLength,
3075
+ ...this.localTzOffset ? { localTzOffset: this.localTzOffset } : {},
3076
+ onWarning: (m) => this.messages.push(m)
3077
+ }) : new TarArchiveWriter({
3078
+ ...settings,
3079
+ umask: this.tarUmask()
3080
+ });
3081
+ const run = new ArchiveRun(this, target, writer, extras);
3082
+ await withTreePathRefusal(this.trees, [target.tree], worktreePathRules(this._workingCopy), async () => {
3083
+ await run.prepare();
3084
+ await run.writeEntries();
3085
+ }, (refusal) => refusal instanceof InvalidPathError ? new GitApiError(refusal.message, { exitCode: 255 }) : refusal);
3086
+ await writer.finish();
3087
+ await filter?.finish();
3088
+ });
3089
+ }
3090
+ /**
3091
+ * `write_tar_filter_archive`: the tar archive's bytes through the filter (the builtin
3092
+ * gzip, else the command, started before anything is written).
3093
+ */
3094
+ openFilter(command, level, output) {
3095
+ if (command === "git archive gzip") {
3096
+ if (level > 9) throw new GitApiError("fatal: deflateInit2: stream consistency error (no message)");
3097
+ const deflater = createDeflater({
3098
+ format: "gzip",
3099
+ level
3100
+ });
3101
+ const send = async (chunks) => {
3102
+ for (const chunk of chunks) await output(chunk);
3103
+ };
3104
+ return {
3105
+ input: (chunk) => send(deflater.push(chunk)),
3106
+ finish: () => send(deflater.finish())
3107
+ };
3108
+ }
3109
+ const cmd = level >= 0 ? `${command} -${level}` : command;
3110
+ if (!cmd) throw new GitApiError("fatal: unable to start '' filter: No such file or directory");
3111
+ const failed = () => new GitApiError(`fatal: '${cmd}' filter reported error`);
3112
+ const streamRunner = this.streamFilterRunner;
3113
+ if (streamRunner) {
3114
+ const queue = createByteQueue({
3115
+ highWaterMark: STREAM_HIGH_WATER_MARK,
3116
+ coalesce: 0
3117
+ });
3118
+ let failure;
3119
+ const pump = (async () => {
3120
+ try {
3121
+ for await (const chunk of streamRunner(cmd, queue.stream)) await output(chunk);
3122
+ } catch {
3123
+ failure = failed();
3124
+ queue.end(failure);
3125
+ }
3126
+ })();
3127
+ return {
3128
+ input: async (chunk) => {
3129
+ if (failure) throw failure;
3130
+ try {
3131
+ await queue.push(chunk);
3132
+ } catch (error) {
3133
+ throw failure ?? error;
3134
+ }
3135
+ },
3136
+ finish: async () => {
3137
+ queue.end();
3138
+ await pump;
3139
+ if (failure) throw failure;
3140
+ }
3141
+ };
3142
+ }
3143
+ const runner = this.filterRunner;
3144
+ if (!runner) throw new GitApiError(`fatal: unable to start '${cmd}' filter`);
3145
+ const chunks = [];
3146
+ return {
3147
+ input: (chunk) => {
3148
+ chunks.push(chunk);
3149
+ },
3150
+ finish: async () => {
3151
+ let filtered;
3152
+ try {
3153
+ filtered = await runner(cmd, join(chunks));
3154
+ } catch {
3155
+ throw failed();
3156
+ }
3157
+ await output(filtered);
3158
+ }
3159
+ };
3160
+ }
3161
+ /**
3162
+ * `--add-file`'s files checked as git stats them while parsing its options (their content
3163
+ * is read when they are written).
3164
+ */
3165
+ async readExtraFiles() {
3166
+ const out = [];
3167
+ for (const extra of this.extraFiles) {
3168
+ const path = !extra.virtual && extra.path.startsWith("/") ? extra.path : `${this.currentDirectory}${extra.path}`;
3169
+ if (extra.content) {
3170
+ const content = extra.content;
3171
+ out.push({
3172
+ path,
3173
+ base: extra.base,
3174
+ read: async () => content,
3175
+ mode: extra.executable ? 33261 : 33188,
3176
+ virtual: extra.virtual
3177
+ });
3178
+ continue;
3179
+ }
3180
+ const host = await this.hostExtraFile(path);
3181
+ if (host === "missing") throw new GitApiError(`fatal: File not found: ${path}`);
3182
+ if (host === "not-regular") throw new GitApiError(`fatal: Not a regular file: ${path}`);
3183
+ if (host) {
3184
+ out.push({
3185
+ path,
3186
+ base: extra.base,
3187
+ read: host.read,
3188
+ mode: host.mode,
3189
+ virtual: false
3190
+ });
3191
+ continue;
3192
+ }
3193
+ const worktree = this.worktreeAccess;
3194
+ const resolved = normalizeWorktreePath(path);
3195
+ const entry = resolved === void 0 ? void 0 : await worktree?.getEntry(resolved).catch(() => void 0);
3196
+ if (!entry) throw new GitApiError(`fatal: File not found: ${path}`);
3197
+ if (entry.isDirectory || (entry.mode & 61440) !== 32768) throw new GitApiError(`fatal: Not a regular file: ${path}`);
3198
+ out.push({
3199
+ path,
3200
+ base: extra.base,
3201
+ read: async () => {
3202
+ const chunks = [];
3203
+ for await (const c of worktree.readContent(resolved)) chunks.push(c);
3204
+ return join(chunks);
3205
+ },
3206
+ mode: entry.mode & 64 ? 33261 : 33188,
3207
+ virtual: false
3208
+ });
3209
+ }
3210
+ return out;
3211
+ }
3212
+ /**
3213
+ * `--add-file`'s `stat` through the host environment: the path from the worktree's top
3214
+ * (a bare repository's git directory), links followed (`realPath`), the file read through
3215
+ * `hostFilesOf`; undefined when the host gives no access to its files (the worktree is
3216
+ * read instead).
3217
+ */
3218
+ async hostExtraFile(path) {
3219
+ const environment = hostEnvironmentOf(this._workingCopy);
3220
+ if (!environment?.hostFilesOf) return void 0;
3221
+ let top;
3222
+ if (!path.startsWith("/")) {
3223
+ top = this.archiveWorktree?.hostPath ?? this._workingCopy.config?.hostGitDir;
3224
+ if (top === void 0) return void 0;
3225
+ }
3226
+ const hostPath = top === void 0 ? path : `${top.replace(/\/+$/, "")}/${path}`;
3227
+ const real = environment.realPath ? await environment.realPath(hostPath).catch(() => void 0) : hostPath;
3228
+ if (real === void 0) return "missing";
3229
+ const location = await environment.hostFilesOf(real).catch(() => void 0);
3230
+ if (!location) return void 0;
3231
+ const stats = (environment.statFile ? await environment.statFile(real).catch(() => void 0) : void 0) ?? await location.files.stats(location.path).catch(() => void 0);
3232
+ if (!stats) return "missing";
3233
+ if (stats.kind !== "file") return "not-regular";
3234
+ const { files, path: inFiles } = location;
3235
+ return {
3236
+ mode: (stats.mode ?? 420) & 64 ? 33261 : 33188,
3237
+ read: async () => {
3238
+ const chunks = [];
3239
+ try {
3240
+ for await (const c of files.read(inFiles)) chunks.push(c);
3241
+ } catch {
3242
+ throw new GitApiError(`error: cannot read '${path}'`, { exitCode: 255 });
3243
+ }
3244
+ return join(chunks);
3245
+ }
3246
+ };
3247
+ }
3248
+ /** `parse_treeish_arg`: the tree, the commit (if any) and the archive's time. */
3249
+ async resolveTreeish(name) {
3250
+ const resolver = this.revisionResolver();
3251
+ if (this.uploadArchive && !this.uploadArchive.allowUnreachable) {
3252
+ const colon = name.indexOf(":");
3253
+ const refName = colon < 0 ? name : name.slice(0, colon);
3254
+ if ((await resolver.dwimRef(refName).catch(() => [])).length === 0) throw new GitApiError(`fatal: no such ref: ${refName}`);
3255
+ }
3256
+ const id = await resolver.resolve(name).catch(() => void 0);
3257
+ if (id === void 0) throw new GitApiError(`fatal: not a valid object name: ${name}`);
3258
+ const colon = name.indexOf(":");
3259
+ const refName = this.uploadArchive && !this.uploadArchive.allowUnreachable && colon >= 0 ? name.slice(0, colon) : name;
3260
+ const ref = (await resolver.dwimRef(refName).catch(() => []))[0]?.ref;
3261
+ const peeled = await resolver.peelTags(id);
3262
+ let commitId;
3263
+ let time;
3264
+ if (peeled.type === "commit") {
3265
+ commitId = peeled.id;
3266
+ time = (await this.commits.load(commitId))?.committer.timestamp ?? 0;
3267
+ } else time = this.clock();
3268
+ if (this.mtime !== void 0) time = approxidateCareful(this.mtime, this.clock()).timestamp;
3269
+ const tree = await resolver.peelToType(id, "tree").catch(() => void 0);
3270
+ if (tree === void 0) throw new GitApiError(`fatal: not a tree object: ${id}`);
3271
+ if (!this.worktreeAttributes) {
3272
+ const refusal = await treePathRefusal(this.trees, tree, worktreePathRules(this._workingCopy));
3273
+ if (refusal instanceof InvalidPathError) {
3274
+ if (this.compatibility === "2.43") throw new GitApiError(refusal.message, { exitCode: 255 });
3275
+ throw new GitApiError(`${refusal.message}\nfatal: failed to unpack tree object ${tree}`, { exitCode: 128 });
3276
+ }
3277
+ if (refusal) throw refusal;
3278
+ }
3279
+ return {
3280
+ tree,
3281
+ time,
3282
+ ...commitId ? { commitId } : {},
3283
+ ...ref ? { ref } : {}
3284
+ };
3285
+ }
3286
+ /** @internal */
3287
+ get archiveWorktree() {
3288
+ return "worktree" in this._workingCopy ? this.worktreeAccess : void 0;
3289
+ }
3290
+ /** @internal */
3291
+ archiveSettings() {
3292
+ return {
3293
+ base: this.base,
3294
+ paths: this.paths,
3295
+ verbose: this.verbose,
3296
+ worktreeAttributes: this.worktreeAttributes,
3297
+ currentDirectory: this.currentDirectory,
3298
+ messages: this.messages
3299
+ };
3300
+ }
3301
+ /** @internal */
3302
+ archiveEntries(id) {
3303
+ return this.treeEntries(id);
3304
+ }
3305
+ /** @internal The size of a blob (`oid_object_info`), undefined when it cannot be read. */
3306
+ archiveBlobSize(id) {
3307
+ return this.blobs.size(id).catch(() => void 0);
3308
+ }
3309
+ /** @internal A blob's bytes as the store reads them (`open_istream`). */
3310
+ async archiveBlobStream(id) {
3311
+ return await this.blobs.load(id).catch(() => void 0) ?? void 0;
3312
+ }
3313
+ /** @internal */
3314
+ archiveCompatibility() {
3315
+ return this.compatibility;
3316
+ }
3317
+ /** @internal */
3318
+ async archiveBlob(id) {
3319
+ const content = await this.blobs.load(id).catch(() => void 0);
3320
+ if (!content) return void 0;
3321
+ const chunks = [];
3322
+ try {
3323
+ for await (const c of content) chunks.push(c);
3324
+ } catch {
3325
+ return;
3326
+ }
3327
+ return join(chunks);
3328
+ }
3329
+ /**
3330
+ * The host's filter drivers (`filter=<name>`) for a repository without a worktree; a
3331
+ * worktree's content filter brings its own.
3332
+ */
3333
+ setFilterDrivers(drivers) {
3334
+ this.checkCallable();
3335
+ this.filterDrivers = drivers;
3336
+ return this;
3337
+ }
3338
+ /** @internal */
3339
+ archiveDrivers() {
3340
+ return this.filterDrivers;
3341
+ }
3342
+ /** @internal */
3343
+ archiveConfigObject() {
3344
+ return this._workingCopy.config;
3345
+ }
3346
+ /** @internal */
3347
+ archiveConfig(key) {
3348
+ return configValue(this._workingCopy, key);
3349
+ }
3350
+ /**
3351
+ * @internal The attributes git reads without a worktree (bare, or `GIT_ATTR_INDEX`). git
3352
+ * 2.43 reads a bare repository's in-tree files from HEAD when no attribute source is set
3353
+ * (2.5x reads none): `--worktree-attributes` in a bare repository sees them there.
3354
+ */
3355
+ archiveBareAttributes(indexTree) {
3356
+ return bareAttributesResolver({
3357
+ workingCopy: this._workingCopy,
3358
+ trees: this.trees,
3359
+ blobs: this.blobs,
3360
+ revisions: () => this.revisionResolver(),
3361
+ ...indexTree ? { indexTree } : {},
3362
+ ...this.compatibility === "2.43" && !("worktree" in this._workingCopy) ? { defaultSource: "HEAD" } : {}
3363
+ });
3364
+ }
3365
+ /** @internal `%h` and friends, `%(describe)`, for `export-subst`. */
3366
+ async archiveSubstitute(format, commitId, describe) {
3367
+ const commit = await this.commits.load(commitId);
3368
+ if (!commit) return "";
3369
+ const abbreviator = createIdAbbreviator(this._workingCopy);
3370
+ const abbreviate = async (id, length) => {
3371
+ if (length === 0) return id;
3372
+ const lengths = await abbreviator.lengths([id], length);
3373
+ return id.slice(0, lengths.get(id) ?? 7);
3374
+ };
3375
+ const tags = this.tagsStore;
3376
+ return formatCommitPretty(format, commit, commitId, {
3377
+ now: this.clock(),
3378
+ abbreviate: (id) => abbreviate(id),
3379
+ ...describe ? { describe: createDescriber({
3380
+ refs: this.refsStore,
3381
+ ...tags ? { tags } : {},
3382
+ commits: this.commits,
3383
+ abbreviate
3384
+ }) } : {}
3385
+ });
3386
+ }
3387
+ /** @internal */
3388
+ get archiveTreeLookup() {
3389
+ return this.trees;
3390
+ }
3391
+ };
3392
+ /** git's `match_extension`: `<name>.<ext>`, the name not empty. */
3393
+ function matchExtension(filename, ext) {
3394
+ const prefixlen = filename.length - ext.length;
3395
+ if (prefixlen < 2 || filename[prefixlen - 1] !== ".") return false;
3396
+ return filename.slice(prefixlen) === ext;
3397
+ }
3398
+ function join(chunks) {
3399
+ if (chunks.length === 1) return chunks[0];
3400
+ if (chunks.length === 0) return /* @__PURE__ */ new Uint8Array(0);
3401
+ let size = 0;
3402
+ for (const c of chunks) size += c.length;
3403
+ const out = new Uint8Array(size);
3404
+ let at = 0;
3405
+ for (const c of chunks) {
3406
+ out.set(c, at);
3407
+ at += c.length;
3408
+ }
3409
+ return out;
3410
+ }
3411
+ /**
3412
+ * A worktree path with `.`, `..` and empty components resolved; undefined when it climbs
3413
+ * above the top (reached only through the host's file system, which the worktree does not
3414
+ * give: pass such files to `addFile` with their content).
3415
+ */
3416
+ function normalizeWorktreePath(path) {
3417
+ const out = [];
3418
+ for (const part of path.split("/")) {
3419
+ if (part === "" || part === ".") continue;
3420
+ if (part === "..") {
3421
+ if (out.length === 0) return void 0;
3422
+ out.pop();
3423
+ } else out.push(part);
3424
+ }
3425
+ return out.join("/");
3426
+ }
3427
+ /** The base name of a path (`basename`). */
3428
+ function baseName(path) {
3429
+ const trimmed = path.replace(/\/+$/, "");
3430
+ const slash = trimmed.lastIndexOf("/");
3431
+ return slash < 0 ? trimmed : trimmed.slice(slash + 1);
3432
+ }
3433
+ /** The pathspec elements as git reads them from `prefix` (`PATHSPEC_PREFER_CWD`). */
3434
+ function prefixedElement(elem, prefix) {
3435
+ if (!prefix) return elem;
3436
+ if (elem.startsWith(":(")) {
3437
+ const close = elem.indexOf(")");
3438
+ if (close < 0) return elem;
3439
+ if (elem.slice(2, close).split(",").includes("top")) return elem;
3440
+ return `${elem.slice(0, close + 1)}${prefix}${elem.slice(close + 1)}`;
3441
+ }
3442
+ if (elem.startsWith(":/")) return elem;
3443
+ if (elem.startsWith(":!") || elem.startsWith(":^")) return `${elem.slice(0, 2)}${prefix}${elem.slice(2)}`;
3444
+ return `${prefix}${elem}`;
3445
+ }
3446
+ /** One `write_archive`: the tree walked, its entries filtered and handed to the writer. */
3447
+ var ArchiveRun = class {
3448
+ cmd;
3449
+ target;
3450
+ writer;
3451
+ extras;
3452
+ settings;
3453
+ pathspec = [];
3454
+ attrCache = /* @__PURE__ */ new Map();
3455
+ bareResolver;
3456
+ filterContext;
3457
+ describeBudget = 1;
3458
+ conversionSettings;
3459
+ base;
3460
+ baseText;
3461
+ constructor(cmd, target, writer, extras) {
3462
+ this.cmd = cmd;
3463
+ this.target = target;
3464
+ this.writer = writer;
3465
+ this.extras = extras;
3466
+ this.settings = cmd.archiveSettings();
3467
+ this.baseText = this.settings.base;
3468
+ this.base = encodeGitPath(this.baseText);
3469
+ }
3470
+ get worktree() {
3471
+ return this.cmd.archiveWorktree;
3472
+ }
3473
+ /** `parse_pathspec_arg` and the attribute sources. */
3474
+ async prepare() {
3475
+ const worktree = this.worktree;
3476
+ if (!this.settings.worktreeAttributes) {
3477
+ if (worktree?.contentFilter) this.filterContext = {
3478
+ direction: "index",
3479
+ index: attributesIndexOfTree(this.cmd.archiveTreeLookup, this.target.tree)
3480
+ };
3481
+ else this.bareResolver = this.cmd.archiveBareAttributes(this.target.tree);
3482
+ } else if (!worktree?.contentFilter) this.bareResolver = this.cmd.archiveBareAttributes(void 0);
3483
+ else this.filterContext = { direction: "checkin" };
3484
+ const prefix = this.settings.currentDirectory;
3485
+ const given = this.settings.paths;
3486
+ const elements = given.length > 0 ? given.map((p) => prefixedElement(p, prefix)) : prefix ? [prefix] : [];
3487
+ this.pathspec = this.parse(elements);
3488
+ for (let i = 0; i < given.length; i++) {
3489
+ const original = given[i];
3490
+ if (!original) continue;
3491
+ const items = this.parse([elements[i]]);
3492
+ if (prefix && await this.matchesOutside(items, prefix)) throw new GitApiError(`fatal: pathspec '${original}' matches files outside the current directory`);
3493
+ if (!await this.pathExists(items)) throw new GitApiError(`fatal: pathspec '${original}' did not match any files`);
3494
+ }
3495
+ }
3496
+ parse(elements) {
3497
+ let items;
3498
+ try {
3499
+ items = parsePathspec(elements, { attr: true });
3500
+ } catch (e) {
3501
+ throw new GitApiError(`fatal: ${e.message}`);
3502
+ }
3503
+ for (const item of items) if (item.attr) item.attrLookup = (p) => this.attrCache.get(p);
3504
+ return items;
3505
+ }
3506
+ /** The attributes of `path` (a directory with `isDirectory`). */
3507
+ async attributes(path, names, isDirectory = false) {
3508
+ if (this.bareResolver) return this.bareResolver.get(path, names, { isDirectory });
3509
+ const filter = this.worktree?.contentFilter;
3510
+ if (!filter?.attributes) return /* @__PURE__ */ new Map();
3511
+ return filter.attributes(path, names, {
3512
+ ...this.filterContext ?? { direction: "checkin" },
3513
+ ...isDirectory ? { isDirectory } : {}
3514
+ });
3515
+ }
3516
+ /** Whether `items` match the file or directory `path` (relative to the tree's top). */
3517
+ async matches(items, path, isDir) {
3518
+ if (items.length === 0) return true;
3519
+ if (isDir) {
3520
+ const plain = items.map((i) => i.attr ? {
3521
+ ...i,
3522
+ attr: void 0
3523
+ } : i);
3524
+ return matchPathspec(plain, path, 3) > 0;
3525
+ }
3526
+ await this.loadAttributes(items, path);
3527
+ return matchPathspec(items, path, 0) > 0;
3528
+ }
3529
+ /** The attributes `:(attr)` elements ask of `path`, read once (git asks them as a file's). */
3530
+ async loadAttributes(items, path) {
3531
+ if (this.attrCache.has(path)) return;
3532
+ const names = [...new Set(items.flatMap((i) => i.attr?.map((a) => a.name) ?? []))];
3533
+ if (names.length > 0) this.attrCache.set(path, await this.attributes(path, names));
3534
+ }
3535
+ /** `path_exists`' `reject_entry` walk: a file, or a directory the element itself names. */
3536
+ async pathExists(items) {
3537
+ const walk = async (tree, base) => {
3538
+ for (const entry of await this.cmd.archiveEntries(tree)) {
3539
+ const path = `${base}${entry.name}`;
3540
+ if (isDirMode(entry.mode)) {
3541
+ if (!await this.matches(items, path, true)) continue;
3542
+ await this.loadAttributes(items, path);
3543
+ if (matchPathspec(items, path, 1) > 0) return true;
3544
+ if (await walk(entry.id, `${path}/`)) return true;
3545
+ } else if (await this.matches(items, path, false)) return true;
3546
+ }
3547
+ return false;
3548
+ };
3549
+ return walk(this.target.tree, "");
3550
+ }
3551
+ /** `reject_outside`: a file the element matches lies outside `prefix`. */
3552
+ async matchesOutside(items, prefix) {
3553
+ const walk = async (tree, base) => {
3554
+ for (const entry of await this.cmd.archiveEntries(tree)) {
3555
+ const path = `${base}${entry.name}`;
3556
+ if (isDirMode(entry.mode)) {
3557
+ if (!await this.matches(items, path, true)) continue;
3558
+ if (await walk(entry.id, `${path}/`)) return true;
3559
+ } else if (await this.matches(items, path, false) && !path.startsWith(prefix)) return true;
3560
+ }
3561
+ return false;
3562
+ };
3563
+ return walk(this.target.tree, "");
3564
+ }
3565
+ report(path) {
3566
+ if (this.settings.verbose) this.settings.messages.push(decodeGitPath(path));
3567
+ }
3568
+ async emit(entry) {
3569
+ const error = await this.writer.entry(entry);
3570
+ if (error) throw new GitApiError(`error: ${error}`, { exitCode: 255 });
3571
+ }
3572
+ /** `write_archive_entries`. */
3573
+ async writeEntries() {
3574
+ const base = this.baseText;
3575
+ if (base.length > 0 && base.endsWith("/")) {
3576
+ let len = base.length;
3577
+ while (len > 1 && base[len - 2] === "/") len--;
3578
+ const path = this.base.subarray(0, encodeGitPath(base.slice(0, len)).length);
3579
+ this.report(path);
3580
+ await this.emit({
3581
+ path,
3582
+ mode: 16895,
3583
+ id: this.target.tree,
3584
+ content: /* @__PURE__ */ new Uint8Array(0)
3585
+ });
3586
+ }
3587
+ await this.walk(this.target.tree, "", []);
3588
+ const hexLength = this.target.commitId?.length ?? this.target.tree.length;
3589
+ const entries = [];
3590
+ const binaries = [];
3591
+ this.extras.forEach((extra, i) => {
3592
+ const id = (i + 1).toString(16).padStart(16, "0").padEnd(hexLength, "0");
3593
+ const text = extra.virtual ? extra.path : `${extra.base}${baseName(extra.path)}`;
3594
+ const path = encodeGitPath(text);
3595
+ const entry = {
3596
+ path,
3597
+ mode: extra.mode,
3598
+ id,
3599
+ content: /* @__PURE__ */ new Uint8Array(0)
3600
+ };
3601
+ binaries.push(this.binaryOf(decodeGitPath(path.subarray(this.base.length))));
3602
+ entries.push(entry);
3603
+ });
3604
+ for (let i = 0; i < entries.length; i++) {
3605
+ const entry = entries[i];
3606
+ const binary = await binaries[i];
3607
+ if (binary !== void 0) entry.binary = binary;
3608
+ entry.content = await this.extras[i].read();
3609
+ await this.emit(entry);
3610
+ }
3611
+ }
3612
+ /** `read_tree` with `queue_or_write_archive_entry`. */
3613
+ async walk(tree, base, ancestors) {
3614
+ for (const entry of await this.cmd.archiveEntries(tree)) {
3615
+ const path = `${base}${entry.name}`;
3616
+ if (isDirMode(entry.mode)) {
3617
+ if (!await this.matches(this.pathspec, path, true)) continue;
3618
+ if ((await this.attributes(path, EXPORT_ATTRS, true)).get("export-ignore") === true) continue;
3619
+ ancestors.push({
3620
+ path,
3621
+ id: entry.id,
3622
+ mode: entry.mode,
3623
+ written: false
3624
+ });
3625
+ await this.walk(entry.id, `${path}/`, ancestors);
3626
+ ancestors.pop();
3627
+ continue;
3628
+ }
3629
+ if (!await this.matches(this.pathspec, path, false)) continue;
3630
+ for (const dir of ancestors) {
3631
+ if (dir.written) continue;
3632
+ dir.written = true;
3633
+ await this.writeEntry(dir.id, dir.path, dir.mode);
3634
+ }
3635
+ await this.writeEntry(entry.id, path, entry.mode);
3636
+ }
3637
+ }
3638
+ /** `write_archive_entry` for `path` (relative to the tree's top). */
3639
+ async writeEntry(id, path, mode) {
3640
+ const isDir = isDirMode(mode) || isGitlinkMode(mode);
3641
+ let convert = false;
3642
+ if (!isDirMode(mode)) {
3643
+ const attrs = await this.attributes(path, EXPORT_ATTRS, isGitlinkMode(mode));
3644
+ if (attrs.get("export-ignore") === true) return;
3645
+ convert = attrs.get("export-subst") === true;
3646
+ }
3647
+ let rel = isDir ? `${path}/` : path;
3648
+ const prefix = this.settings.currentDirectory;
3649
+ if (prefix) {
3650
+ if (!rel.startsWith(prefix) || rel === prefix) return;
3651
+ rel = rel.slice(prefix.length);
3652
+ }
3653
+ const archivePath = encodeGitPath(`${this.baseText}${rel}`);
3654
+ const convertPath = rel;
3655
+ this.report(archivePath);
3656
+ if (isDir) {
3657
+ await this.emit({
3658
+ path: archivePath,
3659
+ mode,
3660
+ id,
3661
+ content: /* @__PURE__ */ new Uint8Array(0)
3662
+ });
3663
+ return;
3664
+ }
3665
+ let size;
3666
+ if (isRegMode(mode) && !convert) {
3667
+ const threshold = this.cmd.archiveBigFileThreshold();
3668
+ size = await this.cmd.archiveBlobSize(id);
3669
+ if (size !== void 0 && size <= threshold) size = void 0;
3670
+ }
3671
+ let entry;
3672
+ if (size !== void 0) {
3673
+ const stream = await this.cmd.archiveBlobStream(id);
3674
+ if (!stream) throw new GitApiError(`error: cannot stream blob ${id}`, { exitCode: 255 });
3675
+ entry = {
3676
+ path: archivePath,
3677
+ mode,
3678
+ id,
3679
+ content: /* @__PURE__ */ new Uint8Array(0),
3680
+ streamed: true,
3681
+ stream,
3682
+ size
3683
+ };
3684
+ } else {
3685
+ let content = await this.cmd.archiveBlob(id);
3686
+ if (!content) throw new GitApiError(`error: cannot read '${id}'`, { exitCode: 255 });
3687
+ if (isRegMode(mode)) {
3688
+ content = await this.smudge(convertPath, id, content, mode);
3689
+ if (convert && this.target.commitId) content = await this.substitute(content);
3690
+ }
3691
+ entry = {
3692
+ path: archivePath,
3693
+ mode,
3694
+ id,
3695
+ content
3696
+ };
3697
+ }
3698
+ if (this.writer instanceof ZipArchiveWriter && (isRegMode(mode) || isLinkMode(mode))) {
3699
+ const binary = await this.binaryOf(convertPath);
3700
+ if (binary !== void 0) entry.binary = binary;
3701
+ }
3702
+ await this.emit(entry);
3703
+ }
3704
+ /** archive.c's `init_checkout_metadata`: the ref, the commit (else the tree), the blob. */
3705
+ metadata(blob) {
3706
+ const treeish = this.target.commitId ?? this.target.tree;
3707
+ return {
3708
+ ...this.target.ref ? { ref: this.target.ref } : {},
3709
+ treeish,
3710
+ blob
3711
+ };
3712
+ }
3713
+ /** zip's `entry_is_binary`: the diff driver's `binary`, undefined to look at the content. */
3714
+ async binaryOf(path) {
3715
+ if (!(this.writer instanceof ZipArchiveWriter)) return void 0;
3716
+ const value = (await this.attributes(path, ["diff"])).get("diff");
3717
+ if (value === false) return true;
3718
+ if (value === true) return false;
3719
+ const name = typeof value === "string" ? value : "default";
3720
+ const setting = this.cmd.archiveConfig(`diff.${name}.binary`);
3721
+ return setting === void 0 ? void 0 : parseGitBool$1(setting);
3722
+ }
3723
+ /** `convert_to_working_tree` with the archive's attributes. */
3724
+ async smudge(path, id, content, mode) {
3725
+ if (this.bareResolver) {
3726
+ const attrs = await this.bareResolver.get(path, CONVERT_ATTRS);
3727
+ this.conversionSettings ??= readConversionSettings(this.cmd.archiveConfigObject(), "lf");
3728
+ const ca = asGitDeath(() => convAttrsOf(new Map(attrs), this.conversionSettings, this.cmd.archiveDrivers()));
3729
+ let out = content;
3730
+ if (ca.ident) out = identToWorktree(out, id);
3731
+ out = crlfToWorktree(out, ca.crlfAction, this.conversionSettings);
3732
+ if (ca.workingTreeEncoding && out.length > 0) {
3733
+ const encoded = reencode(out, ca.workingTreeEncoding, "UTF-8");
3734
+ if (encoded) out = encoded;
3735
+ else this.settings.messages.push(`error: failed to encode '${path}' from UTF-8 to ${ca.workingTreeEncoding}`);
3736
+ }
3737
+ const smudge = ca.driver?.host?.smudge;
3738
+ const command = ca.driver?.smudge;
3739
+ let filtered;
3740
+ if (smudge && command !== "") try {
3741
+ filtered = await smudge.call(ca.driver?.host, out, {
3742
+ path,
3743
+ ...command !== void 0 ? { command } : {},
3744
+ metadata: this.metadata(id)
3745
+ });
3746
+ } catch (error) {
3747
+ if (command !== void 0 && !ca.driver?.required) {
3748
+ const own = error instanceof FilterDriverRunError ? error.lines : [];
3749
+ for (const line of [...own, `external filter '${command}' failed`]) this.settings.messages.push(`error: ${line}`);
3750
+ }
3751
+ }
3752
+ if (filtered === void 0 && ca.driver?.required) throw new GitApiError(`fatal: ${path}: smudge filter ${ca.driver.name} failed`);
3753
+ return filtered ?? out;
3754
+ }
3755
+ const filter = this.worktree?.contentFilter;
3756
+ if (!filter || !isRegMode(mode)) return content;
3757
+ try {
3758
+ const conversion = await filter.checkout(path, this.filterContext);
3759
+ if (!conversion) return content;
3760
+ return await conversion.apply(content, {
3761
+ onWarning: (message) => this.settings.messages.push(message),
3762
+ metadata: this.metadata(id)
3763
+ });
3764
+ } catch (error) {
3765
+ if (error instanceof FilterDriverError || isEncodingAttributeError(error)) throw new GitApiError(`fatal: ${error.message}`);
3766
+ throw error;
3767
+ }
3768
+ }
3769
+ /** `format_subst`: each `$Format:<fmt>$` expanded for the commit. */
3770
+ async substitute(content) {
3771
+ const text = latin1$1(content);
3772
+ let out = "";
3773
+ let at = 0;
3774
+ for (;;) {
3775
+ const b = text.indexOf("$Format:", at);
3776
+ if (b < 0) break;
3777
+ const c = text.indexOf("$", b + 8);
3778
+ if (c < 0) break;
3779
+ out += text.slice(at, b);
3780
+ const { format, describe } = this.limitDescribe(text.slice(b + 8, c));
3781
+ const expanded = await this.cmd.archiveSubstitute(decodeGitPath(latin1Bytes(format)), this.target.commitId, describe);
3782
+ out += latin1$1(encodeGitPath(expanded));
3783
+ at = c + 1;
3784
+ }
3785
+ out += text.slice(at);
3786
+ return latin1Bytes(out);
3787
+ }
3788
+ /**
3789
+ * `%(describe)` expands once per archive (`describe_status.max_invocations`): later ones
3790
+ * stay as written, escaped here so the formatter keeps them.
3791
+ */
3792
+ limitDescribe(format) {
3793
+ let out = "";
3794
+ let describe = false;
3795
+ for (let i = 0; i < format.length; i++) {
3796
+ if (format[i] === "%" && format[i + 1] === "%") {
3797
+ out += "%%";
3798
+ i++;
3799
+ continue;
3800
+ }
3801
+ if (format.startsWith("%(describe", i)) {
3802
+ if (this.describeBudget > 0) {
3803
+ this.describeBudget--;
3804
+ describe = true;
3805
+ out += "%";
3806
+ } else out += "%%";
3807
+ continue;
3808
+ }
3809
+ out += format[i];
3810
+ }
3811
+ return {
3812
+ format: out,
3813
+ describe
3814
+ };
3815
+ }
3816
+ };
3817
+ /** convert.c's death for `working-tree-encoding` set or unset (no value). */
3818
+ function isEncodingAttributeError(error) {
3819
+ return error instanceof Error && error.message === "true/false are no valid working-tree-encodings";
3820
+ }
3821
+ /** `fn`'s result, convert.c's attribute deaths turned into git's `fatal:`. */
3822
+ function asGitDeath(fn) {
3823
+ try {
3824
+ return fn();
3825
+ } catch (error) {
3826
+ if (isEncodingAttributeError(error)) throw new GitApiError(`fatal: ${error.message}`);
3827
+ throw error;
3828
+ }
3829
+ }
3830
+ function latin1$1(bytes) {
3831
+ let s = "";
3832
+ for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
3833
+ return s;
3834
+ }
3835
+ function latin1Bytes(text) {
3836
+ const out = new Uint8Array(text.length);
3837
+ for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i) & 255;
3838
+ return out;
3839
+ }
3840
+ //#endregion
3841
+ //#region src/commands/bundle/bundle-format.ts
3842
+ /**
3843
+ * git's bundle files (bundle.c, `Documentation/gitformat-bundle.adoc`): a header naming the
3844
+ * refs the bundle carries and the commits it needs, then a pack.
3845
+ *
3846
+ * @example
3847
+ * ```typescript
3848
+ * // # v3 git bundle
3849
+ * // @object-format=sha256
3850
+ * // -<id> <subject> (a prerequisite)
3851
+ * // <id> refs/heads/main (a ref)
3852
+ * // (an empty line, then the pack)
3853
+ * const header = parseBundleHeader(bytes);
3854
+ * if (header.ok) for (const ref of header.header.references) console.log(ref.id, ref.name);
3855
+ * ```
3856
+ */
3857
+ /** The first line of a v2 bundle. */
3858
+ const V2_BUNDLE_SIGNATURE = "# v2 git bundle\n";
3859
+ /** The first line of a v3 bundle (capabilities may follow). */
3860
+ const V3_BUNDLE_SIGNATURE = "# v3 git bundle\n";
3861
+ /** git's sane_ctype isspace: SP, HT, LF, CR */
3862
+ const SPACE = (c) => c === 32 || c === 9 || c === 10 || c === 13;
3863
+ const HEX = /^[0-9a-fA-F]$/;
3864
+ /**
3865
+ * bundle.c's `read_bundle_header_fd`: the signature, then lines up to an empty one (or the
3866
+ * end): v3 capabilities (`@object-format=`, `@filter=`), prerequisites (`-<id>` optionally
3867
+ * followed by a space and a comment) and refs (`<id> <name>`), each line right-trimmed.
3868
+ * `name` is how a bad signature is reported (git's `report_path`).
3869
+ *
3870
+ * @example
3871
+ * ```typescript
3872
+ * const parsed = parseBundleHeader(bytes, "repo.bundle");
3873
+ * if (!parsed.ok) console.error(`error: ${parsed.error}`);
3874
+ * ```
3875
+ */
3876
+ function parseBundleHeader(bytes, name = "<bundle>", defaultFormat = SHA1_OBJECT_FORMAT$1) {
3877
+ let at = 0;
3878
+ /** strbuf_getwholeline_fd: the next line with its LF; undefined at the end */
3879
+ const nextLine = () => {
3880
+ if (at >= bytes.length) return void 0;
3881
+ const lf = bytes.indexOf(10, at);
3882
+ const end = lf < 0 ? bytes.length : lf + 1;
3883
+ const line = bytes.subarray(at, end);
3884
+ at = end;
3885
+ return line;
3886
+ };
3887
+ const first = nextLine();
3888
+ const signature = first ? latin1(first) : "";
3889
+ const version = signature === "# v2 git bundle\n" ? 2 : signature === "# v3 git bundle\n" ? 3 : 0;
3890
+ if (version === 0) return {
3891
+ ok: false,
3892
+ error: `'${name}' does not look like a v2 or v3 bundle file`,
3893
+ notABundle: true
3894
+ };
3895
+ let objectFormat = defaultFormat;
3896
+ let filter;
3897
+ const prerequisites = [];
3898
+ const references = [];
3899
+ const fail = (error) => ({
3900
+ ok: false,
3901
+ error,
3902
+ notABundle: false
3903
+ });
3904
+ for (let line = nextLine(); line !== void 0; line = nextLine()) {
3905
+ if (line.length === 0 || line[0] === 10) break;
3906
+ let end = line.length;
3907
+ while (end > 0 && SPACE(line[end - 1])) end--;
3908
+ let text = line.subarray(0, end);
3909
+ if (version === 3 && text[0] === 64) {
3910
+ const capability = decodeGitPath(text.subarray(1));
3911
+ if (capability.startsWith("object-format=")) {
3912
+ const format = objectFormatByName$1(capability.slice(14));
3913
+ if (!format) return fail(`unrecognized bundle hash algorithm: ${capability.slice(14)}`);
3914
+ objectFormat = format;
3915
+ continue;
3916
+ }
3917
+ if (capability.startsWith("filter=")) {
3918
+ filter = capability.slice(7);
3919
+ continue;
3920
+ }
3921
+ return fail(`unknown capability '${capability}'`);
3922
+ }
3923
+ const prereq = text[0] === 45;
3924
+ if (prereq) text = text.subarray(1);
3925
+ const hex = objectFormat.hexLength;
3926
+ let valid = text.length >= hex;
3927
+ for (let i = 0; valid && i < hex; i++) valid = HEX.test(String.fromCharCode(text[i]));
3928
+ const rest = text.subarray(hex);
3929
+ if (valid && rest.length > 0 && !SPACE(rest[0])) valid = false;
3930
+ if (valid && !prereq && rest.length === 0) valid = false;
3931
+ if (!valid) return fail(`unrecognized header: ${prereq ? "-" : ""}${decodeGitPath(text)} (${text.length})`);
3932
+ const id = latin1(text.subarray(0, hex)).toLowerCase();
3933
+ if (prereq) prerequisites.push({
3934
+ id,
3935
+ comment: decodeGitPath(rest.subarray(1)).trim()
3936
+ });
3937
+ else references.push({
3938
+ id,
3939
+ name: decodeGitPath(rest.subarray(1))
3940
+ });
3941
+ }
3942
+ return {
3943
+ ok: true,
3944
+ header: {
3945
+ version,
3946
+ objectFormat,
3947
+ ...filter !== void 0 ? { filter } : {},
3948
+ prerequisites,
3949
+ references
3950
+ },
3951
+ packOffset: at
3952
+ };
3953
+ }
3954
+ /**
3955
+ * The header `create_bundle` writes: the signature (v3 with `@object-format=` and, for a
3956
+ * filtered bundle, `@filter=`), `-<id> <comment>` per prerequisite, `<id> <name>` per ref,
3957
+ * then the empty line the pack follows.
3958
+ *
3959
+ * @example
3960
+ * ```typescript
3961
+ * const bytes = encodeBundleHeader({ version: 2, objectFormat: SHA1_OBJECT_FORMAT,
3962
+ * prerequisites: [], references: [{ id, name: "refs/heads/main" }] });
3963
+ * ```
3964
+ */
3965
+ function encodeBundleHeader(header) {
3966
+ const parts = [];
3967
+ const text = (s) => parts.push(encodeGitPath(s));
3968
+ if (header.version === 2) text(V2_BUNDLE_SIGNATURE);
3969
+ else {
3970
+ text(V3_BUNDLE_SIGNATURE);
3971
+ text(`@object-format=${header.objectFormat.name}\n`);
3972
+ if (header.filter !== void 0) text(`@filter=${header.filter}\n`);
3973
+ }
3974
+ for (const p of header.prerequisites) text(`-${p.id} ${p.comment}\n`);
3975
+ for (const r of header.references) text(`${r.id} ${r.name}\n`);
3976
+ text("\n");
3977
+ let length = 0;
3978
+ for (const p of parts) length += p.length;
3979
+ const out = new Uint8Array(length);
3980
+ let at = 0;
3981
+ for (const p of parts) {
3982
+ out.set(p, at);
3983
+ at += p.length;
3984
+ }
3985
+ return out;
3986
+ }
3987
+ /**
3988
+ * bundle.c's `list_refs`: `<id> <name>` per ref, only those named in `names` when any are
3989
+ * (exact names, as `git bundle list-heads <file> <refname>...` and `unbundle` take them).
3990
+ * A prerequisite is listed with an empty name (`<id> `), as `git bundle verify` prints it.
3991
+ */
3992
+ function listBundleRefs(refs, names = []) {
3993
+ let out = "";
3994
+ for (const ref of refs) {
3995
+ const name = "name" in ref ? ref.name : "";
3996
+ if (names.length > 0 && !names.includes(name)) continue;
3997
+ out += `${ref.id} ${name}\n`;
3998
+ }
3999
+ return out;
4000
+ }
4001
+ function latin1(bytes) {
4002
+ let s = "";
4003
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
4004
+ return s;
4005
+ }
4006
+ //#endregion
4007
+ //#region src/commands/bundle/bundle-verify.ts
4008
+ /**
4009
+ * bundle.c's reading side without a command: a bundle's bytes read (`read_bundle_header`)
4010
+ * and checked against a repository (`verify_bundle`), as the bundle commands and the bundle
4011
+ * transport do.
4012
+ */
4013
+ /** The bytes of a {@link BundleInput}, collected. */
4014
+ async function bundleBytes(input) {
4015
+ if (input instanceof Uint8Array) return input;
4016
+ const chunks = [];
4017
+ let length = 0;
4018
+ for await (const chunk of input) {
4019
+ chunks.push(chunk);
4020
+ length += chunk.length;
4021
+ }
4022
+ const out = new Uint8Array(length);
4023
+ let at = 0;
4024
+ for (const chunk of chunks) {
4025
+ out.set(chunk, at);
4026
+ at += chunk.length;
4027
+ }
4028
+ return out;
4029
+ }
4030
+ /**
4031
+ * builtin/bundle.c's `open_bundle` (`read_bundle_header`): the header and the pack, or git's
4032
+ * `error:` line (the bundle reported as `name`: its path, `<stdin>` for `-`).
4033
+ */
4034
+ function openBundle(bytes, name, defaultFormat) {
4035
+ const parsed = parseBundleHeader(bytes, name, defaultFormat);
4036
+ if (!parsed.ok) return {
4037
+ ok: false,
4038
+ error: `error: ${parsed.error}\n`
4039
+ };
4040
+ return {
4041
+ ok: true,
4042
+ bundle: {
4043
+ header: parsed.header,
4044
+ pack: bytes.subarray(parsed.packOffset)
4045
+ }
4046
+ };
4047
+ }
4048
+ /**
4049
+ * bundle.c's `verify_bundle`: every prerequisite must be an object here (each missing one
4050
+ * on an `error:` line after `Repository lacks these prerequisite commits:`, unless quiet),
4051
+ * then connected to the refs (`check_connected` of the prerequisites, `--not --all`); with
4052
+ * `verbose`, what the bundle holds on stdout.
4053
+ */
4054
+ async function verifyBundleIn(repository, header, options = {}) {
4055
+ const objects = historyWithoutLazyFetch(repository.history);
4056
+ let stderr = "";
4057
+ let missing = 0;
4058
+ for (const prerequisite of header.prerequisites) {
4059
+ if (await objectExists(objects, prerequisite.id)) continue;
4060
+ missing++;
4061
+ if (options.quiet) continue;
4062
+ if (missing === 1) stderr += "error: Repository lacks these prerequisite commits:\n";
4063
+ stderr += `error: ${prerequisite.id} \n`;
4064
+ }
4065
+ if (missing > 0) return {
4066
+ ok: false,
4067
+ stdout: "",
4068
+ stderr
4069
+ };
4070
+ let ok = true;
4071
+ const tips = header.prerequisites.map((p) => p.id);
4072
+ if (tips.length > 0) {
4073
+ const facade = createRepositoryFacade({ history: objects });
4074
+ if (await connectivityErrors(facade, tips, {
4075
+ known: await repository.refValues(),
4076
+ shallow: new Set(await repository.shallow())
4077
+ })) {
4078
+ ok = false;
4079
+ stderr += "error: some prerequisite commits exist in the object store, but are not connected to the repository's history\n";
4080
+ }
4081
+ }
4082
+ let stdout = "";
4083
+ if (options.verbose) {
4084
+ const refs = header.references;
4085
+ stdout += refs.length === 1 ? "The bundle contains this ref:\n" : `The bundle contains these ${refs.length} refs:\n`;
4086
+ stdout += listBundleRefs(refs);
4087
+ const prereqs = header.prerequisites;
4088
+ if (prereqs.length === 0) stdout += "The bundle records a complete history.\n";
4089
+ else {
4090
+ stdout += prereqs.length === 1 ? "The bundle requires this ref:\n" : `The bundle requires these ${prereqs.length} refs:\n`;
4091
+ stdout += listBundleRefs(prereqs);
4092
+ }
4093
+ stdout += `The bundle uses this hash algorithm: ${header.objectFormat.name}\n`;
4094
+ if (header.filter !== void 0) stdout += `The bundle uses this filter: ${header.filter}\n`;
4095
+ }
4096
+ return {
4097
+ ok,
4098
+ stdout,
4099
+ stderr
4100
+ };
4101
+ }
4102
+ /** git's `parse_object` succeeds: the object is here, whatever its type. */
4103
+ async function objectExists(history, id) {
4104
+ const objects = history.objects;
4105
+ if (objects) return objects.has(id).catch(() => false);
4106
+ for (const store of [
4107
+ history.commits,
4108
+ history.trees,
4109
+ history.blobs,
4110
+ history.tags
4111
+ ]) if (await store.has(id).catch(() => false)) return true;
4112
+ return false;
4113
+ }
4114
+ //#endregion
4115
+ //#region src/commands/bundle/bundle-transport.ts
4116
+ /**
4117
+ * git's bundle transport (transport.c's `bundle_vtable`): a remote URL that is a path to a
4118
+ * bundle file is read as a repository whose refs are the bundle's and whose only pack is the
4119
+ * bundle's. Fetch, clone, pull and ls-remote reach it through an upload-pack served in
4120
+ * process from the bundle: its refs advertised (in git's order: the bundle's refs reversed,
4121
+ * as `get_refs_from_bundle` prepends each), and any fetch answered with the bundle's pack,
4122
+ * once the fetching repository has the bundle's prerequisites (`unbundle`'s `verify_bundle`).
4123
+ */
4124
+ /**
4125
+ * A fetch from a bundle the repository lacks the prerequisites of: `verify_bundle`'s lines
4126
+ * (`git fetch` exits 1; `git clone` adds `fatal: remote transport reported error`, 128).
4127
+ */
4128
+ var BundlePrerequisitesError = class extends TransportError$1 {
4129
+ lines;
4130
+ constructor(lines) {
4131
+ super(lines.replace(/\n$/, ""), void 0, { exitCode: 1 });
4132
+ this.lines = lines;
4133
+ this.name = "BundlePrerequisitesError";
4134
+ }
4135
+ };
4136
+ /** Bytes per chunk the served pack is cut into. */
4137
+ const CHUNK = 65536;
4138
+ /**
4139
+ * Runs `run` over a connection to an upload-pack serving the bundle (protocol v0). A fetch
4140
+ * that needs the pack verifies the bundle first: when the repository lacks its prerequisites
4141
+ * the fetch fails with git's lines (exit 1, as `git fetch` returns).
4142
+ */
4143
+ async function withBundleUploadPack(remote, createPair, run) {
4144
+ const { header, pack } = remote.bundle;
4145
+ let refused;
4146
+ const facade = {
4147
+ objectFormat: header.objectFormat,
4148
+ importPack: () => Promise.reject(/* @__PURE__ */ new Error("a bundle cannot be written to")),
4149
+ async *exportPack() {
4150
+ const verified = await remote.verify();
4151
+ if (!verified.ok) {
4152
+ refused = verified.stderr;
4153
+ throw new Error("bundle prerequisites missing");
4154
+ }
4155
+ for (let at = 0; at < pack.length; at += CHUNK) yield pack.subarray(at, at + CHUNK);
4156
+ },
4157
+ has: async (oid) => header.references.some((r) => r.id === oid),
4158
+ async *walkAncestors() {}
4159
+ };
4160
+ const [client, server] = createPair();
4161
+ const serving = serveOverDuplex({
4162
+ duplex: server,
4163
+ repository: facade,
4164
+ refStore: bundleRefStore(header),
4165
+ service: "git-upload-pack"
4166
+ }).finally(() => server.close?.());
4167
+ try {
4168
+ const connection = await openDuplexConnection(client, { closeDuplex: true });
4169
+ try {
4170
+ return await run(connection);
4171
+ } catch (error) {
4172
+ if (refused !== void 0) throw new BundlePrerequisitesError(refused);
4173
+ throw error;
4174
+ } finally {
4175
+ await connection.close();
4176
+ }
4177
+ } finally {
4178
+ await client.close?.();
4179
+ await serving.catch(() => void 0);
4180
+ }
4181
+ }
4182
+ /** The refs a bundle advertises: read-only, in `get_refs_from_bundle`'s (reversed) order. */
4183
+ function bundleRefStore(header) {
4184
+ const refs = [...header.references].reverse();
4185
+ return {
4186
+ get: async (name) => refs.find((r) => r.name === name)?.id,
4187
+ update: () => Promise.reject(/* @__PURE__ */ new Error("a bundle cannot be written to")),
4188
+ listAll: async () => refs.map((r) => [r.name, r.id]),
4189
+ isRefTip: async (oid) => refs.some((r) => r.id === oid)
4190
+ };
4191
+ }
4192
+ //#endregion
4193
+ //#region src/commands/archive/upload-archive-writer.ts
4194
+ const encoder = new TextEncoder();
4195
+ /**
4196
+ * Runs `git archive <args>` as upload-archive's writer runs it in `workingCopy` (a
4197
+ * repository's, its worktree never read): git's options parsed from `args`, only formats
4198
+ * served remotely, a tree-ish only by ref unless `allowUnreachable`. The archive goes to
4199
+ * `sink` as it is written ({@link ArchiveCommand.callStream}: never held whole, the writer
4200
+ * waiting on each chunk), stderr's lines with it as they are printed; resolves with git's
4201
+ * exit status. Never throws: git's deaths are a stderr line and the status (a sink that
4202
+ * rejects, the client gone, stops the writer the same way).
4203
+ *
4204
+ * @example
4205
+ * ```ts
4206
+ * const exitCode = await runArchiveWriter(workingCopy, ["--format=zip", "HEAD"], {
4207
+ * stdout: async (chunk) => file.write(chunk),
4208
+ * stderr: async (text) => log(text),
4209
+ * });
4210
+ * ```
4211
+ */
4212
+ async function runArchiveWriter(workingCopy, args, sink, options = {}) {
4213
+ let command;
4214
+ let sent = 0;
4215
+ const flushMessages = async () => {
4216
+ if (!command) return;
4217
+ const lines = command.getMessages(sent);
4218
+ sent += lines.length;
4219
+ if (lines.length > 0) await sink.stderr(lines.map((m) => `${m}\n`).join(""));
4220
+ };
4221
+ try {
4222
+ command = new ArchiveCommand(workingCopy).setUploadArchive({ allowUnreachable: options.allowUnreachable === true });
4223
+ options.configure?.(command);
4224
+ if (applyArchiveArgs(command, args)) {
4225
+ const lines = command.listFormats().map((name) => `${name}\n`);
4226
+ await sink.stdout(encoder.encode(lines.join("")));
4227
+ return 0;
4228
+ }
4229
+ for await (const chunk of command.callStream()) {
4230
+ await flushMessages();
4231
+ await sink.stdout(chunk);
4232
+ }
4233
+ await flushMessages();
4234
+ return 0;
4235
+ } catch (error) {
4236
+ const message = error.message ?? String(error);
4237
+ const exitCode = error instanceof GitApiError ? error.exitCode : 128;
4238
+ const text = /^(fatal|error|usage|warning):/.test(message) ? message : `fatal: ${message}`;
4239
+ await flushMessages().catch(() => {});
4240
+ await sink.stderr(`${text}\n`).catch(() => {});
4241
+ return exitCode;
4242
+ }
4243
+ }
4244
+ /**
4245
+ * {@link runArchiveWriter} for an opened repository (`Worktree.openRepository`), as git's
4246
+ * upload-archive serves it: in its git directory (no worktree), `uploadarchive.allowUnreachable`
4247
+ * read from its configuration. Undefined for a repository without worktrees to open (a
4248
+ * key-value or SQL store).
4249
+ *
4250
+ * @example
4251
+ * ```ts
4252
+ * const writer = uploadArchiveWriterOf(opened);
4253
+ * if (writer) await serveUploadArchive(duplex, writer);
4254
+ * ```
4255
+ */
4256
+ function uploadArchiveWriterOf(repository, options = {}) {
4257
+ const worktrees = repository.worktrees;
4258
+ if (!worktrees) return void 0;
4259
+ return async (args, sink) => {
4260
+ const value = repository.config?.getAll("uploadarchive.allowUnreachable").at(-1);
4261
+ const allowUnreachable = value === void 0 ? false : parseGitBool$1(value ?? "true") ?? false;
4262
+ const admin = await worktrees.openAdmin();
4263
+ return runArchiveWriter(withoutWorktree(worktreeAdminWorkingCopy(admin)), args, sink, {
4264
+ allowUnreachable,
4265
+ ...options
4266
+ });
4267
+ };
4268
+ }
4269
+ /** `workingCopy` read as git's upload-archive reads it: a git directory, no worktree. */
4270
+ function withoutWorktree(workingCopy) {
4271
+ if (!("worktree" in workingCopy)) return workingCopy;
4272
+ return new Proxy(workingCopy, {
4273
+ get: (target, key) => {
4274
+ if (key === "worktree") return void 0;
4275
+ const value = Reflect.get(target, key, target);
4276
+ return typeof value === "function" ? value.bind(target) : value;
4277
+ },
4278
+ has: (target, key) => key !== "worktree" && key in target
4279
+ });
4280
+ }
4281
+ /** archive.c's options (`parse_archive_args`). */
4282
+ const VALUE_OPTIONS = /* @__PURE__ */ new Set([
4283
+ "format",
4284
+ "prefix",
4285
+ "add-file",
4286
+ "add-virtual-file",
4287
+ "mtime"
4288
+ ]);
4289
+ /**
4290
+ * Applies `git archive`'s arguments to `command` as archive.c's `parse_archive_args` reads
4291
+ * them in a writer (`--remote`, `--exec` and `--output` refused): options anywhere before
4292
+ * `--`, the first other argument the tree-ish, the rest paths. True for `--list`.
4293
+ */
4294
+ function applyArchiveArgs(command, args) {
4295
+ const positional = [];
4296
+ let list = false;
4297
+ let format;
4298
+ let extraFiles = false;
4299
+ for (let i = 0; i < args.length; i++) {
4300
+ const arg = args[i];
4301
+ if (arg === "--") {
4302
+ positional.push(...args.slice(i + 1));
4303
+ break;
4304
+ }
4305
+ if (!arg.startsWith("-") || arg === "-") {
4306
+ positional.push(arg);
4307
+ continue;
4308
+ }
4309
+ if (/^-\d+$/.test(arg)) {
4310
+ command.setCompressionLevel(Number(arg.slice(1)));
4311
+ continue;
4312
+ }
4313
+ if (arg.startsWith("--")) {
4314
+ const eq = arg.indexOf("=");
4315
+ const name = eq < 0 ? arg.slice(2) : arg.slice(2, eq);
4316
+ let value = eq < 0 ? void 0 : arg.slice(eq + 1);
4317
+ if (VALUE_OPTIONS.has(name) || name === "output" || name === "remote" || name === "exec") {
4318
+ if (value === void 0) {
4319
+ if (i + 1 >= args.length) throw new GitApiError(`error: option \`${name}' requires a value`, { exitCode: 129 });
4320
+ value = args[++i];
4321
+ }
4322
+ } else if (value !== void 0) throw new GitApiError(`error: option \`${name}' takes no value`, { exitCode: 129 });
4323
+ switch (name) {
4324
+ case "format":
4325
+ format = value;
4326
+ break;
4327
+ case "prefix":
4328
+ command.setPrefix(value);
4329
+ break;
4330
+ case "add-file": throw new GitApiError(`fatal: File not found: ${value}`);
4331
+ case "add-virtual-file":
4332
+ extraFiles = true;
4333
+ break;
4334
+ case "mtime":
4335
+ command.setMtime(value);
4336
+ break;
4337
+ case "worktree-attributes":
4338
+ command.setWorktreeAttributes(true);
4339
+ break;
4340
+ case "verbose":
4341
+ command.setVerbose(true);
4342
+ break;
4343
+ case "list":
4344
+ list = true;
4345
+ break;
4346
+ case "output": throw new GitApiError("fatal: Unexpected option --output");
4347
+ case "remote": throw new GitApiError("fatal: Unexpected option --remote");
4348
+ case "exec": throw new GitApiError("fatal: the option '--exec' requires '--remote'");
4349
+ default: throw new GitApiError(`error: unknown option \`${name}'`, { exitCode: 129 });
4350
+ }
4351
+ continue;
4352
+ }
4353
+ for (let j = 1; j < arg.length; j++) {
4354
+ const c = arg[j];
4355
+ if (c === "v") command.setVerbose(true);
4356
+ else if (c === "l") list = true;
4357
+ else if (c === "o") throw new GitApiError("fatal: Unexpected option --output");
4358
+ else throw new GitApiError(`error: unknown switch \`${c}'`, { exitCode: 129 });
4359
+ }
4360
+ }
4361
+ if (extraFiles) throw new GitApiError("fatal: options '--add-file' and '--remote' cannot be used together");
4362
+ if (format !== void 0) command.setFormat(format);
4363
+ if (list) return true;
4364
+ const [tree, ...paths] = positional;
4365
+ if (tree !== void 0) command.setTree(tree);
4366
+ for (const path of paths) command.addPath(path);
4367
+ return false;
4368
+ }
4369
+ //#endregion
4370
+ //#region src/commands/serve-repository.ts
4371
+ /**
4372
+ * A repository on disk served to other peers: what `serveGitConnection` / `serveGitService`
4373
+ * (vcs-transport) need from an opened repository, with the settings git's upload-pack and
4374
+ * receive-pack read from it.
4375
+ */
4376
+ /** What the served repository's config decides: left to `serveGitService`'s layering. */
4377
+ const CONFIG_KEYS = [
4378
+ "allowDeletes",
4379
+ "allowNonFastForward",
4380
+ "denyCurrentBranch",
4381
+ "denyDeleteCurrent",
4382
+ "shallowUpdate",
4383
+ "advertisePushOptions",
4384
+ "advertiseSID",
4385
+ "promisorRemoteInfo",
4386
+ "advertiseAtomic",
4387
+ "maxInputSize",
4388
+ "certNonceSeed",
4389
+ "certNonceSlop",
4390
+ "receiveKeepAliveMs",
4391
+ "unpackLimit",
4392
+ "uploadPackHideRefs",
4393
+ "receivePackHideRefs",
4394
+ "procReceiveRefs",
4395
+ "receivePackConfigError"
4396
+ ];
4397
+ /** A repository without a config reads as one with nothing set: git's defaults. */
4398
+ const EMPTY_CONFIG = { getAll: () => [] };
4399
+ /**
4400
+ * An opened repository (`Worktree.openRepository`) as a git server serves it: its objects and
4401
+ * refs, its configuration (git-daemon's `daemon.<service>`, `receive.*`, hidden refs), and the
4402
+ * settings of git's receive-pack (the current branch and the branches its worktrees have checked
4403
+ * out, `receive.denyCurrentBranch=updateInstead`, the hooks given), and the files of its git
4404
+ * directory a dumb HTTP client fetches, where it is in a FilesApi (`OpenedRepository.files`).
4405
+ *
4406
+ * The `receive.*` and hidden ref settings are not in `settings` but left to `config`, so
4407
+ * `serveGitService` applies only what the repository's config sets over the operator's
4408
+ * `settings` (git's defaults under both); a repository without a config is served with git's
4409
+ * defaults.
4410
+ *
4411
+ * @example
4412
+ * ```ts
4413
+ * await serveGitConnection({
4414
+ * duplex,
4415
+ * enableReceivePack: true,
4416
+ * resolveRepository: createBasePathResolver({
4417
+ * files, // the worktree's FilesApi
4418
+ * basePath: "/srv",
4419
+ * exportAll: true, // else only repositories with git-daemon-export-ok
4420
+ * openRepository: async (gitDir) => {
4421
+ * // includes of the repository's config confined to the storage (on a shared host)
4422
+ * const opened = await worktree
4423
+ * .openRepository?.(gitDir, { configIncludes: "files" })
4424
+ * .catch(() => undefined);
4425
+ * return opened && (await servedRepositoryOf(opened));
4426
+ * },
4427
+ * }),
4428
+ * });
4429
+ * ```
4430
+ */
4431
+ async function servedRepositoryOf(remote, options = {}) {
4432
+ const host = {
4433
+ ...options.host,
4434
+ confineFiles: true
4435
+ };
4436
+ const full = await receivePackSettingsOf(remote, options.hooks, void 0, host);
4437
+ const settings = { ...full };
4438
+ for (const key of CONFIG_KEYS) delete settings[key];
4439
+ const fsckError = receiveFsckSettingsOf(remote, host).configError;
4440
+ if (fsckError !== void 0 && full.receivePackConfigError === fsckError) settings.receivePackConfigError = fsckError;
4441
+ const hooks = options.hooks;
4442
+ if ((options.host?.compatibility ?? hooks?.compatibility) === "2.43") settings.acknowledgeEveryHave = true;
4443
+ if (options.packObjectsHook !== false && hooks) {
4444
+ const hook = await packObjectsHookOf(hooks);
4445
+ if (hook) settings.packObjectsHook = hook;
4446
+ }
4447
+ const facadeOf = (history) => createRepositoryFacade({
4448
+ history,
4449
+ useBitmaps: servedUseBitmaps(remote),
4450
+ sparseFilterPatterns: sparseFilterMatcher,
4451
+ maxTreeDepth: servedMaxTreeDepth(remote)
4452
+ });
4453
+ const plain = historyWithoutLazyFetch(remote.history);
4454
+ const forUploadPack = await uploadPackHistory(remote, options.lazyFetch, hooks?.hostEnvironment);
4455
+ return {
4456
+ repository: facadeOf(plain),
4457
+ ...forUploadPack !== plain ? { uploadPackRepository: facadeOf(forUploadPack) } : {},
4458
+ refStore: createTransportRefStore(remote.history.refs),
4459
+ config: remote.config ?? EMPTY_CONFIG,
4460
+ settings,
4461
+ ...remote.files ? { files: servedGitFilesOf(remote.files, remote.commonDir ?? remote.gitDir) } : {},
4462
+ ...(() => {
4463
+ const uploadArchive = uploadArchiveWriterOf(remote);
4464
+ return uploadArchive ? { uploadArchive } : {};
4465
+ })(),
4466
+ around: (service, serve, client) => {
4467
+ if (service !== "git-receive-pack") return serve();
4468
+ if (!hooks?.enabled) return serve();
4469
+ const env = {
4470
+ ...client?.namespace ? { GIT_NAMESPACE: client.namespace } : {},
4471
+ ...httpBackendEnv(hooks, client)
4472
+ };
4473
+ const session = Object.keys(env).length > 0 ? hooks.withEnv(env) : hooks;
4474
+ return withReceiveTransactionHook(remote, session, serve);
4475
+ }
4476
+ };
4477
+ }
4478
+ /**
4479
+ * upload-pack's `uploadpack.packObjectsHook` as the host runs it: the last value of the
4480
+ * protected configuration of the session's host environment (upload_pack_protected_config:
4481
+ * system, global, command line; a key without a value is git's `config_error_nonbool`, no
4482
+ * hook here), started through the session's runner as git starts it (`<hook> git
4483
+ * pack-objects ...` through the shell, in the git directory). Undefined when none is set or
4484
+ * no runner can start it.
4485
+ *
4486
+ * With `commandLine: false` the command line's entries (scope `command`) do not count: git's
4487
+ * local transport starts `git-upload-pack '<path>'` with connect.c's `local_repo_env` cleared
4488
+ * (`GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT`), so only the system and global files reach it.
4489
+ *
4490
+ * @example
4491
+ * ```ts
4492
+ * // ~/.gitconfig: [uploadpack] packObjectsHook = /srv/bin/pack-cache
4493
+ * const hook = await packObjectsHookOf(remoteHookSession(workingCopy, opened));
4494
+ * ```
4495
+ */
4496
+ async function packObjectsHookOf(hooks, options = {}) {
4497
+ const environment = hooks?.hostEnvironment;
4498
+ if (!hooks?.enabled || !environment) return void 0;
4499
+ let command;
4500
+ for (const entry of await readProtectedConfig(environment)) {
4501
+ if (options.commandLine === false && entry.scope === "command") continue;
4502
+ if (entry.key.toLowerCase() === "uploadpack.packobjectshook") command = entry.value;
4503
+ }
4504
+ if (!command) return void 0;
4505
+ const hookCommand = command;
4506
+ const legacy = hooks.compatibility === "2.43";
4507
+ return ({ args, options, stdin, onStderr }) => hooks.startShellCommand("pack-objects-hook", hookCommand, legacy ? packObjectsHookArgs(options, "2.43") : args, stdin, onStderr);
4508
+ }
4509
+ //#endregion
4510
+ //#region src/commands/remote-transport.ts
4511
+ /**
4512
+ * How a remote command reaches a remote, as git's `transport_get` and `git_connect` decide:
4513
+ * the URL (already rewritten by `url.<base>.insteadOf`, see `RemoteConfigStore`) is checked
4514
+ * against `protocol.allow`; a path or `file://` URL is git's local transport (served in
4515
+ * process, see `local-transport.ts`); anything else goes to the connector the transport
4516
+ * registry names for it (smart HTTP by default).
4517
+ */
4518
+ var remote_transport_exports = /* @__PURE__ */ __exportAll({
4519
+ bundleRemoteOf: () => bundleRemoteOf,
4520
+ checkTransportAllowed: () => checkTransportAllowed,
4521
+ httpSessionSettings: () => httpSessionSettings,
4522
+ isTransportAllowed: () => isTransportAllowed,
4523
+ localLazyFetchOf: () => localLazyFetchOf,
4524
+ openBundleRemote: () => openBundleRemote,
4525
+ openResolvedRemote: () => openResolvedRemote,
4526
+ prepareRemote: () => prepareRemote,
4527
+ protocolVersionOf: () => protocolVersionOf,
4528
+ remoteContextOf: () => remoteContextOf,
4529
+ resolveRemote: () => resolveRemote,
4530
+ withRemoteReceivePack: () => withRemoteReceivePack,
4531
+ withRemoteSession: () => withRemoteSession,
4532
+ withRemoteUploadPack: () => withRemoteUploadPack
4533
+ });
4534
+ const NO_PATH = "fatal: no path specified; see 'git help pull' for valid url syntax";
4535
+ /** transport.c's `parse_protocol_config`. */
4536
+ function parsePolicy(key, value) {
4537
+ const lower = value.toLowerCase();
4538
+ if (lower === "always" || lower === "never" || lower === "user") return lower;
4539
+ throw new InvalidConfigError(key, `fatal: unknown value for config '${key}': ${value}`);
4540
+ }
4541
+ /**
4542
+ * transport.c's `is_transport_allowed`: `GIT_ALLOW_PROTOCOL` when set (the only transports
4543
+ * allowed); else `protocol.<type>.allow`, then `protocol.allow`, then git's defaults (http,
4544
+ * https, git and ssh always; ext never; any other, `file` included, only when
4545
+ * `GIT_PROTOCOL_FROM_USER` is not false).
4546
+ *
4547
+ * @example
4548
+ * ```ts
4549
+ * isTransportAllowed("ext", store); // false
4550
+ * isTransportAllowed("file", store, { protocolFromUser: false } as GitHostEnvironment); // false
4551
+ * ```
4552
+ */
4553
+ function isTransportAllowed(type, config, environment) {
4554
+ if (environment?.allowProtocol !== void 0) return environment.allowProtocol.split(":").includes(type);
4555
+ const key = `protocol.${type}.allow`;
4556
+ const own = config.value(key);
4557
+ const fallback = config.value("protocol.allow");
4558
+ let policy;
4559
+ if (own !== void 0) policy = parsePolicy(key, own);
4560
+ else if (fallback !== void 0) policy = parsePolicy("protocol.allow", fallback);
4561
+ else if ([
4562
+ "http",
4563
+ "https",
4564
+ "git",
4565
+ "ssh"
4566
+ ].includes(type)) policy = "always";
4567
+ else if (type === "ext") policy = "never";
4568
+ else policy = "user";
4569
+ if (policy === "user") return environment?.protocolFromUser ?? true;
4570
+ return policy === "always";
4571
+ }
4572
+ /** transport.c's `transport_check_allowed`: git's "transport '<type>' not allowed". */
4573
+ function checkTransportAllowed(type, config, environment) {
4574
+ if (!isTransportAllowed(type, config, environment)) throw new TransportError$1(`fatal: transport '${type}' not allowed`);
4575
+ }
4576
+ /**
4577
+ * `protocol.version` (git's `get_protocol_version_config`): 0, 1 or 2, default 2; any other
4578
+ * value is git's "unknown value for config 'protocol.version'".
4579
+ */
4580
+ function protocolVersionOf(config) {
4581
+ const value = config.value("protocol.version");
4582
+ if (value === void 0) return 2;
4583
+ if (value === "0" || value === "1" || value === "2") return Number(value);
4584
+ throw new InvalidConfigError("protocol.version", `fatal: unknown value for config 'protocol.version': ${value}`);
4585
+ }
4586
+ /**
4587
+ * Resolves a remote URL (already rewritten by `insteadOf`) to its transport, in git's order
4588
+ * (transport_get, then git_connect): a `<helper>::<address>` URL goes to the connector for
4589
+ * the helper; `rsync:` is refused; a path or `file://` URL is the local transport (its path
4590
+ * checked first, then `protocol.file.allow`); `ssh`/`git` URLs (path, then
4591
+ * `protocol.<scheme>.allow`) and any other `<scheme>://` (`protocol.<scheme>.allow`) go to
4592
+ * the registry's connector. Without one, git's words: "unable to find remote helper" where
4593
+ * git would run a remote helper, ours for ssh and git:// (git would connect directly).
4594
+ *
4595
+ * @throws TransportError git's lines (exit 128)
4596
+ */
4597
+ function resolveRemote(url, context) {
4598
+ const { config, environment, transports } = context;
4599
+ const parsed = parseGitUrl(url);
4600
+ const viaConnector = (type) => {
4601
+ checkTransportAllowed(type, config, environment);
4602
+ const connector = transports.resolve(parsed);
4603
+ return connector ? {
4604
+ kind: "connector",
4605
+ url,
4606
+ parsed,
4607
+ connector
4608
+ } : void 0;
4609
+ };
4610
+ const helperMissing = (helper) => new TransportError$1(`fatal: unable to find remote helper for '${helper}'`);
4611
+ if (parsed.address !== void 0) return viaConnector(parsed.scheme) ?? throwError(helperMissing(parsed.scheme));
4612
+ if (url.startsWith("rsync:")) throw new TransportError$1("fatal: git-over-rsync is no longer supported");
4613
+ if (!(!isGitUrl(url) || /^(?:file|git|ssh|git\+ssh|ssh\+git):\/\//.test(url) || url === "")) {
4614
+ const scheme = url.slice(0, url.indexOf(":"));
4615
+ return viaConnector(scheme) ?? throwError(helperMissing(scheme));
4616
+ }
4617
+ if (!parsed.path && !parsed.scpLike) throw new TransportError$1(NO_PATH);
4618
+ if (parsed.scheme === "ssh" || parsed.local) checkNotAnOption("pathname", parsed.path);
4619
+ if (parsed.scheme === "file") {
4620
+ checkTransportAllowed("file", config, environment);
4621
+ return {
4622
+ kind: "local",
4623
+ url,
4624
+ path: parsed.path
4625
+ };
4626
+ }
4627
+ if (parsed.scheme === "ssh") {
4628
+ checkTransportAllowed("ssh", config, environment);
4629
+ checkNotAnOption("hostname", `${parsed.user !== void 0 ? `${parsed.user}@` : ""}${parsed.host ?? ""}`);
4630
+ }
4631
+ return viaConnector(parsed.scheme) ?? throwError(new TransportError$1(`fatal: cannot connect to '${url}': only http(s) and local repositories are reachable here`));
4632
+ }
4633
+ /**
4634
+ * connect.c's `looks_like_command_line_option` checks: git's "strange hostname '<host>'
4635
+ * blocked" (and pathname), so a remote URL cannot smuggle an option into the command git
4636
+ * runs (`ssh -oProxyCommand=...`).
4637
+ *
4638
+ * @throws TransportError git's line (exit 128)
4639
+ */
4640
+ function checkNotAnOption(what, value) {
4641
+ if (value.startsWith("-")) throw new TransportError$1(`fatal: strange ${what} '${value}' blocked`);
4642
+ }
4643
+ function throwError(error) {
4644
+ throw error;
4645
+ }
4646
+ /**
4647
+ * {@link resolveRemote}, then a local remote's repository opened (git's "does not appear to
4648
+ * be a git repository" when it cannot be).
4649
+ */
4650
+ async function prepareRemote(workingCopy, url, transports) {
4651
+ return openResolvedRemote(workingCopy, resolveRemote(url, remoteContextOf(workingCopy, transports)));
4652
+ }
4653
+ /** A resolved remote with its local repository opened ({@link prepareRemote}'s second half). */
4654
+ async function openResolvedRemote(workingCopy, resolved) {
4655
+ if (resolved.kind !== "local") return resolved;
4656
+ const bundle = await openBundleRemote(workingCopy, resolved.url, resolved.path);
4657
+ if (bundle) return {
4658
+ kind: "bundle",
4659
+ url: resolved.url,
4660
+ path: resolved.path,
4661
+ remote: bundle
4662
+ };
4663
+ return {
4664
+ ...resolved,
4665
+ repository: await openLocalRemote(workingCopy, resolved.path)
4666
+ };
4667
+ }
4668
+ /**
4669
+ * transport_get's `url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)`: a path
4670
+ * (not a `file://` URL) to a regular file whose header reads as a bundle's, with what checks
4671
+ * it against `workingCopy` (the repository fetching); undefined for anything else.
4672
+ */
4673
+ async function openBundleRemote(workingCopy, url, path) {
4674
+ if (/^file:/i.test(url)) return void 0;
4675
+ const bytes = await repositoryPlaceOf(workingCopy)?.readLocalFile?.(path).catch(() => void 0);
4676
+ if (!bytes) return void 0;
4677
+ return bundleRemoteOf(workingCopy, bytes, path);
4678
+ }
4679
+ /**
4680
+ * A bundle's bytes as a remote of `workingCopy` (the repository fetching): undefined when
4681
+ * they do not read as a bundle. `name` is how git reports it (its path as given).
4682
+ */
4683
+ function bundleRemoteOf(workingCopy, bytes, name) {
4684
+ const opened = openBundle(bytes, name);
4685
+ if (!opened.ok) return void 0;
4686
+ const history = workingCopy.history;
4687
+ return {
4688
+ bundle: opened.bundle,
4689
+ verify: () => verifyBundleIn({
4690
+ history,
4691
+ refValues: () => refValuesOf(history.refs),
4692
+ shallow: async () => await history.refs.getShallow?.().catch(() => void 0) ?? []
4693
+ }, opened.bundle.header)
4694
+ };
4695
+ }
4696
+ /** Every ref's value and HEAD's (what `rev-list --all` starts from). */
4697
+ async function refValuesOf(refs) {
4698
+ const out = /* @__PURE__ */ new Set();
4699
+ for await (const ref of refs.list()) {
4700
+ const id = "objectId" in ref && ref.objectId ? ref.objectId : (await refs.resolve(ref.name).catch(() => void 0))?.objectId;
4701
+ if (id) out.add(id);
4702
+ }
4703
+ const head = (await refs.resolve("HEAD").catch(() => void 0))?.objectId;
4704
+ if (head) out.add(head);
4705
+ return [...out];
4706
+ }
4707
+ /** The resolution context of a working copy: its configuration and host environment. */
4708
+ function remoteContextOf(workingCopy, transports) {
4709
+ const environment = hostEnvironmentOf(workingCopy);
4710
+ return {
4711
+ config: RemoteConfigStore.from(workingCopy),
4712
+ ...environment ? { environment } : {},
4713
+ transports
4714
+ };
4715
+ }
4716
+ /**
4717
+ * What a local remote's upload-pack inherits of the client for its lazy fetch: only under
4718
+ * the host environment's `GIT_NO_LAZY_FETCH=0` (git's upload-pack sets it to 1 unless the
4719
+ * variable is set), through the client's transports and per-URL credential helper. Static
4720
+ * credentials and headers never go: the promisor URLs are the remote repository's config.
4721
+ */
4722
+ function localLazyFetchOf(environment, options) {
4723
+ if (environment?.noLazyFetch !== false) return {};
4724
+ return { localLazyFetch: {
4725
+ ...options,
4726
+ environment
4727
+ } };
4728
+ }
4729
+ /**
4730
+ * The dumb-HTTP settings a session takes from the configuration and the environment
4731
+ * (`http.followRedirects` and the other `http.*` keys come with `httpSettings`): which
4732
+ * alternates a dumb fetch may use (http-walker's `is_transport_allowed(<scheme>, 0)`: as a
4733
+ * transport not from the user) and `$GIT_SMART_HTTP`.
4734
+ */
4735
+ function httpSessionSettings(workingCopy) {
4736
+ const config = RemoteConfigStore.from(workingCopy);
4737
+ const environment = hostEnvironmentOf(workingCopy);
4738
+ const notFromUser = {
4739
+ ...environment,
4740
+ protocolFromUser: false
4741
+ };
4742
+ return {
4743
+ alternateAllowed: (scheme) => isTransportAllowed(scheme, config, notFromUser),
4744
+ ...environment?.smartHttp === false ? { smartHttp: false } : {}
4745
+ };
4746
+ }
4747
+ function connectRequest(remote, service, options) {
4748
+ return {
4749
+ url: remote.parsed,
4750
+ service,
4751
+ protocolVersion: protocolVersionFor(service, options.protocolVersion),
4752
+ ...options.program !== void 0 ? { program: options.program } : {},
4753
+ ...options.credentials ? { credentials: options.credentials } : {},
4754
+ ...options.headers ? { headers: options.headers } : {},
4755
+ ...options.timeout !== void 0 ? { timeout: options.timeout } : {},
4756
+ ...options.signal ? { signal: options.signal } : {},
4757
+ ...options.httpSettings ? { http: options.httpSettings(remote.url) } : {},
4758
+ ...options.credentialHelper ? { credentialHelper: options.credentialHelper } : {}
4759
+ };
4760
+ }
4761
+ /**
4762
+ * A native session whose stream closes once: the connection opened over it closes the stream
4763
+ * (`closeDuplex`), and {@link withRemoteSession} closes it again for a `run` that opened none
4764
+ * or failed before; the second close does nothing.
4765
+ */
4766
+ function closingOnce(session) {
4767
+ if (session.kind !== "native") return session;
4768
+ const inner = session.duplex;
4769
+ let closing;
4770
+ const duplex = {
4771
+ [Symbol.asyncIterator]: () => inner[Symbol.asyncIterator](),
4772
+ write: (data) => inner.write(data),
4773
+ ...inner.end ? { end: () => inner.end?.() ?? Promise.resolve() } : {},
4774
+ close: () => {
4775
+ closing ??= inner.close?.() ?? Promise.resolve();
4776
+ return closing;
4777
+ }
4778
+ };
4779
+ return {
4780
+ ...session,
4781
+ duplex
4782
+ };
4783
+ }
4784
+ /**
4785
+ * Runs `run` over a session the remote's connector opens for `service` (the request's
4786
+ * protocol version as git_connect asks for it: v0 for receive-pack when v2 is configured); a
4787
+ * native session's stream is closed afterwards, once, whether or not `run` closed it.
4788
+ */
4789
+ async function withRemoteSession(remote, service, options, run) {
4790
+ const request = connectRequest(remote, service, options);
4791
+ let session;
4792
+ try {
4793
+ session = closingOnce(await remote.connector.connect(request));
4794
+ return await run(session, request);
4795
+ } catch (error) {
4796
+ throw connectorDeath(error);
4797
+ } finally {
4798
+ if (session?.kind === "native") await session.duplex.close?.().catch(() => void 0);
4799
+ }
4800
+ }
4801
+ /**
4802
+ * A connector's or the protocol layer's own death in git's words (a plain transport error
4803
+ * whose message is git's `fatal:` lines: a refused ssh host, an `ext::` placeholder, a
4804
+ * remote that closed before it spoke) as the command error git's exit status goes with (128);
4805
+ * anything else unchanged.
4806
+ */
4807
+ function connectorDeath(error) {
4808
+ if (error instanceof Error && !(error instanceof GitApiError) && error.name === "TransportError" && /^fatal: /m.test(error.message)) return new TransportError$1(error.message, void 0, {
4809
+ cause: error,
4810
+ exitCode: 128
4811
+ });
4812
+ return error;
4813
+ }
4814
+ /**
4815
+ * Runs `run` over a connection to upload-pack of a remote: in process for a local one
4816
+ * (`withLocalUploadPack`, protocol v2 unless `protocol.version` says otherwise), else over
4817
+ * the session its connector opens (`openUploadPack`).
4818
+ */
4819
+ async function withRemoteUploadPack(remote, options, run) {
4820
+ if (remote.kind === "local") {
4821
+ const packObjectsHook = await packObjectsHookOf(options.localHooks?.(remote.repository), { commandLine: false });
4822
+ return withLocalUploadPack(remote.repository, run, {
4823
+ protocolVersion: options.protocolVersion,
4824
+ ...options.localLazyFetch ? { lazyFetch: options.localLazyFetch } : {},
4825
+ ...options.namespace ? { namespace: options.namespace } : {},
4826
+ ...packObjectsHook ? { packObjectsHook } : {}
4827
+ });
4828
+ }
4829
+ if (remote.kind === "bundle") return withBundleUploadPack(remote.remote, createDuplexPair, run);
4830
+ return withRemoteSession(remote, "git-upload-pack", options, async (session, request) => {
4831
+ const connection = await openUploadPack(session, request, {
4832
+ ...options.gzipRequests !== void 0 ? { gzipRequests: options.gzipRequests } : {},
4833
+ ...options.alternateAllowed ? { alternateAllowed: options.alternateAllowed } : {},
4834
+ ...options.smartHttp === false ? { smartHttp: false } : {}
4835
+ });
4836
+ try {
4837
+ return await run(connection);
4838
+ } finally {
4839
+ await connection.close();
4840
+ }
4841
+ });
4842
+ }
4843
+ /**
4844
+ * Runs `run` over a connection to receive-pack of a remote: in process for a local one
4845
+ * (`withLocalReceivePack`, with the remote repository's hooks), else over the session its
4846
+ * connector opens (`openReceivePack`).
4847
+ */
4848
+ async function withRemoteReceivePack(remote, options, run, hooks, transactionHooks, local = {}) {
4849
+ if (remote.kind === "bundle") throw new TransportError$1(`error: failed to push some refs to '${remote.url}'`, void 0, { exitCode: 1 });
4850
+ if (remote.kind === "local") return withLocalReceivePack(remote.repository, run, hooks, transactionHooks, {
4851
+ protocolVersion: options.protocolVersion,
4852
+ ...options.namespace ? { namespace: options.namespace } : {},
4853
+ ...local
4854
+ });
4855
+ return withRemoteSession(remote, "git-receive-pack", options, async (session, request) => {
4856
+ const connection = await openReceivePack(session, request, { ...options.streamRequestBody !== void 0 ? { streamRequestBody: options.streamRequestBody } : {} });
4857
+ try {
4858
+ return await run(connection);
4859
+ } finally {
4860
+ await connection.close();
4861
+ }
4862
+ });
4863
+ }
4864
+ //#endregion
4865
+ export { ZipArchiveWriter as A, TarArchiveWriter as B, V2_BUNDLE_SIGNATURE as C, parseBundleHeader as D, listBundleRefs as E, GrepEngine as F, DescribeDeath as H, GrepError as I, bufferIsBinary as L, GrepCommand as M, grepNoIndex as N, ArchiveCommand as O, DEFAULT_GREP_COLORS as P, grepPattern as R, verifyBundleIn as S, encodeBundleHeader as T, Describer as U, DESCRIBE_MAX_TAGS as V, createDescriber as W, uploadArchiveWriterOf as _, prepareRemote as a, bundleBytes as b, remote_transport_exports as c, withRemoteSession as d, withRemoteUploadPack as f, runArchiveWriter as g, applyArchiveArgs as h, openResolvedRemote as i, dosTime as j, INTERNAL_GZIP_COMMAND as k, resolveRemote as l, servedRepositoryOf as m, httpSessionSettings as n, protocolVersionOf as o, packObjectsHookOf as p, localLazyFetchOf as r, remoteContextOf as s, bundleRemoteOf as t, withRemoteReceivePack as u, BundlePrerequisitesError as v, V3_BUNDLE_SIGNATURE as w, openBundle as x, withBundleUploadPack as y, grepPatternFile as z };