@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
@@ -1,10 +1,15 @@
1
1
  import type {
2
+ BlobRead,
2
3
  Blobs,
3
4
  Commit,
4
5
  Commits,
5
6
  ObjectId,
7
+ PersonIdent,
6
8
  Ref,
9
+ RefLogOptions,
10
+ RefRemoveOptions,
7
11
  Refs,
12
+ RefTransactionHook,
8
13
  SymbolicRef,
9
14
  Tag,
10
15
  Tags,
@@ -12,10 +17,68 @@ import type {
12
17
  TreeEntry,
13
18
  Trees,
14
19
  } from "@statewalker/vcs-core";
15
- import { isSymbolicRef } from "@statewalker/vcs-core";
16
- import type { Staging, WorkingCopy, Worktree } from "@statewalker/vcs-working-tree";
17
-
18
- import { NoHeadError, RefNotFoundError } from "./errors/index.js";
20
+ import {
21
+ createReplacedBlobs,
22
+ createReplacedCommits,
23
+ createReplacedTags,
24
+ createReplacedTrees,
25
+ type GraftFileBase,
26
+ graftFileBaseDir,
27
+ graftFileReader,
28
+ hasReplacements,
29
+ isSymbolicRef,
30
+ type LoadedObjectReplacements,
31
+ loadObjectReplacements,
32
+ overlayMethods,
33
+ } from "@statewalker/vcs-core";
34
+ import { OrderedMap, parseGitBool } from "@statewalker/vcs-utils";
35
+ import {
36
+ type AttributesSourceResolver,
37
+ basicStatMatches,
38
+ clearSkipWorktreeFromPresentFiles,
39
+ compareWithWorktree,
40
+ IndexChangedError,
41
+ type OperationOptions,
42
+ type SparseCheckoutPatterns,
43
+ type Staging,
44
+ type WorkingCopy,
45
+ type Worktree,
46
+ } from "@statewalker/vcs-working-tree";
47
+ import { attributesSourceResolver } from "./commands/attributes-source.js";
48
+ import {
49
+ configLoadError,
50
+ createIdAbbreviator,
51
+ type IdAbbreviator,
52
+ worktreeModeTrust,
53
+ } from "./commands/core-config.js";
54
+ import { HookSession, refTransactionHookOf } from "./commands/git-hooks.js";
55
+ import {
56
+ authorIdentOf,
57
+ committerIdentOf,
58
+ hostEnvironmentOf,
59
+ type IdentRole,
60
+ resolveIdentDate,
61
+ withoutCrud,
62
+ } from "./commands/git-ident.js";
63
+ import { indexHostOf, indexVersionConfigError } from "./commands/index-host.js";
64
+ import type { NotesContext } from "./commands/notes-support.js";
65
+ import { postIndexChangeHookOf } from "./commands/post-index-change.js";
66
+ import { createPromisorFetcher, promisorOf } from "./commands/promisor-remote.js";
67
+ import { reflogLine } from "./commands/reflog-messages.js";
68
+ import {
69
+ type ArgumentFiles,
70
+ lstatExists,
71
+ type WorktreeLookup,
72
+ } from "./commands/revision-filenames.js";
73
+ import { type ResolveOptions, RevisionResolver } from "./commands/revision-resolver.js";
74
+ import { readSparseCheckoutPatterns } from "./commands/sparse-checkout-support.js";
75
+ import {
76
+ InvalidConfigError,
77
+ NoHeadError,
78
+ NotACommitError,
79
+ RefNotFoundError,
80
+ } from "./errors/index.js";
81
+ import { RemoteConfigStore } from "./remote-config/index.js";
19
82
 
20
83
  /**
21
84
  * Extended Trees interface with legacy method names for command compatibility.
@@ -30,9 +93,24 @@ export interface CommandTrees extends Trees {
30
93
  /**
31
94
  * Extended Refs interface with legacy method names for command compatibility.
32
95
  */
96
+ /** A ref store that runs the reference-transaction hook (the files store). */
97
+ interface TransactionHookStore {
98
+ setTransactionHook?(hook: RefTransactionHook | undefined): void;
99
+ getTransactionHook?(): RefTransactionHook | undefined;
100
+ }
101
+
102
+ /**
103
+ * The reference-transaction hooks commands installed: a command without hooks removes one
104
+ * of these left on its store (a command that wrote refs outside its `call`), never a hook
105
+ * someone else set (the receive side of a local push, a library user).
106
+ */
107
+ const commandTransactionHooks = new WeakSet<RefTransactionHook>();
108
+ /** The post-index-change hooks commands installed (see `installIndexWriteHook`). */
109
+ const commandIndexWriteHooks = new WeakSet<() => Promise<void>>();
110
+
33
111
  export interface CommandRefs extends Refs {
34
112
  /** Delete a reference - alias for remove() */
35
- delete(name: string): Promise<boolean>;
113
+ delete(name: string, options?: RefRemoveOptions): Promise<boolean>;
36
114
  }
37
115
 
38
116
  /**
@@ -80,7 +158,7 @@ function wrapTrees(trees: Trees): CommandTrees {
80
158
  function wrapRefs(refs: Refs): CommandRefs {
81
159
  const wrapper = refs as CommandRefs;
82
160
  if (!wrapper.delete) {
83
- wrapper.delete = (name: string) => refs.remove(name);
161
+ wrapper.delete = (name: string, options?: RefRemoveOptions) => refs.remove(name, options);
84
162
  }
85
163
  return wrapper;
86
164
  }
@@ -137,6 +215,18 @@ function wrapCommits(commits: Commits): CommandCommits {
137
215
  return wrapper as CommandCommits;
138
216
  }
139
217
 
218
+ /** git's advice when it reads a grafts file (2.5x wording). */
219
+ const GRAFT_FILE_ADVICE = [
220
+ "hint: Support for <GIT_DIR>/info/grafts is deprecated",
221
+ "hint: and will be removed in a future Git version.",
222
+ "hint:",
223
+ 'hint: Please use "git replace --convert-graft-file"',
224
+ "hint: to convert the grafts into replace refs.",
225
+ "hint:",
226
+ "hint: Turn this message off by running",
227
+ 'hint: "git config set advice.graftFileDeprecated false"',
228
+ ];
229
+
140
230
  /**
141
231
  * Abstract base class for all Git commands.
142
232
  *
@@ -149,55 +239,590 @@ function wrapCommits(commits: Commits): CommandCommits {
149
239
  *
150
240
  * @typeParam T - The return type of the command's call() method
151
241
  */
242
+ /** Trees the commands sharing reads keep (see `GitCommand.shareReadsOf`). */
243
+ const SHARED_TREES = 1024;
244
+ /** Bytes of blob content the commands sharing reads keep, and the largest blob kept */
245
+ export const SHARED_BLOB_BYTES = 64 * 2 ** 20;
246
+ export const SHARED_BLOB_MAX = 2 ** 20;
247
+
248
+ /** Blob contents kept for the commands sharing reads, most recently used last */
249
+ export interface SharedBlobs {
250
+ recent: OrderedMap<ObjectId, Uint8Array>;
251
+ bytes: number;
252
+ }
253
+
254
+ /**
255
+ * `blobs` keeping the small blobs it reads in `shared` until they are read again: `git log -p`
256
+ * reads a file's version as the old side of one commit's diff and again as the new side of
257
+ * the next one down, then no more. The bytes handed out are shared between the readers,
258
+ * never to be changed.
259
+ */
260
+ export function sharingBlobs(blobs: Blobs, shared: SharedBlobs): Blobs {
261
+ const open = async (id: ObjectId): Promise<BlobRead | undefined> => {
262
+ const known = shared.recent.get(id);
263
+ if (known) {
264
+ // the second read is mostly the last (newest first, a version is read as the old side
265
+ // of the change after it, then as the new side of its own): it leaves the cache, which
266
+ // so holds the versions still to come instead of the ones done with
267
+ shared.recent.delete(id);
268
+ shared.bytes -= known.length;
269
+ return { size: known.length, bytes: known, content: single(known) };
270
+ }
271
+ const blob = await blobs.open?.(id);
272
+ if (blob?.bytes && blob.size <= SHARED_BLOB_MAX) {
273
+ // another open of the same id may have kept it while this one read: hand out that copy
274
+ const kept = shared.recent.get(id);
275
+ if (kept) return { size: kept.length, bytes: kept, content: single(kept) };
276
+ shared.recent.set(id, blob.bytes);
277
+ shared.bytes += blob.bytes.length;
278
+ while (shared.bytes > SHARED_BLOB_BYTES && shared.recent.size > 0) {
279
+ const oldest = shared.recent.oldestKey() as ObjectId;
280
+ shared.bytes -= shared.recent.get(oldest)?.length ?? 0;
281
+ shared.recent.delete(oldest);
282
+ }
283
+ if (shared.recent.size === 0) shared.bytes = 0;
284
+ }
285
+ return blob;
286
+ };
287
+ return overlayMethods(blobs, {
288
+ open,
289
+ load: async (id: ObjectId) => {
290
+ const blob = await open(id);
291
+ if (!blob) return undefined;
292
+ return blob.bytes ? single(blob.bytes) : blob.content;
293
+ },
294
+ size: async (id: ObjectId) => {
295
+ const blob = await open(id);
296
+ if (!blob) return -1;
297
+ if (!blob.bytes) await blob.content[Symbol.asyncIterator]().return?.();
298
+ return blob.size;
299
+ },
300
+ });
301
+ }
302
+
303
+ /** One chunk as a stream */
304
+ async function* single(bytes: Uint8Array): AsyncGenerator<Uint8Array> {
305
+ yield bytes;
306
+ }
307
+
308
+ /** The entry points (`call`, `callText`, ...) of each command class, found once per class */
309
+ const ENTRY_POINTS = new WeakMap<object, readonly string[]>();
310
+
311
+ /**
312
+ * The names of the entry points a command's prototype chain defines (`call` and `callX`
313
+ * methods), looked up once per class: `git log -p` makes a command per commit.
314
+ */
315
+ function entryPointNames(prototype: object): readonly string[] {
316
+ const known = ENTRY_POINTS.get(prototype);
317
+ if (known) return known;
318
+ const names = new Set<string>();
319
+ for (
320
+ let proto = prototype;
321
+ proto && proto !== Object.prototype;
322
+ proto = Object.getPrototypeOf(proto)
323
+ ) {
324
+ for (const name of Object.getOwnPropertyNames(proto)) {
325
+ if (!/^call(?:[A-Z]\w*)?$/.test(name)) continue;
326
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
327
+ if (typeof descriptor?.value === "function") names.add(name);
328
+ }
329
+ }
330
+ const found = [...names];
331
+ ENTRY_POINTS.set(prototype, found);
332
+ return found;
333
+ }
334
+
152
335
  export abstract class GitCommand<T> {
153
336
  protected readonly _workingCopy: WorkingCopy;
154
337
  private callable = true;
338
+ private racyCheckInstalled = false;
339
+ /** `--no-replace-objects` (false) or not given (undefined: config and environment decide) */
340
+ protected useReplaceRefsOverride?: boolean;
341
+ private replacementsLoad?: Promise<LoadedObjectReplacements | undefined>;
342
+ private reflogActionOverride?: string;
343
+ /** The time of this command's reflog lines, read once (git's ident_default_date). */
344
+ private reflogClock?: number;
345
+ /** The hooks this command runs (made when first asked for) */
346
+ private hookSession?: HookSession;
155
347
 
156
348
  constructor(workingCopy: WorkingCopy) {
157
349
  this._workingCopy = workingCopy;
350
+ this.installAttributesSource();
351
+ // a partial clone's absent objects come from its promisor remotes (unless the library
352
+ // user installed a fetcher of their own)
353
+ const promisor = promisorOf(workingCopy);
354
+ if (promisor && !promisor.fetcher) promisor.setFetcher(createPromisorFetcher(workingCopy));
355
+ this.releaseHooksAfterCalls();
356
+ }
357
+
358
+ /**
359
+ * Each entry point of the command (`call`, `callText`, ...) puts back the ref store's
360
+ * reference-transaction hook when it ends, whatever the outcome.
361
+ */
362
+ private releaseHooksAfterCalls(): void {
363
+ const self = this as unknown as Record<string, unknown>;
364
+ for (const name of entryPointNames(Object.getPrototypeOf(this))) {
365
+ const method = self[name];
366
+ if (typeof method !== "function") continue;
367
+ self[name] = (...args: unknown[]) => {
368
+ let result: unknown;
369
+ try {
370
+ result = (method as (...a: unknown[]) => unknown).apply(this, args);
371
+ } catch (error) {
372
+ this.releaseRefTransactionHook();
373
+ throw error;
374
+ }
375
+ if (result && typeof (result as Promise<unknown>).finally === "function") {
376
+ return (result as Promise<unknown>).finally(() => this.releaseRefTransactionHook());
377
+ }
378
+ this.releaseRefTransactionHook();
379
+ return result;
380
+ };
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Runs `enter` as each entry point of the command (`call`, `callText`, ...) starts; the
386
+ * function it returns runs when that call ends, whatever the outcome (subclasses scope
387
+ * state to their calls with it: a transport command's promisor fetcher).
388
+ */
389
+ protected aroundEntryPoints(enter: () => (() => void) | undefined): void {
390
+ const self = this as unknown as Record<string, unknown>;
391
+ for (const name of entryPointNames(Object.getPrototypeOf(this))) {
392
+ const method = self[name];
393
+ if (typeof method !== "function") continue;
394
+ self[name] = (...args: unknown[]) => {
395
+ const leave = enter();
396
+ let result: unknown;
397
+ try {
398
+ result = (method as (...a: unknown[]) => unknown).apply(this, args);
399
+ } catch (error) {
400
+ leave?.();
401
+ throw error;
402
+ }
403
+ if (leave && result && typeof (result as Promise<unknown>).finally === "function") {
404
+ return (result as Promise<unknown>).finally(leave);
405
+ }
406
+ leave?.();
407
+ return result;
408
+ };
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Lets git's content filter resolve an attribute source (`$GIT_ATTR_SOURCE`, `attr.tree`)
414
+ * with git's revision syntax over this repository.
415
+ */
416
+ private installAttributesSource(): void {
417
+ let worktree: Worktree | undefined;
418
+ try {
419
+ worktree = this._workingCopy.worktree;
420
+ } catch {
421
+ // a bare repository's working copy refuses its worktree
422
+ return;
423
+ }
424
+ const filter = worktree?.contentFilter as
425
+ | { setAttributesSourceResolver?: (resolve: AttributesSourceResolver) => void }
426
+ | undefined;
427
+ if (!filter?.setAttributesSourceResolver || !this._workingCopy.history) return;
428
+ filter.setAttributesSourceResolver(attributesSourceResolver(() => this.revisionResolver()));
429
+ }
430
+
431
+ /**
432
+ * The hooks this command runs (git's `run_hooks_opt`), through the host environment's
433
+ * `hookRunner`; with none, no hook runs.
434
+ */
435
+ protected get hooks(): HookSession {
436
+ if (!this.hookSession) this.hookSession = new HookSession(this._workingCopy);
437
+ return this.hookSession;
438
+ }
439
+
440
+ /**
441
+ * Runs this command's hooks in another command's session: a command that runs another
442
+ * (merge committing, rebase picking) gathers the output of both in one place. With `env`,
443
+ * this command's hooks also get those variables, as the hooks of a git command git runs as
444
+ * a child process with them set (a sequencer's `git commit` with GIT_REFLOG_ACTION).
445
+ */
446
+ shareHooksOf(source: GitCommand<unknown>, env?: Record<string, string>): this {
447
+ this.hookSession = env ? source.hooks.withEnv(env) : source.hooks;
448
+ return this;
449
+ }
450
+
451
+ /**
452
+ * What the hooks this command ran wrote, in order, with git's hints about hooks it ignored
453
+ * (`advice.ignoredHook`): git relays all of it on its stderr (a hook's stdout included,
454
+ * except for the hooks whose stdout git keeps apart). Empty when no hook ran.
455
+ */
456
+ getHookOutput(): string {
457
+ return this.hookSession?.output ?? "";
458
+ }
459
+
460
+ /** What the hooks whose stdout git keeps on its own stdout (pre-push) wrote there. */
461
+ getHookStdout(): string {
462
+ return this.hookSession?.stdout ?? "";
463
+ }
464
+
465
+ /**
466
+ * The action named in the reflog lines this command writes, in place of its own (git's
467
+ * `GIT_REFLOG_ACTION`): `git pull` runs its merge as `pull`, so the line reads
468
+ * `pull: Fast-forward`. Each command uses it where git does: as the whole message of
469
+ * `checkout`, as the prefix of `commit`, `merge`, `fetch`, `rebase`, `cherry-pick`.
470
+ */
471
+ setReflogAction(action: string): this {
472
+ this.checkCallable();
473
+ this.reflogActionOverride = action;
474
+ return this;
475
+ }
476
+
477
+ /** The reflog action set with {@link setReflogAction}, else `fallback`. */
478
+ protected reflogAction(fallback: string): string {
479
+ return this.reflogActionOverride ?? fallback;
480
+ }
481
+
482
+ /** Whether {@link setReflogAction} named an action. */
483
+ protected hasReflogAction(): boolean {
484
+ return this.reflogActionOverride !== undefined;
485
+ }
486
+
487
+ /**
488
+ * A reflog line's options: `message` with `who` (a commit's committer) as its identity,
489
+ * else git's committer ident from the environment and configuration, at the time this
490
+ * command first asked for a line.
491
+ */
492
+ protected reflogLine(message: string, who?: PersonIdent): RefLogOptions {
493
+ return reflogLine(this._workingCopy, message, who, this.clock());
494
+ }
495
+
496
+ /**
497
+ * The clock of this command's identities and reflog lines, in seconds: read once per
498
+ * command (a rebase's finish logs the branch and HEAD at one time, as git's process reads
499
+ * its default date once), and again where git resets it ({@link resetClock}).
500
+ */
501
+ protected clock(): number {
502
+ this.reflogClock ??= Math.floor(Date.now() / 1000);
503
+ return this.reflogClock;
504
+ }
505
+
506
+ /**
507
+ * git's `reset_ident_date()`: the clock read again, for the commit about to be made and
508
+ * the lines after it (the sequencer does this before each pick).
509
+ */
510
+ protected resetClock(): number {
511
+ this.reflogClock = Math.floor(Date.now() / 1000);
512
+ return this.reflogClock;
513
+ }
514
+
515
+ /**
516
+ * The committer of a commit (or tagger of a tag) this command makes, as git resolves it
517
+ * (`resolveCommitterIdent`): `GIT_COMMITTER_*`, `committer.*`, `user.*`, the clock;
518
+ * `fallback`'s name and email (an identity given explicitly) where git would guess them;
519
+ * never `fallback`'s date.
520
+ */
521
+ protected resolveCommitter(fallback?: Pick<PersonIdent, "name" | "email">): PersonIdent {
522
+ return committerIdentOf(this._workingCopy, { now: this.clock(), fallback });
523
+ }
524
+
525
+ /**
526
+ * The author of a commit this command makes, as git resolves it (`resolveAuthorIdent`):
527
+ * `GIT_AUTHOR_*`, `author.*`, `user.*`, the clock; `fallback`'s name and email where git
528
+ * would guess them.
529
+ */
530
+ protected resolveAuthor(fallback?: Pick<PersonIdent, "name" | "email">): PersonIdent {
531
+ return authorIdentOf(this._workingCopy, { now: this.clock(), fallback });
532
+ }
533
+
534
+ /**
535
+ * An identity named explicitly (`--author=<who>`), dated as git dates `role` now; its
536
+ * name and email without crud, as git writes them.
537
+ */
538
+ protected datedIdent(role: IdentRole, who: { name: string; email: string }): PersonIdent {
539
+ const date = resolveIdentDate(role, hostEnvironmentOf(this._workingCopy), this.clock());
540
+ return { name: withoutCrud(who.name), email: withoutCrud(who.email), ...date };
541
+ }
542
+
543
+ /** What git's notes code reads and writes through this command (`notes-support.ts`). */
544
+ protected notesContext(): NotesContext {
545
+ const tags = this.tagsStore;
546
+ return {
547
+ workingCopy: this._workingCopy,
548
+ blobs: this.blobs,
549
+ trees: this.trees,
550
+ commits: this.commits,
551
+ refs: this.refsStore,
552
+ ...(tags ? { tags } : {}),
553
+ author: () => this.resolveAuthor(),
554
+ committer: () => this.resolveCommitter(),
555
+ reflogLine: (message) => this.reflogLine(message),
556
+ // a full object id is itself (get_oid_basic); the resolver would also look for refs
557
+ // spelled as it, for an ambiguity warning the notes commands do not print — a ref
558
+ // lookup per line of `git notes copy --stdin` that costs most of its time
559
+ resolve: (name) =>
560
+ /^[0-9a-fA-F]{40}$/.test(name)
561
+ ? Promise.resolve(name.toLowerCase())
562
+ : this.revisionResolver()
563
+ .resolve(name)
564
+ .catch(() => undefined),
565
+ };
158
566
  }
159
567
 
160
568
  // ============ Store Accessors ============
161
569
 
162
570
  /**
163
- * Access blob storage.
571
+ * Whether this command reads objects through replace refs and grafts (see {@link commits}).
572
+ * git applies them to every object read but those of gc, prune, pack-objects, upload-pack,
573
+ * index-pack, fsck and commit-graph; the commands doing those override this to read the
574
+ * objects as stored.
164
575
  */
165
- protected get blobs(): Blobs {
576
+ protected readsReplacedObjects(): boolean {
577
+ return true;
578
+ }
579
+
580
+ /** The stored objects, as {@link storedCommits} reads commits. */
581
+ private historyOf(): NonNullable<WorkingCopy["history"]> {
166
582
  if (!this._workingCopy.history) {
167
583
  throw new Error("WorkingCopy.history is required for commands");
168
584
  }
169
- return this._workingCopy.history.blobs as unknown as Blobs;
585
+ return this._workingCopy.history;
586
+ }
587
+
588
+ /** Whether an object was read through the replacements (git then read them, and printed) */
589
+ private replacementsRead = false;
590
+
591
+ /** The views of the stored objects through the replacements, made once per command */
592
+ private replacedViews?: {
593
+ blobs: Blobs;
594
+ trees: CommandTrees;
595
+ commits: CommandCommits;
596
+ tags?: CommandTags;
597
+ };
598
+
599
+ private views() {
600
+ if (!this.replacedViews) {
601
+ const history = this.historyOf();
602
+ const load = () => {
603
+ this.replacementsRead = true;
604
+ return this.objectReplacements();
605
+ };
606
+ const storedTrees = wrapTrees(history.trees as unknown as Trees);
607
+ const trees = createReplacedTrees(storedTrees, load);
608
+ const rawTags = history.tags ? wrapTags(history.tags as unknown as Tags) : undefined;
609
+ const tags = rawTags ? createReplacedTags(rawTags, load) : undefined;
610
+ this.replacedViews = {
611
+ blobs: createReplacedBlobs(history.blobs as unknown as Blobs, load),
612
+ // the legacy names read through the view too
613
+ trees: overlayMethods(trees, {
614
+ loadTree: async function* (id: ObjectId): AsyncIterable<TreeEntry> {
615
+ const entries = await trees.load(id);
616
+ if (entries) yield* entries;
617
+ },
618
+ }),
619
+ commits: createReplacedCommits(
620
+ wrapCommits(history.commits as unknown as Commits),
621
+ load,
622
+ ) as CommandCommits,
623
+ ...(tags
624
+ ? { tags: overlayMethods(tags, { loadTag: (id: ObjectId) => tags.load(id) }) }
625
+ : {}),
626
+ };
627
+ }
628
+ return this.replacedViews;
170
629
  }
171
630
 
172
631
  /**
173
- * Access tree storage.
632
+ * Access blob storage: a blob replaced by `refs/replace/<id>` reads as its replacement,
633
+ * unless this command reads the objects as stored ({@link readsReplacedObjects}).
174
634
  */
175
- protected get trees(): CommandTrees {
176
- if (!this._workingCopy.history) {
177
- throw new Error("WorkingCopy.history is required for commands");
635
+ protected get blobs(): Blobs {
636
+ const blobs = this.readsReplacedObjects() ? this.views().blobs : this.storedBlobs;
637
+ const shared = this.sharedBlobs;
638
+ if (!shared || !blobs.open) return blobs;
639
+ if (this.sharedBlobsView?.of !== blobs) {
640
+ this.sharedBlobsView = { of: blobs, view: sharingBlobs(blobs, shared) };
178
641
  }
179
- return wrapTrees(this._workingCopy.history.trees as unknown as Trees);
642
+ return this.sharedBlobsView.view;
180
643
  }
181
644
 
645
+ /** Blob contents read lately by the commands sharing reads ({@link shareReadsOf}) */
646
+ private sharedBlobs?: SharedBlobs;
647
+ private sharedBlobsView?: { of: Blobs; view: Blobs };
648
+
182
649
  /**
183
- * Access commit storage.
650
+ * Access tree storage: a tree replaced by `refs/replace/<id>` reads as its replacement,
651
+ * unless this command reads the objects as stored ({@link readsReplacedObjects}).
652
+ */
653
+ protected get trees(): CommandTrees {
654
+ return this.readsReplacedObjects() ? this.views().trees : this.storedTrees;
655
+ }
656
+
657
+ /**
658
+ * Access commit storage, as git reads commits: a commit replaced by `refs/replace/<id>`
659
+ * reads as its replacement (keeping its id), a commit in `info/grafts` with its grafted
660
+ * parents, a shallow commit with none; merge bases, ancestry and walks follow them (see
661
+ * `createReplacedCommits`). Without replace refs or grafts, or in a command that reads the
662
+ * objects as stored ({@link readsReplacedObjects}), it is the store itself.
184
663
  */
185
664
  protected get commits(): CommandCommits {
186
- if (!this._workingCopy.history) {
187
- throw new Error("WorkingCopy.history is required for commands");
665
+ return this.readsReplacedObjects() ? this.views().commits : this.storedCommits;
666
+ }
667
+
668
+ /** The blobs as stored, without replace refs. */
669
+ protected get storedBlobs(): Blobs {
670
+ return this.historyOf().blobs as unknown as Blobs;
671
+ }
672
+
673
+ /** The trees as stored, without replace refs. */
674
+ protected get storedTrees(): CommandTrees {
675
+ return wrapTrees(this.historyOf().trees as unknown as Trees);
676
+ }
677
+
678
+ /** The commits as stored, without replace refs or grafts. */
679
+ protected get storedCommits(): CommandCommits {
680
+ return wrapCommits(this.historyOf().commits as unknown as Commits);
681
+ }
682
+
683
+ /**
684
+ * Whether replace refs apply to this command's history walks: `false` is git's
685
+ * `--no-replace-objects`. Unset, `core.useReplaceRefs` (default true) decides, and
686
+ * `GIT_NO_REPLACE_OBJECTS` in the host environment turns them off.
687
+ */
688
+ setUseReplaceRefs(use: boolean): this {
689
+ this.checkCallable();
690
+ this.useReplaceRefsOverride = use;
691
+ return this;
692
+ }
693
+
694
+ /** Whether replace refs apply (see {@link setUseReplaceRefs}). */
695
+ protected useReplaceRefs(): boolean {
696
+ if (this.useReplaceRefsOverride !== undefined) return this.useReplaceRefsOverride;
697
+ if (hostEnvironmentOf(this._workingCopy)?.noReplaceObjects) return false;
698
+ const value = this._workingCopy.config
699
+ ? RemoteConfigStore.from(this._workingCopy).value("core.useReplaceRefs")
700
+ : undefined;
701
+ return parseGitBool(value) ?? true;
702
+ }
703
+
704
+ /**
705
+ * Where a relative `GIT_GRAFT_FILE` is read from: the worktree top (the git directory when
706
+ * `core.bare`), as the host names it (the working copy's `hostGitDir`), where git's setup
707
+ * has changed to before opening the file; undefined when the host path is unknown.
708
+ */
709
+ protected graftFileBase(): GraftFileBase | undefined {
710
+ const gitDir = (this._workingCopy.config as { hostGitDir?: string } | undefined)?.hostGitDir;
711
+ if (gitDir === undefined) return undefined;
712
+ const bare = this._workingCopy.config
713
+ ? parseGitBool(RemoteConfigStore.from(this._workingCopy).value("core.bare"))
714
+ : undefined;
715
+ return { dir: graftFileBaseDir(gitDir, bare) };
716
+ }
717
+
718
+ /**
719
+ * The directory git runs in, as the host names it: the worktree top (the git directory when
720
+ * `core.bare`), where git reads a relative path from the configuration
721
+ * (`fetch.fsck.skipList`); from the working copy's `hostGitDir`, else from the repository's
722
+ * FilesApi root. Undefined when the host path is unknown.
723
+ */
724
+ protected async hostWorkingDir(): Promise<string | undefined> {
725
+ const known = this.graftFileBase()?.dir;
726
+ if (known !== undefined) return known;
727
+ const gitDir = await this.hooks.hostGitDir({ real: false }).catch(() => undefined);
728
+ if (gitDir === undefined) return undefined;
729
+ const bare = this._workingCopy.config
730
+ ? parseGitBool(RemoteConfigStore.from(this._workingCopy).value("core.bare"))
731
+ : undefined;
732
+ return graftFileBaseDir(gitDir, bare);
733
+ }
734
+
735
+ /** The commits as git's history walks read them: {@link commits}. */
736
+ protected get walkCommits(): CommandCommits {
737
+ return this.commits;
738
+ }
739
+
740
+ /**
741
+ * The replace refs and grafts this command's reads apply, read once; undefined when there
742
+ * are none (or they cannot be read).
743
+ */
744
+ protected objectReplacements(): Promise<LoadedObjectReplacements | undefined> {
745
+ return this.loadedReplacements().then((r) => (hasReplacements(r) ? r : undefined));
746
+ }
747
+
748
+ /**
749
+ * The replace refs and grafts as read, with the messages git prints while reading them
750
+ * (`bad graft data`, `bad replace ref name`), read once.
751
+ */
752
+ protected loadedReplacements(): Promise<LoadedObjectReplacements | undefined> {
753
+ if (!this.replacementsLoad) {
754
+ const environment = hostEnvironmentOf(this._workingCopy);
755
+ const replaceRefBase = environment?.replaceRefBase;
756
+ // GIT_GRAFT_FILE: that file is read in place of info/grafts (an empty one is a grafts
757
+ // file all the same: git gives its deprecation advice)
758
+ const readGraftFile = graftFileReader(environment, this.graftFileBase());
759
+ this.replacementsLoad = loadObjectReplacements({
760
+ refs: this.refsStore,
761
+ useReplaceRefs: this.useReplaceRefs(),
762
+ ...(replaceRefBase !== undefined ? { replaceRefBase } : {}),
763
+ ...(readGraftFile ? { readGraftFile } : {}),
764
+ }).catch(() => undefined);
188
765
  }
189
- return wrapCommits(this._workingCopy.history.commits as unknown as Commits);
766
+ return this.replacementsLoad;
767
+ }
768
+
769
+ /**
770
+ * What git prints on stderr while it reads the replace refs and grafts, once this command
771
+ * has read an object through them (`git log`, `git rev-parse HEAD~1`; not `git rev-parse
772
+ * HEAD`, which reads no object): `warning: bad replace ref name: <name>`, the advice that
773
+ * `info/grafts` is deprecated (unless `advice.graftFileDeprecated` is false), `error: bad
774
+ * graft data: <line>`. The advice is worded as git 2.5x words it.
775
+ */
776
+ async replacementMessages(): Promise<string[]> {
777
+ if (!this.replacementsRead) return [];
778
+ const loaded = await this.loadedReplacements();
779
+ if (!loaded) return [];
780
+ const advice =
781
+ loaded.graftFile &&
782
+ parseGitBool(
783
+ this._workingCopy.config
784
+ ? RemoteConfigStore.from(this._workingCopy).value("advice.graftFileDeprecated")
785
+ : undefined,
786
+ ) !== false
787
+ ? GRAFT_FILE_ADVICE
788
+ : [];
789
+ return [...loaded.replaceMessages, ...advice, ...loaded.graftMessages];
790
+ }
791
+
792
+ /**
793
+ * The error lines git prints on stderr when it prepares the object database and reads the
794
+ * repository's alternates (odb.c: `error: object directory <path> does not exist; check
795
+ * .git/objects/info/alternates`, `error: unable to normalize alternate object path: <path>`,
796
+ * `error: <path>: ignoring alternate object stores, nesting too deep`), in git's order; empty
797
+ * when the alternates read cleanly. git prints them once per process, when it first looks up
798
+ * an object (status, log, diff, fsck, gc, fetch, push, commit all do), so a caller printing a
799
+ * command's stderr prints these once, first. Where git runs child git processes it repeats
800
+ * them per child (gc's repack and prune, 2.5x fsck's `refs verify` and index-pack checks,
801
+ * commit), and 2.43's `rev-parse HEAD` reads no object and prints none: ours are read with
802
+ * the repository, once.
803
+ *
804
+ * This is the channel for these lines: commands whose results have no stderr of their own
805
+ * (status, log, diff, commit, fetch, push, clone, ...) leave them here for the caller to print
806
+ * first. Where a result carries git's stderr they are folded in as well, first and once:
807
+ * `FsckResult.errorOutput`/`findings` and `GcResult.errors`.
808
+ */
809
+ alternatesErrors(): string[] {
810
+ return [...(this._workingCopy.history?.objects?.alternates?.errors ?? [])];
811
+ }
812
+
813
+ /** Marks that this command read objects through the replacements (see replacementMessages). */
814
+ protected markReplacementsRead(): void {
815
+ this.replacementsRead = true;
190
816
  }
191
817
 
192
818
  /**
193
- * Access tag storage.
819
+ * Access tag storage: an annotated tag replaced by `refs/replace/<id>` reads as its
820
+ * replacement, unless this command reads the objects as stored.
194
821
  * Named tagsStore to avoid conflict with command properties.
195
822
  */
196
823
  protected get tagsStore(): CommandTags | undefined {
197
- if (!this._workingCopy.history) {
198
- throw new Error("WorkingCopy.history is required for commands");
199
- }
200
- const tags = this._workingCopy.history.tags as unknown as Tags | undefined;
824
+ if (this.readsReplacedObjects()) return this.views().tags;
825
+ const tags = this.historyOf().tags as unknown as Tags | undefined;
201
826
  return tags ? wrapTags(tags) : undefined;
202
827
  }
203
828
 
@@ -209,7 +834,223 @@ export abstract class GitCommand<T> {
209
834
  if (!this._workingCopy.history) {
210
835
  throw new Error("WorkingCopy.history is required for commands");
211
836
  }
212
- return wrapRefs(this._workingCopy.history.refs as unknown as Refs);
837
+ const refs = wrapRefs(this._workingCopy.history.refs as unknown as Refs);
838
+ this.installRefTransactionHook(refs);
839
+ return refs;
840
+ }
841
+
842
+ /**
843
+ * Deletes `names` whatever their values, as git's `delete_refs` (branch -d, tag -d, remote
844
+ * prune): on a store with `removeAll`, one transaction for them all (git 2.5x), or as git
845
+ * 2.43's files backend when the hooks follow 2.43 (their reference-transaction calls and
846
+ * a failure's outcome differ); else one by one. Returns the names that no longer exist
847
+ * and the failure, if any (git reports it after the others are deleted).
848
+ */
849
+ protected async removeRefsAsGit(
850
+ names: string[],
851
+ message?: string,
852
+ ): Promise<{ removed: string[]; error?: unknown }> {
853
+ const refs = this.refsStore;
854
+ let error: unknown;
855
+ try {
856
+ if (refs.removeAll) {
857
+ await refs.removeAll(names, {
858
+ legacy: this.hooks.compatibility === "2.43",
859
+ ...(message !== undefined ? { message } : {}),
860
+ });
861
+ } else {
862
+ for (const name of names) {
863
+ try {
864
+ await refs.delete(name, { deleteRefs: true });
865
+ } catch (e) {
866
+ error ??= e;
867
+ }
868
+ }
869
+ }
870
+ } catch (e) {
871
+ error = e;
872
+ }
873
+ const removed: string[] = [];
874
+ for (const name of names) if (!(await refs.has(name).catch(() => true))) removed.push(name);
875
+ return error === undefined ? { removed } : { removed, error };
876
+ }
877
+
878
+ /** The reference-transaction hook this command installs on its ref store (made once). */
879
+ private refTransactionHook?: RefTransactionHook;
880
+ /** The store it is installed on, and the hook that was there before (put back at the end) */
881
+ private refTransactionInstalled?: {
882
+ store: TransactionHookStore;
883
+ previous: RefTransactionHook | undefined;
884
+ };
885
+
886
+ /**
887
+ * git's reference-transaction hook (see {@link refTransactionHookOf}) on a ref store that
888
+ * supports it (the files store), while this command runs: the hook that was there before
889
+ * is put back when the command's `call` ends ({@link releaseRefTransactionHook}), so a
890
+ * later write never routes its output to this command. A command without hooks (no
891
+ * runner) removes a command's hook left there, and leaves any other hook in place.
892
+ */
893
+ private installRefTransactionHook(refs: Refs): void {
894
+ const store = refs as TransactionHookStore;
895
+ if (!store.setTransactionHook) return;
896
+ if (!this.hooks.enabled) {
897
+ const current = store.getTransactionHook?.();
898
+ if (current && commandTransactionHooks.has(current)) store.setTransactionHook(undefined);
899
+ return;
900
+ }
901
+ if (!this.refTransactionHook) {
902
+ const env = this.refTransactionHookEnv();
903
+ const plain = refTransactionHookOf(this.hooks, env ? { env } : {});
904
+ // a git child process with variables of its own (withRefTransactionEnv) runs it with them
905
+ this.refTransactionHook = (state, updates, context) => {
906
+ const extra = this.refTransactionExtraEnv;
907
+ if (!extra) return plain(state, updates, context);
908
+ return refTransactionHookOf(this.hooks, { env: { ...(env ?? {}), ...extra } })(
909
+ state,
910
+ updates,
911
+ context,
912
+ );
913
+ };
914
+ commandTransactionHooks.add(this.refTransactionHook);
915
+ }
916
+ if (!this.refTransactionInstalled) {
917
+ this.refTransactionInstalled = { store, previous: store.getTransactionHook?.() };
918
+ }
919
+ store.setTransactionHook(this.refTransactionHook);
920
+ }
921
+
922
+ /** Variables the reference-transaction hook gets for now (see {@link withRefTransactionEnv}) */
923
+ private refTransactionExtraEnv?: Record<string, string>;
924
+
925
+ /**
926
+ * Runs `body` with `env` added to the reference-transaction hook's variables: the ref
927
+ * updates of a git command git runs as a child process with variables set (a sequencer's
928
+ * `git commit` with GIT_REFLOG_ACTION).
929
+ */
930
+ protected async withRefTransactionEnv<T>(
931
+ env: Record<string, string>,
932
+ body: () => Promise<T>,
933
+ ): Promise<T> {
934
+ const previous = this.refTransactionExtraEnv;
935
+ this.refTransactionExtraEnv = { ...(previous ?? {}), ...env };
936
+ try {
937
+ return await body();
938
+ } finally {
939
+ this.refTransactionExtraEnv = previous;
940
+ }
941
+ }
942
+
943
+ /**
944
+ * Variables git's command exports for every hook it runs, the reference-transaction hook
945
+ * included (merge's GIT_REFLOG_ACTION); none by default.
946
+ */
947
+ protected refTransactionHookEnv(): Record<string, string> | undefined {
948
+ return undefined;
949
+ }
950
+
951
+ /** The post-index-change hook this command installs on its staging (made once). */
952
+ private indexWriteHook?: () => Promise<void>;
953
+ /** The staging it is installed on, and the hook that was there before (put back at the end) */
954
+ private indexWriteInstalled?: {
955
+ staging: Staging;
956
+ previous: (() => Promise<void>) | undefined;
957
+ };
958
+
959
+ /**
960
+ * git's post-index-change hook (see {@link postIndexChangeHookOf}) after each index write
961
+ * of this command's staging (one that supports it), while the command runs: the hook
962
+ * that was there before is put back when its `call` ends. Without a hook runner, a
963
+ * command's hook left there is removed.
964
+ */
965
+ private installIndexWriteHook(staging: Staging): void {
966
+ if (!staging.setWriteHook) return;
967
+ if (!this.hooks.enabled) {
968
+ const current = staging.getWriteHook?.();
969
+ if (current && commandIndexWriteHooks.has(current)) staging.setWriteHook(undefined);
970
+ return;
971
+ }
972
+ if (this.indexWriteInstalled?.staging === staging) {
973
+ if (staging.getWriteHook?.() !== this.indexWriteHook) {
974
+ staging.setWriteHook(this.indexWriteHook);
975
+ }
976
+ return;
977
+ }
978
+ if (!this.indexWriteHook) {
979
+ const run = postIndexChangeHookOf(this.hooks, staging);
980
+ this.indexWriteRun = run;
981
+ this.indexWriteHook = async () => {
982
+ const scope = this.indexWriteScope;
983
+ if (!scope) return run();
984
+ // one hook run for the writes of a scope (see withOneIndexWrite)
985
+ if (scope.written) return;
986
+ scope.written = true;
987
+ if (scope.at === "first") await run();
988
+ };
989
+ commandIndexWriteHooks.add(this.indexWriteHook);
990
+ }
991
+ this.indexWriteInstalled = { staging, previous: staging.getWriteHook?.() };
992
+ staging.setWriteHook(this.indexWriteHook);
993
+ }
994
+
995
+ /** What the installed hook runs (post-index-change with the flags marked) */
996
+ private indexWriteRun?: () => Promise<void>;
997
+ /** Index writes git makes once (see {@link withOneIndexWrite}) */
998
+ private indexWriteScope?: { at: "first" | "last"; written: boolean };
999
+
1000
+ /**
1001
+ * Runs `body` with its index writes counted as git's one write of the index: the
1002
+ * post-index-change hook runs once, at the first write (`first`: `commit -a`, while the
1003
+ * lock is held) or after `body` when it wrote (`last`: a reset that writes the index
1004
+ * again after updating the worktree), with every flag marked meanwhile.
1005
+ */
1006
+ protected async withOneIndexWrite<T>(
1007
+ at: "first" | "last",
1008
+ body: () => Promise<T>,
1009
+ options: { holdWrites?: boolean } = {},
1010
+ ): Promise<T> {
1011
+ if (this.indexWriteScope) return body();
1012
+ const scope = { at, written: false };
1013
+ this.indexWriteScope = scope;
1014
+ // `holdWrites`: the writes before the last one are held back, the index written once at
1015
+ // the end (a body that reads the index back between its writes must not hold them)
1016
+ const release = options.holdWrites ? this.staging.holdWrites?.() : undefined;
1017
+ try {
1018
+ const result = await body();
1019
+ await release?.();
1020
+ return result;
1021
+ } catch (error) {
1022
+ await release?.();
1023
+ throw error;
1024
+ } finally {
1025
+ this.indexWriteScope = undefined;
1026
+ if (at === "last" && scope.written) await this.indexWriteRun?.();
1027
+ }
1028
+ }
1029
+
1030
+ /** Puts back the post-index-change hook the staging had before this command's. */
1031
+ private releaseIndexWriteHook(): void {
1032
+ const installed = this.indexWriteInstalled;
1033
+ if (!installed) return;
1034
+ this.indexWriteInstalled = undefined;
1035
+ const current = installed.staging.getWriteHook?.();
1036
+ if (current === undefined || current === this.indexWriteHook) {
1037
+ installed.staging.setWriteHook?.(installed.previous);
1038
+ }
1039
+ }
1040
+
1041
+ /**
1042
+ * Puts back the reference-transaction hook the store had before this command installed
1043
+ * its own (when its own is still the one installed), and the post-index-change hook.
1044
+ */
1045
+ protected releaseRefTransactionHook(): void {
1046
+ this.releaseIndexWriteHook();
1047
+ const installed = this.refTransactionInstalled;
1048
+ if (!installed) return;
1049
+ this.refTransactionInstalled = undefined;
1050
+ const current = installed.store.getTransactionHook?.();
1051
+ if (current === undefined || current === this.refTransactionHook) {
1052
+ installed.store.setTransactionHook?.(installed.previous);
1053
+ }
213
1054
  }
214
1055
 
215
1056
  /**
@@ -217,6 +1058,103 @@ export abstract class GitCommand<T> {
217
1058
  * Supports both new architecture (checkout.staging) and legacy/init (staging directly).
218
1059
  */
219
1060
  protected get staging(): Staging {
1061
+ const staging = this.resolveStaging();
1062
+ if (!this.racyCheckInstalled) {
1063
+ this.racyCheckInstalled = true;
1064
+ this.installRacyCheck(staging);
1065
+ }
1066
+ this.installIndexWriteHook(staging);
1067
+ this.installIndexHost(staging);
1068
+ return staging;
1069
+ }
1070
+
1071
+ /**
1072
+ * Gives the staging what its index file reads from the repository (`indexHostOf`: the
1073
+ * split and sparse index settings, the trees), once: a host already there stays (the
1074
+ * sparse-checkout command installs its own while it writes new patterns).
1075
+ */
1076
+ private installIndexHost(staging: Staging): void {
1077
+ if (!staging.setIndexHost || staging.getIndexHost?.() !== undefined) return;
1078
+ staging.setIndexHost(
1079
+ indexHostOf(this._workingCopy, staging, () => this.historyOf().trees as unknown as Trees),
1080
+ );
1081
+ }
1082
+
1083
+ /**
1084
+ * The index as it is on disk at the start of an index-writing command, as git reads the
1085
+ * index at the start of every command (`repo_read_index`): when another writer replaced
1086
+ * the index since this instance read or wrote it, the index is read again, unless this
1087
+ * instance holds edits it has not written (they would be lost), which refuses the
1088
+ * command with `IndexChangedError` before it touches the worktree, the index or a ref.
1089
+ * A staging area that cannot be outdated (no index file) is left as it is.
1090
+ *
1091
+ * @param refuseUnwritten false for a command that writes no index (`clean`): unwritten
1092
+ * edits are then kept and used instead of refusing
1093
+ */
1094
+ protected async readCurrentIndex(refuseUnwritten = true): Promise<void> {
1095
+ const staging = this.staging;
1096
+ if (await staging.isOutdated()) {
1097
+ if (staging.hasUnwrittenChanges?.() !== false) {
1098
+ if (!refuseUnwritten) return;
1099
+ throw new IndexChangedError("index");
1100
+ }
1101
+ await staging.read();
1102
+ }
1103
+ await this.clearPresentSkipWorktree();
1104
+ }
1105
+
1106
+ /**
1107
+ * git's `clear_skip_worktree_from_present_files`, which `repo_read_index` runs on every
1108
+ * index read: with `core.sparseCheckout` on (and `sparse.expectFilesOutsideOfPatterns`
1109
+ * off), a skip-worktree entry whose path exists in the worktree loses the flag, written
1110
+ * with the index when the command writes it. Nothing is stat'ed outside a sparse checkout.
1111
+ */
1112
+ protected async clearPresentSkipWorktree(): Promise<void> {
1113
+ // a bare repository's working copy refuses its worktree: asked without touching it
1114
+ if (!("worktree" in this._workingCopy)) return;
1115
+ const worktree = this._workingCopy.worktree;
1116
+ if (!worktree || !this._workingCopy.config) return;
1117
+ const config = RemoteConfigStore.from(this._workingCopy);
1118
+ if (parseGitBool(config.value("core.sparseCheckout")) !== true) return;
1119
+ if (parseGitBool(config.value("sparse.expectFilesOutsideOfPatterns")) === true) return;
1120
+ await clearSkipWorktreeFromPresentFiles(this.staging, worktree);
1121
+ }
1122
+
1123
+ /**
1124
+ * The sparse checkout's patterns (`$GIT_DIR/info/sparse-checkout`, cone matching with
1125
+ * `core.sparseCheckoutCone`, case folded with `core.ignoreCase`) for git's
1126
+ * `path_in_sparse_checkout`, or undefined when `core.sparseCheckout` is off (every path
1127
+ * is in the checkout).
1128
+ */
1129
+ protected async sparseCheckoutPatterns(): Promise<SparseCheckoutPatterns | undefined> {
1130
+ return readSparseCheckoutPatterns(this._workingCopy);
1131
+ }
1132
+
1133
+ /**
1134
+ * Gives the staging git's racy-git smudging for its writes: an entry whose mtime second is
1135
+ * not older than the index file and whose content changed behind a matching stat is
1136
+ * written with size 0 (`ce_smudge_racily_clean_entry`), so a later same-size edit in that
1137
+ * second is never taken as clean.
1138
+ */
1139
+ private installRacyCheck(staging: Staging): void {
1140
+ const worktree = this._workingCopy.worktree;
1141
+ if (!worktree || typeof staging.setRacyCheck !== "function") return;
1142
+ const trust = worktreeModeTrust(this._workingCopy, worktree);
1143
+ staging.setRacyCheck(async (entry, indexTime) => {
1144
+ try {
1145
+ // git returns early when the basic stat already differs: changed, nothing to smudge
1146
+ const current = await worktree.getEntry(entry.path);
1147
+ if (!current || current.isDirectory || !basicStatMatches(entry, current, trust)) {
1148
+ return false;
1149
+ }
1150
+ return (await compareWithWorktree(worktree, entry, { trust, indexTime })).smudge === true;
1151
+ } catch {
1152
+ return false;
1153
+ }
1154
+ });
1155
+ }
1156
+
1157
+ private resolveStaging(): Staging {
220
1158
  // Try new architecture first (checkout.staging)
221
1159
  if (this._workingCopy.checkout?.staging) {
222
1160
  return this._workingCopy.checkout.staging as unknown as Staging;
@@ -237,6 +1175,18 @@ export abstract class GitCommand<T> {
237
1175
  return this._workingCopy.worktree;
238
1176
  }
239
1177
 
1178
+ /**
1179
+ * Runs `fn` as one worktree operation (`Worktree.batch`, which nests): the configuration,
1180
+ * `info/attributes` and the `.gitattributes` files are read once for every path the
1181
+ * command converts, filters or checks, instead of once per path (each attributes lookup
1182
+ * outside an operation opens one of its own). Without a worktree, `fn` runs as it is.
1183
+ * `options` go to the content filter's operation (`keepAttributes`).
1184
+ */
1185
+ protected inOneOperation<T>(fn: () => Promise<T>, options?: OperationOptions): Promise<T> {
1186
+ const worktree = "worktree" in this._workingCopy ? this._workingCopy.worktree : undefined;
1187
+ return worktree?.batch ? worktree.batch(fn, options) : fn();
1188
+ }
1189
+
240
1190
  /**
241
1191
  * Get the WorkingCopy.
242
1192
  */
@@ -251,22 +1201,40 @@ export abstract class GitCommand<T> {
251
1201
  abstract call(): Promise<T>;
252
1202
 
253
1203
  /**
254
- * Verify the command hasn't been called yet.
1204
+ * Verify the command hasn't been called yet, and that the configuration loads as git
1205
+ * loads it (see {@link checkConfigOnLoad}). Every `call()` starts here, before it reads or
1206
+ * writes anything, so a command git would refuse to start changes nothing.
255
1207
  * @throws Error if command was already executed
1208
+ * @throws InvalidConfigError if git would die loading the configuration
256
1209
  */
257
1210
  protected checkCallable(): void {
258
1211
  if (!this.callable) {
259
1212
  throw new Error(`Command ${this.constructor.name} has already been called`);
260
1213
  }
1214
+ this.checkConfigOnLoad();
261
1215
  }
262
1216
 
263
- /**
264
- * Mark command as no longer callable.
265
- */
1217
+ /** Mark command as no longer callable (or callable again). */
266
1218
  protected setCallable(value: boolean): void {
267
1219
  this.callable = value;
268
1220
  }
269
1221
 
1222
+ /**
1223
+ * What every git command dies on before it runs, `status` included: configuration git's
1224
+ * `git_default_config` refuses (an unknown `core.disambiguate`, see {@link configLoadError}).
1225
+ * Checked each time, so a setter run before the configuration changed does not excuse
1226
+ * the `call()` after it.
1227
+ *
1228
+ * @throws InvalidConfigError with git's `error:` and `fatal:` lines
1229
+ */
1230
+ protected checkConfigOnLoad(): void {
1231
+ const failure = configLoadError(this._workingCopy);
1232
+ if (failure) throw new InvalidConfigError(failure.key, failure.message);
1233
+ // prepare_repo_settings, which every command but `git config` runs before its work
1234
+ const indexVersion = indexVersionConfigError(this._workingCopy);
1235
+ if (indexVersion) throw indexVersion;
1236
+ }
1237
+
270
1238
  /**
271
1239
  * Resolve HEAD to its target commit.
272
1240
  *
@@ -295,118 +1263,238 @@ export abstract class GitCommand<T> {
295
1263
  }
296
1264
 
297
1265
  /**
298
- * Resolve a ref name to its ObjectId.
299
- *
300
- * @param refName Ref name, commit ID, or commit-ish
301
- * @returns ObjectId of the resolved ref
302
- * @throws RefNotFoundError if ref cannot be resolved
1266
+ * A resolver for git's revision syntax over this command's stores (see
1267
+ * {@link RevisionResolver}); its `warnings` hold what git would print.
303
1268
  */
304
- protected async resolveRef(refName: string): Promise<ObjectId> {
305
- // Handle relative refs like HEAD~1, HEAD^
306
- if (refName.includes("~") || refName.includes("^")) {
307
- return this.resolveRelativeRef(refName);
308
- }
1269
+ protected revisionResolver(): RevisionResolver {
1270
+ return new RevisionResolver({
1271
+ refs: this.refsStore,
1272
+ commits: this.walkCommits,
1273
+ trees: this.trees,
1274
+ blobs: this.blobs,
1275
+ tags: this.tagsStore,
1276
+ staging: () => this.staging,
1277
+ workingCopy: this._workingCopy,
1278
+ objects: this._workingCopy.history?.objects,
1279
+ abbreviate: (ids) => this.idAbbreviator().lengths(ids),
1280
+ ...this.worktreeSources(),
1281
+ });
1282
+ }
309
1283
 
310
- // Try as direct ref first
311
- const ref = await this.refsStore.resolve(refName);
312
- if (ref?.objectId) {
313
- // Peel tag objects to commits
314
- return this.peelToCommit(ref.objectId);
315
- }
1284
+ /**
1285
+ * The worktree as git's checks of revision-or-path arguments see it (`check_filename`),
1286
+ * from the current directory `prefix` below the top.
1287
+ */
1288
+ protected argumentFiles(prefix = ""): ArgumentFiles {
1289
+ const exists = this.worktreeSources().fileExists;
1290
+ return {
1291
+ inWorktree: exists !== undefined,
1292
+ prefix,
1293
+ exists: exists ?? (async () => false),
1294
+ };
1295
+ }
316
1296
 
317
- // Try as branch name
318
- const branchRef = await this.refsStore.resolve(`refs/heads/${refName}`);
319
- if (branchRef?.objectId) {
320
- return branchRef.objectId;
1297
+ /** What a resolver checks in the worktree (git's `lstat` of an argument). */
1298
+ protected worktreeSources(): {
1299
+ fileExists?: (path: string) => Promise<boolean>;
1300
+ worktreeHostPath?: string;
1301
+ } {
1302
+ let worktree: Worktree | undefined;
1303
+ try {
1304
+ worktree = this._workingCopy.worktree;
1305
+ } catch {
1306
+ // a bare repository's admin copy refuses its worktree (no work tree)
1307
+ return {};
321
1308
  }
1309
+ if (!worktree) return {};
1310
+ const host = (worktree as { hostPath?: string }).hostPath;
1311
+ const wt = worktree;
1312
+ const lookup: WorktreeLookup = {
1313
+ kind: async (path) => {
1314
+ const entry = await wt.getEntry(path).catch(() => undefined);
1315
+ if (!entry) return undefined;
1316
+ if ((entry.mode & 0o170000) === 0o120000) return "symlink";
1317
+ return entry.isDirectory ? "directory" : "file";
1318
+ },
1319
+ readlink: async (path) => {
1320
+ try {
1321
+ const chunks: Uint8Array[] = [];
1322
+ for await (const chunk of wt.readContent(path)) chunks.push(chunk);
1323
+ return new TextDecoder().decode(concatBytes(chunks));
1324
+ } catch {
1325
+ return undefined;
1326
+ }
1327
+ },
1328
+ ...(host !== undefined ? { hostPath: host } : {}),
1329
+ };
1330
+ return {
1331
+ // git's lstat of the path as written, from the top (links among its parents followed)
1332
+ fileExists: async (path) => {
1333
+ try {
1334
+ return await lstatExists(lookup, path);
1335
+ } catch {
1336
+ return false;
1337
+ }
1338
+ },
1339
+ ...(host !== undefined ? { worktreeHostPath: host } : {}),
1340
+ };
1341
+ }
322
1342
 
323
- // Try as tag name
324
- const tagRef = await this.refsStore.resolve(`refs/tags/${refName}`);
325
- if (tagRef?.objectId) {
326
- // Peel tag objects to commits
327
- return this.peelToCommit(tagRef.objectId);
328
- }
1343
+ private abbreviator?: IdAbbreviator;
329
1344
 
330
- // Try as direct commit ID
331
- if (await this.commits.has(refName)) {
332
- return refName;
333
- }
1345
+ /**
1346
+ * This command's id abbreviator: the objects are counted once for git's automatic length,
1347
+ * however many ids the command prints (see {@link createIdAbbreviator}).
1348
+ */
1349
+ protected idAbbreviator(): IdAbbreviator {
1350
+ this.abbreviator ??= createIdAbbreviator(this._workingCopy, {
1351
+ cacheListings: this.writesNoObjects(),
1352
+ });
1353
+ return this.abbreviator;
1354
+ }
334
1355
 
335
- throw new RefNotFoundError(refName);
1356
+ /**
1357
+ * Whether this command stores no objects while it abbreviates ids: its abbreviator then
1358
+ * lists each loose fan-out directory once (see `IdAbbreviatorOptions.cacheListings`).
1359
+ */
1360
+ protected writesNoObjects(): boolean {
1361
+ return false;
336
1362
  }
337
1363
 
338
1364
  /**
339
- * Resolve a relative ref like HEAD~1 or HEAD^2.
1365
+ * Read objects through the replace refs and grafts `source` reads, and abbreviate ids with
1366
+ * its object count: git reads both once per process, so a command run for each commit of
1367
+ * another (`git log -p` runs a diff per commit) reads them once.
340
1368
  */
341
- private async resolveRelativeRef(ref: string): Promise<ObjectId> {
342
- // Parse the ref
343
- const match = ref.match(/^([^~^]+)((?:[~^]\d*)+)$/);
344
- if (!match) {
345
- throw new RefNotFoundError(ref);
346
- }
1369
+ shareReadsOf(source: GitCommand<unknown>): this {
1370
+ this.replacementsLoad = source.loadedReplacements();
1371
+ this.abbreviator = source.idAbbreviator();
1372
+ source.sharedTrees ??= new OrderedMap();
1373
+ this.sharedTrees = source.sharedTrees;
1374
+ source.sharedBlobs ??= { recent: new OrderedMap(), bytes: 0 };
1375
+ this.sharedBlobs = source.sharedBlobs;
1376
+ return this;
1377
+ }
347
1378
 
348
- const baseRef = match[1];
349
- const modifiers = match[2];
1379
+ /** Trees read lately by the commands sharing reads ({@link shareReadsOf}), newest last */
1380
+ private sharedTrees?: OrderedMap<ObjectId, TreeEntry[]>;
350
1381
 
351
- let commitId = await this.resolveRef(baseRef);
1382
+ /**
1383
+ * A tree's entries through the replacements (`trees.loadTree`), kept a while for the
1384
+ * commands that share reads: one commit's tree is the next one's parent tree.
1385
+ */
1386
+ protected async treeEntries(id: ObjectId): Promise<readonly TreeEntry[]> {
1387
+ const trees = this.trees;
1388
+ // a store that caches decoded trees hands them out as they are (no copy per read)
1389
+ if (trees.entries) {
1390
+ // a missing tree reads as empty, as `loadTree` yields nothing for it
1391
+ return (await trees.entries(id)) ?? [];
1392
+ }
1393
+ const cache = this.sharedTrees;
1394
+ const known = cache?.get(id);
1395
+ if (known) {
1396
+ cache?.delete(id);
1397
+ cache?.set(id, known);
1398
+ return known;
1399
+ }
1400
+ const entries: TreeEntry[] = [];
1401
+ for await (const e of this.trees.loadTree(id)) entries.push(e);
1402
+ if (cache) {
1403
+ cache.set(id, entries);
1404
+ while (cache.size > SHARED_TREES) cache.delete(cache.oldestKey() as ObjectId);
1405
+ }
1406
+ return entries;
1407
+ }
352
1408
 
353
- // Process each modifier
354
- const modifierMatch = modifiers.matchAll(/([~^])(\d*)/g);
355
- for (const m of modifierMatch) {
356
- const type = m[1];
357
- const count = m[2] ? parseInt(m[2], 10) : 1;
1409
+ /** `id` abbreviated as git prints it, through {@link idAbbreviator}. */
1410
+ protected abbreviateObjectId(id: ObjectId): Promise<string> {
1411
+ return this.idAbbreviator().abbreviate(id);
1412
+ }
358
1413
 
359
- if (type === "~") {
360
- // ~N means follow first parent N times
361
- for (let i = 0; i < count; i++) {
362
- const commit = await this.commits.load(commitId);
363
- if (!commit || commit.parents.length === 0) {
364
- throw new RefNotFoundError(ref, `Cannot resolve ${ref}: no parent`);
365
- }
366
- commitId = commit.parents[0];
367
- }
368
- } else if (type === "^") {
369
- // ^N means follow Nth parent
370
- const commit = await this.commits.load(commitId);
371
- if (!commit) {
372
- throw new RefNotFoundError(ref, `Cannot resolve ${ref}: commit not found`);
373
- }
374
- const parentIndex = count > 0 ? count - 1 : 0;
375
- if (commit.parents.length <= parentIndex) {
376
- throw new RefNotFoundError(ref, `Cannot resolve ${ref}: no parent ${count}`);
377
- }
378
- commitId = commit.parents[parentIndex];
379
- }
380
- }
1414
+ /**
1415
+ * The object a revision names, as git's `get_oid` finds it: refs by git's rules, object
1416
+ * ids, `@`, `@{-N}`, `@{u}`, `@{push}`, `<ref>@{<n>}`, `<ref>@{<date>}`, `~`, `^`,
1417
+ * `^{<type>}`, `^{/<regex>}`, `:/<regex>`, `<rev>:<path>`, `:<n>:<path>`. An annotated
1418
+ * tag is returned as the tag object.
1419
+ *
1420
+ * @throws RefNotFoundError if it names nothing
1421
+ * @throws RevisionError where git dies (no upstream, reflog too short)
1422
+ */
1423
+ protected async resolveRevision(name: string, options?: ResolveOptions): Promise<ObjectId> {
1424
+ const id = await this.revisionResolver().resolve(name, options);
1425
+ if (id === undefined) throw new RefNotFoundError(name);
1426
+ return id;
1427
+ }
381
1428
 
382
- return commitId;
1429
+ /**
1430
+ * Resolve a revision (see {@link resolveRevision}) to a commit, as git's
1431
+ * `lookup_commit_reference` does: tags are peeled, and a revision that ends at a tree, a
1432
+ * blob or a missing object is refused with git's lines, `error: object <id> is a tree,
1433
+ * not a commit` (not for a missing object) and `fatal` (by default reset's `fatal: Could
1434
+ * not parse object '<name>'.`).
1435
+ *
1436
+ * @param name Ref name, commit ID, or any revision expression
1437
+ * @param fatal The command's last line for a revision that names no commit
1438
+ * @returns ObjectId of the resolved commit
1439
+ * @throws RefNotFoundError if it cannot be resolved
1440
+ * @throws NotACommitError if it names something else
1441
+ * @throws RevisionError where git dies (no upstream, reflog too short)
1442
+ */
1443
+ protected async resolveRef(
1444
+ name: string,
1445
+ fatal: (name: string) => string = (n) => `fatal: Could not parse object '${n}'.`,
1446
+ ): Promise<ObjectId> {
1447
+ // a commit is wanted: an abbreviation is read as a committish (repo_get_oid_committish)
1448
+ const id = await this.resolveRevision(name, { hint: "committish" });
1449
+ const peeled = await this.revisionResolver().peelTags(id);
1450
+ if (peeled.type === "commit") return peeled.id;
1451
+ const lines = peeled.type
1452
+ ? [`error: object ${peeled.id} is a ${peeled.type}, not a commit`, fatal(name)]
1453
+ : [fatal(name)];
1454
+ throw new NotACommitError(name, peeled.id, peeled.type, lines.join("\n"));
383
1455
  }
384
1456
 
385
1457
  /**
386
- * Peel an object ID to a commit (follows tag objects).
1458
+ * git's `setup_branch_path` (`INTERPRET_BRANCH_LOCAL`): the local branch a name's branch
1459
+ * syntax stands for (`loc@{u}` is `main` when loc tracks main with `remote = .`), else
1460
+ * the name as given.
1461
+ *
1462
+ * @throws RevisionError where git dies reading it (`@{u}` without an upstream)
387
1463
  */
388
- private async peelToCommit(objectId: ObjectId): Promise<ObjectId> {
389
- // If it's already a commit, return it
390
- if (await this.commits.has(objectId)) {
391
- return objectId;
392
- }
1464
+ protected async interpretLocalBranch(name: string): Promise<string> {
1465
+ if (!name.includes("@")) return name;
1466
+ const value = await this.revisionResolver().interpretBranchName(name);
1467
+ return value?.startsWith("refs/heads/") ? value.slice("refs/heads/".length) : name;
1468
+ }
393
1469
 
394
- // Try to load as tag and get target
395
- const tags = this.tagsStore;
396
- if (tags) {
397
- try {
398
- const tag = await tags.load(objectId);
399
- if (tag) {
400
- // Recursively peel
401
- return this.peelToCommit(tag.object);
402
- }
403
- } catch {
404
- // Not a tag
405
- }
1470
+ /**
1471
+ * git's `interpret_nth_prior_checkout`: the name a leading `@{-N}` stands for, the
1472
+ * branch (or detached commit) the Nth most recent `checkout: moving from <x> to <y>`
1473
+ * line of HEAD's reflog left, followed by the rest of `name` (`@{-1}~2` is `main~2`).
1474
+ * A name without it, or an `@{-N}` the reflog cannot answer, is returned as given.
1475
+ *
1476
+ * @example
1477
+ * ```typescript
1478
+ * await this.expandPriorCheckout("@{-1}"); // "feat" after `checkout feat` + `checkout main`
1479
+ * ```
1480
+ */
1481
+ protected async expandPriorCheckout(name: string): Promise<string> {
1482
+ const match = /^@\{-(\d+)\}/.exec(name);
1483
+ if (!match) return name;
1484
+ const nth = Number.parseInt(match[1] ?? "0", 10);
1485
+ if (!(nth > 0)) return name;
1486
+ const log = await this.refsStore.getReflog?.("HEAD");
1487
+ if (!log) return name;
1488
+ let remaining = nth;
1489
+ for (const entry of await log.getReverseEntries()) {
1490
+ const prefix = "checkout: moving from ";
1491
+ if (!entry.comment.startsWith(prefix)) continue;
1492
+ const rest = entry.comment.slice(prefix.length);
1493
+ const to = rest.indexOf(" to ");
1494
+ if (to < 0) continue;
1495
+ if (--remaining === 0) return rest.slice(0, to) + name.slice(match[0].length);
406
1496
  }
407
-
408
- // Return as-is (might be a tree or blob in some contexts)
409
- return objectId;
1497
+ return name;
410
1498
  }
411
1499
 
412
1500
  /**
@@ -419,3 +1507,15 @@ export abstract class GitCommand<T> {
419
1507
  return this.refsStore.get(refName);
420
1508
  }
421
1509
  }
1510
+
1511
+ /** `chunks` as one array. */
1512
+ function concatBytes(chunks: Uint8Array[]): Uint8Array {
1513
+ if (chunks.length === 1) return chunks[0];
1514
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
1515
+ let offset = 0;
1516
+ for (const chunk of chunks) {
1517
+ out.set(chunk, offset);
1518
+ offset += chunk.length;
1519
+ }
1520
+ return out;
1521
+ }