@statewalker/vcs-commands 0.4.0 → 0.6.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 (561) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +299 -34
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +67 -4
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +179 -7
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +93 -0
  73. package/dist/commands/core-config.d.ts.map +1 -0
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +244 -23
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +55 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +146 -6
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +69 -13
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +214 -26
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +10 -2
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-list-command.d.ts +2 -4
  237. package/dist/commands/stash-list-command.d.ts.map +1 -1
  238. package/dist/commands/stash-working-tree.d.ts +95 -0
  239. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  240. package/dist/commands/status-command.d.ts +320 -28
  241. package/dist/commands/status-command.d.ts.map +1 -1
  242. package/dist/commands/status-format.d.ts +155 -0
  243. package/dist/commands/status-format.d.ts.map +1 -0
  244. package/dist/commands/status-header.d.ts +64 -0
  245. package/dist/commands/status-header.d.ts.map +1 -0
  246. package/dist/commands/strerror.d.ts +7 -0
  247. package/dist/commands/strerror.d.ts.map +1 -0
  248. package/dist/commands/submodule-config.d.ts +38 -0
  249. package/dist/commands/submodule-config.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary-command.d.ts +80 -0
  251. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  252. package/dist/commands/submodule-summary.d.ts +150 -0
  253. package/dist/commands/submodule-summary.d.ts.map +1 -0
  254. package/dist/commands/switch-command.d.ts +132 -0
  255. package/dist/commands/switch-command.d.ts.map +1 -0
  256. package/dist/commands/tag-command.d.ts +23 -2
  257. package/dist/commands/tag-command.d.ts.map +1 -1
  258. package/dist/commands/tracking-info.d.ts +64 -0
  259. package/dist/commands/tracking-info.d.ts.map +1 -0
  260. package/dist/commands/trailers.d.ts +73 -0
  261. package/dist/commands/trailers.d.ts.map +1 -0
  262. package/dist/commands/tree-restore.d.ts +137 -6
  263. package/dist/commands/tree-restore.d.ts.map +1 -1
  264. package/dist/commands/untracked-cache-support.d.ts +53 -0
  265. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  266. package/dist/commands/worktree-add-command.d.ts +108 -0
  267. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-list-command.d.ts +69 -0
  269. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-lock-command.d.ts +44 -0
  271. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-overwrite-checks.d.ts +204 -0
  273. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  274. package/dist/commands/worktree-prune-command.d.ts +48 -0
  275. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-remove-command.d.ts +59 -0
  277. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-repair-command.d.ts +35 -0
  279. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-support.d.ts +64 -0
  281. package/dist/commands/worktree-support.d.ts.map +1 -0
  282. package/dist/commands-DnmlfwGV.js +61620 -0
  283. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  284. package/dist/core-commands/index.d.ts +0 -3
  285. package/dist/core-commands/index.d.ts.map +1 -1
  286. package/dist/errors/add-errors.d.ts +55 -0
  287. package/dist/errors/add-errors.d.ts.map +1 -1
  288. package/dist/errors/checkout-errors.d.ts +29 -0
  289. package/dist/errors/checkout-errors.d.ts.map +1 -1
  290. package/dist/errors/command-errors.d.ts +77 -0
  291. package/dist/errors/command-errors.d.ts.map +1 -1
  292. package/dist/errors/commit-errors.d.ts +9 -0
  293. package/dist/errors/commit-errors.d.ts.map +1 -1
  294. package/dist/errors/git-api-error.d.ts +59 -2
  295. package/dist/errors/git-api-error.d.ts.map +1 -1
  296. package/dist/errors/index.d.ts +1 -0
  297. package/dist/errors/index.d.ts.map +1 -1
  298. package/dist/errors/index.js +371 -19
  299. package/dist/errors/rebase-errors.d.ts +9 -0
  300. package/dist/errors/rebase-errors.d.ts.map +1 -1
  301. package/dist/errors/ref-errors.d.ts +32 -0
  302. package/dist/errors/ref-errors.d.ts.map +1 -1
  303. package/dist/errors/transport-errors.d.ts +12 -2
  304. package/dist/errors/transport-errors.d.ts.map +1 -1
  305. package/dist/errors/worktree-errors.d.ts +35 -0
  306. package/dist/errors/worktree-errors.d.ts.map +1 -0
  307. package/dist/git-command-DxvwPrPB.js +7612 -0
  308. package/dist/git-command.d.ts +422 -32
  309. package/dist/git-command.d.ts.map +1 -1
  310. package/dist/git.d.ts +326 -5
  311. package/dist/git.d.ts.map +1 -1
  312. package/dist/index.d.ts +1 -1
  313. package/dist/index.d.ts.map +1 -1
  314. package/dist/index.js +5 -5
  315. package/dist/remote-config/index.d.ts +1 -0
  316. package/dist/remote-config/index.d.ts.map +1 -1
  317. package/dist/remote-config/remote-config-store.d.ts +123 -3
  318. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  319. package/dist/remote-config/remote-refs.d.ts +41 -0
  320. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  321. package/dist/rename/detect-renames.d.ts +148 -0
  322. package/dist/rename/detect-renames.d.ts.map +1 -0
  323. package/dist/rename/git-similarity.d.ts +44 -0
  324. package/dist/rename/git-similarity.d.ts.map +1 -0
  325. package/dist/rename/index.d.ts +2 -0
  326. package/dist/rename/index.d.ts.map +1 -1
  327. package/dist/results/binary-patch.d.ts +11 -0
  328. package/dist/results/binary-patch.d.ts.map +1 -0
  329. package/dist/results/blame-format.d.ts +55 -0
  330. package/dist/results/blame-format.d.ts.map +1 -0
  331. package/dist/results/cherry-pick-result.d.ts +10 -0
  332. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  333. package/dist/results/clone-result.d.ts +16 -0
  334. package/dist/results/clone-result.d.ts.map +1 -1
  335. package/dist/results/combined-diff.d.ts +77 -0
  336. package/dist/results/combined-diff.d.ts.map +1 -0
  337. package/dist/results/diff-entry.d.ts +32 -0
  338. package/dist/results/diff-entry.d.ts.map +1 -1
  339. package/dist/results/diff-formatter.d.ts +34 -60
  340. package/dist/results/diff-formatter.d.ts.map +1 -1
  341. package/dist/results/diff-order.d.ts +25 -0
  342. package/dist/results/diff-order.d.ts.map +1 -0
  343. package/dist/results/diff-output.d.ts +249 -0
  344. package/dist/results/diff-output.d.ts.map +1 -0
  345. package/dist/results/fetch-result.d.ts +24 -1
  346. package/dist/results/fetch-result.d.ts.map +1 -1
  347. package/dist/results/index.d.ts +5 -0
  348. package/dist/results/index.d.ts.map +1 -1
  349. package/dist/results/index.js +2 -252
  350. package/dist/results/merge-result.d.ts +15 -1
  351. package/dist/results/merge-result.d.ts.map +1 -1
  352. package/dist/results/pull-result.d.ts +12 -3
  353. package/dist/results/pull-result.d.ts.map +1 -1
  354. package/dist/results/push-result.d.ts +42 -0
  355. package/dist/results/push-result.d.ts.map +1 -1
  356. package/dist/results/quote-path.d.ts +27 -0
  357. package/dist/results/quote-path.d.ts.map +1 -0
  358. package/dist/results/rebase-result.d.ts +28 -1
  359. package/dist/results/rebase-result.d.ts.map +1 -1
  360. package/dist/results/revert-result.d.ts +10 -0
  361. package/dist/results/revert-result.d.ts.map +1 -1
  362. package/dist/results/stash-result.d.ts +5 -0
  363. package/dist/results/stash-result.d.ts.map +1 -1
  364. package/dist/results/status-result.d.ts +143 -18
  365. package/dist/results/status-result.d.ts.map +1 -1
  366. package/dist/results-BZGa2Z3I.js +2934 -0
  367. package/dist/transport-command.d.ts +56 -1
  368. package/dist/transport-command.d.ts.map +1 -1
  369. package/package.json +15 -10
  370. package/src/commands/add-command.ts +1291 -224
  371. package/src/commands/add-patch/add-interactive.ts +941 -0
  372. package/src/commands/add-patch/add-patch.ts +1169 -0
  373. package/src/commands/add-patch/index.ts +5 -0
  374. package/src/commands/add-patch/patch-backend.ts +239 -0
  375. package/src/commands/add-patch/patch-modes.ts +249 -0
  376. package/src/commands/add-patch/patch-session.ts +159 -0
  377. package/src/commands/am/am-command.ts +1111 -0
  378. package/src/commands/am/index.ts +2 -0
  379. package/src/commands/am/mailinfo.ts +1015 -0
  380. package/src/commands/am/patch-format.ts +121 -0
  381. package/src/commands/apply/apply-command.ts +832 -0
  382. package/src/commands/apply/apply-engine.ts +1603 -0
  383. package/src/commands/apply/apply-parse.ts +1209 -0
  384. package/src/commands/apply/apply-types.ts +112 -0
  385. package/src/commands/apply/index.ts +5 -0
  386. package/src/commands/apply/latin1.ts +171 -0
  387. package/src/commands/apply/whitespace.ts +260 -0
  388. package/src/commands/attributes-source.ts +96 -0
  389. package/src/commands/backfill-command.ts +694 -0
  390. package/src/commands/bisect/bisect-checkout.ts +217 -0
  391. package/src/commands/bisect/bisect-command.ts +788 -0
  392. package/src/commands/bisect/bisect-engine.ts +1079 -0
  393. package/src/commands/bisect/bisect-graph.ts +595 -0
  394. package/src/commands/bisect/bisect-quote.ts +92 -0
  395. package/src/commands/bisect/index.ts +4 -0
  396. package/src/commands/blame-command.ts +711 -986
  397. package/src/commands/branch-command.ts +354 -32
  398. package/src/commands/branch-tracking.ts +331 -0
  399. package/src/commands/checkout-command.ts +1426 -297
  400. package/src/commands/checkout-paths.ts +784 -0
  401. package/src/commands/cherry-pick-command.ts +156 -396
  402. package/src/commands/clean-command.ts +532 -85
  403. package/src/commands/clone-command.ts +826 -55
  404. package/src/commands/commit-command.ts +1781 -166
  405. package/src/commands/core-config.ts +196 -0
  406. package/src/commands/date-format.ts +668 -0
  407. package/src/commands/describe-command.ts +2 -0
  408. package/src/commands/diff-command.ts +1898 -110
  409. package/src/commands/diff-textconv.ts +50 -0
  410. package/src/commands/fetch-command.ts +1038 -79
  411. package/src/commands/format-patch-command.ts +969 -0
  412. package/src/commands/fsck/fetch-fsck.ts +229 -0
  413. package/src/commands/fsck/fsck-command.ts +3347 -0
  414. package/src/commands/fsck/fsck-loose.ts +287 -0
  415. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  416. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  417. package/src/commands/fsck/fsck-object-table.ts +363 -0
  418. package/src/commands/fsck/fsck-pack.ts +604 -0
  419. package/src/commands/fsck/index.ts +5 -0
  420. package/src/commands/fsck/verify-pack-command.ts +249 -0
  421. package/src/commands/gc-command.ts +147 -1
  422. package/src/commands/git-date.ts +895 -0
  423. package/src/commands/git-describe.ts +316 -0
  424. package/src/commands/git-hooks.ts +1472 -0
  425. package/src/commands/git-ident.ts +344 -0
  426. package/src/commands/hook-command.ts +247 -0
  427. package/src/commands/index-adder.ts +706 -0
  428. package/src/commands/index-host.ts +291 -0
  429. package/src/commands/index.ts +83 -0
  430. package/src/commands/init-command.ts +60 -11
  431. package/src/commands/local-clone.ts +183 -0
  432. package/src/commands/local-transport.ts +762 -0
  433. package/src/commands/log-command.ts +1915 -170
  434. package/src/commands/log-graph.ts +671 -0
  435. package/src/commands/log-output.ts +1359 -0
  436. package/src/commands/ls-remote-command.ts +101 -58
  437. package/src/commands/mailmap.ts +129 -0
  438. package/src/commands/merge-bases.ts +296 -0
  439. package/src/commands/merge-command.ts +1386 -491
  440. package/src/commands/merge-config.ts +25 -0
  441. package/src/commands/merge-drivers.ts +306 -0
  442. package/src/commands/merge-support.ts +1198 -0
  443. package/src/commands/message-cleanup.ts +275 -0
  444. package/src/commands/mv-command.ts +976 -0
  445. package/src/commands/notes-command.ts +890 -0
  446. package/src/commands/notes-commands.ts +87 -0
  447. package/src/commands/notes-merge-command.ts +768 -0
  448. package/src/commands/notes-support.ts +402 -0
  449. package/src/commands/notes-tree.ts +602 -0
  450. package/src/commands/object-id-input.ts +27 -0
  451. package/src/commands/octopus-merge.ts +377 -0
  452. package/src/commands/ort-merge.ts +1660 -0
  453. package/src/commands/ort-recursive.ts +160 -0
  454. package/src/commands/pack-refs-command.ts +39 -22
  455. package/src/commands/patch-id.ts +196 -0
  456. package/src/commands/pathspec-attributes.ts +162 -0
  457. package/src/commands/pathspec.ts +1199 -0
  458. package/src/commands/post-index-change.ts +62 -0
  459. package/src/commands/pretty-format.ts +1431 -0
  460. package/src/commands/promisor-remote.ts +298 -0
  461. package/src/commands/pull-command.ts +207 -22
  462. package/src/commands/push-command.ts +236 -23
  463. package/src/commands/read-tree-command.ts +857 -0
  464. package/src/commands/rebase-command.ts +3808 -371
  465. package/src/commands/rebase-todo.ts +584 -0
  466. package/src/commands/ref-decoration-filter.ts +118 -0
  467. package/src/commands/reflog-messages.ts +177 -0
  468. package/src/commands/remote-command.ts +500 -19
  469. package/src/commands/remote-transport.ts +383 -0
  470. package/src/commands/reset-command.ts +828 -91
  471. package/src/commands/restore-command.ts +350 -0
  472. package/src/commands/rev-list-command.ts +167 -0
  473. package/src/commands/rev-parse-command.ts +277 -0
  474. package/src/commands/revert-command.ts +152 -399
  475. package/src/commands/revision-filenames.ts +254 -0
  476. package/src/commands/revision-range.ts +222 -0
  477. package/src/commands/revision-resolver.ts +1379 -0
  478. package/src/commands/rm-command.ts +613 -67
  479. package/src/commands/sequencer-pick.ts +869 -0
  480. package/src/commands/sequencer-support.ts +869 -0
  481. package/src/commands/serve-repository.ts +125 -0
  482. package/src/commands/sparse-checkout-command.ts +1389 -0
  483. package/src/commands/sparse-checkout-support.ts +793 -0
  484. package/src/commands/stash-apply-command.ts +692 -124
  485. package/src/commands/stash-create-command.ts +752 -89
  486. package/src/commands/stash-drop-command.ts +67 -6
  487. package/src/commands/stash-list-command.ts +10 -4
  488. package/src/commands/stash-working-tree.ts +387 -0
  489. package/src/commands/status-command.ts +1426 -97
  490. package/src/commands/status-format.ts +775 -0
  491. package/src/commands/status-header.ts +330 -0
  492. package/src/commands/strerror.ts +29 -0
  493. package/src/commands/submodule-config.ts +94 -0
  494. package/src/commands/submodule-summary-command.ts +334 -0
  495. package/src/commands/submodule-summary.ts +446 -0
  496. package/src/commands/switch-command.ts +402 -0
  497. package/src/commands/tag-command.ts +129 -41
  498. package/src/commands/tracking-info.ts +201 -0
  499. package/src/commands/trailers.ts +417 -0
  500. package/src/commands/tree-restore.ts +344 -15
  501. package/src/commands/untracked-cache-support.ts +194 -0
  502. package/src/commands/worktree-add-command.ts +458 -0
  503. package/src/commands/worktree-list-command.ts +208 -0
  504. package/src/commands/worktree-lock-command.ts +96 -0
  505. package/src/commands/worktree-overwrite-checks.ts +641 -0
  506. package/src/commands/worktree-prune-command.ts +99 -0
  507. package/src/commands/worktree-remove-command.ts +186 -0
  508. package/src/commands/worktree-repair-command.ts +59 -0
  509. package/src/commands/worktree-support.ts +214 -0
  510. package/src/core-commands/add.command.impl.ts +9 -5
  511. package/src/core-commands/index.ts +0 -8
  512. package/src/errors/add-errors.ts +45 -0
  513. package/src/errors/checkout-errors.ts +46 -2
  514. package/src/errors/command-errors.ts +101 -1
  515. package/src/errors/commit-errors.ts +18 -2
  516. package/src/errors/git-api-error.ts +82 -2
  517. package/src/errors/index.ts +1 -0
  518. package/src/errors/merge-errors.ts +2 -2
  519. package/src/errors/rebase-errors.ts +12 -0
  520. package/src/errors/ref-errors.ts +56 -2
  521. package/src/errors/remote-errors.ts +2 -2
  522. package/src/errors/stash-errors.ts +1 -1
  523. package/src/errors/transport-errors.ts +20 -4
  524. package/src/errors/worktree-errors.ts +49 -0
  525. package/src/git-command.ts +1218 -118
  526. package/src/git.ts +552 -11
  527. package/src/index.ts +1 -1
  528. package/src/remote-config/index.ts +1 -0
  529. package/src/remote-config/remote-config-store.ts +326 -16
  530. package/src/remote-config/remote-refs.ts +119 -0
  531. package/src/rename/detect-renames.ts +711 -0
  532. package/src/rename/git-similarity.ts +116 -0
  533. package/src/rename/index.ts +2 -0
  534. package/src/results/binary-patch.ts +401 -0
  535. package/src/results/blame-format.ts +239 -0
  536. package/src/results/cherry-pick-result.ts +10 -0
  537. package/src/results/clone-result.ts +18 -0
  538. package/src/results/combined-diff.ts +585 -0
  539. package/src/results/diff-entry.ts +35 -0
  540. package/src/results/diff-formatter.ts +152 -288
  541. package/src/results/diff-order.ts +64 -0
  542. package/src/results/diff-output.ts +1051 -0
  543. package/src/results/fetch-result.ts +24 -1
  544. package/src/results/index.ts +5 -0
  545. package/src/results/merge-result.ts +15 -1
  546. package/src/results/pull-result.ts +12 -3
  547. package/src/results/push-result.ts +43 -0
  548. package/src/results/quote-path.ts +103 -0
  549. package/src/results/rebase-result.ts +37 -0
  550. package/src/results/revert-result.ts +10 -0
  551. package/src/results/stash-result.ts +6 -0
  552. package/src/results/status-result.ts +288 -27
  553. package/src/transport-command.ts +139 -2
  554. package/dist/commands-BpeXZTC3.js +0 -10278
  555. package/dist/core-commands/checkout.command.d.ts +0 -103
  556. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  557. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  558. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  559. package/dist/status-result-BapZoQaR.js +0 -411
  560. package/src/core-commands/checkout.command.impl.ts +0 -564
  561. package/src/core-commands/checkout.command.ts +0 -125
@@ -0,0 +1,3347 @@
1
+ import {
2
+ badPackIntIdAt,
3
+ type CommitGraph,
4
+ commitGraphCompatible,
5
+ type FilesApi,
6
+ type GitObject,
7
+ type GitObjects,
8
+ type GraphCommitData,
9
+ graftFileBaseDir,
10
+ graftFileReader,
11
+ isSymbolicRef,
12
+ loadMultiPackIndex,
13
+ objectsWithoutLazyFetch,
14
+ openPack,
15
+ type PackFile,
16
+ type PackIndex,
17
+ PromisorObjectReadError,
18
+ parseGraftFile,
19
+ parseGraphCommit,
20
+ type Refs,
21
+ readCommitGraph,
22
+ readPackIndex,
23
+ runSteps,
24
+ type Steps,
25
+ scanPackObjects,
26
+ type Trees,
27
+ verifyCommitGraph,
28
+ } from "@statewalker/vcs-core";
29
+ import { multiPackIndexVerify } from "@statewalker/vcs-store-files";
30
+ import { decodeGitPath } from "@statewalker/vcs-utils/encoding";
31
+ import { readFile } from "@statewalker/vcs-utils/files";
32
+ import { createSha1 } from "@statewalker/vcs-utils/hash/hasher";
33
+ import { bytesToHex } from "@statewalker/vcs-utils/hash/utils";
34
+ import {
35
+ type CacheTree,
36
+ IndexCorruptError,
37
+ parseCacheTree,
38
+ parseResolveUndo,
39
+ type ResolveUndoRecord,
40
+ readIndexFileEntries,
41
+ type Staging,
42
+ } from "@statewalker/vcs-working-tree";
43
+ import { GitCommand } from "../../git-command.js";
44
+ import { RemoteConfigStore } from "../../remote-config/index.js";
45
+ import { hostEnvironmentOf } from "../git-ident.js";
46
+ import { configBool, configValue } from "../merge-config.js";
47
+ import { hasPromisorRemote } from "../promisor-remote.js";
48
+ import { DEFAULT_BIG_FILE_THRESHOLD, readLooseObject } from "./fsck-loose.js";
49
+ import { FSCK_MSG_IDS, FsckMessageTypes, type FsckMsgId } from "./fsck-msg-ids.js";
50
+ import {
51
+ canonMode,
52
+ fsckBlob,
53
+ fsckCommit,
54
+ fsckTag,
55
+ fsckTree,
56
+ hexIdAt,
57
+ parseCommitLinks,
58
+ parseTagBuffer,
59
+ rawIdAt,
60
+ scanTree,
61
+ type TreeEntryTable,
62
+ } from "./fsck-object-checks.js";
63
+ import {
64
+ HAS_OBJ,
65
+ OBJ_BLOB,
66
+ OBJ_COMMIT,
67
+ OBJ_NONE,
68
+ OBJ_TAG,
69
+ OBJ_TREE,
70
+ ObjectTable,
71
+ type ObjType,
72
+ PARSED,
73
+ REACHABLE,
74
+ SEEN,
75
+ TYPE_NAME,
76
+ typeOf,
77
+ USED,
78
+ } from "./fsck-object-table.js";
79
+ import { checkPack, collect, objectIdOf } from "./fsck-pack.js";
80
+
81
+ /** Exit status bits, as `git fsck` returns them (git 2.43's builtin/fsck.c). */
82
+ export const FSCK_ERROR_OBJECT = 0o1;
83
+ export const FSCK_ERROR_REACHABLE = 0o2;
84
+ export const FSCK_ERROR_PACK = 0o4;
85
+ export const FSCK_ERROR_REFS = 0o10;
86
+ /** `git commit-graph verify` failed (git's ERROR_COMMIT_GRAPH). */
87
+ export const FSCK_ERROR_COMMIT_GRAPH = 0o20;
88
+ /** `git multi-pack-index verify` failed, in git 2.43 (its ERROR_MULTI_PACK_INDEX; 2.5x: object bit). */
89
+ export const FSCK_ERROR_MULTI_PACK_INDEX_243 = 0o40;
90
+ /** A bitmap file's checksum is wrong, in git 2.43 (its ERROR_BITMAP; 2.5x sets the object bit). */
91
+ export const FSCK_ERROR_BITMAP_243 = 0o200;
92
+
93
+ /** What one line of fsck's output reports. */
94
+ export type FsckFindingKind =
95
+ /** a reachable object that is not stored (`missing <type> <id>`) */
96
+ | "missing"
97
+ /** an unreachable object nothing points to (`dangling <type> <id>`) */
98
+ | "dangling"
99
+ /** an unreachable object, with `--unreachable` */
100
+ | "unreachable"
101
+ /** a reachable object points to one that is not stored (`broken link from ...`) */
102
+ | "broken-link"
103
+ /** a message of git's object checks (`error in tree <id>: duplicateEntries: ...`) */
104
+ | "object"
105
+ /** `root <id>`, with `--root` */
106
+ | "root"
107
+ /** `tagged <type> <id> (<name>) in <id>`, with `--tags` */
108
+ | "tagged"
109
+ /** anything else git prints with `error()` (corrupt objects and packs, bad refs) */
110
+ | "error"
111
+ /** `notice: ...` and `bad sha1 file: ...` */
112
+ | "notice"
113
+ /** what `git commit-graph verify` prints (fsck runs it unless `core.commitGraph` is false) */
114
+ | "commit-graph"
115
+ /** what `git multi-pack-index verify` prints (unless `core.multiPackIndex` is false) */
116
+ | "multi-pack-index";
117
+
118
+ /** One line of output, as git prints it, with what it is about. */
119
+ export interface FsckFinding {
120
+ kind: FsckFindingKind;
121
+ /** Where git prints it. */
122
+ stream: "stdout" | "stderr";
123
+ /** The line, without its newline. */
124
+ text: string;
125
+ objectId?: string;
126
+ objectType?: string;
127
+ /** The message id of an `object` finding. */
128
+ msgId?: FsckMsgId;
129
+ /** How an `object` finding was reported. */
130
+ severity?: "error" | "warning";
131
+ }
132
+
133
+ /** Result of `git fsck`. */
134
+ export interface FsckResult {
135
+ /** git's exit status: the `FSCK_ERROR_*` bits that apply (0 when nothing is wrong). */
136
+ exitCode: number;
137
+ /** Every line, in the order git prints them. */
138
+ findings: FsckFinding[];
139
+ /** What git prints on stdout. */
140
+ output: string;
141
+ /** What git prints on stderr. */
142
+ errorOutput: string;
143
+ /**
144
+ * The work behind the result: objects read whole from the store (`objectsRead`; the
145
+ * sequential pack checks of a full run are not counted) and, in `--connectivity-only` runs,
146
+ * commits whose tree and parents came from the commit-graph instead (`commitsFromGraph`).
147
+ * A `--connectivity-only` run unpacks the commits and trees of each pack in one read in
148
+ * pack order first (`objectsScanned` of them); `objectsRead` counts the objects the walk
149
+ * takes from that read as well, once each, as it counts those it reads from the store.
150
+ * What is kept in memory from the reads in pack order is bounded (`setMemoryLimits`):
151
+ * `linksKept` tree entries and commit links (the walk reads the others from the store) and
152
+ * `graphCommitsKept` commits for the commit-graph verification (it reads the others).
153
+ */
154
+ statistics: {
155
+ objectsRead: number;
156
+ commitsFromGraph: number;
157
+ objectsScanned: number;
158
+ linksKept: number;
159
+ graphCommitsKept: number;
160
+ };
161
+ }
162
+
163
+ /** What a run keeps in memory from the reads in pack order (`FsckCommand.setMemoryLimits`). */
164
+ export interface FsckMemoryLimits {
165
+ /**
166
+ * Tree entries and commit links kept for the walk (4 bytes each), in all: those of the
167
+ * pack-order scan and of the trees the walk records. 32 Mi by default; 0 keeps none.
168
+ */
169
+ links?: number;
170
+ /** Commits kept for the commit-graph verification: 256 Ki by default. */
171
+ graphCommits?: number;
172
+ }
173
+
174
+ const DEFAULT_LINKS_KEPT = 32 * 1024 * 1024;
175
+ const DEFAULT_GRAPH_COMMITS_KEPT = 256 * 1024;
176
+
177
+ /** The git version whose output `FsckCommand` reproduces where versions differ. */
178
+ export type FsckCompatibility = "2.43" | "2.56";
179
+
180
+ /** The files of a git repository, for the checks that read them (`setRepositoryFiles`). */
181
+ export interface FsckRepositoryFiles {
182
+ files: FilesApi;
183
+ /** Path of the `.git` directory within `files` (default ".git"). */
184
+ gitDir?: string;
185
+ }
186
+
187
+ const ZERO_ID = "0000000000000000000000000000000000000000";
188
+ const OID = /^[0-9a-f]{40}$/;
189
+ const LOOSE_NAME = /^[0-9a-f]{38}$/;
190
+ const PACK_IDX = /^pack-[0-9a-f]{40}\.idx$/;
191
+ /** Refs one worktree has of its own (git's `is_per_worktree_ref`). */
192
+ const PER_WORKTREE = /^(?:refs\/(?:bisect|worktree|rewritten)\/|[A-Z_]+$)/;
193
+ const dec = new TextDecoder();
194
+ const EMPTY = new Uint8Array(0);
195
+
196
+ /** A config value git dies on (`bad numeric config value`), as `call` reports it. */
197
+ export class FsckConfigError extends Error {
198
+ override name = "FsckConfigError";
199
+ }
200
+
201
+ /**
202
+ * A git size setting as `git_config_ulong` parses it: `strtoumax` (leading blanks, an optional
203
+ * `+`, decimal, `0x` hex or `0` octal) then an optional k, m or g. Undefined when unset; a value
204
+ * git dies on throws `FsckConfigError` with git's message.
205
+ */
206
+ function sizeValue(key: string, value: string | undefined): number | undefined {
207
+ if (value === undefined) return undefined;
208
+ const bad = (why: string) =>
209
+ new FsckConfigError(`bad numeric config value '${value}' for '${key.toLowerCase()}': ${why}`);
210
+ if (value.includes("-")) throw bad("invalid unit");
211
+ const m = /^[ \t\n\v\f\r]*\+?(?:(0[xX])([0-9a-fA-F]+)|(0[0-7]*)|([1-9][0-9]*))(.*)$/s.exec(value);
212
+ if (!m) throw bad("invalid unit");
213
+ const digits = m[2] ?? m[3] ?? (m[4] as string);
214
+ const n =
215
+ m[2] !== undefined
216
+ ? BigInt(`0x${digits}`)
217
+ : m[3] !== undefined
218
+ ? BigInt(`0o${digits}`)
219
+ : BigInt(digits);
220
+ const unit = ({ "": 1n, k: 1024n, m: 1024n ** 2n, g: 1024n ** 3n } as Record<string, bigint>)[
221
+ (m[5] as string).toLowerCase()
222
+ ];
223
+ if (unit === undefined) throw bad("invalid unit");
224
+ if (n * unit > 2n ** 64n - 1n) throw bad("out of range");
225
+ return Number(n * unit);
226
+ }
227
+
228
+ /** A path within the repository's files, as git prints it (`.git/objects/ab/cd...`). */
229
+ const pathOf = (...parts: string[]) => parts.join("/");
230
+
231
+ /**
232
+ * Whether git's parse_commit_buffer reads past a commit's tree line (to its grafts): the data
233
+ * is longer than `tree <40 hex digits>\n`, starts with it, and the digits are hex.
234
+ */
235
+ function treeLineSound(data: Uint8Array): boolean {
236
+ if (data.length <= 46 || data[45] !== 0x0a) return false;
237
+ for (let i = 0; i < 5; i++) if (data[i] !== "tree ".charCodeAt(i)) return false;
238
+ for (let i = 5; i < 45; i++) {
239
+ const c = data[i] as number;
240
+ if (!((c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x66) || (c >= 0x41 && c <= 0x46)))
241
+ return false;
242
+ }
243
+ return true;
244
+ }
245
+
246
+ /**
247
+ * Verify the connectivity and validity of the objects in the repository.
248
+ *
249
+ * Equivalent to `git fsck --no-references`, after git's `builtin/fsck.c` and `fsck.c` (2.56 by
250
+ * default, 2.43 with `setCompatibility`): every stored object is read and checked (git's
251
+ * message ids, severities and texts, `fsck.<msg-id>` config and `--strict`), then everything reachable from the refs, the reflogs, the index (its
252
+ * entries, cache-tree and resolve-undo), the HEADs of linked worktrees and the stash is
253
+ * walked, and objects that are missing, dangling or (with `--unreachable`) unreachable are
254
+ * listed in git's order.
255
+ *
256
+ * Over a files repository (`setRepositoryFiles`) loose objects are read from their files
257
+ * (zlib streams, headers and hashes checked as git checks them) and packs are verified as
258
+ * git's `verify_pack` does (idx and pack checksums, each entry's CRC-32 and hash); reflogs,
259
+ * index files and linked worktrees are read from `.git`. Over any other store the objects of
260
+ * `history.objects` are read and checked, the reflogs come from `refs.getReflog` and the index
261
+ * from the staging area.
262
+ *
263
+ * Memory holds per object only its type, a few flags and a commit's tree and parents (as git
264
+ * does), and for a tree checked in full the object numbers of its entries (so the connectivity
265
+ * walk does not unpack it again); contents are read one object at a time. Packs are checked in
266
+ * one sequential read each (see `fsck-pack.ts`); `--connectivity-only` inflates no blob (a
267
+ * dangling one's type comes from its pack entry's header).
268
+ *
269
+ * Over a files repository the commit-graph is verified as git's fsck runs `git commit-graph
270
+ * verify` (unless `core.commitGraph` is false): its messages follow the rest on stderr and a
271
+ * failure sets exit bit 16 (`FSCK_ERROR_COMMIT_GRAPH`).
272
+ *
273
+ * In a partial clone (a promisor remote) the promisor objects are taken as git's fsck takes
274
+ * them (`is_promisor_object`: the objects of promisor packs and the objects they name): marked
275
+ * reachable without being walked further, never reported missing, valid as ref and reflog
276
+ * values; nothing is fetched lazily while fsck runs.
277
+ *
278
+ * The multi-pack-index is verified as git runs `git multi-pack-index verify` for each source
279
+ * (unless `core.multiPackIndex` is false): 2.5x after the source's packs (object bit), 2.43 last
280
+ * (exit bit 040); a midx git refuses fatally on load ends fsck with status 128.
281
+ *
282
+ * Not done: the ref database checks of `git refs verify` (git 2.45+),
283
+ * reverse-index verification, the commit-graphs
284
+ * of alternates, `fsck.skipList`, and explicit `<object>` heads. The objects of alternates
285
+ * (`history.objects.alternates`) are read and checked as git's default `--full` reads them
286
+ * (their dangling objects listed too): 2.56 source by source, 2.43 every source's loose
287
+ * objects, then every pack.
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * const result = await git.fsck().setRepositoryFiles({ files }).setUnreachable(true).call();
292
+ * process.stdout.write(result.output);
293
+ * process.stderr.write(result.errorOutput);
294
+ * process.exitCode = result.exitCode;
295
+ * ```
296
+ */
297
+ export class FsckCommand extends GitCommand<FsckResult> {
298
+ private _strict = false;
299
+
300
+ /** git's fsck and gc read the objects as stored, never through replace refs. */
301
+ protected override readsReplacedObjects(): boolean {
302
+ return false;
303
+ }
304
+ private _connectivityOnly = false;
305
+ private _dangling = true;
306
+ private _unreachable = false;
307
+ private _reflogs = true;
308
+ private _nameObjects = false;
309
+ private _root = false;
310
+ private _tags = false;
311
+ private _lostFound = false;
312
+ private _compatibility: FsckCompatibility = "2.56";
313
+ private _limits: FsckMemoryLimits = {};
314
+ private _repository?: FsckRepositoryFiles;
315
+ private readonly _messageTypes: [string, string][] = [];
316
+
317
+ /** `--strict`: warnings are errors, and mode 100664 a bad file mode. */
318
+ setStrict(strict: boolean): this {
319
+ this.checkCallable();
320
+ this._strict = strict;
321
+ return this;
322
+ }
323
+
324
+ /** `--connectivity-only`: check only that reachable objects are there, not their contents. */
325
+ setConnectivityOnly(connectivityOnly: boolean): this {
326
+ this.checkCallable();
327
+ this._connectivityOnly = connectivityOnly;
328
+ return this;
329
+ }
330
+
331
+ /** `--[no-]dangling` (on by default): list unreachable objects nothing points to. */
332
+ setDangling(dangling: boolean): this {
333
+ this.checkCallable();
334
+ this._dangling = dangling;
335
+ return this;
336
+ }
337
+
338
+ /** `--unreachable`: list every unreachable object. */
339
+ setUnreachable(unreachable: boolean): this {
340
+ this.checkCallable();
341
+ this._unreachable = unreachable;
342
+ return this;
343
+ }
344
+
345
+ /** `--[no-]reflogs` (on by default): reflog entries are roots. */
346
+ setReflogs(reflogs: boolean): this {
347
+ this.checkCallable();
348
+ this._reflogs = reflogs;
349
+ return this;
350
+ }
351
+
352
+ /** `--name-objects`: name reachable objects by how they were reached (`HEAD~2:src/`). */
353
+ setNameObjects(nameObjects: boolean): this {
354
+ this.checkCallable();
355
+ this._nameObjects = nameObjects;
356
+ return this;
357
+ }
358
+
359
+ /** `--root`: report root commits. */
360
+ setRoot(root: boolean): this {
361
+ this.checkCallable();
362
+ this._root = root;
363
+ return this;
364
+ }
365
+
366
+ /** `--tags`: report tags. */
367
+ setTags(tags: boolean): this {
368
+ this.checkCallable();
369
+ this._tags = tags;
370
+ return this;
371
+ }
372
+
373
+ /**
374
+ * `--lost-found`: write dangling objects to `.git/lost-found/commit/<id>` and
375
+ * `.git/lost-found/other/<id>` (blobs with their content, others with their id). Needs
376
+ * `setRepositoryFiles`; turns reflogs off, as git does.
377
+ */
378
+ setLostFound(lostFound: boolean): this {
379
+ this.checkCallable();
380
+ this._lostFound = lostFound;
381
+ return this;
382
+ }
383
+
384
+ /**
385
+ * Which git's output to reproduce where versions differ (default `2.56`):
386
+ * - `2.56` (the default) is `git fsck --no-references` of git 2.45+: the refs and worktree
387
+ * HEADs are read (and created in the object hash) before the objects, then their reflogs;
388
+ * HEAD itself is not checked (`HEAD points to an unborn branch`, `HEAD points to something
389
+ * strange`, `detached HEAD points at nothing` and `invalid HEAD` moved to git's
390
+ * `refs verify`, which is not implemented, and which plain `git fsck` runs first); an
391
+ * unparsable object is `<id>: object corrupt or missing`; a bad pack sets bit 1; a tag's
392
+ * `gpgsig` header after the tagger is not an extra header;
393
+ * - `2.43`: refs are read after the objects; HEAD and the HEADs of linked worktrees are
394
+ * checked (`notice: HEAD points to an unborn branch`, `HEAD points to something strange`,
395
+ * `detached HEAD points at nothing`, following symbolic refs to the end of the chain); an
396
+ * object that cannot be parsed is `<id>: object could not be parsed: <path>`; a bad pack
397
+ * sets exit bit 4 (`FSCK_ERROR_PACK`); a tag's `gpgsig` header is an `extraHeaderEntry`.
398
+ */
399
+ setCompatibility(version: FsckCompatibility): this {
400
+ this.checkCallable();
401
+ this._compatibility = version;
402
+ return this;
403
+ }
404
+
405
+ /**
406
+ * Bounds what the run keeps from its reads in pack order (the trees and commits a full run
407
+ * checks, the commits and trees a `--connectivity-only` run unpacks first, the commits the
408
+ * commit-graph verification compares): past them the objects are read from the store again
409
+ * when needed. The output is the same whatever the limits.
410
+ */
411
+ setMemoryLimits(limits: FsckMemoryLimits): this {
412
+ this.checkCallable();
413
+ this._limits = { ...limits };
414
+ return this;
415
+ }
416
+
417
+ /** `fsck.<msg-id>=<type>` for this run (`error`, `warn` or `ignore`), after the config's. */
418
+ setMessageType(msgId: string, type: string): this {
419
+ this.checkCallable();
420
+ this._messageTypes.push([msgId, type]);
421
+ return this;
422
+ }
423
+
424
+ /**
425
+ * The repository's files: loose objects, packs, reflogs, index files and linked worktrees
426
+ * are then read and checked as git reads them.
427
+ */
428
+ setRepositoryFiles(repository: FsckRepositoryFiles): this {
429
+ this.checkCallable();
430
+ this._repository = repository;
431
+ return this;
432
+ }
433
+
434
+ async call(): Promise<FsckResult> {
435
+ this.checkCallable();
436
+ this.setCallable(false);
437
+ const types = new FsckMessageTypes({ strict: this._strict });
438
+ for (const id of Object.keys(FSCK_MSG_IDS)) {
439
+ const value = configValue(this.workingCopy, `fsck.${id}`);
440
+ if (value !== undefined) types.set(id, value);
441
+ }
442
+ for (const [id, type] of this._messageTypes) types.set(id, type);
443
+ // git dies on a bad value when it reads the config, before it checks anything
444
+ const bigFileThreshold =
445
+ sizeValue("core.bigFileThreshold", configValue(this.workingCopy, "core.bigFileThreshold")) ??
446
+ DEFAULT_BIG_FILE_THRESHOLD;
447
+ const stored = this.workingCopy.history.objects;
448
+ if (!stored) throw new Error("fsck needs the object store (history.objects)");
449
+ // fsck knows how to handle missing promisor objects (fetch_if_missing = 0): in a partial
450
+ // clone it reads through the store's view without lazy fetch
451
+ const partial =
452
+ stored.promisor !== undefined && hasPromisorRemote(RemoteConfigStore.from(this.workingCopy));
453
+ const objects = partial ? objectsWithoutLazyFetch(stored) : stored;
454
+ const stores: RunStores = {
455
+ refs: this.refsStore,
456
+ staging: () => this.staging,
457
+ trees: () => this.storedTrees,
458
+ };
459
+ const promisor = objects.promisor;
460
+ const loadPromised =
461
+ promisor && partial
462
+ ? (skipUnreadable?: boolean) => promisor.promisedObjects({ skipUnreadable })
463
+ : undefined;
464
+ const run = new FsckRun(stores, objects, types, {
465
+ ...(loadPromised ? { loadPromised } : {}),
466
+ connectivityOnly: this._connectivityOnly,
467
+ dangling: this._dangling,
468
+ unreachable: this._unreachable,
469
+ reflogs: this._reflogs && !this._lostFound,
470
+ nameObjects: this._nameObjects,
471
+ root: this._root,
472
+ tags: this._tags,
473
+ lostFound: this._lostFound,
474
+ compatibility: this._compatibility,
475
+ repository: this._repository,
476
+ // git's fsck reads every source (`--full`, the default): the alternates' objects too
477
+ alternateDirs: this._repository
478
+ ? ((await objects.alternates?.list()) ?? []).map((a) => a.objectsDir)
479
+ : [],
480
+ bigFileThreshold,
481
+ linksKept: Math.max(0, this._limits.links ?? DEFAULT_LINKS_KEPT),
482
+ graphCommitsKept: Math.max(0, this._limits.graphCommits ?? DEFAULT_GRAPH_COMMITS_KEPT),
483
+ graftsAdvice: configBool(this.workingCopy, "advice.graftFileDeprecated", true),
484
+ readGraftFile: graftFileReader(
485
+ hostEnvironmentOf(this.workingCopy),
486
+ this._repository
487
+ ? {
488
+ files: this._repository.files,
489
+ dir: graftFileBaseDir(
490
+ this._repository.gitDir ?? ".git",
491
+ configBool(this.workingCopy, "core.bare", false) || undefined,
492
+ ),
493
+ }
494
+ : this.graftFileBase(),
495
+ ),
496
+ multiPackIndex: configBool(this.workingCopy, "core.multiPackIndex", true),
497
+ commitGraph: {
498
+ enabled: configBool(this.workingCopy, "core.commitGraph", true),
499
+ generationVersion:
500
+ intValue(configValue(this.workingCopy, "commitGraph.generationVersion")) ?? 2,
501
+ changedPathsVersion:
502
+ intValue(configValue(this.workingCopy, "commitGraph.changedPathsVersion")) ??
503
+ (configBool(this.workingCopy, "commitGraph.readChangedPaths", true) ? -1 : 0),
504
+ },
505
+ });
506
+ const result = await run.run();
507
+ // git prints the alternates' error lines when it first reads an object: first on stderr
508
+ // (once here; git repeats them in its child processes)
509
+ const alternates = this.alternatesErrors();
510
+ if (alternates.length === 0) return result;
511
+ return {
512
+ ...result,
513
+ findings: [
514
+ ...alternates.map((text): FsckFinding => ({ kind: "error", stream: "stderr", text })),
515
+ ...result.findings,
516
+ ],
517
+ errorOutput: `${alternates.map((l) => `${l}\n`).join("")}${result.errorOutput}`,
518
+ };
519
+ }
520
+ }
521
+
522
+ /** The stores a run reads besides the objects. */
523
+ interface RunStores {
524
+ refs: Refs;
525
+ /** The trees as stored (a sparse index expands from them) */
526
+ trees: () => Pick<Trees, "load" | "store">;
527
+ /** The staging area (throws when the working copy has none). */
528
+ staging: () => Staging;
529
+ }
530
+
531
+ interface RunOptions {
532
+ /**
533
+ * A partial clone's promisor objects (git's `is_promisor_object`): reachable without being
534
+ * walked, never missing, valid ref and reflog values; absent outside a partial clone
535
+ */
536
+ promised?: ReadonlySet<string>;
537
+ /**
538
+ * Reads {@link promised} when the walk first asks (git's `is_promisor_object` builds the
539
+ * set on its first call): an object of a promisor pack that cannot be read is git's death
540
+ * there (2.5x asks for every reachable object; 2.43 only for a missing one, so ours reads
541
+ * no set then)
542
+ */
543
+ loadPromised?: (skipUnreadable?: boolean) => Promise<ReadonlySet<string>>;
544
+ connectivityOnly: boolean;
545
+ dangling: boolean;
546
+ unreachable: boolean;
547
+ reflogs: boolean;
548
+ nameObjects: boolean;
549
+ root: boolean;
550
+ tags: boolean;
551
+ lostFound: boolean;
552
+ compatibility: FsckCompatibility;
553
+ repository?: FsckRepositoryFiles;
554
+ /** `core.bigFileThreshold`: larger loose blobs are streamed */
555
+ bigFileThreshold: number;
556
+ /** `advice.graftFileDeprecated` (on by default) */
557
+ graftsAdvice: boolean;
558
+ /**
559
+ * The grafts file's text, read in place of `info/grafts` (git's `GIT_GRAFT_FILE`);
560
+ * undefined when that file does not exist. Unset: `info/grafts` is read.
561
+ */
562
+ readGraftFile?: () => Promise<string | undefined>;
563
+ /** Tree entries and commit links kept from the reads in pack order, at most */
564
+ linksKept: number;
565
+ /** Commits kept for the commit-graph verification, at most */
566
+ graphCommitsKept: number;
567
+ /** `core.commitGraph` and the graph read settings, for `git commit-graph verify` */
568
+ commitGraph: { enabled: boolean; generationVersion: number; changedPathsVersion: number };
569
+ /** `core.multiPackIndex`: fsck runs `git multi-pack-index verify` for each source */
570
+ multiPackIndex?: boolean;
571
+ /** The alternates' objects directories in `repository.files`, in git's order */
572
+ alternateDirs?: readonly string[];
573
+ }
574
+
575
+ /** A git integer setting (decimal), undefined when unset or not a number. */
576
+ function intValue(value: string | undefined): number | undefined {
577
+ if (value === undefined || !/^\s*[-+]?\d+\s*$/.test(value)) return undefined;
578
+ return Number.parseInt(value, 10);
579
+ }
580
+
581
+ /** A pack of the repository, with its idx read (for `has_object_pack`). */
582
+ interface RepoPack {
583
+ packPath: string;
584
+ idxPath: string;
585
+ idx: PackIndex;
586
+ /** The idx file, read once for the listing, the checks and the open */
587
+ idxBytes: Uint8Array;
588
+ /** The object directory it is in: 0 the repository's, then its alternates' */
589
+ source: number;
590
+ }
591
+
592
+ /** An object read whole. */
593
+ interface Whole {
594
+ type: string;
595
+ content: Uint8Array;
596
+ }
597
+
598
+ /** The reflog of one ref: its name as git prints it and its entries, oldest first. */
599
+ interface Reflog {
600
+ name: string;
601
+ /** The file it was read from, as git prints it (none when read through the refs store) */
602
+ path?: string;
603
+ entries: { oldId: string; newId: string; timestamp: number }[];
604
+ }
605
+
606
+ /** One worktree's state: its HEAD, its reflogs and its index. */
607
+ interface WorktreeState {
608
+ /** `HEAD`, or `worktrees/<id>/HEAD` */
609
+ headName: string;
610
+ /** Where the worktree's files are (the `.git` dir or `.git/worktrees/<id>`) */
611
+ dir?: string;
612
+ current: boolean;
613
+ }
614
+
615
+ /** One `git fsck` run (builtin/fsck.c's globals). */
616
+ class FsckRun {
617
+ private readonly t = new ObjectTable();
618
+ private readonly findings: FsckFinding[] = [];
619
+ private errorsFound = 0;
620
+ private readonly pending: number[] = [];
621
+ private readonly names?: Map<string, string>;
622
+ private defaultRefs = 0;
623
+ private showUnreachable: boolean;
624
+ private readonly gitmodulesFound = new Set<string>();
625
+ private readonly gitmodulesDone = new Set<string>();
626
+ private readonly gitattributesFound = new Set<string>();
627
+ private readonly gitattributesDone = new Set<string>();
628
+ private shallow = new Set<string>();
629
+ /** A partial clone's promisor objects, once read (see `RunOptions.loadPromised`) */
630
+ private promised?: ReadonlySet<string>;
631
+ /** git 2.43's death when the walk first asks about a promisor object (see `run`) */
632
+ private promisorDeathAt?: { at: number; error: PromisorObjectReadError };
633
+ /** the first midx entry whose pack-int-id is out of range (git dies when it reads it) */
634
+ private midxBadEntry?: { id: string; line: string };
635
+ /**
636
+ * The commit grafts of `info/grafts` (git's parse_commit_buffer gives a grafted commit those
637
+ * parents, its own not looked up), and what reading them reported, printed when the first
638
+ * commit is parsed
639
+ */
640
+ private grafts?: Map<string, string[]>;
641
+ private graftErrors: string[] = [];
642
+ /** The grafts file's errors, as every process that reads the file prints them */
643
+ private graftErrorLines: string[] = [];
644
+ /** Whether there is a grafts file (`info/grafts`, or the one `GIT_GRAFT_FILE` names) */
645
+ private graftFileExists = false;
646
+ private packs: RepoPack[] = [];
647
+ /**
648
+ * Trees checked in full, as their entries' objects: object number -> start in `kids`, where
649
+ * the entry count comes first, then `(object << 1) | isTree` per entry (gitlinks left out).
650
+ * Only for trees whose entries all resolved, in full runs without `--name-objects`, so the
651
+ * connectivity walk need not read them again (git reads them again: a few bytes per entry
652
+ * here against unpacking every tree twice). Indexed by object number, holding start + 1 (0 for
653
+ * a tree not recorded).
654
+ */
655
+ private treeStart = new Int32Array(0);
656
+ /** The table `walkUsed` decodes each tree into (one tree at a time). */
657
+ private readonly usedTable: TreeEntryTable = { count: 0, fields: new Int32Array(0) };
658
+ /** The table the connectivity walk decodes each tree into. */
659
+ private readonly walkTable: TreeEntryTable = { count: 0, fields: new Int32Array(0) };
660
+ private kids = new Int32Array(0);
661
+ private kidsLength = 0;
662
+ /** The tree `walkUsed` decoded last, for `fsckTree` to check without decoding it again. */
663
+ private lastTree?: { content: Uint8Array; table: TreeEntryTable };
664
+ /** Whether `walkUsed` records the trees it walks (`treeEntries`). */
665
+ private readonly recordTrees: boolean;
666
+ /**
667
+ * Objects with a copy that failed a check: the connectivity walk reads these from the store
668
+ * (which may read that copy), never from `treeEntries`.
669
+ */
670
+ private readonly badCopy = new Set<string>();
671
+ /** Where an id parsed from hex is written for a lookup. */
672
+ private readonly idScratch = new Uint8Array(20);
673
+ /**
674
+ * The object `parseObject` read last: the connectivity walk of a tree it parsed walks these
675
+ * bytes instead of reading the tree again (git's parse_tree reads it once).
676
+ */
677
+ private lastRead?: { id: string; obj: Whole };
678
+ /**
679
+ * The commit-graph (connectivity-only runs): git's repo_parse_commit takes a commit's tree
680
+ * and parents from it (parse_commit_in_graph) instead of reading the commit.
681
+ */
682
+ private graph?: CommitGraph;
683
+ /** Commits parsed from the graph: commits not read from the object store */
684
+ private graphParsed = 0;
685
+ /** Objects read whole from the store (`readWhole`) */
686
+ private objectsRead = 0;
687
+ /** Objects the pack-order scan of a connectivity-only run unpacked. */
688
+ private objectsScanned = 0;
689
+ /**
690
+ * What the pack-order scan (`scanPacks`) found of each commit and tree it unpacked: object
691
+ * number -> start + 1 in `scanKids` (0 for an object not scanned). At the start
692
+ * `(count << 2) | type`, then a tree's entries as `(object << 1) | isTree` (gitlinks left
693
+ * out), or a commit's tree and parents. Only objects whose every link names an object the
694
+ * table holds, so the walk replays the lookups git makes on them in its own order.
695
+ */
696
+ private scanAt = new Int32Array(0);
697
+ /**
698
+ * Commits as `git commit-graph verify` compares them with the graph, by id, kept from the
699
+ * reads in pack order (the object pass of a full run, the scan of a connectivity-only one)
700
+ * when the repository has a commit-graph: the verification then reads only the others.
701
+ */
702
+ private graphCommits?: Map<string, GraphCommitData | null>;
703
+ /** Commits `graphCommits` holds (its `null`s left out). */
704
+ private graphCommitsKept = 0;
705
+ private scanKids = new Int32Array(0);
706
+ private scanKidsLength = 0;
707
+ private readonly files?: FilesApi;
708
+ private readonly gitDir: string;
709
+
710
+ constructor(
711
+ private readonly stores: RunStores,
712
+ private readonly objects: GitObjects,
713
+ private readonly types: FsckMessageTypes,
714
+ private readonly o: RunOptions,
715
+ ) {
716
+ if (o.nameObjects) this.names = new Map();
717
+ this.showUnreachable = o.unreachable;
718
+ this.recordTrees = !o.connectivityOnly && !o.nameObjects;
719
+ this.files = o.repository?.files;
720
+ this.gitDir = (o.repository?.gitDir ?? ".git").replace(/\/+$/, "");
721
+ }
722
+
723
+ async run(): Promise<FsckResult> {
724
+ // git loads the midx when it first reads a packed object and dies on one it refuses
725
+ // fatally (a wrong signature or version, a required chunk missing; 2.5x: a fan-out out of
726
+ // order too)
727
+ if (this.files && this.o.multiPackIndex !== false) {
728
+ const loaded = await loadMultiPackIndex(this.files, pathOf(this.looseDir(), "pack"), {
729
+ compatibility: this.o.compatibility,
730
+ });
731
+ if (loaded.fatal) return this.death(loaded.errors);
732
+ const bad = loaded.midx && badPackIntIdAt(loaded.midx);
733
+ if (bad && loaded.midx)
734
+ this.midxBadEntry = { id: loaded.midx.idAt(bad.pos), line: `fatal: ${bad.message}` };
735
+ }
736
+ this.graftFileExists = (await this.graftFileText()) !== undefined;
737
+ this.graftsFile = this.graftFileExists && this.o.graftsAdvice;
738
+ this.graftsHint = this.graftsFile;
739
+ if (this.files && this.o.commitGraph.enabled && (await this.hasCommitGraphFile())) {
740
+ this.graphCommits = new Map();
741
+ }
742
+ const refs = this.stores.refs;
743
+ this.shallow = new Set((await refs.getShallow?.()) ?? []);
744
+ await this.readGrafts();
745
+ if (this.files) this.packs = await this.listPacks();
746
+ // git 2.45+: the refs are snapshotted before the objects are read
747
+ const snapshot = this.o.compatibility === "2.56" ? await this.snapshotRefs() : undefined;
748
+ // 2.5x parses each ref's object at the snapshot, through the midx: a tip whose pack-int-id
749
+ // is out of range dies there
750
+ const badMidx = this.midxBadEntry;
751
+ if (snapshot && badMidx && snapshot.some((r) => r.id === badMidx.id))
752
+ return this.death([badMidx.line]);
753
+
754
+ /** connectivity-only: each pack's objects by idx position, and the loose ones */
755
+ let packed: Int32Array[] | undefined;
756
+ let loose: number[] | undefined;
757
+ if (this.o.connectivityOnly) {
758
+ const t = this.t;
759
+ const scan = this.files !== undefined && !this.names && this.packs.length > 0;
760
+ if (scan) {
761
+ packed = this.packs.map((p) => new Int32Array(p.idx.objectCount));
762
+ loose = [];
763
+ }
764
+ await this.forEachStored((raw, at, pack, pos) => {
765
+ // git's lookup_unknown_object
766
+ let n = t.lookupRaw(raw, at);
767
+ if (n < 0) n = t.createRaw(raw, at, OBJ_NONE);
768
+ t.addFlags(n, HAS_OBJ);
769
+ if (packed) {
770
+ if (pack < 0) loose?.push(n);
771
+ else (packed[pack] as Int32Array)[pos] = n;
772
+ }
773
+ });
774
+ } else {
775
+ if (this.files) {
776
+ for (const step of this.sourceSteps()) {
777
+ if ("loose" in step) await this.fsckLooseObjects(step.loose);
778
+ else {
779
+ const packs = step.packs.map((k) => this.packs[k] as RepoPack);
780
+ await this.fsckPacks(packs);
781
+ // 2.5x's verify_bitmap_files, after the source's packs (2.43: at the end)
782
+ if (
783
+ this.o.compatibility === "2.56" &&
784
+ (await this.verifyBitmapFiles(packs, step.dir ?? this.looseDir()))
785
+ )
786
+ this.errorsFound |= FSCK_ERROR_OBJECT;
787
+ // then 2.5x's verify_midx: `git multi-pack-index verify --object-dir <source>`
788
+ if (this.o.compatibility === "2.56" && (await this.verifyMultiPackIndex(step.dir)))
789
+ this.errorsFound |= FSCK_ERROR_OBJECT;
790
+ }
791
+ }
792
+ } else {
793
+ await this.fsckStoredObjects();
794
+ }
795
+ if (await this.fsckFinish()) this.errorsFound |= FSCK_ERROR_OBJECT;
796
+ }
797
+
798
+ // is_promisor_object's set, built when the walk from the refs first asks
799
+ this.promised = this.o.promised;
800
+ if (this.o.loadPromised) {
801
+ try {
802
+ const loaded = await this.o.loadPromised();
803
+ this.promised = loaded.size > 0 ? loaded : undefined;
804
+ } catch (error) {
805
+ if (!(error instanceof PromisorObjectReadError)) throw error;
806
+ if (this.o.compatibility === "2.56") {
807
+ for (const pack of this.opened.values()) pack?.close();
808
+ return this.promisorDeath(error);
809
+ }
810
+ // 2.43 asks only for an object that is missing: it dies there, at the first question
811
+ const loaded = await this.o.loadPromised(true);
812
+ const findings = this.findings;
813
+ const run = this;
814
+ this.promised = {
815
+ has(id: string) {
816
+ run.promisorDeathAt ??= { at: findings.length, error };
817
+ return loaded.has(id);
818
+ },
819
+ } as ReadonlySet<string>;
820
+ }
821
+ }
822
+ const walkAt = this.findings.length;
823
+ if (snapshot) await this.processSnapshot(snapshot);
824
+ else await this.processRefs();
825
+ const indexDeath = await this.processIndexes();
826
+ if (indexDeath) {
827
+ for (const pack of this.opened.values()) pack?.close();
828
+ return this.death(indexDeath);
829
+ }
830
+ if (this.o.connectivityOnly) this.graph = await this.loadCommitGraph();
831
+ if (packed) await this.scanPacks(packed, loose ?? []);
832
+ try {
833
+ await this.checkConnectivity();
834
+ // the walk reads through the midx what it parses again (every object but blobs when
835
+ // connectivity only, else the trees, whose buffers git frees once checked): an object of
836
+ // a pack-int-id out of range dies there, after the lines printed before the walk
837
+ if (badMidx) {
838
+ const n = this.t.lookup(badMidx.id);
839
+ if (
840
+ n >= 0 &&
841
+ this.t.flags(n) & REACHABLE &&
842
+ (this.o.connectivityOnly ? this.t.type(n) !== OBJ_BLOB : this.t.type(n) === OBJ_TREE)
843
+ ) {
844
+ this.findings.length = walkAt;
845
+ return this.death([badMidx.line]);
846
+ }
847
+ }
848
+ await this.verifyCommitGraph();
849
+ // 2.43 checks every pack's bitmap last, --connectivity-only too (ERROR_BITMAP, 0200)
850
+ if (
851
+ this.files &&
852
+ this.o.compatibility === "2.43" &&
853
+ (await this.verifyBitmapFiles(this.packs))
854
+ )
855
+ this.errorsFound |= FSCK_ERROR_BITMAP_243;
856
+ // 2.43 runs `git multi-pack-index verify` for every source last (ERROR_MULTI_PACK_INDEX)
857
+ if (this.files && this.o.compatibility === "2.43") {
858
+ for (const dir of this.sourceDirs())
859
+ if (await this.verifyMultiPackIndex(dir))
860
+ this.errorsFound |= FSCK_ERROR_MULTI_PACK_INDEX_243;
861
+ }
862
+ } finally {
863
+ for (const pack of this.opened.values()) pack?.close();
864
+ }
865
+
866
+ if (this.promisorDeathAt) {
867
+ this.findings.length = this.promisorDeathAt.at;
868
+ return this.promisorDeath(this.promisorDeathAt.error);
869
+ }
870
+ const out = this.findings.filter((f) => f.stream === "stdout").map((f) => `${f.text}\n`);
871
+ const err = this.findings.filter((f) => f.stream === "stderr").map((f) => `${f.text}\n`);
872
+ return {
873
+ exitCode: this.errorsFound,
874
+ findings: this.findings,
875
+ output: out.join(""),
876
+ errorOutput: err.join(""),
877
+ statistics: {
878
+ objectsRead: this.objectsRead,
879
+ commitsFromGraph: this.graphParsed,
880
+ objectsScanned: this.objectsScanned,
881
+ linksKept: this.kidsLength + this.scanKidsLength,
882
+ graphCommitsKept: this.graphCommitsKept,
883
+ },
884
+ };
885
+ }
886
+
887
+ /**
888
+ * One `git multi-pack-index verify --object-dir <objectsDir>` child of fsck: its stderr
889
+ * follows; true when it failed. Nothing without `core.multiPackIndex` or a FilesApi.
890
+ */
891
+ private async verifyMultiPackIndex(objectsDir: string | undefined): Promise<boolean> {
892
+ if (!this.files || objectsDir === undefined || this.o.multiPackIndex === false) return false;
893
+ const result = await multiPackIndexVerify({
894
+ files: this.files,
895
+ objectsDir,
896
+ compatibility: this.o.compatibility,
897
+ });
898
+ for (const text of result.stderr)
899
+ this.emit({ kind: "multi-pack-index", stream: "stderr", text });
900
+ return result.exitCode !== 0;
901
+ }
902
+
903
+ /** A death with git's lines on stderr: exit 128. */
904
+ private death(lines: readonly string[]): FsckResult {
905
+ for (const text of lines) this.emit({ kind: "error", stream: "stderr", text });
906
+ const err = this.findings.filter((f) => f.stream === "stderr").map((f) => `${f.text}\n`);
907
+ const out = this.findings.filter((f) => f.stream === "stdout").map((f) => `${f.text}\n`);
908
+ return {
909
+ exitCode: 128,
910
+ findings: this.findings,
911
+ output: out.join(""),
912
+ errorOutput: err.join(""),
913
+ statistics: {
914
+ objectsRead: this.objectsRead,
915
+ commitsFromGraph: this.graphParsed,
916
+ objectsScanned: this.objectsScanned,
917
+ linksKept: this.kidsLength + this.scanKidsLength,
918
+ graphCommitsKept: this.graphCommitsKept,
919
+ },
920
+ };
921
+ }
922
+
923
+ /** add_promisor_object's death on a promisor pack's unreadable object: exit 128. */
924
+ private promisorDeath(error: PromisorObjectReadError): FsckResult {
925
+ const pack = this.packs.find((p) => p.idx.has(error.objectId));
926
+ const where = pack ? pack.packPath : `pack-${error.packId}.pack`;
927
+ this.emit({
928
+ kind: "error",
929
+ stream: "stderr",
930
+ text: `fatal: packed object ${error.objectId} (stored in ${where}) is corrupt`,
931
+ });
932
+ const out = this.findings.filter((f) => f.stream === "stdout").map((f) => `${f.text}\n`);
933
+ const err = this.findings.filter((f) => f.stream === "stderr").map((f) => `${f.text}\n`);
934
+ return {
935
+ exitCode: 128,
936
+ findings: this.findings,
937
+ output: out.join(""),
938
+ errorOutput: err.join(""),
939
+ statistics: {
940
+ objectsRead: this.objectsRead,
941
+ commitsFromGraph: this.graphParsed,
942
+ objectsScanned: this.objectsScanned,
943
+ linksKept: this.kidsLength + this.scanKidsLength,
944
+ graphCommitsKept: this.graphCommitsKept,
945
+ },
946
+ };
947
+ }
948
+
949
+ /**
950
+ * git's fsck runs `git commit-graph verify --object-dir <objects>` for every object
951
+ * directory (the repository's, then each alternate's) when `core.commitGraph` is on: their
952
+ * stderr follows, and a failure sets ERROR_COMMIT_GRAPH.
953
+ */
954
+ private async verifyCommitGraph(): Promise<void> {
955
+ const settings = this.o.commitGraph;
956
+ if (!this.files || !settings.enabled) return;
957
+ // fsck itself loads the graph when it parses the commit of a ref (parse_object looks it
958
+ // up there first; fsck disables replace refs): what loading prints comes once from fsck,
959
+ // for each directory read until one has a graph (prepare_commit_graph)
960
+ if (
961
+ (await this.hasRefs()) &&
962
+ (await commitGraphCompatible({
963
+ files: this.files,
964
+ gitDir: this.gitDir,
965
+ useReplaceRefs: false,
966
+ readGraftFile: () => this.graftFileText(),
967
+ }))
968
+ ) {
969
+ for (const dir of this.sourceDirs()) {
970
+ const read = await readCommitGraph(this.files, dir, settings, this.sourceDirs());
971
+ for (const d of read.diagnostics) {
972
+ this.emit({ kind: "commit-graph", stream: "stderr", text: `${d.level}: ${d.message}` });
973
+ }
974
+ if (read.graph) break;
975
+ }
976
+ }
977
+ for (const dir of this.sourceDirs()) await this.verifySourceCommitGraph(dir);
978
+ }
979
+
980
+ /** One `git commit-graph verify --object-dir <objectsDir>` child of fsck. */
981
+ private async verifySourceCommitGraph(objectsDir: string): Promise<void> {
982
+ const settings = this.o.commitGraph;
983
+ if (!this.files) return;
984
+ // git's `git commit-graph verify` reads each commit (in the graph's order) from the first
985
+ // pack of its most-recently-used list that has it: a commit in several packs is read from
986
+ // the one the commit before it came from, when that one has it too
987
+ const packs = this.packs;
988
+ const mru = [...packs];
989
+ const packOf = (id: string): RepoPack | undefined => {
990
+ for (let i = 0; i < mru.length; i++) {
991
+ const p = mru[i] as RepoPack;
992
+ if (!p.idx.has(id)) continue;
993
+ if (i > 0) {
994
+ mru.splice(i, 1);
995
+ mru.unshift(p);
996
+ }
997
+ return p;
998
+ }
999
+ return undefined;
1000
+ };
1001
+ // The verification is a process of its own, which reads the grafts file again (and gives
1002
+ // its hint again) when it parses its first commit: parse_commit_buffer looks the commit's
1003
+ // grafts up once the tree line is read, so not for a commit that is missing, of another
1004
+ // type, or without a sound tree line.
1005
+ // Once read, a grafted commit reads with its grafted parents, and the commits it grafts
1006
+ // lose the parents they were given from the graph (register_commit_graft unparses them):
1007
+ // their graph parent lists read as empty.
1008
+ let childGrafts = this.graftFileExists;
1009
+ let graftsRead = false;
1010
+ const reachGrafts = (note: (line: string) => void, data?: Uint8Array) => {
1011
+ if (!childGrafts || (data && !treeLineSound(data))) return;
1012
+ childGrafts = false;
1013
+ graftsRead = true;
1014
+ if (this.graftsFile) for (const line of this.graftsHintLines()) note(line);
1015
+ for (const line of this.graftErrorLines) note(line);
1016
+ };
1017
+ const grafted = (data: GraphCommitData | undefined, id: string) => {
1018
+ const parents = graftsRead && data ? this.graftedParents(id) : undefined;
1019
+ return parents && data ? { ...data, parents } : data;
1020
+ };
1021
+ const result = await verifyCommitGraph(
1022
+ this.files,
1023
+ objectsDir,
1024
+ (id, note) => {
1025
+ const read = this.readVerifiedCommit(id, note, packs, packOf, reachGrafts);
1026
+ return read instanceof Promise ? read.then((d) => grafted(d, id)) : grafted(read, id);
1027
+ },
1028
+ {
1029
+ settings,
1030
+ // the child's layers come from every object directory of the repository
1031
+ objectDirs: this.sourceDirs(),
1032
+ ...(this.grafts
1033
+ ? {
1034
+ ungraphedParents: (id: string) => graftsRead && this.graftedParents(id) !== undefined,
1035
+ }
1036
+ : {}),
1037
+ },
1038
+ );
1039
+ for (const text of result.messages) this.emit({ kind: "commit-graph", stream: "stderr", text });
1040
+ if (result.exitCode !== 0) this.errorsFound |= FSCK_ERROR_COMMIT_GRAPH;
1041
+ }
1042
+
1043
+ /** Commit `id` as `git commit-graph verify` reads it from the object database. */
1044
+ private readVerifiedCommit(
1045
+ id: string,
1046
+ note: (line: string) => void,
1047
+ packs: RepoPack[],
1048
+ packOf: (id: string) => RepoPack | undefined,
1049
+ reachGrafts: (note: (line: string) => void, data?: Uint8Array) => void,
1050
+ ): GraphCommitData | undefined | Promise<GraphCommitData | undefined> {
1051
+ const objects = this.objects;
1052
+ const from = packs.length > 1 ? packOf(id) : undefined;
1053
+ if (from && from !== packs.find((p) => p.idx.has(id))) {
1054
+ // not the copy kept (the newest pack's): that pack's own
1055
+ return this.readPackedCommit(from, id, (data) => reachGrafts(note, data));
1056
+ }
1057
+ const kept = this.graphCommits?.get(id);
1058
+ if (kept) {
1059
+ reachGrafts(note);
1060
+ return kept;
1061
+ }
1062
+ const parse = (o: GitObject | undefined, data: Uint8Array) => {
1063
+ if (o?.type !== "commit") return undefined;
1064
+ reachGrafts(note, data);
1065
+ return parseGraphCommit(data, id);
1066
+ };
1067
+ const slow = async (o: GitObject | undefined | Promise<GitObject | undefined>) => {
1068
+ try {
1069
+ const obj = await o;
1070
+ if (!obj) return undefined;
1071
+ return parse(obj, obj.bytes ?? (await collect(obj)));
1072
+ } catch {
1073
+ return undefined;
1074
+ }
1075
+ };
1076
+ try {
1077
+ // without a promise when the store has the commit in memory
1078
+ const o = objects.getNow ? objects.getNow(id) : objects.get(id);
1079
+ if (o instanceof Promise || (o && !o.bytes)) return slow(o);
1080
+ return o ? parse(o, o.bytes as Uint8Array) : undefined;
1081
+ } catch {
1082
+ return undefined;
1083
+ }
1084
+ }
1085
+
1086
+ /**
1087
+ * Commit `id` as pack `p` holds it, unchecked, for the commit-graph verification; `parsing`
1088
+ * sees its data before it is parsed.
1089
+ */
1090
+ private async readPackedCommit(
1091
+ p: RepoPack,
1092
+ id: string,
1093
+ parsing: (data: Uint8Array) => void,
1094
+ ): Promise<GraphCommitData | undefined> {
1095
+ try {
1096
+ const pack = await this.openRepoPack(p);
1097
+ const obj = await pack?.get(id);
1098
+ if (obj?.type !== "commit") return undefined;
1099
+ const data = await collect(obj);
1100
+ parsing(data);
1101
+ return parseGraphCommit(data, id);
1102
+ } catch {
1103
+ return undefined;
1104
+ }
1105
+ }
1106
+
1107
+ /** Whether the objects directory has a commit-graph file or chain. */
1108
+ private async hasCommitGraphFile(): Promise<boolean> {
1109
+ const files = this.files as FilesApi;
1110
+ const info = pathOf(this.gitDir, "objects", "info");
1111
+ try {
1112
+ if ((await files.stats(pathOf(info, "commit-graph")))?.kind === "file") return true;
1113
+ return (await files.stats(pathOf(info, "commit-graphs")))?.kind === "directory";
1114
+ } catch {
1115
+ return false;
1116
+ }
1117
+ }
1118
+
1119
+ /**
1120
+ * A commit read in pack order, kept for the commit-graph verification (`graphCommits`), when
1121
+ * this is the copy the verification reads (git's repo_read_object_file: the first pack in
1122
+ * pack order that has it, unchecked): the callers pass each pack's copies in that order and
1123
+ * `skipGraphCommit` for a copy they could not unpack. At most `graphCommitsKept` of them.
1124
+ */
1125
+ private keepGraphCommit(id: string, content: Uint8Array): void {
1126
+ const map = this.graphCommits;
1127
+ if (!map || this.graphCommitsKept >= this.o.graphCommitsKept || map.has(id)) return;
1128
+ try {
1129
+ map.set(id, parseGraphCommit(content, id));
1130
+ this.graphCommitsKept++;
1131
+ } catch {
1132
+ // read again (and failed again) by the verification
1133
+ map.set(id, null);
1134
+ }
1135
+ }
1136
+
1137
+ /** A copy `keepGraphCommit` cannot take: the verification reads the object from the store. */
1138
+ private skipGraphCommit(id: string): void {
1139
+ const map = this.graphCommits;
1140
+ if (map && !map.has(id)) map.set(id, null);
1141
+ }
1142
+
1143
+ /**
1144
+ * The graph git's repo_parse_commit reads commits from: `core.commitGraph` on, a repository
1145
+ * the graph is valid for (no grafts, not shallow; fsck disables replace refs), a graph that
1146
+ * loads. Undefined otherwise: commits are read from the object store.
1147
+ */
1148
+ private async loadCommitGraph(): Promise<CommitGraph | undefined> {
1149
+ const settings = this.o.commitGraph;
1150
+ if (!this.files || !settings.enabled) return undefined;
1151
+ try {
1152
+ if (
1153
+ !(await commitGraphCompatible({
1154
+ files: this.files,
1155
+ gitDir: this.gitDir,
1156
+ useReplaceRefs: false,
1157
+ readGraftFile: () => this.graftFileText(),
1158
+ }))
1159
+ ) {
1160
+ return undefined;
1161
+ }
1162
+ // the first graph among the object directories (prepare_commit_graph)
1163
+ for (const dir of this.sourceDirs()) {
1164
+ const graph = (await readCommitGraph(this.files, dir, settings, this.sourceDirs())).graph;
1165
+ if (graph) return graph;
1166
+ }
1167
+ return undefined;
1168
+ } catch {
1169
+ return undefined;
1170
+ }
1171
+ }
1172
+
1173
+ /**
1174
+ * git's parse_commit_in_graph for object `n`, a commit not parsed yet: its parents (looked up
1175
+ * first, as fill_commit_in_graph inserts them) and its tree from the graph. False when the
1176
+ * graph does not have it (or names something of another type): the commit is read then.
1177
+ */
1178
+ private parseCommitInGraph(n: number, id: string): boolean {
1179
+ const g = this.graph as CommitGraph;
1180
+ const t = this.t;
1181
+ const pos = g.positionOfBytes(t.idBytes(n));
1182
+ if (pos < 0) return false;
1183
+ const parents: number[] = [];
1184
+ if (!this.shallow.has(id)) {
1185
+ for (const pp of g.parentPositionsAt(pos)) {
1186
+ const [layer, local] = g.locate(pp);
1187
+ const parent = t.lookupTypedRaw(
1188
+ layer.bytes,
1189
+ layer.oidLookup.offset + 20 * local,
1190
+ OBJ_COMMIT,
1191
+ );
1192
+ if (typeof parent !== "number") return false;
1193
+ parents.push(parent);
1194
+ }
1195
+ }
1196
+ const [layer, local] = g.locate(pos);
1197
+ const tree = t.lookupTypedRaw(layer.bytes, layer.dataOffset(local), OBJ_TREE);
1198
+ if (typeof tree !== "number") return false;
1199
+ t.links.set(n, { tree, parents });
1200
+ t.addFlags(n, PARSED);
1201
+ this.graphParsed++;
1202
+ return true;
1203
+ }
1204
+
1205
+ /**
1206
+ * git's prepare_commit_graft for fsck: the grafts file read (`info/grafts`, or the file
1207
+ * `GIT_GRAFT_FILE` names; fsck applies grafts, as every parse_commit does; replace refs it
1208
+ * turns off), its bad lines kept to be reported.
1209
+ */
1210
+ private async readGrafts(): Promise<void> {
1211
+ const text = await this.graftFileText();
1212
+ if (text === undefined) return;
1213
+ const { grafts, messages } = parseGraftFile(text);
1214
+ if (grafts.size > 0) this.grafts = grafts;
1215
+ this.graftErrors = messages;
1216
+ this.graftErrorLines = messages;
1217
+ }
1218
+
1219
+ /**
1220
+ * The grafts file's text (git's repo_get_graft_file: `GIT_GRAFT_FILE`, else
1221
+ * `<GIT_DIR>/info/grafts`), read once; undefined when there is none or it cannot be read
1222
+ * (git warns and goes on).
1223
+ */
1224
+ private graftFileText(): Promise<string | undefined> {
1225
+ if (!this.graftText) {
1226
+ const read = this.o.readGraftFile;
1227
+ const files = this.files;
1228
+ const path = pathOf(this.gitDir, "info", "grafts");
1229
+ this.graftText = (async () => {
1230
+ if (read) return read();
1231
+ if (!files || (await files.stats(path))?.kind !== "file") return undefined;
1232
+ return new TextDecoder().decode(await readFile(files, path));
1233
+ })().catch(() => undefined);
1234
+ }
1235
+ return this.graftText;
1236
+ }
1237
+
1238
+ /** The grafts file's text once read (see graftFileText). */
1239
+ private graftText?: Promise<string | undefined>;
1240
+
1241
+ /** The grafted parents of commit `id`; undefined when not grafted (or shallow). */
1242
+ private graftedParents(id: string): string[] | undefined {
1243
+ if (!this.grafts || this.shallow.has(id)) return undefined;
1244
+ return this.grafts.get(id);
1245
+ }
1246
+
1247
+ /** The grafts file's errors (`error: bad graft data: <line>`), once. */
1248
+ private reportGraftErrors(): void {
1249
+ const errors = this.graftErrors;
1250
+ this.graftErrors = [];
1251
+ for (const text of errors) this.emit({ kind: "error", stream: "stderr", text });
1252
+ }
1253
+
1254
+ /** Whether HEAD or any ref names an object. */
1255
+ private async hasRefs(): Promise<boolean> {
1256
+ const refs = this.stores.refs;
1257
+ for await (const ref of refs.list("refs/")) if (!isSymbolicRef(ref)) return true;
1258
+ return (await refs.resolve("HEAD").catch(() => undefined))?.objectId !== undefined;
1259
+ }
1260
+
1261
+ // ------------------------------------------------------------------------------------------
1262
+ // Output
1263
+
1264
+ private emit(finding: FsckFinding): void {
1265
+ this.findings.push(finding);
1266
+ }
1267
+
1268
+ /** Whether the grafts file's deprecation hint is still to be printed (`adviseGrafts`). */
1269
+ private graftsHint = false;
1270
+ /** Whether `<GIT_DIR>/info/grafts` is a file and `advice.graftFileDeprecated` is on. */
1271
+ private graftsFile = false;
1272
+
1273
+ /**
1274
+ * git's read_graft_file, when the first commit is parsed (prepare_commit_graft): the hint
1275
+ * that `<GIT_DIR>/info/grafts` is deprecated, once, as each version words it.
1276
+ */
1277
+ private adviseGrafts(): void {
1278
+ if (!this.graftsHint) return;
1279
+ this.graftsHint = false;
1280
+ for (const text of this.graftsHintLines())
1281
+ this.emit({ kind: "notice", stream: "stderr", text });
1282
+ }
1283
+
1284
+ /** The grafts file's deprecation hint, as each version words it. */
1285
+ private graftsHintLines(): string[] {
1286
+ const v243 = this.o.compatibility === "2.43";
1287
+ const blank = v243 ? "hint: " : "hint:";
1288
+ const lines = [
1289
+ "hint: Support for <GIT_DIR>/info/grafts is deprecated",
1290
+ "hint: and will be removed in a future Git version.",
1291
+ blank,
1292
+ 'hint: Please use "git replace --convert-graft-file"',
1293
+ "hint: to convert the grafts into replace refs.",
1294
+ blank,
1295
+ "hint: Turn this message off by running",
1296
+ v243
1297
+ ? 'hint: "git config advice.graftFileDeprecated false"'
1298
+ : 'hint: "git config set advice.graftFileDeprecated false"',
1299
+ ];
1300
+ return lines;
1301
+ }
1302
+
1303
+ /** git's `error()`: `error: <message>` on stderr. */
1304
+ private error(message: string, objectId?: string): void {
1305
+ this.emit({ kind: "error", stream: "stderr", text: `error: ${message}`, objectId });
1306
+ }
1307
+
1308
+ private describe(id: string): string {
1309
+ const name = this.names?.get(id);
1310
+ return name === undefined ? id : `${id} (${name})`;
1311
+ }
1312
+
1313
+ private putName(id: string, name: string): void {
1314
+ if (this.names && !this.names.has(id)) this.names.set(id, name);
1315
+ }
1316
+
1317
+ /** git's `printable_type`: the object's type, read from the store when not known yet. */
1318
+ private async printableType(n: number): Promise<string> {
1319
+ const type = this.t.type(n);
1320
+ if (type !== OBJ_NONE) return TYPE_NAME[type];
1321
+ const stored = await this.storeType(this.t.id(n));
1322
+ return stored ?? "unknown";
1323
+ }
1324
+
1325
+ /** git's `objerror`. */
1326
+ private async objerror(n: number, message: string): Promise<void> {
1327
+ this.errorsFound |= FSCK_ERROR_OBJECT;
1328
+ const id = this.t.id(n);
1329
+ const type = await this.printableType(n);
1330
+ this.emit({
1331
+ kind: "error",
1332
+ stream: "stderr",
1333
+ text: `error in ${type} ${this.describe(id)}: ${message}`,
1334
+ objectId: id,
1335
+ objectType: type,
1336
+ });
1337
+ }
1338
+
1339
+ /** The report function of git's object checks for one object. */
1340
+ private reporter(id: string, type: string) {
1341
+ return (msgId: FsckMsgId, message: string): number => {
1342
+ const severity = this.types.severity(msgId);
1343
+ if (severity === "ignore") return 0;
1344
+ const label = severity === "error" ? "error" : "warning";
1345
+ this.emit({
1346
+ kind: "object",
1347
+ stream: "stderr",
1348
+ text: `${label} in ${type} ${this.describe(id)}: ${msgId}: ${message}`,
1349
+ objectId: id,
1350
+ objectType: type,
1351
+ msgId,
1352
+ severity,
1353
+ });
1354
+ return severity === "error" ? 1 : 0;
1355
+ };
1356
+ }
1357
+
1358
+ // ------------------------------------------------------------------------------------------
1359
+ // The object store
1360
+
1361
+ /** The zlib error of the last failed read, as git's `git_inflate` prints it. */
1362
+ private lastZlibError?: string;
1363
+
1364
+ private async readObject(id: string): Promise<GitObject | undefined> {
1365
+ this.lastZlibError = undefined;
1366
+ try {
1367
+ return await this.objects.get(id);
1368
+ } catch (e) {
1369
+ this.noteReadError(e);
1370
+ return undefined;
1371
+ }
1372
+ }
1373
+
1374
+ private noteReadError(e: unknown): void {
1375
+ const inflate = /inflate failed: (.*)$/.exec(e instanceof Error ? e.message : "")?.[1];
1376
+ if (inflate) this.lastZlibError = `inflate: data stream error (${inflate})`;
1377
+ }
1378
+
1379
+ /**
1380
+ * The whole object from the store, without a promise when the store holds it in memory (a
1381
+ * packed object in a loaded window or the base cache: `getNow`).
1382
+ */
1383
+ private readWhole(id: string): Whole | undefined | Promise<Whole | undefined> {
1384
+ this.lastZlibError = undefined;
1385
+ this.objectsRead++;
1386
+ let obj: GitObject | undefined | Promise<GitObject | undefined>;
1387
+ try {
1388
+ obj = this.objects.getNow ? this.objects.getNow(id) : this.objects.get(id);
1389
+ } catch (e) {
1390
+ this.noteReadError(e);
1391
+ return undefined;
1392
+ }
1393
+ if (obj instanceof Promise) {
1394
+ return obj.then(
1395
+ (o) => this.wholeOf(o),
1396
+ (e) => {
1397
+ this.noteReadError(e);
1398
+ return undefined;
1399
+ },
1400
+ );
1401
+ }
1402
+ return this.wholeOf(obj);
1403
+ }
1404
+
1405
+ private wholeOf(obj: GitObject | undefined): Whole | undefined | Promise<Whole | undefined> {
1406
+ if (!obj) return undefined;
1407
+ // in memory already (the buffer is ours, and `content` needs no release)
1408
+ if (obj.bytes) return { type: obj.type, content: obj.bytes };
1409
+ return collect(obj).then(
1410
+ (content) => ({ type: obj.type, content }),
1411
+ (e) => {
1412
+ this.noteReadError(e);
1413
+ return undefined;
1414
+ },
1415
+ );
1416
+ }
1417
+
1418
+ private async storeType(id: string): Promise<string | undefined> {
1419
+ if (this.o.connectivityOnly) {
1420
+ const type = await this.packedType(id);
1421
+ if (type) return type;
1422
+ }
1423
+ const obj = await this.readObject(id);
1424
+ if (!obj) return undefined;
1425
+ await obj.content[Symbol.asyncIterator]().return?.();
1426
+ return obj.type;
1427
+ }
1428
+
1429
+ /** The repository's packs, opened to read entry headers (`packedType`). */
1430
+ private readonly opened = new Map<RepoPack, PackFile | undefined>();
1431
+
1432
+ /** Pack `p`, opened once (undefined when it cannot be). */
1433
+ private async openRepoPack(p: RepoPack): Promise<PackFile | undefined> {
1434
+ if (!this.opened.has(p)) {
1435
+ const pack = await openPack(this.files as FilesApi, p.packPath, p.idxPath, {
1436
+ idxBytes: p.idxBytes,
1437
+ }).catch(() => undefined);
1438
+ this.opened.set(p, pack);
1439
+ }
1440
+ return this.opened.get(p);
1441
+ }
1442
+
1443
+ /**
1444
+ * The type of a packed object from its entry header, following a delta's bases through
1445
+ * theirs, as git's `packed_object_info`: nothing is inflated (connectivity-only runs read no
1446
+ * blob). Undefined when the headers do not tell (the object is not packed, a base is
1447
+ * elsewhere, a header is corrupt): the store reads the object then.
1448
+ */
1449
+ private async packedType(id: string): Promise<string | undefined> {
1450
+ const p = this.packs.find((x) => x.idx.has(id));
1451
+ if (!p) return undefined;
1452
+ const pack = await this.openRepoPack(p);
1453
+ if (!pack || p.idx.version < 2) return undefined;
1454
+ try {
1455
+ let at = id;
1456
+ for (let depth = 0; depth <= 4096; depth++) {
1457
+ const e = await pack.entry(at);
1458
+ if (!e) return undefined;
1459
+ if (e.kind <= 4) return TYPE_NAME[e.kind as ObjType];
1460
+ if (!e.baseId || !pack.has(e.baseId)) return undefined;
1461
+ at = e.baseId;
1462
+ }
1463
+ } catch {
1464
+ // a corrupt entry: read through the store
1465
+ }
1466
+ return undefined;
1467
+ }
1468
+
1469
+ /** git's `has_object`. */
1470
+ private async hasObject(id: string): Promise<boolean> {
1471
+ try {
1472
+ return await this.objects.has(id);
1473
+ } catch {
1474
+ return false;
1475
+ }
1476
+ }
1477
+
1478
+ /** git's `has_object_pack`. */
1479
+ private inPack(id: string): boolean {
1480
+ return this.packs.some((p) => p.idx.has(id));
1481
+ }
1482
+
1483
+ private looseDir(): string {
1484
+ return pathOf(this.gitDir, "objects");
1485
+ }
1486
+
1487
+ /** The object directories: the repository's, then its alternates' (git's odb sources). */
1488
+ private sourceDirs(): string[] {
1489
+ return [this.looseDir(), ...(this.o.alternateDirs ?? [])];
1490
+ }
1491
+
1492
+ /**
1493
+ * Every pack of every source, in the order git lists them: 2.56 source by source (each
1494
+ * source's packs newest first), 2.43 the repository's packs, then all of its alternates'
1495
+ * (get_all_packs' sort_pack: local first, then the most recently modified).
1496
+ */
1497
+ private async listPacks(): Promise<RepoPack[]> {
1498
+ const dirs = this.sourceDirs();
1499
+ const all: (RepoPack & { mtime: number })[] = [];
1500
+ for (let i = 0; i < dirs.length; i++)
1501
+ all.push(...(await this.listSourcePacks(dirs[i] as string, i)));
1502
+ if (this.o.compatibility === "2.43") {
1503
+ all.sort(
1504
+ (a, b) =>
1505
+ Number(a.source !== 0) - Number(b.source !== 0) ||
1506
+ b.mtime - a.mtime ||
1507
+ (a.packPath < b.packPath ? -1 : 1),
1508
+ );
1509
+ }
1510
+ return all;
1511
+ }
1512
+
1513
+ private async listSourcePacks(
1514
+ objectsDir: string,
1515
+ source: number,
1516
+ ): Promise<(RepoPack & { mtime: number })[]> {
1517
+ const files = this.files as FilesApi;
1518
+ const dir = pathOf(objectsDir, "pack");
1519
+ if ((await files.stats(dir))?.kind !== "directory") return [];
1520
+ const found: (RepoPack & { mtime: number })[] = [];
1521
+ for await (const e of files.list(dir)) {
1522
+ if (e.kind !== "file" || !PACK_IDX.test(e.name)) continue;
1523
+ const idxPath = pathOf(dir, e.name);
1524
+ const packPath = `${idxPath.slice(0, -4)}.pack`;
1525
+ const stats = await files.stats(packPath);
1526
+ if (stats?.kind !== "file") continue;
1527
+ try {
1528
+ const idxBytes = await readAll(files, idxPath);
1529
+ const idx = readPackIndex(idxBytes);
1530
+ found.push({ packPath, idxPath, idx, idxBytes, source, mtime: stats.lastModified ?? 0 });
1531
+ } catch {
1532
+ // git does not list a pack whose idx cannot be opened
1533
+ }
1534
+ }
1535
+ // git's sort_pack: the most recently modified first
1536
+ found.sort((a, b) => b.mtime - a.mtime || (a.packPath < b.packPath ? -1 : 1));
1537
+ return found;
1538
+ }
1539
+
1540
+ /**
1541
+ * The loose object files of each fan-out directory of `objectsDir` (default the
1542
+ * repository's), in directory order, and its other entries.
1543
+ */
1544
+ private async *looseEntries(
1545
+ objectsDir = this.looseDir(),
1546
+ ): AsyncIterable<{ id?: string; path: string; name: string }> {
1547
+ const files = this.files as FilesApi;
1548
+ for (let i = 0; i < 256; i++) {
1549
+ const sub = i.toString(16).padStart(2, "0");
1550
+ const dir = pathOf(objectsDir, sub);
1551
+ if ((await files.stats(dir))?.kind !== "directory") continue;
1552
+ const entries: { name: string; path: string }[] = [];
1553
+ for await (const e of files.list(dir)) entries.push({ name: e.name, path: e.path });
1554
+ // in the order the files list them, as git's readdir loop: it decides hash collisions
1555
+ for (const e of entries) {
1556
+ const path = pathOf(dir, e.name);
1557
+ yield LOOSE_NAME.test(e.name)
1558
+ ? { id: sub + e.name, path, name: e.name }
1559
+ : { path, name: e.name };
1560
+ }
1561
+ }
1562
+ }
1563
+
1564
+ /**
1565
+ * The order git reads the sources in: 2.56 one source at a time (its loose objects, then its
1566
+ * packs: odb_fsck / odb_for_each_object), 2.43 the loose objects of every source, then every
1567
+ * pack. Each step names a source's loose objects (`loose`) or the packs to read (`packs`,
1568
+ * indexes into `this.packs`).
1569
+ */
1570
+ private sourceSteps(): ({ loose: string } | { packs: number[]; dir?: string })[] {
1571
+ const dirs = this.sourceDirs();
1572
+ const all = this.packs.map((_, k) => k);
1573
+ if (this.o.compatibility === "2.43") {
1574
+ return [...dirs.map((loose) => ({ loose })), { packs: all }];
1575
+ }
1576
+ return dirs.flatMap((loose, i) => [
1577
+ { loose },
1578
+ { packs: all.filter((k) => (this.packs[k] as RepoPack).source === i), dir: loose },
1579
+ ]);
1580
+ }
1581
+
1582
+ /**
1583
+ * Every stored id, as its 20 bytes at `at` in `raw` (valid during the call): loose ones, then
1584
+ * each pack's in idx order (git's for_each_*_object). A pack's ids are read from its idx.
1585
+ */
1586
+ private async forEachStored(
1587
+ visit: (raw: Uint8Array, at: number, pack: number, pos: number) => void | Promise<void>,
1588
+ ): Promise<void> {
1589
+ const scratch = new Uint8Array(20);
1590
+ // ids listed here are 40 lowercase hex digits
1591
+ const nibble = (c: number) => (c <= 0x39 ? c - 0x30 : c - 0x57);
1592
+ const parsed = (id: string) => {
1593
+ for (let i = 0; i < 20; i++)
1594
+ scratch[i] = (nibble(id.charCodeAt(2 * i)) << 4) | nibble(id.charCodeAt(2 * i + 1));
1595
+ return scratch;
1596
+ };
1597
+ if (!this.files) {
1598
+ const ids: string[] = [];
1599
+ for await (const id of this.objects.list()) ids.push(id);
1600
+ ids.sort();
1601
+ for (const id of ids) {
1602
+ const r = visit(parsed(id), 0, -1, -1);
1603
+ if (r) await r;
1604
+ }
1605
+ return;
1606
+ }
1607
+ for (const step of this.sourceSteps()) {
1608
+ if ("loose" in step) {
1609
+ for await (const e of this.looseEntries(step.loose)) {
1610
+ if (!e.id) continue;
1611
+ const r = visit(parsed(e.id), 0, -1, -1);
1612
+ if (r) await r;
1613
+ }
1614
+ continue;
1615
+ }
1616
+ for (const k of step.packs) {
1617
+ const p = this.packs[k] as RepoPack;
1618
+ const v2 = p.idx.version > 1;
1619
+ const idsAt = v2 ? 8 + 1024 : 1024 + 4;
1620
+ const stride = v2 ? 20 : 24;
1621
+ for (let i = 0, n = p.idx.objectCount; i < n; i++) {
1622
+ const r = visit(p.idxBytes, idsAt + i * stride, k, i);
1623
+ if (r) await r;
1624
+ }
1625
+ }
1626
+ }
1627
+ }
1628
+
1629
+ // ------------------------------------------------------------------------------------------
1630
+ // Reading and checking every object
1631
+
1632
+ /**
1633
+ * git's `parse_object_buffer`: the object, or undefined (git's errors printed). `raw` holds
1634
+ * the id's 20 bytes at `rawAt`, when the caller has them (an idx).
1635
+ */
1636
+ private parseObjectBuffer(
1637
+ id: string,
1638
+ type: ObjType,
1639
+ content: Uint8Array,
1640
+ raw?: Uint8Array,
1641
+ rawAt = 0,
1642
+ ): number | undefined {
1643
+ const t = this.t;
1644
+ const self = raw ? t.lookupTypedRaw(raw, rawAt, type) : t.lookupTyped(id, type);
1645
+ if (typeof self !== "number") {
1646
+ this.error(self.error, id);
1647
+ return undefined;
1648
+ }
1649
+ const n = self;
1650
+ if (type === OBJ_BLOB || type === OBJ_TREE) {
1651
+ t.addFlags(n, PARSED);
1652
+ return n;
1653
+ }
1654
+ if (t.flags(n) & PARSED) return n;
1655
+ if (type === OBJ_COMMIT) {
1656
+ if (this.graftsHint) this.adviseGrafts();
1657
+ if (this.graftErrors.length > 0) this.reportGraftErrors();
1658
+ const parsed = parseCommitLinks(content, id);
1659
+ if ("error" in parsed) {
1660
+ this.error(parsed.error, id);
1661
+ return undefined;
1662
+ }
1663
+ const raw = this.idScratch;
1664
+ const tree = t.lookupTypedRaw(rawIdAt(content, parsed.tree, raw), 0, OBJ_TREE);
1665
+ if (typeof tree !== "number") {
1666
+ this.error(tree.error);
1667
+ this.error(`bad tree pointer ${hexIdAt(content, parsed.tree)} in commit ${id}`, id);
1668
+ return undefined;
1669
+ }
1670
+ const parents: number[] = [];
1671
+ const grafted = this.graftedParents(id);
1672
+ if (grafted) {
1673
+ for (const p of grafted) {
1674
+ const parent = t.lookupTyped(p, OBJ_COMMIT);
1675
+ if (typeof parent !== "number") {
1676
+ this.error(parent.error);
1677
+ this.error(`bad graft parent ${p} in commit ${id}`, id);
1678
+ return undefined;
1679
+ }
1680
+ parents.push(parent);
1681
+ }
1682
+ } else if (!this.shallow.has(id)) {
1683
+ for (const at of parsed.parents) {
1684
+ const parent = t.lookupTypedRaw(rawIdAt(content, at, raw), 0, OBJ_COMMIT);
1685
+ if (typeof parent !== "number") {
1686
+ this.error(parent.error);
1687
+ this.error(`bad parent ${hexIdAt(content, at)} in commit ${id}`, id);
1688
+ return undefined;
1689
+ }
1690
+ parents.push(parent);
1691
+ }
1692
+ }
1693
+ t.links.set(n, { tree, parents });
1694
+ t.addFlags(n, PARSED);
1695
+ return n;
1696
+ }
1697
+ // tag
1698
+ const parsed = parseTagBuffer(content, id);
1699
+ if ("error" in parsed) {
1700
+ if (parsed.error) this.error(parsed.error, id);
1701
+ return undefined;
1702
+ }
1703
+ const tagged = t.lookupTyped(parsed.object, typeOf(parsed.type));
1704
+ if (typeof tagged !== "number") {
1705
+ this.error(tagged.error);
1706
+ this.error(`bad tag pointer to ${parsed.object} in ${id}`, id);
1707
+ return undefined;
1708
+ }
1709
+ if (parsed.tag === undefined) return undefined;
1710
+ t.links.set(n, { tagged, tag: parsed.tag });
1711
+ t.addFlags(n, PARSED);
1712
+ return n;
1713
+ }
1714
+
1715
+ /**
1716
+ * git's `parse_object`: an object already parsed, or read from the store with its hash
1717
+ * checked (`hash mismatch <id>`, and undefined, when its bytes hash to another id: the copy
1718
+ * the store reads first, packed before loose, as git's) and parsed. The roots (refs, the
1719
+ * cache-tree, resolve-undo) and the objects the walk meets untyped (reflog entries in
1720
+ * connectivity-only runs) are parsed this way, trees again each time; the walk reads typed objects unchecked
1721
+ * (`parseAs`, git's repo_parse_commit, parse_tree and parse_tag).
1722
+ */
1723
+ private parseObject(id: string): number | undefined | Promise<number | undefined> {
1724
+ const known = this.t.lookup(id);
1725
+ // a tree is read again: git frees each tree's buffer once checked or walked (parsed = 0)
1726
+ if (known >= 0 && this.t.flags(known) & PARSED && this.t.type(known) !== OBJ_TREE) {
1727
+ return known;
1728
+ }
1729
+ const obj = this.readWhole(id);
1730
+ if (obj instanceof Promise) return obj.then((o) => this.parseVerified(id, o));
1731
+ return this.parseVerified(id, obj);
1732
+ }
1733
+
1734
+ /**
1735
+ * `parseRead` once the bytes hash to `id` (git's check_object_signature). Hashed here, not by
1736
+ * the store: a verified read would mark the copy bad there, and git reads it again as it is.
1737
+ */
1738
+ private parseVerified(id: string, obj: Whole | undefined): number | undefined {
1739
+ if (obj && objectIdOf(obj.type, obj.content) !== id) {
1740
+ this.error(`hash mismatch ${id}`, id);
1741
+ return undefined;
1742
+ }
1743
+ return this.parseRead(id, obj);
1744
+ }
1745
+
1746
+ /**
1747
+ * git's repo_parse_commit and parse_tag of object `n`, a commit or a tag not parsed yet: read
1748
+ * without a hash check, `Could not read <id>` when that fails and `Object <id> not a <type>`
1749
+ * when the store holds another type.
1750
+ */
1751
+ private parseAs(n: number, id: string): void | Promise<void> {
1752
+ const obj = this.readWhole(id);
1753
+ if (obj instanceof Promise) return obj.then((o) => this.parseAsRead(n, id, o));
1754
+ this.parseAsRead(n, id, obj);
1755
+ }
1756
+
1757
+ private parseAsRead(n: number, id: string, obj: Whole | undefined): void {
1758
+ const want = this.t.type(n);
1759
+ if (!obj) {
1760
+ if (this.lastZlibError) this.error(this.lastZlibError);
1761
+ this.error(`Could not read ${id}`);
1762
+ return;
1763
+ }
1764
+ if (typeOf(obj.type) !== want) {
1765
+ this.error(`Object ${id} not a ${TYPE_NAME[want]}`);
1766
+ return;
1767
+ }
1768
+ this.lastRead = { id, obj };
1769
+ this.parseObjectBuffer(id, want, obj.content);
1770
+ }
1771
+
1772
+ private parseRead(id: string, obj: Whole | undefined): number | undefined {
1773
+ if (!obj) {
1774
+ if (this.lastZlibError) this.error(this.lastZlibError);
1775
+ return undefined;
1776
+ }
1777
+ this.lastRead = { id, obj };
1778
+ return this.parseObjectBuffer(id, typeOf(obj.type), obj.content);
1779
+ }
1780
+
1781
+ /**
1782
+ * git's `fsck_obj_buffer` / the end of `fsck_loose`: parses the object, marks it stored and
1783
+ * checks it. Returns nonzero when the object is bad.
1784
+ */
1785
+ private fsckObjBuffer(
1786
+ id: string,
1787
+ type: ObjType,
1788
+ content: Uint8Array | undefined,
1789
+ unparsable: string,
1790
+ size = content?.length ?? 0,
1791
+ raw?: Uint8Array,
1792
+ rawAt = 0,
1793
+ ): number | Promise<number> {
1794
+ // no content: a blob streamed past core.bigFileThreshold (git's NULL buffer)
1795
+ const n = this.parseObjectBuffer(id, type, content ?? EMPTY, raw, rawAt);
1796
+ if (n === undefined) {
1797
+ this.errorsFound |= FSCK_ERROR_OBJECT;
1798
+ this.error(unparsable, id);
1799
+ return -1;
1800
+ }
1801
+ this.t.clearFlags(n, REACHABLE | SEEN);
1802
+ this.t.addFlags(n, HAS_OBJ);
1803
+ return this.fsckObj(n, id, content, size);
1804
+ }
1805
+
1806
+ /** git's `fsck_obj`: without a promise unless it reports through the store. */
1807
+ private fsckObj(
1808
+ n: number,
1809
+ id: string,
1810
+ content: Uint8Array | undefined,
1811
+ size: number,
1812
+ ): number | Promise<number> {
1813
+ const t = this.t;
1814
+ if (t.flags(n) & SEEN) return 0;
1815
+ t.addFlags(n, SEEN);
1816
+ if (this.walkUsed(n, content ?? EMPTY, this.recordTrees)) {
1817
+ return this.objerror(n, "broken links").then(() => this.fsckObjChecks(n, id, content, size));
1818
+ }
1819
+ return this.fsckObjChecks(n, id, content, size);
1820
+ }
1821
+
1822
+ /** The rest of `fsck_obj`: the object checks, `--root` and `--tags`. */
1823
+ private fsckObjChecks(
1824
+ n: number,
1825
+ id: string,
1826
+ content: Uint8Array | undefined,
1827
+ size: number,
1828
+ ): number | Promise<number> {
1829
+ const t = this.t;
1830
+ const type = t.type(n);
1831
+ const err = this.fsckBuffer(id, type, content, size);
1832
+ if (err) return err;
1833
+ if (type === OBJ_COMMIT && this.o.root && t.links.get(n)?.parents?.length === 0) {
1834
+ this.emit({
1835
+ kind: "root",
1836
+ stream: "stdout",
1837
+ text: `root ${this.describe(id)}`,
1838
+ objectId: id,
1839
+ });
1840
+ }
1841
+ if (type === OBJ_TAG && this.o.tags) {
1842
+ const links = t.links.get(n);
1843
+ if (links?.tagged !== undefined) {
1844
+ const target = links.tagged;
1845
+ return this.printableType(target).then((printable) => {
1846
+ this.emit({
1847
+ kind: "tagged",
1848
+ stream: "stdout",
1849
+ text: `tagged ${printable} ${this.describe(t.id(target))} (${links.tag}) in ${this.describe(id)}`,
1850
+ objectId: id,
1851
+ });
1852
+ return 0;
1853
+ });
1854
+ }
1855
+ }
1856
+ return 0;
1857
+ }
1858
+
1859
+ /** Records that tree `n`'s entries start at `start` in `kids` (`treeStart` holds start + 1). */
1860
+ private setTreeStart(n: number, start: number): void {
1861
+ if (n >= this.treeStart.length) {
1862
+ const grown = new Int32Array(Math.max(1024, this.t.size * 2, n + 1));
1863
+ grown.set(this.treeStart);
1864
+ this.treeStart = grown;
1865
+ }
1866
+ this.treeStart[n] = start + 1;
1867
+ }
1868
+
1869
+ /**
1870
+ * Room in `kids` for `more` values past `kidsLength`, within what `linksKept` leaves after
1871
+ * `scanKids` (the limit is the two together); false past it. The array grows by doubling up
1872
+ * to that limit, never past it.
1873
+ */
1874
+ private reserveKids(more: number): boolean {
1875
+ const need = this.kidsLength + more;
1876
+ const limit = this.o.linksKept - this.scanKidsLength;
1877
+ if (need > limit) return false;
1878
+ if (need <= this.kids.length) return true;
1879
+ let size = Math.max(this.kids.length * 2, 1 << 12);
1880
+ while (size < need) size *= 2;
1881
+ const kids = new Int32Array(Math.min(size, limit));
1882
+ kids.set(this.kids.subarray(0, this.kidsLength));
1883
+ this.kids = kids;
1884
+ return true;
1885
+ }
1886
+
1887
+ /**
1888
+ * git's `fsck_walk` with `mark_used`: marks what the object points to as used. With `record`,
1889
+ * a tree whose entries all resolve is remembered as its entries' objects (`treeEntries`).
1890
+ */
1891
+ private walkUsed(n: number, content: Uint8Array, record = false): number {
1892
+ const t = this.t;
1893
+ const type = t.type(n);
1894
+ if (type === OBJ_TREE) {
1895
+ const walk = scanTree(content, this.usedTable);
1896
+ this.lastTree = { content, table: walk };
1897
+ if (walk.initError) {
1898
+ this.error(walk.initError);
1899
+ return -1;
1900
+ }
1901
+ let res = 0;
1902
+ const start = this.kidsLength;
1903
+ // past the limit the walk reads the tree again
1904
+ if (record && !this.reserveKids(1 + walk.count)) record = false;
1905
+ let at = start + 1;
1906
+ const f = walk.fields;
1907
+ for (let i = 0; i < walk.count; i++) {
1908
+ const mode = canonMode(f[3 * i] as number);
1909
+ if (mode === 0o160000) continue;
1910
+ const isTree = mode === 0o040000;
1911
+ const child = t.lookupTypedRaw(
1912
+ content,
1913
+ f[3 * i + 2] as number,
1914
+ isTree ? OBJ_TREE : OBJ_BLOB,
1915
+ );
1916
+ if (typeof child !== "number") {
1917
+ this.error(child.error);
1918
+ res ||= 1;
1919
+ continue;
1920
+ }
1921
+ t.addFlags(child, USED);
1922
+ if (record) this.kids[at++] = (child << 1) | (isTree ? 1 : 0);
1923
+ }
1924
+ if (walk.error) this.error(walk.error);
1925
+ if (record && res === 0 && !walk.error) {
1926
+ this.kids[start] = at - start - 1;
1927
+ this.kidsLength = at;
1928
+ this.setTreeStart(n, start);
1929
+ }
1930
+ return res;
1931
+ }
1932
+ const links = t.links.get(n);
1933
+ if (type === OBJ_COMMIT && links) {
1934
+ if (links.tree !== undefined) t.addFlags(links.tree, USED);
1935
+ for (const p of links.parents ?? []) t.addFlags(p, USED);
1936
+ } else if (type === OBJ_TAG && links?.tagged !== undefined) {
1937
+ t.addFlags(links.tagged, USED);
1938
+ }
1939
+ return 0;
1940
+ }
1941
+
1942
+ /** git's `fsck_buffer`: the object checks of `fsck.c`. */
1943
+ private fsckBuffer(
1944
+ id: string,
1945
+ type: ObjType,
1946
+ buffer: Uint8Array | undefined,
1947
+ size: number,
1948
+ ): number {
1949
+ const report = this.reporter(id, TYPE_NAME[type]);
1950
+ if (type === OBJ_BLOB) return this.fsckBlobOf(id, buffer, size, report);
1951
+ const content = buffer ?? EMPTY;
1952
+ switch (type) {
1953
+ case OBJ_TREE: {
1954
+ const found = { gitmodules: [] as string[], gitattributes: [] as string[] };
1955
+ // the walk just before decoded this tree already
1956
+ const last = this.lastTree;
1957
+ this.lastTree = undefined;
1958
+ const r = fsckTree(
1959
+ content,
1960
+ this.types,
1961
+ report,
1962
+ (m) => this.error(m),
1963
+ found,
1964
+ last?.content === content ? last.table : undefined,
1965
+ );
1966
+ for (const g of found.gitmodules) this.gitmodulesFound.add(g);
1967
+ for (const g of found.gitattributes) this.gitattributesFound.add(g);
1968
+ return r;
1969
+ }
1970
+ case OBJ_COMMIT:
1971
+ return fsckCommit(content, report);
1972
+ case OBJ_TAG:
1973
+ return fsckTag(content, report, { gpgsig: this.o.compatibility !== "2.43" });
1974
+ default:
1975
+ return report("unknownType", `unknown type '${type}' (internal fsck error)`);
1976
+ }
1977
+ }
1978
+
1979
+ private fsckBlobOf(
1980
+ id: string,
1981
+ content: Uint8Array | undefined,
1982
+ size: number,
1983
+ report: ReturnType<FsckRun["reporter"]>,
1984
+ ): number {
1985
+ const gitmodules = this.gitmodulesFound.has(id);
1986
+ const gitattributes = this.gitattributesFound.has(id);
1987
+ if (!gitmodules && !gitattributes) return 0;
1988
+ if (gitmodules) this.gitmodulesDone.add(id);
1989
+ if (gitattributes) this.gitattributesDone.add(id);
1990
+ if (gitmodules && content && content.length < size) {
1991
+ // a loose blob whose stream ended early: git parses its zeros too (`.gitattributes` is
1992
+ // read up to the first NUL, the same with them or without)
1993
+ const padded = new Uint8Array(size);
1994
+ padded.set(content);
1995
+ content = padded;
1996
+ }
1997
+ return fsckBlob(content, size, { gitmodules, gitattributes }, report);
1998
+ }
1999
+
2000
+ /** git's `fsck_finish`: `.gitmodules` and `.gitattributes` blobs not checked yet. */
2001
+ private async fsckFinish(): Promise<number> {
2002
+ let ret = 0;
2003
+ const pass = async (
2004
+ found: Set<string>,
2005
+ done: Set<string>,
2006
+ missing: FsckMsgId,
2007
+ nonBlob: FsckMsgId,
2008
+ name: string,
2009
+ ) => {
2010
+ for (const id of found) {
2011
+ if (done.has(id)) continue;
2012
+ const obj = await this.readWhole(id);
2013
+ if (!obj) {
2014
+ ret |= this.reporter(id, "blob")(missing, `unable to read ${name} blob`);
2015
+ continue;
2016
+ }
2017
+ if (obj.type === "blob") {
2018
+ ret |= this.fsckBlobOf(id, obj.content, obj.content.length, this.reporter(id, "blob"));
2019
+ } else {
2020
+ ret |= this.reporter(id, obj.type)(nonBlob, `non-blob found at ${name}`);
2021
+ }
2022
+ }
2023
+ };
2024
+ await pass(
2025
+ this.gitmodulesFound,
2026
+ this.gitmodulesDone,
2027
+ "gitmodulesMissing",
2028
+ "gitmodulesBlob",
2029
+ ".gitmodules",
2030
+ );
2031
+ await pass(
2032
+ this.gitattributesFound,
2033
+ this.gitattributesDone,
2034
+ "gitattributesMissing",
2035
+ "gitattributesBlob",
2036
+ ".gitattributes",
2037
+ );
2038
+ return ret;
2039
+ }
2040
+
2041
+ /** Blobs whose content a check needs (`.gitmodules`, `.gitattributes`). */
2042
+ private keepBlob = (id: string): boolean =>
2043
+ this.gitmodulesFound.has(id) || this.gitattributesFound.has(id);
2044
+
2045
+ /** git's `fsck_object_dir`: every loose object file of `objectsDir`. */
2046
+ private async fsckLooseObjects(objectsDir: string): Promise<void> {
2047
+ const files = this.files as FilesApi;
2048
+ for await (const e of this.looseEntries(objectsDir)) {
2049
+ if (!e.id) {
2050
+ if (!e.name.startsWith("tmp_obj_")) {
2051
+ this.emit({ kind: "notice", stream: "stderr", text: `bad sha1 file: ${e.path}` });
2052
+ }
2053
+ continue;
2054
+ }
2055
+ const read = await readLooseObject(files, e.path, e.id, {
2056
+ bigFileThreshold: this.o.bigFileThreshold,
2057
+ });
2058
+ for (const m of read.errors) this.error(m, e.id);
2059
+ if (read.errors.length > 0) this.badCopy.add(e.id);
2060
+ if (!read.object) {
2061
+ this.badCopy.add(e.id);
2062
+ if (read.realId)
2063
+ this.error(`${read.realId}: hash-path mismatch, found at: ${e.path}`, e.id);
2064
+ else this.error(`${e.id}: object corrupt or missing: ${e.path}`, e.id);
2065
+ this.errorsFound |= FSCK_ERROR_OBJECT;
2066
+ continue;
2067
+ }
2068
+ const r = await this.fsckObjBuffer(
2069
+ e.id,
2070
+ typeOf(read.object.type),
2071
+ read.object.content,
2072
+ this.o.compatibility === "2.56"
2073
+ ? `${e.id}: object corrupt or missing`
2074
+ : `${e.id}: object could not be parsed: ${e.path}`,
2075
+ read.object.size,
2076
+ );
2077
+ if (r > 0) this.errorsFound |= FSCK_ERROR_OBJECT;
2078
+ }
2079
+ }
2080
+
2081
+ /**
2082
+ * git's `verify_bitmap_files`: the trailing SHA-1 of each pack's `.bitmap` (a missing file
2083
+ * is fine). True if one is wrong.
2084
+ */
2085
+ private async verifyBitmapFiles(
2086
+ packs: readonly RepoPack[],
2087
+ objectsDir: string = this.looseDir(),
2088
+ ): Promise<boolean> {
2089
+ const files = this.files as FilesApi;
2090
+ let bad = false;
2091
+ // the multi-pack-index's bitmap first (its name carries the midx checksum)
2092
+ const paths: string[] = [];
2093
+ if (this.o.multiPackIndex !== false) {
2094
+ const loaded = await loadMultiPackIndex(files, pathOf(objectsDir, "pack"), {
2095
+ compatibility: this.o.compatibility,
2096
+ });
2097
+ if (loaded.midx)
2098
+ paths.push(pathOf(objectsDir, "pack", `multi-pack-index-${loaded.midx.checksum}.bitmap`));
2099
+ }
2100
+ for (const p of packs) paths.push(`${p.packPath.replace(/\.pack$/, "")}.bitmap`);
2101
+ for (const path of paths) {
2102
+ const st = await files.stats(path).catch(() => undefined);
2103
+ if (st?.kind !== "file") continue;
2104
+ const size = st.size ?? 0;
2105
+ let valid = size >= 20;
2106
+ if (valid) {
2107
+ const hasher = createSha1();
2108
+ for await (const c of files.read(path, { start: 0, length: size - 20 })) hasher.update(c);
2109
+ const sum = hasher.digest();
2110
+ const tail: number[] = [];
2111
+ for await (const c of files.read(path, { start: size - 20, length: 20 })) tail.push(...c);
2112
+ valid = tail.length === 20 && sum.every((b, i) => b === tail[i]);
2113
+ }
2114
+ if (!valid) {
2115
+ this.error(`bitmap file '${path}' has invalid checksum`);
2116
+ bad = true;
2117
+ }
2118
+ }
2119
+ return bad;
2120
+ }
2121
+
2122
+ /** git's `verify_pack` for each of `packs`, with `fsck_obj_buffer` for each object. */
2123
+ private async fsckPacks(packs: readonly RepoPack[]): Promise<void> {
2124
+ const files = this.files as FilesApi;
2125
+ for (const p of packs) {
2126
+ let err = 0;
2127
+ // git prints the pack checksum errors before any entry's output
2128
+ let checksumAt = 0;
2129
+ const result = await checkPack(
2130
+ files,
2131
+ p.packPath,
2132
+ p.idxPath,
2133
+ {
2134
+ error: (m) => this.error(m),
2135
+ opened: () => {
2136
+ checksumAt = this.findings.length;
2137
+ },
2138
+ checksumError: (m) => {
2139
+ this.findings.splice(checksumAt++, 0, {
2140
+ kind: "error",
2141
+ stream: "stderr",
2142
+ text: `error: ${m}`,
2143
+ objectId: undefined,
2144
+ });
2145
+ },
2146
+ entry: (entry, unpacked) => {
2147
+ if (p.idx.version > 1 && !entry.crcOk) {
2148
+ this.error(
2149
+ `index CRC mismatch for object ${entry.id} from ${p.packPath} at offset ${entry.offset}`,
2150
+ entry.id,
2151
+ );
2152
+ err = 1;
2153
+ }
2154
+ if ("error" in unpacked) {
2155
+ if (unpacked.zlib) this.error(unpacked.zlib);
2156
+ if (unpacked.base) this.error(unpacked.base);
2157
+ this.error(unpacked.error, entry.id);
2158
+ this.badCopy.add(entry.id);
2159
+ // the verification reads this copy (git does not check its hash there)
2160
+ this.skipGraphCommit(entry.id);
2161
+ err = 1;
2162
+ return;
2163
+ }
2164
+ if (unpacked.type === "commit") this.keepGraphCommit(entry.id, unpacked.content);
2165
+ const r = this.fsckObjBuffer(
2166
+ entry.id,
2167
+ typeOf(unpacked.type),
2168
+ unpacked.content,
2169
+ `${entry.id}: object corrupt or missing`,
2170
+ unpacked.content.length,
2171
+ entry.ids,
2172
+ entry.idAt,
2173
+ );
2174
+ if (r instanceof Promise) {
2175
+ return r.then((x) => {
2176
+ if (x !== 0) err = 1;
2177
+ });
2178
+ }
2179
+ if (r !== 0) err = 1;
2180
+ },
2181
+ },
2182
+ {
2183
+ externalBase: (id) => this.readObject(id),
2184
+ read: { bytes: p.idxBytes, idx: p.idx },
2185
+ keepBlob: this.keepBlob,
2186
+ },
2187
+ );
2188
+ if (result.failed) err = 1;
2189
+ if (err) {
2190
+ this.errorsFound |= this.o.compatibility === "2.56" ? FSCK_ERROR_OBJECT : FSCK_ERROR_PACK;
2191
+ }
2192
+ }
2193
+ }
2194
+
2195
+ /** Every object of a store without files: read, hash-checked and checked. */
2196
+ private async fsckStoredObjects(): Promise<void> {
2197
+ const ids: string[] = [];
2198
+ for await (const id of this.objects.list()) ids.push(id);
2199
+ ids.sort();
2200
+ for (const id of ids) {
2201
+ let read: { type: string; content: Uint8Array } | undefined;
2202
+ try {
2203
+ const obj = await this.objects.get(id, { verify: true });
2204
+ if (obj) {
2205
+ if (obj.type === "blob" && !this.keepBlob(id)) {
2206
+ for await (const _ of obj.content) {
2207
+ // hashed as it streams
2208
+ }
2209
+ read = { type: obj.type, content: new Uint8Array(0) };
2210
+ } else {
2211
+ read = { type: obj.type, content: await collect(obj) };
2212
+ }
2213
+ }
2214
+ } catch {
2215
+ read = undefined;
2216
+ }
2217
+ if (!read) {
2218
+ this.error(`${id}: object corrupt or missing`, id);
2219
+ this.errorsFound |= FSCK_ERROR_OBJECT;
2220
+ continue;
2221
+ }
2222
+ const r = await this.fsckObjBuffer(
2223
+ id,
2224
+ typeOf(read.type),
2225
+ read.content,
2226
+ `${id}: object corrupt or missing`,
2227
+ );
2228
+ if (r > 0) this.errorsFound |= FSCK_ERROR_OBJECT;
2229
+ }
2230
+ }
2231
+
2232
+ // ------------------------------------------------------------------------------------------
2233
+ // Roots: refs, HEADs, reflogs, index files
2234
+
2235
+ /**
2236
+ * `markObject` where it needs no await: an object of the expected type that is reachable
2237
+ * already, or stored (then queued). False, with nothing done, otherwise.
2238
+ */
2239
+ private markReachable(n: number | undefined, type: ObjType): boolean {
2240
+ const t = this.t;
2241
+ if (n === undefined || t.type(n) !== type) return false;
2242
+ const flags = t.flags(n);
2243
+ if (flags & REACHABLE) return true;
2244
+ if (this.promised?.has(t.id(n))) {
2245
+ // a promisor object: reachable, not walked further (mark_object)
2246
+ t.addFlags(n, REACHABLE);
2247
+ return true;
2248
+ }
2249
+ if (!(flags & HAS_OBJ)) return false;
2250
+ t.addFlags(n, REACHABLE);
2251
+ this.pending.push(n);
2252
+ return true;
2253
+ }
2254
+
2255
+ /** git's `mark_object`: without a promise when it reports nothing. */
2256
+ private markObject(
2257
+ n: number | undefined,
2258
+ type: ObjType | "any",
2259
+ parent: number | undefined,
2260
+ ): number | Promise<number> {
2261
+ const t = this.t;
2262
+ if (n !== undefined && (type === "any" || parent === undefined || t.type(n) === type)) {
2263
+ const flags = t.flags(n);
2264
+ if (flags & REACHABLE) return 0;
2265
+ if (this.promised?.has(t.id(n))) {
2266
+ t.addFlags(n, REACHABLE);
2267
+ return 0;
2268
+ }
2269
+ if (flags & HAS_OBJ) {
2270
+ t.addFlags(n, REACHABLE);
2271
+ this.pending.push(n);
2272
+ return 0;
2273
+ }
2274
+ }
2275
+ return this.markObjectReporting(n, type, parent);
2276
+ }
2277
+
2278
+ /** `markObject` where it may report: a broken link, a wrong type, an object not stored. */
2279
+ private async markObjectReporting(
2280
+ n: number | undefined,
2281
+ type: ObjType | "any",
2282
+ parent: number | undefined,
2283
+ ): Promise<number> {
2284
+ const t = this.t;
2285
+ if (n === undefined) {
2286
+ const p = parent as number;
2287
+ this.emit({
2288
+ kind: "broken-link",
2289
+ stream: "stdout",
2290
+ text: `broken link from ${(await this.printableType(p)).padStart(7)} ${this.describe(t.id(p))}`,
2291
+ objectId: t.id(p),
2292
+ });
2293
+ this.emit({
2294
+ kind: "broken-link",
2295
+ stream: "stdout",
2296
+ text: `broken link from ${(type === "any" ? "unknown" : TYPE_NAME[type]).padStart(7)} unknown`,
2297
+ });
2298
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
2299
+ return 1;
2300
+ }
2301
+ if (type !== "any" && t.type(n) !== type && parent !== undefined) {
2302
+ await this.objerror(parent, "wrong object type in link");
2303
+ }
2304
+ if (t.flags(n) & REACHABLE) return 0;
2305
+ t.addFlags(n, REACHABLE);
2306
+ // a promisor object needs no further recursion (it is not missing: it will be fetched);
2307
+ // 2.43 asks only for an object it does not have
2308
+ if (
2309
+ (this.o.compatibility === "2.56" || !(t.flags(n) & HAS_OBJ)) &&
2310
+ this.promised?.has(t.id(n))
2311
+ ) {
2312
+ return 0;
2313
+ }
2314
+ if (!(t.flags(n) & HAS_OBJ)) {
2315
+ const id = t.id(n);
2316
+ if (parent !== undefined && !(await this.hasObject(id))) {
2317
+ const pid = t.id(parent);
2318
+ this.emit({
2319
+ kind: "broken-link",
2320
+ stream: "stdout",
2321
+ text: `broken link from ${(await this.printableType(parent)).padStart(7)} ${this.describe(pid)}`,
2322
+ objectId: pid,
2323
+ });
2324
+ this.emit({
2325
+ kind: "broken-link",
2326
+ stream: "stdout",
2327
+ text: ` to ${(await this.printableType(n)).padStart(7)} ${this.describe(id)}`,
2328
+ objectId: id,
2329
+ });
2330
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
2331
+ }
2332
+ return 1;
2333
+ }
2334
+ this.pending.push(n);
2335
+ return 0;
2336
+ }
2337
+
2338
+ /** git's `fsck_handle_ref`. */
2339
+ private async handleRef(name: string, id: string): Promise<void> {
2340
+ const n = await this.parseObject(id);
2341
+ if (n === undefined) {
2342
+ // a promisor object: a valid ref
2343
+ if (this.promised?.has(id)) {
2344
+ this.defaultRefs++;
2345
+ return;
2346
+ }
2347
+ this.error(`${name}: invalid sha1 pointer ${id}`, id);
2348
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
2349
+ return;
2350
+ }
2351
+ if (this.t.type(n) !== OBJ_COMMIT && name.startsWith("refs/heads/")) {
2352
+ this.error(`${name}: not a commit`, id);
2353
+ this.errorsFound |= FSCK_ERROR_REFS;
2354
+ }
2355
+ this.defaultRefs++;
2356
+ this.t.addFlags(n, USED);
2357
+ this.putName(id, name);
2358
+ await this.markObject(n, "any", undefined);
2359
+ }
2360
+
2361
+ /** git's `fsck_handle_reflog_oid`. */
2362
+ private async handleReflogOid(refname: string, id: string, timestamp: number): Promise<void> {
2363
+ if (id === ZERO_ID) return;
2364
+ const n = this.t.lookup(id);
2365
+ if (n >= 0 && this.t.flags(n) & HAS_OBJ) {
2366
+ if (timestamp) this.putName(id, `${refname}@{${timestamp}}`);
2367
+ this.t.addFlags(n, USED);
2368
+ await this.markObject(n, "any", undefined);
2369
+ } else if (!this.promised?.has(id)) {
2370
+ this.error(`${refname}: invalid reflog entry ${id}`, id);
2371
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
2372
+ }
2373
+ }
2374
+
2375
+ /**
2376
+ * What a listed ref resolves to, or the null id when it does not resolve (a dangling symbolic
2377
+ * ref, or one deeper than git's 5 reads: git's `for_each_rawref` passes those with a null id).
2378
+ */
2379
+ private async resolvedId(name: string): Promise<string> {
2380
+ try {
2381
+ return (await this.followChain(name, 0))?.id || ZERO_ID;
2382
+ } catch {
2383
+ return ZERO_ID;
2384
+ }
2385
+ }
2386
+
2387
+ /** git's `get_default_heads`. */
2388
+ private async processRefs(): Promise<void> {
2389
+ const refs = this.stores.refs;
2390
+ const listed: string[] = [];
2391
+ for await (const ref of refs.list("refs/")) listed.push(ref.name);
2392
+ listed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
2393
+ for (const name of [...new Set(listed)]) {
2394
+ // a symbolic ref that resolves to nothing is the null id to git (`invalid sha1 pointer`)
2395
+ await this.handleRef(name, await this.resolvedId(name));
2396
+ }
2397
+
2398
+ for (const wt of await this.worktrees()) {
2399
+ await this.headLink(wt);
2400
+ if (this.o.reflogs) await this.processReflogs(wt);
2401
+ }
2402
+
2403
+ if (!this.defaultRefs) {
2404
+ this.emit({ kind: "notice", stream: "stderr", text: "notice: No default references" });
2405
+ this.showUnreachable = false;
2406
+ }
2407
+ }
2408
+
2409
+ /** git 2.45+'s `snapshot_refs`: every ref, then each worktree's HEAD, parsed before the objects. */
2410
+ private async snapshotRefs(): Promise<{ name: string; id: string }[]> {
2411
+ const refs = this.stores.refs;
2412
+ const snapshot: { name: string; id: string }[] = [];
2413
+ const snapshotRef = async (name: string, id: string) => {
2414
+ const n = await this.parseObject(id);
2415
+ if (n === undefined) {
2416
+ if (this.promised?.has(id)) {
2417
+ this.defaultRefs++;
2418
+ return;
2419
+ }
2420
+ this.error(`${name}: invalid sha1 pointer ${id}`, id);
2421
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
2422
+ return;
2423
+ }
2424
+ if (this.t.type(n) !== OBJ_COMMIT && name.startsWith("refs/heads/")) {
2425
+ this.error(`${name}: not a commit`, id);
2426
+ this.errorsFound |= FSCK_ERROR_REFS;
2427
+ }
2428
+ this.defaultRefs++;
2429
+ snapshot.push({ name, id });
2430
+ };
2431
+ const listed: string[] = [];
2432
+ for await (const ref of refs.list("refs/")) listed.push(ref.name);
2433
+ listed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
2434
+ for (const name of [...new Set(listed)]) await snapshotRef(name, await this.resolvedId(name));
2435
+ for (const wt of await this.worktrees()) {
2436
+ const id = await this.headId(wt);
2437
+ if (id && id !== ZERO_ID) await snapshotRef(wt.headName, id);
2438
+ }
2439
+ return snapshot;
2440
+ }
2441
+
2442
+ /** git 2.45+'s `process_refs`: the snapshotted refs, then every worktree's reflogs. */
2443
+ private async processSnapshot(snapshot: { name: string; id: string }[]): Promise<void> {
2444
+ for (const { name, id } of snapshot) {
2445
+ const n = await this.parseObject(id);
2446
+ if (n === undefined) continue;
2447
+ this.t.addFlags(n, USED);
2448
+ this.putName(id, name);
2449
+ await this.markObject(n, "any", undefined);
2450
+ }
2451
+ if (this.o.reflogs) {
2452
+ for (const wt of await this.worktrees()) await this.processReflogs(wt);
2453
+ }
2454
+ if (!this.defaultRefs) {
2455
+ this.emit({ kind: "notice", stream: "stderr", text: "notice: No default references" });
2456
+ this.showUnreachable = false;
2457
+ }
2458
+ }
2459
+
2460
+ private async processReflogs(wt: WorktreeState): Promise<void> {
2461
+ for (const log of await this.reflogs(wt)) {
2462
+ // git 2.43's reflog iterator resolves each ref first and skips one deeper than 5 reads
2463
+ if (this.o.compatibility === "2.43" && log.path && (await this.tooDeep(wt, log.name))) {
2464
+ this.error(`bad ref for ${log.path}`);
2465
+ continue;
2466
+ }
2467
+ for (const e of log.entries) {
2468
+ await this.handleReflogOid(log.name, e.oldId, 0);
2469
+ await this.handleReflogOid(log.name, e.newId, e.timestamp);
2470
+ }
2471
+ }
2472
+ }
2473
+
2474
+ /** What a worktree's HEAD resolves to, if anything (within git's 5 reads, HEAD's included). */
2475
+ private async headId(wt: WorktreeState): Promise<string | undefined> {
2476
+ if (wt.current) {
2477
+ const head = await this.stores.refs.get("HEAD");
2478
+ if (!head) return undefined;
2479
+ if (!isSymbolicRef(head)) return head.objectId;
2480
+ return (await this.followChain(head.target, 1))?.id;
2481
+ }
2482
+ const text = (await readText(this.files as FilesApi, pathOf(wt.dir as string, "HEAD")))?.trim();
2483
+ if (!text) return undefined;
2484
+ if (text.startsWith("ref:")) return (await this.followChain(text.slice(4).trim(), 1))?.id;
2485
+ return OID.test(text.slice(0, 40)) ? text.slice(0, 40) : undefined;
2486
+ }
2487
+
2488
+ /**
2489
+ * Whether the ref of the reflog `logName` is a symbolic ref chain deeper than git's 5 reads
2490
+ * (`resolve_ref_unsafe` fails: git 2.43 prints `bad ref for <log>`; a missing ref is fine).
2491
+ */
2492
+ private async tooDeep(wt: WorktreeState, logName: string): Promise<boolean> {
2493
+ try {
2494
+ if (logName === "HEAD" && wt.current) {
2495
+ const head = await this.stores.refs.get("HEAD");
2496
+ return !!head && isSymbolicRef(head) && !(await this.followChain(head.target, 1));
2497
+ }
2498
+ if (logName.startsWith("worktrees/")) {
2499
+ if (!wt.dir || !logName.endsWith("/HEAD") || logName.split("/").length !== 3) return false;
2500
+ const text = (await readText(this.files as FilesApi, pathOf(wt.dir, "HEAD")))?.trim();
2501
+ return !!text?.startsWith("ref:") && !(await this.followChain(text.slice(4).trim(), 1));
2502
+ }
2503
+ return !(await this.followChain(logName, 0));
2504
+ } catch {
2505
+ return false;
2506
+ }
2507
+ }
2508
+
2509
+ /** The main worktree, then the linked ones (`.git/worktrees/<id>`). */
2510
+ private async worktrees(): Promise<WorktreeState[]> {
2511
+ const list: WorktreeState[] = [{ headName: "HEAD", dir: this.gitDir, current: true }];
2512
+ const files = this.files;
2513
+ if (!files) return list;
2514
+ const dir = pathOf(this.gitDir, "worktrees");
2515
+ if ((await files.stats(dir))?.kind !== "directory") return list;
2516
+ const names: string[] = [];
2517
+ for await (const e of files.list(dir)) {
2518
+ if (e.kind === "directory" && (await files.stats(pathOf(e.path, "HEAD")))?.kind === "file") {
2519
+ names.push(e.name);
2520
+ }
2521
+ }
2522
+ names.sort();
2523
+ for (const name of names) {
2524
+ list.push({ headName: `worktrees/${name}/HEAD`, dir: pathOf(dir, name), current: false });
2525
+ }
2526
+ return list;
2527
+ }
2528
+
2529
+ /**
2530
+ * Where the symbolic ref chain from `target` ends, as git's `resolve_ref_unsafe` follows it:
2531
+ * the last name and its id (none when that ref does not exist), or undefined when the chain
2532
+ * takes more than git's SYMREF_MAXDEPTH (5) reads in all. `reads` is how many were made
2533
+ * before `target` (1 when HEAD, read first, points at it).
2534
+ */
2535
+ private async followChain(
2536
+ target: string,
2537
+ reads: number,
2538
+ ): Promise<{ name: string; id?: string } | undefined> {
2539
+ let name = target;
2540
+ for (let read = reads + 1; ; read++) {
2541
+ const value = await this.stores.refs.get(name);
2542
+ if (!value) return { name };
2543
+ if (!isSymbolicRef(value)) return { name, id: value.objectId };
2544
+ if (read >= 5) return undefined;
2545
+ name = value.target;
2546
+ }
2547
+ }
2548
+
2549
+ /** git's `fsck_head_link` and the HEAD of a worktree as a root. */
2550
+ private async headLink(wt: WorktreeState): Promise<void> {
2551
+ const name = wt.headName;
2552
+ let target: string | undefined;
2553
+ let id: string | undefined;
2554
+ const invalid = () => {
2555
+ this.errorsFound |= FSCK_ERROR_REFS;
2556
+ this.error(`invalid ${name}`);
2557
+ };
2558
+ let symref: string | undefined;
2559
+ if (wt.current) {
2560
+ const head = await this.stores.refs.get("HEAD");
2561
+ if (!head) return invalid();
2562
+ if (isSymbolicRef(head)) symref = head.target;
2563
+ else id = head.objectId;
2564
+ } else {
2565
+ const text = (
2566
+ await readText(this.files as FilesApi, pathOf(wt.dir as string, "HEAD"))
2567
+ )?.trim();
2568
+ if (!text) return invalid();
2569
+ if (text.startsWith("ref:")) symref = text.slice(4).trim();
2570
+ else if (OID.test(text.slice(0, 40))) id = text.slice(0, 40);
2571
+ else return invalid();
2572
+ }
2573
+ if (symref !== undefined) {
2574
+ // the whole chain: HEAD -> refs/heads/alias -> refs/remotes/origin/x points at the last
2575
+ // HEAD itself was the first of git's 5 reads
2576
+ const end = await this.followChain(symref, 1);
2577
+ if (!end) return invalid();
2578
+ target = end.name;
2579
+ id = end.id;
2580
+ }
2581
+ if (target !== undefined && !target.startsWith("refs/heads/")) {
2582
+ this.errorsFound |= FSCK_ERROR_REFS;
2583
+ this.error(`${name} points to something strange (${target})`);
2584
+ // git still takes what HEAD resolves to as a root
2585
+ if (id && id !== ZERO_ID) await this.handleRef(name, id);
2586
+ return;
2587
+ }
2588
+ if (!id || id === ZERO_ID) {
2589
+ if (target === undefined) {
2590
+ this.errorsFound |= FSCK_ERROR_REFS;
2591
+ this.error(`${name}: detached HEAD points at nothing`);
2592
+ return;
2593
+ }
2594
+ this.emit({
2595
+ kind: "notice",
2596
+ stream: "stderr",
2597
+ text: `notice: ${name} points to an unborn branch (${target.slice(11)})`,
2598
+ });
2599
+ return;
2600
+ }
2601
+ await this.handleRef(name, id);
2602
+ }
2603
+
2604
+ /** The reflogs of one worktree, in git's order (sorted by name, as git 2.45+ lists them). */
2605
+ private async reflogs(wt: WorktreeState): Promise<Reflog[]> {
2606
+ const files = this.files;
2607
+ if (!files) return wt.current ? this.storeReflogs() : [];
2608
+ const logs: Reflog[] = [];
2609
+ const collectDir = async (base: string, keep: (name: string) => boolean, prefix: string) => {
2610
+ const found: { name: string; path: string }[] = [];
2611
+ const walk = async (dir: string, rel: string) => {
2612
+ if ((await files.stats(dir))?.kind !== "directory") return;
2613
+ const entries: { name: string; path: string; kind: string }[] = [];
2614
+ for await (const e of files.list(dir)) entries.push(e);
2615
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
2616
+ for (const e of entries) {
2617
+ const name = rel ? `${rel}/${e.name}` : e.name;
2618
+ if (e.kind === "directory") await walk(e.path, name);
2619
+ else if (keep(name)) found.push({ name, path: e.path });
2620
+ }
2621
+ };
2622
+ await walk(base, "");
2623
+ for (const f of found) {
2624
+ logs.push({
2625
+ name: prefix + f.name,
2626
+ path: pathOf(base, f.name),
2627
+ entries: parseReflog(await readText(files, f.path)),
2628
+ });
2629
+ }
2630
+ };
2631
+ if (wt.current) {
2632
+ await collectDir(pathOf(this.gitDir, "logs"), () => true, "");
2633
+ } else {
2634
+ const dir = wt.dir as string;
2635
+ const id = dir.slice(dir.lastIndexOf("/") + 1);
2636
+ await collectDir(pathOf(dir, "logs"), (n) => PER_WORKTREE.test(n), `worktrees/${id}/`);
2637
+ await collectDir(pathOf(this.gitDir, "logs"), (n) => !PER_WORKTREE.test(n), "");
2638
+ logs.sort((a, b) => {
2639
+ const x = a.name.replace(/^worktrees\/[^/]+\//, "");
2640
+ const y = b.name.replace(/^worktrees\/[^/]+\//, "");
2641
+ return x < y ? -1 : x > y ? 1 : 0;
2642
+ });
2643
+ }
2644
+ return logs;
2645
+ }
2646
+
2647
+ /** Reflogs through the refs store (a store without files): HEAD and every ref. */
2648
+ private async storeReflogs(): Promise<Reflog[]> {
2649
+ const refs = this.stores.refs;
2650
+ if (!refs.getReflog) return [];
2651
+ const names = ["HEAD"];
2652
+ for await (const ref of refs.list("refs/")) names.push(ref.name);
2653
+ const sorted = [...new Set(names)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
2654
+ const logs: Reflog[] = [];
2655
+ for (const name of sorted) {
2656
+ const reader = await refs.getReflog(name);
2657
+ if (!reader) continue;
2658
+ const entries = (await reader.getReverseEntries()).reverse();
2659
+ if (entries.length === 0) continue;
2660
+ logs.push({
2661
+ name,
2662
+ entries: entries.map((e) => ({
2663
+ oldId: e.oldId,
2664
+ newId: e.newId,
2665
+ timestamp: e.who.timestamp,
2666
+ })),
2667
+ });
2668
+ }
2669
+ return logs;
2670
+ }
2671
+
2672
+ /**
2673
+ * git's index pass: every worktree's index (`fsck_index`). Returns git's lines when it dies
2674
+ * reading one (`read_index_from` with `verify_index_checksum`: a wrong trailer, of the index
2675
+ * or its shared index, is `error: bad index file sha1 signature` then `fatal: index file
2676
+ * corrupt`, exit 128).
2677
+ */
2678
+ private async processIndexes(): Promise<readonly string[] | undefined> {
2679
+ const files = this.files;
2680
+ if (!files) {
2681
+ await this.storeIndex();
2682
+ return undefined;
2683
+ }
2684
+ for (const wt of await this.worktrees()) {
2685
+ const indexPath = pathOf(wt.dir as string, "index");
2686
+ if ((await files.stats(indexPath))?.kind !== "file") continue;
2687
+ // a split index merged with its shared index, a sparse index expanded (repo_read_index)
2688
+ let read: Awaited<ReturnType<typeof readIndexFileEntries>>;
2689
+ try {
2690
+ // fsck alone checks the index's trailing hash (verify_index_checksum)
2691
+ read = await readIndexFileEntries(files, indexPath, {
2692
+ gitDir: wt.dir as string,
2693
+ trees: this.stores.trees(),
2694
+ verifyChecksum: true,
2695
+ });
2696
+ } catch (error) {
2697
+ if (error instanceof IndexCorruptError) return error.lines;
2698
+ // a sparse directory whose tree is missing: its own entry stands for it (the index
2699
+ // and its shared index were hashed before the expansion failed)
2700
+ try {
2701
+ read = await readIndexFileEntries(files, indexPath, { gitDir: wt.dir as string });
2702
+ } catch (again) {
2703
+ if (again instanceof IndexCorruptError) return again.lines;
2704
+ throw again;
2705
+ }
2706
+ }
2707
+ if (!read) continue;
2708
+ const parsed = { entries: read.entries, extensionData: read.extensions };
2709
+ const prefix = wt.current ? "" : indexPath;
2710
+ const entries = parsed.entries.map((e) => ({
2711
+ path: e.path,
2712
+ mode: e.mode,
2713
+ objectId: e.objectId,
2714
+ }));
2715
+ let cacheTree: CacheTree | undefined;
2716
+ let resolveUndo: ResolveUndoRecord[] = [];
2717
+ for (const ext of parsed.extensionData) {
2718
+ if (ext.signature === "TREE") cacheTree = parseCacheTree(ext.data);
2719
+ else if (ext.signature === "REUC") resolveUndo = parseResolveUndo(ext.data);
2720
+ }
2721
+ await this.fsckIndex(entries, cacheTree, resolveUndo, indexPath, prefix);
2722
+ }
2723
+ return undefined;
2724
+ }
2725
+
2726
+ /** The staging area of a store without files, as the current worktree's index. */
2727
+ private async storeIndex(): Promise<void> {
2728
+ let staging: Staging;
2729
+ try {
2730
+ staging = this.stores.staging();
2731
+ } catch {
2732
+ return;
2733
+ }
2734
+ const entries: { path: string; mode: number; objectId: string }[] = [];
2735
+ for await (const e of staging.entries()) {
2736
+ entries.push({ path: e.path, mode: e.mode, objectId: e.objectId });
2737
+ }
2738
+ await this.fsckIndex(entries, staging.getCacheTree?.(), [], `${this.gitDir}/index`, "");
2739
+ }
2740
+
2741
+ /** git's `fsck_index`. */
2742
+ private async fsckIndex(
2743
+ entries: { path: string; mode: number; objectId: string }[],
2744
+ cacheTree: CacheTree | undefined,
2745
+ resolveUndo: ResolveUndoRecord[],
2746
+ indexPath: string,
2747
+ prefix: string,
2748
+ ): Promise<void> {
2749
+ for (const e of entries) {
2750
+ if ((e.mode & 0o170000) === 0o160000) continue;
2751
+ const blob = this.t.lookupTyped(e.objectId, OBJ_BLOB);
2752
+ if (typeof blob !== "number") {
2753
+ this.error(blob.error);
2754
+ continue;
2755
+ }
2756
+ this.t.addFlags(blob, USED);
2757
+ this.putName(e.objectId, `${prefix}:${e.path}`);
2758
+ await this.markObject(blob, "any", undefined);
2759
+ }
2760
+ if (cacheTree) await this.fsckCacheTree(cacheTree, indexPath);
2761
+ // resolve-undo: git keeps it as a string list sorted by path
2762
+ const sorted = [...resolveUndo].sort((a, b) =>
2763
+ a.path < b.path ? -1 : a.path > b.path ? 1 : 0,
2764
+ );
2765
+ for (const record of sorted) {
2766
+ for (let i = 0; i < 3; i++) {
2767
+ const mode = record.modes[i] ?? 0;
2768
+ const id = record.objectIds[i];
2769
+ if (!mode || (mode & 0o170000) !== 0o100000 || !id) continue;
2770
+ const n = await this.parseObject(id);
2771
+ if (n === undefined) {
2772
+ this.error(`${id}: invalid sha1 pointer in resolve-undo of ${indexPath}`, id);
2773
+ this.errorsFound |= FSCK_ERROR_REFS;
2774
+ continue;
2775
+ }
2776
+ this.t.addFlags(n, USED);
2777
+ this.putName(id, `:(${i}):${record.path}`);
2778
+ await this.markObject(n, "any", undefined);
2779
+ }
2780
+ }
2781
+ }
2782
+
2783
+ /** git's `fsck_cache_tree`. */
2784
+ private async fsckCacheTree(node: CacheTree, indexPath: string): Promise<void> {
2785
+ if (node.entryCount >= 0 && node.id) {
2786
+ const n = await this.parseObject(node.id);
2787
+ if (n === undefined) {
2788
+ this.error(`${node.id}: invalid sha1 pointer in cache-tree of ${indexPath}`, node.id);
2789
+ this.errorsFound |= FSCK_ERROR_REFS;
2790
+ return;
2791
+ }
2792
+ this.t.addFlags(n, USED);
2793
+ this.putName(node.id, ":");
2794
+ await this.markObject(n, "any", undefined);
2795
+ if (this.t.type(n) !== OBJ_TREE) await this.objerror(n, "non-tree in cache-tree");
2796
+ }
2797
+ for (const sub of node.subtrees) await this.fsckCacheTree(sub.tree, indexPath);
2798
+ }
2799
+
2800
+ // ------------------------------------------------------------------------------------------
2801
+ // Connectivity
2802
+
2803
+ /**
2804
+ * The pack-order scan of a connectivity-only run (`scanPackObjects`): the commits (unless a
2805
+ * commit-graph gives them) and trees of each pack, unpacked in one read and kept as the
2806
+ * objects they link to (`scanAt`). An object is taken from the first pack that holds it,
2807
+ * as the store reads it, and never when it is loose too (the store may read that copy); a
2808
+ * pack that cannot be read leaves its objects to the walk's reads. At most `linksKept`
2809
+ * links are kept: the scan stops there, and the walk reads the rest from the store.
2810
+ */
2811
+ private async scanPacks(packed: Int32Array[], loose: number[]): Promise<void> {
2812
+ const files = this.files as FilesApi;
2813
+ const t = this.t;
2814
+ const claimed = new Uint8Array(t.size);
2815
+ for (const n of loose) claimed[n] = 1;
2816
+ this.scanAt = new Int32Array(t.size);
2817
+ this.scanKids = new Int32Array(
2818
+ Math.max(0, Math.min(1 << 16, this.o.linksKept - this.kidsLength)),
2819
+ );
2820
+ const withCommits = !this.graph;
2821
+ const keepCommits = this.graphCommits !== undefined;
2822
+ /** objects whose copy the commit-graph verification reads is decided (an earlier pack's) */
2823
+ const decided = keepCommits ? new Uint8Array(t.size) : undefined;
2824
+ let full = false;
2825
+ for (let k = 0; k < this.packs.length && !full; k++) {
2826
+ const p = this.packs[k] as RepoPack;
2827
+ const ns = packed[k] as Int32Array;
2828
+ try {
2829
+ this.objectsScanned += await scanPackObjects(
2830
+ files,
2831
+ p.packPath,
2832
+ p.idxBytes,
2833
+ p.idx,
2834
+ (type) => type === OBJ_TREE || (type === OBJ_COMMIT && (withCommits || keepCommits)),
2835
+ (pos, type, content) => {
2836
+ const n = ns[pos] as number;
2837
+ if (type === OBJ_COMMIT && decided && !decided[n]) {
2838
+ decided[n] = 1;
2839
+ const at = p.idx.version > 1 ? 8 + 1024 + pos * 20 : 1024 + 4 + pos * 24;
2840
+ this.keepGraphCommit(bytesToHex(p.idxBytes.subarray(at, at + 20)), content);
2841
+ }
2842
+ if (type === OBJ_COMMIT && !withCommits) return;
2843
+ if (claimed[n]) return;
2844
+ claimed[n] = 1;
2845
+ if (!this.recordScanned(n, type, content)) {
2846
+ full = true;
2847
+ return false;
2848
+ }
2849
+ },
2850
+ );
2851
+ } catch {
2852
+ // the walk reads what this pack holds through the store
2853
+ }
2854
+ for (let i = 0; i < ns.length; i++) {
2855
+ claimed[ns[i] as number] = 1;
2856
+ if (decided) decided[ns[i] as number] = 1;
2857
+ }
2858
+ }
2859
+ }
2860
+
2861
+ /**
2862
+ * `scanAt` for object `n`, a commit or a tree, from its content. False when it does not fit
2863
+ * in `linksKept` (nothing recorded).
2864
+ */
2865
+ private recordScanned(n: number, type: number, content: Uint8Array): boolean {
2866
+ const t = this.t;
2867
+ const start = this.scanKidsLength;
2868
+ let at = start + 1;
2869
+ if (type === OBJ_TREE) {
2870
+ // the entries as `scanTree` decodes them, for a tree it decodes without an error (any
2871
+ // other is left to the walk, which reports it)
2872
+ const len = content.length;
2873
+ if (len > 0 && (len < 23 || content[len - 21] !== 0)) return true;
2874
+ if (!this.reserveScanKids(1 + Math.floor(len / 23))) return false;
2875
+ const kids = this.scanKids;
2876
+ let p = 0;
2877
+ while (p < len) {
2878
+ if (len - p < 23 || content[p] === 0x20) return true;
2879
+ let mode = 0;
2880
+ for (;;) {
2881
+ const c = content[p++] as number;
2882
+ if (c === 0x20) break;
2883
+ if (c < 0x30 || c > 0x37) return true;
2884
+ mode = (mode * 8 + (c - 0x30)) & 0xffff;
2885
+ }
2886
+ if (content[p] === 0) return true;
2887
+ while (p < len && content[p] !== 0) p++;
2888
+ if (p + 21 > len) return true;
2889
+ const idAt = p + 1;
2890
+ p = idAt + 20;
2891
+ const format = mode & 0o170000;
2892
+ // gitlinks are not walked (canon_mode makes every other format one)
2893
+ if (format !== 0o100000 && format !== 0o120000 && format !== 0o040000) continue;
2894
+ const c = t.peekRaw(content, idAt);
2895
+ if (c < 0) return true;
2896
+ kids[at++] = (c << 1) | (format === 0o040000 ? 1 : 0);
2897
+ }
2898
+ } else {
2899
+ const parsed = parseCommitLinks(content, "");
2900
+ if ("error" in parsed) return true;
2901
+ if (!this.reserveScanKids(2 + parsed.parents.length)) return false;
2902
+ const kids = this.scanKids;
2903
+ const raw = this.idScratch;
2904
+ const tree = t.peekRaw(rawIdAt(content, parsed.tree, raw), 0);
2905
+ if (tree < 0) return true;
2906
+ kids[at++] = tree;
2907
+ for (const p of parsed.parents) {
2908
+ const c = t.peekRaw(rawIdAt(content, p, raw), 0);
2909
+ if (c < 0) return true;
2910
+ kids[at++] = c;
2911
+ }
2912
+ }
2913
+ this.scanKids[start] = ((at - start - 1) << 2) | type;
2914
+ this.scanKidsLength = at;
2915
+ this.scanAt[n] = start + 1;
2916
+ return true;
2917
+ }
2918
+
2919
+ /**
2920
+ * Room in `scanKids` for `more` values, within what `linksKept` leaves after `kids` (the
2921
+ * limit is the two together); false past it.
2922
+ */
2923
+ private reserveScanKids(more: number): boolean {
2924
+ const need = this.scanKidsLength + more;
2925
+ const limit = this.o.linksKept - this.kidsLength;
2926
+ if (need > limit) return false;
2927
+ if (need <= this.scanKids.length) return true;
2928
+ let size = Math.max(this.scanKids.length * 2, 16);
2929
+ while (size < need) size *= 2;
2930
+ const kids = new Int32Array(Math.min(size, limit));
2931
+ kids.set(this.scanKids.subarray(0, this.scanKidsLength));
2932
+ this.scanKids = kids;
2933
+ return true;
2934
+ }
2935
+
2936
+ /**
2937
+ * git's parse of commit `n` from what the scan kept (`scanAt` start `s`): the lookups
2938
+ * `parse_commit_buffer` makes, in its order. False, with nothing done, when one of them would
2939
+ * fail (an object of another type): the walk then reads the commit as it reads any other.
2940
+ */
2941
+ private parseScannedCommit(n: number, s: number): boolean {
2942
+ const t = this.t;
2943
+ const kids = this.scanKids;
2944
+ const count = (kids[s] as number) >> 2;
2945
+ const tree = kids[s + 1] as number;
2946
+ const have = t.type(tree);
2947
+ if (have !== OBJ_NONE && have !== OBJ_TREE) return false;
2948
+ // a grafted commit is read as any other (its parents are not the ones scanned)
2949
+ if (this.grafts?.has(t.id(n))) return false;
2950
+ const shallow = this.shallow.size > 0 && this.shallow.has(t.id(n));
2951
+ if (!shallow) {
2952
+ for (let i = s + 2; i <= s + count; i++) {
2953
+ const p = kids[i] as number;
2954
+ const pt = t.type(p);
2955
+ if (p === tree || (pt !== OBJ_NONE && pt !== OBJ_COMMIT)) return false;
2956
+ }
2957
+ }
2958
+ if (this.graftsHint) this.adviseGrafts();
2959
+ if (this.graftErrors.length > 0) this.reportGraftErrors();
2960
+ // parse_object's lookup, then parse_object_buffer's
2961
+ t.touch(n);
2962
+ t.setType(n, OBJ_COMMIT);
2963
+ this.objectsRead++;
2964
+ t.lookupTypedN(tree, OBJ_TREE);
2965
+ const parents: number[] = [];
2966
+ if (!shallow) {
2967
+ for (let i = s + 2; i <= s + count; i++) {
2968
+ const p = kids[i] as number;
2969
+ t.lookupTypedN(p, OBJ_COMMIT);
2970
+ parents.push(p);
2971
+ }
2972
+ }
2973
+ t.links.set(n, { tree, parents });
2974
+ t.addFlags(n, PARSED);
2975
+ return true;
2976
+ }
2977
+
2978
+ /**
2979
+ * git's `fsck_walk` with `mark_object` (`traverse_one_object`), for `runSteps`: it yields only
2980
+ * the promises it waits for, so an object whose reads are in memory is walked synchronously.
2981
+ */
2982
+ private *traverseOne(n: number): Steps<void> {
2983
+ const t = this.t;
2984
+ // fsck_walk returns at once for a blob (no id to build, nothing to read)
2985
+ if (t.type(n) === OBJ_BLOB) return;
2986
+ if (t.type(n) === OBJ_TREE && t.flags(n) & PARSED) {
2987
+ const start = n < this.treeStart.length ? (this.treeStart[n] as number) - 1 : -1;
2988
+ if (start >= 0) {
2989
+ if (this.badCopy.size === 0 || !this.badCopy.has(t.id(n))) {
2990
+ // checked in full already: its entries again, as they resolved then
2991
+ const kids = this.kids;
2992
+ for (let i = start + 1, end = start + 1 + (kids[start] as number); i < end; i++) {
2993
+ const v = kids[i] as number;
2994
+ const c = v >> 1;
2995
+ const type = v & 1 ? OBJ_TREE : OBJ_BLOB;
2996
+ t.touch(c); // the lookup git makes moves it in the hash
2997
+ if (!this.markReachable(c, type)) {
2998
+ const r = this.markObject(c, type, n);
2999
+ if (r instanceof Promise) yield r;
3000
+ }
3001
+ }
3002
+ return;
3003
+ }
3004
+ }
3005
+ }
3006
+ // what the pack-order scan kept of it, when it holds an object of the type the walk expects
3007
+ // (an object met untyped is parse_object's, which checks its hash: read from the store)
3008
+ const s = n < this.scanAt.length ? (this.scanAt[n] as number) - 1 : -1;
3009
+ let scanned = false;
3010
+ if (s >= 0 && !(t.flags(n) & PARSED)) {
3011
+ const kids = this.scanKids;
3012
+ const head = kids[s] as number;
3013
+ const have = t.type(n);
3014
+ if ((head & 3) === OBJ_TREE && have === OBJ_TREE) {
3015
+ const rest = this.walkScannedTree(n, s);
3016
+ if (rest) yield* rest;
3017
+ return;
3018
+ }
3019
+ if ((head & 3) === OBJ_COMMIT && have === OBJ_COMMIT) {
3020
+ scanned = this.parseScannedCommit(n, s);
3021
+ }
3022
+ }
3023
+ const id = t.id(n);
3024
+ this.lastRead = undefined;
3025
+ if (t.type(n) === OBJ_NONE) {
3026
+ // fsck_walk's parse_object, hash-checked
3027
+ const r = this.parseObject(id);
3028
+ if (r instanceof Promise) yield r;
3029
+ } else if (
3030
+ !scanned &&
3031
+ (t.type(n) === OBJ_COMMIT || t.type(n) === OBJ_TAG) &&
3032
+ !(t.flags(n) & PARSED)
3033
+ ) {
3034
+ // repo_parse_commit (from the commit-graph when it has the commit) / parse_tag
3035
+ if (!(t.type(n) === OBJ_COMMIT && this.graph && this.parseCommitInGraph(n, id))) {
3036
+ const r = this.parseAs(n, id);
3037
+ if (r instanceof Promise) yield r;
3038
+ }
3039
+ }
3040
+ const name = this.names?.get(id);
3041
+ switch (t.type(n)) {
3042
+ case OBJ_BLOB:
3043
+ return;
3044
+ case OBJ_TREE: {
3045
+ // the tree just parsed, or read now
3046
+ const last = this.lastRead as { id: string; obj: Whole } | undefined;
3047
+ let obj: Whole | undefined | Promise<Whole | undefined> =
3048
+ last !== undefined && last.id === id ? last.obj : this.readWhole(id);
3049
+ this.lastRead = undefined;
3050
+ if (obj instanceof Promise) obj = (yield obj) as Whole | undefined;
3051
+ // git's parse_tree
3052
+ if (!obj) {
3053
+ if (this.lastZlibError) this.error(this.lastZlibError);
3054
+ this.error(`Could not read ${id}`);
3055
+ return;
3056
+ }
3057
+ if (obj.type !== "tree") {
3058
+ this.error(`Object ${id} not a tree`);
3059
+ return;
3060
+ }
3061
+ t.addFlags(n, PARSED);
3062
+ const walk = scanTree(obj.content, this.walkTable);
3063
+ if (walk.initError) {
3064
+ this.error(walk.initError);
3065
+ return;
3066
+ }
3067
+ const content = obj.content;
3068
+ const f = walk.fields;
3069
+ for (let i = 0; i < walk.count; i++) {
3070
+ const mode = canonMode(f[3 * i] as number);
3071
+ if (mode === 0o160000) continue;
3072
+ const isTree = mode === 0o040000;
3073
+ const idAt = f[3 * i + 2] as number;
3074
+ const child = t.lookupTypedRaw(content, idAt, isTree ? OBJ_TREE : OBJ_BLOB);
3075
+ let c: number | undefined;
3076
+ if (typeof child === "number") c = child;
3077
+ else this.error(child.error);
3078
+ if (name !== undefined && c !== undefined) {
3079
+ const entryName = content.subarray(f[3 * i + 1] as number, idAt - 1);
3080
+ this.putName(t.id(c), `${name}${decodeGitPath(entryName)}${isTree ? "/" : ""}`);
3081
+ }
3082
+ if (!this.markReachable(c, isTree ? OBJ_TREE : OBJ_BLOB)) {
3083
+ const r = this.markObject(c, isTree ? OBJ_TREE : OBJ_BLOB, n);
3084
+ if (r instanceof Promise) yield r;
3085
+ }
3086
+ }
3087
+ if (walk.error) this.error(walk.error);
3088
+ return;
3089
+ }
3090
+ case OBJ_COMMIT: {
3091
+ // the parse reported why it failed
3092
+ if (!(t.flags(n) & PARSED)) return;
3093
+ const links = t.links.get(n);
3094
+ if (!links || links.tree === undefined) return;
3095
+ if (name !== undefined) this.putName(t.id(links.tree), `${name}:`);
3096
+ const marked = this.markObject(links.tree, OBJ_TREE, n);
3097
+ if (marked instanceof Promise) yield marked;
3098
+ const parents = links.parents ?? [];
3099
+ let generation = 0;
3100
+ let prefixLength = 0;
3101
+ if (name !== undefined && parents.length > 0) {
3102
+ if (name.endsWith("^")) {
3103
+ generation = 1;
3104
+ prefixLength = name.length - 1;
3105
+ } else {
3106
+ const m = /~(\d+)$/.exec(name);
3107
+ if (m && (m[1] as string).length > 0) {
3108
+ generation = Number(m[1]);
3109
+ prefixLength = name.length - (m[1] as string).length - 1;
3110
+ } else {
3111
+ generation = 0;
3112
+ prefixLength = name.length;
3113
+ }
3114
+ }
3115
+ }
3116
+ let counter = 0;
3117
+ for (const p of parents) {
3118
+ if (name !== undefined) {
3119
+ const pid = t.id(p);
3120
+ if (counter++) this.putName(pid, `${name}^${counter}`);
3121
+ else if (generation > 0)
3122
+ this.putName(pid, `${name.slice(0, prefixLength)}~${generation + 1}`);
3123
+ else this.putName(pid, `${name}^`);
3124
+ }
3125
+ const r = this.markObject(p, OBJ_COMMIT, n);
3126
+ if (r instanceof Promise) yield r;
3127
+ }
3128
+ return;
3129
+ }
3130
+ case OBJ_TAG: {
3131
+ const links = t.links.get(n);
3132
+ if (!(t.flags(n) & PARSED)) return;
3133
+ if (links?.tagged === undefined) return;
3134
+ if (name !== undefined) this.putName(t.id(links.tagged), name);
3135
+ const marked = this.markObject(links.tagged, "any", n);
3136
+ if (marked instanceof Promise) yield marked;
3137
+ return;
3138
+ }
3139
+ default:
3140
+ this.error(`Unknown object type for ${this.describe(id)}`);
3141
+ }
3142
+ }
3143
+
3144
+ /**
3145
+ * The walk of tree `n` from what the scan kept (`scanAt` start `s`): parse_object's lookup
3146
+ * and parse, then the tree's entries, looked up in order and marked. Synchronous while every
3147
+ * entry is marked without a report; the steps for the rest otherwise.
3148
+ */
3149
+ private walkScannedTree(n: number, s: number): Steps<void> | undefined {
3150
+ const t = this.t;
3151
+ const kids = this.scanKids;
3152
+ t.touch(n);
3153
+ t.setType(n, OBJ_TREE);
3154
+ t.addFlags(n, PARSED);
3155
+ this.objectsRead++;
3156
+ for (let i = s + 1, end = s + 1 + ((kids[s] as number) >> 2); i < end; i++) {
3157
+ const v = kids[i] as number;
3158
+ const type = v & 1 ? OBJ_TREE : OBJ_BLOB;
3159
+ const child = t.lookupTypedN(v >> 1, type);
3160
+ if (typeof child === "number" && this.markReachable(child, type)) continue;
3161
+ return this.walkScannedRest(n, s, i, child);
3162
+ }
3163
+ return undefined;
3164
+ }
3165
+
3166
+ /** `walkScannedTree` from entry `i` on, whose lookup gave `child`. */
3167
+ private *walkScannedRest(
3168
+ n: number,
3169
+ s: number,
3170
+ i: number,
3171
+ child: number | { error: string },
3172
+ ): Steps<void> {
3173
+ const t = this.t;
3174
+ const kids = this.scanKids;
3175
+ for (const end = s + 1 + ((kids[s] as number) >> 2); ; ) {
3176
+ const type = (kids[i] as number) & 1 ? OBJ_TREE : OBJ_BLOB;
3177
+ let c: number | undefined;
3178
+ if (typeof child === "number") c = child;
3179
+ else this.error(child.error);
3180
+ if (!this.markReachable(c, type)) {
3181
+ const r = this.markObject(c, type, n);
3182
+ if (r instanceof Promise) yield r;
3183
+ }
3184
+ if (++i >= end) return;
3185
+ const v = kids[i] as number;
3186
+ child = t.lookupTypedN(v >> 1, v & 1 ? OBJ_TREE : OBJ_BLOB);
3187
+ }
3188
+ }
3189
+
3190
+ /** git's `mark_unreachable_referents` (connectivity-only runs). */
3191
+ private markUnreachableReferents(raw: Uint8Array, at: number): void | Promise<void> {
3192
+ const t = this.t;
3193
+ const n = t.lookupRaw(raw, at);
3194
+ if (n < 0 || !(t.flags(n) & HAS_OBJ) || t.flags(n) & REACHABLE) return;
3195
+ return this.markReferents(n);
3196
+ }
3197
+
3198
+ private async markReferents(n: number): Promise<void> {
3199
+ const t = this.t;
3200
+ const id = t.id(n);
3201
+ if (t.type(n) === OBJ_NONE) {
3202
+ const type = typeOf((await this.storeType(id)) ?? "");
3203
+ if (type !== OBJ_NONE) t.setType(n, type);
3204
+ }
3205
+ const type = t.type(n);
3206
+ if (type === OBJ_TREE) {
3207
+ const obj = await this.readWhole(id);
3208
+ if (!obj) return;
3209
+ if (obj.type !== "tree") {
3210
+ // git's parse_tree
3211
+ this.error(`Object ${id} not a tree`);
3212
+ return;
3213
+ }
3214
+ this.walkUsed(n, obj.content);
3215
+ } else if (type === OBJ_COMMIT || type === OBJ_TAG) {
3216
+ // repo_parse_commit / parse_tag: no hash check
3217
+ if (!(t.flags(n) & PARSED)) await this.parseAs(n, id);
3218
+ if (t.flags(n) & PARSED) this.walkUsed(n, new Uint8Array(0));
3219
+ }
3220
+ }
3221
+
3222
+ /** git's `check_connectivity`. */
3223
+ private async checkConnectivity(): Promise<void> {
3224
+ const t = this.t;
3225
+ const pending = this.pending;
3226
+ const scanAt = this.scanAt;
3227
+ while (pending.length > 0) {
3228
+ const n = pending.pop() as number;
3229
+ // fsck_walk returns at once for a blob
3230
+ if (t.type(n) === OBJ_BLOB) continue;
3231
+ // a tree the scan kept, walked without steps while it needs no await
3232
+ const s = n < scanAt.length ? (scanAt[n] as number) - 1 : -1;
3233
+ if (
3234
+ s >= 0 &&
3235
+ ((this.scanKids[s] as number) & 3) === OBJ_TREE &&
3236
+ !(t.flags(n) & PARSED) &&
3237
+ t.type(n) === OBJ_TREE
3238
+ ) {
3239
+ const rest = this.walkScannedTree(n, s);
3240
+ if (rest) {
3241
+ const r = runSteps(rest);
3242
+ if (r instanceof Promise) await r;
3243
+ }
3244
+ continue;
3245
+ }
3246
+ const r = runSteps(this.traverseOne(n));
3247
+ if (r instanceof Promise) await r;
3248
+ }
3249
+ if (this.o.connectivityOnly && (this.o.dangling || this.o.lostFound)) {
3250
+ await this.forEachStored((raw, at) => this.markUnreachableReferents(raw, at));
3251
+ }
3252
+ for (const n of [...t.inSlotOrder()]) {
3253
+ const id = t.id(n);
3254
+ const flags = t.flags(n);
3255
+ if (flags & REACHABLE) {
3256
+ if (this.promised?.has(id) || flags & HAS_OBJ || this.inPack(id)) continue;
3257
+ const type = await this.printableType(n);
3258
+ this.emit({
3259
+ kind: "missing",
3260
+ stream: "stdout",
3261
+ text: `missing ${type} ${this.describe(id)}`,
3262
+ objectId: id,
3263
+ objectType: type,
3264
+ });
3265
+ this.errorsFound |= FSCK_ERROR_REACHABLE;
3266
+ continue;
3267
+ }
3268
+ if (!(flags & HAS_OBJ)) continue;
3269
+ if (this.showUnreachable) {
3270
+ const type = await this.printableType(n);
3271
+ this.emit({
3272
+ kind: "unreachable",
3273
+ stream: "stdout",
3274
+ text: `unreachable ${type} ${this.describe(id)}`,
3275
+ objectId: id,
3276
+ objectType: type,
3277
+ });
3278
+ continue;
3279
+ }
3280
+ if (!(flags & USED)) {
3281
+ const type = await this.printableType(n);
3282
+ if (this.o.dangling) {
3283
+ this.emit({
3284
+ kind: "dangling",
3285
+ stream: "stdout",
3286
+ text: `dangling ${type} ${this.describe(id)}`,
3287
+ objectId: id,
3288
+ objectType: type,
3289
+ });
3290
+ }
3291
+ if (this.o.lostFound) await this.writeLostFound(id, type);
3292
+ }
3293
+ }
3294
+ }
3295
+
3296
+ /** `--lost-found`: a dangling object into `.git/lost-found/{commit,other}/<id>`. */
3297
+ private async writeLostFound(id: string, type: string): Promise<void> {
3298
+ const files = this.files;
3299
+ if (!files) return;
3300
+ const dir = pathOf(this.gitDir, "lost-found", type === "commit" ? "commit" : "other");
3301
+ await files.mkdir(dir);
3302
+ const path = pathOf(dir, id);
3303
+ if (type === "blob") {
3304
+ const obj = await this.readObject(id);
3305
+ if (obj) await files.write(path, obj.content);
3306
+ } else {
3307
+ await files.write(path, [new TextEncoder().encode(`${id}\n`)]);
3308
+ }
3309
+ }
3310
+ }
3311
+
3312
+ async function readAll(files: FilesApi, path: string): Promise<Uint8Array> {
3313
+ const parts: Uint8Array[] = [];
3314
+ let n = 0;
3315
+ for await (const c of files.read(path)) {
3316
+ parts.push(c);
3317
+ n += c.length;
3318
+ }
3319
+ if (parts.length === 1) return parts[0] as Uint8Array;
3320
+ const out = new Uint8Array(n);
3321
+ let o = 0;
3322
+ for (const p of parts) {
3323
+ out.set(p, o);
3324
+ o += p.length;
3325
+ }
3326
+ return out;
3327
+ }
3328
+
3329
+ async function readText(files: FilesApi, path: string): Promise<string | undefined> {
3330
+ if ((await files.stats(path))?.kind !== "file") return undefined;
3331
+ return dec.decode(await readAll(files, path));
3332
+ }
3333
+
3334
+ /** The entries of a reflog file, oldest first: old id, new id and the entry's timestamp. */
3335
+ function parseReflog(text: string | undefined): Reflog["entries"] {
3336
+ const entries: Reflog["entries"] = [];
3337
+ for (const line of text?.split("\n") ?? []) {
3338
+ const oldId = line.slice(0, 40);
3339
+ const newId = line.slice(41, 81);
3340
+ if (!OID.test(oldId) || !OID.test(newId)) continue;
3341
+ const tab = line.indexOf("\t");
3342
+ const ident = tab < 0 ? line.slice(82) : line.slice(82, tab);
3343
+ const m = /> (\d+) [+-]\d{4}$/.exec(ident);
3344
+ entries.push({ oldId, newId, timestamp: m ? Number(m[1]) : 0 });
3345
+ }
3346
+ return entries;
3347
+ }