@statewalker/vcs-commands 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (561) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +299 -34
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +67 -4
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +179 -7
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +93 -0
  73. package/dist/commands/core-config.d.ts.map +1 -0
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +244 -23
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +55 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +146 -6
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +69 -13
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +214 -26
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +10 -2
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-list-command.d.ts +2 -4
  237. package/dist/commands/stash-list-command.d.ts.map +1 -1
  238. package/dist/commands/stash-working-tree.d.ts +95 -0
  239. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  240. package/dist/commands/status-command.d.ts +320 -28
  241. package/dist/commands/status-command.d.ts.map +1 -1
  242. package/dist/commands/status-format.d.ts +155 -0
  243. package/dist/commands/status-format.d.ts.map +1 -0
  244. package/dist/commands/status-header.d.ts +64 -0
  245. package/dist/commands/status-header.d.ts.map +1 -0
  246. package/dist/commands/strerror.d.ts +7 -0
  247. package/dist/commands/strerror.d.ts.map +1 -0
  248. package/dist/commands/submodule-config.d.ts +38 -0
  249. package/dist/commands/submodule-config.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary-command.d.ts +80 -0
  251. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  252. package/dist/commands/submodule-summary.d.ts +150 -0
  253. package/dist/commands/submodule-summary.d.ts.map +1 -0
  254. package/dist/commands/switch-command.d.ts +132 -0
  255. package/dist/commands/switch-command.d.ts.map +1 -0
  256. package/dist/commands/tag-command.d.ts +23 -2
  257. package/dist/commands/tag-command.d.ts.map +1 -1
  258. package/dist/commands/tracking-info.d.ts +64 -0
  259. package/dist/commands/tracking-info.d.ts.map +1 -0
  260. package/dist/commands/trailers.d.ts +73 -0
  261. package/dist/commands/trailers.d.ts.map +1 -0
  262. package/dist/commands/tree-restore.d.ts +137 -6
  263. package/dist/commands/tree-restore.d.ts.map +1 -1
  264. package/dist/commands/untracked-cache-support.d.ts +53 -0
  265. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  266. package/dist/commands/worktree-add-command.d.ts +108 -0
  267. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-list-command.d.ts +69 -0
  269. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-lock-command.d.ts +44 -0
  271. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-overwrite-checks.d.ts +204 -0
  273. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  274. package/dist/commands/worktree-prune-command.d.ts +48 -0
  275. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-remove-command.d.ts +59 -0
  277. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-repair-command.d.ts +35 -0
  279. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-support.d.ts +64 -0
  281. package/dist/commands/worktree-support.d.ts.map +1 -0
  282. package/dist/commands-DnmlfwGV.js +61620 -0
  283. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  284. package/dist/core-commands/index.d.ts +0 -3
  285. package/dist/core-commands/index.d.ts.map +1 -1
  286. package/dist/errors/add-errors.d.ts +55 -0
  287. package/dist/errors/add-errors.d.ts.map +1 -1
  288. package/dist/errors/checkout-errors.d.ts +29 -0
  289. package/dist/errors/checkout-errors.d.ts.map +1 -1
  290. package/dist/errors/command-errors.d.ts +77 -0
  291. package/dist/errors/command-errors.d.ts.map +1 -1
  292. package/dist/errors/commit-errors.d.ts +9 -0
  293. package/dist/errors/commit-errors.d.ts.map +1 -1
  294. package/dist/errors/git-api-error.d.ts +59 -2
  295. package/dist/errors/git-api-error.d.ts.map +1 -1
  296. package/dist/errors/index.d.ts +1 -0
  297. package/dist/errors/index.d.ts.map +1 -1
  298. package/dist/errors/index.js +371 -19
  299. package/dist/errors/rebase-errors.d.ts +9 -0
  300. package/dist/errors/rebase-errors.d.ts.map +1 -1
  301. package/dist/errors/ref-errors.d.ts +32 -0
  302. package/dist/errors/ref-errors.d.ts.map +1 -1
  303. package/dist/errors/transport-errors.d.ts +12 -2
  304. package/dist/errors/transport-errors.d.ts.map +1 -1
  305. package/dist/errors/worktree-errors.d.ts +35 -0
  306. package/dist/errors/worktree-errors.d.ts.map +1 -0
  307. package/dist/git-command-DxvwPrPB.js +7612 -0
  308. package/dist/git-command.d.ts +422 -32
  309. package/dist/git-command.d.ts.map +1 -1
  310. package/dist/git.d.ts +326 -5
  311. package/dist/git.d.ts.map +1 -1
  312. package/dist/index.d.ts +1 -1
  313. package/dist/index.d.ts.map +1 -1
  314. package/dist/index.js +5 -5
  315. package/dist/remote-config/index.d.ts +1 -0
  316. package/dist/remote-config/index.d.ts.map +1 -1
  317. package/dist/remote-config/remote-config-store.d.ts +123 -3
  318. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  319. package/dist/remote-config/remote-refs.d.ts +41 -0
  320. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  321. package/dist/rename/detect-renames.d.ts +148 -0
  322. package/dist/rename/detect-renames.d.ts.map +1 -0
  323. package/dist/rename/git-similarity.d.ts +44 -0
  324. package/dist/rename/git-similarity.d.ts.map +1 -0
  325. package/dist/rename/index.d.ts +2 -0
  326. package/dist/rename/index.d.ts.map +1 -1
  327. package/dist/results/binary-patch.d.ts +11 -0
  328. package/dist/results/binary-patch.d.ts.map +1 -0
  329. package/dist/results/blame-format.d.ts +55 -0
  330. package/dist/results/blame-format.d.ts.map +1 -0
  331. package/dist/results/cherry-pick-result.d.ts +10 -0
  332. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  333. package/dist/results/clone-result.d.ts +16 -0
  334. package/dist/results/clone-result.d.ts.map +1 -1
  335. package/dist/results/combined-diff.d.ts +77 -0
  336. package/dist/results/combined-diff.d.ts.map +1 -0
  337. package/dist/results/diff-entry.d.ts +32 -0
  338. package/dist/results/diff-entry.d.ts.map +1 -1
  339. package/dist/results/diff-formatter.d.ts +34 -60
  340. package/dist/results/diff-formatter.d.ts.map +1 -1
  341. package/dist/results/diff-order.d.ts +25 -0
  342. package/dist/results/diff-order.d.ts.map +1 -0
  343. package/dist/results/diff-output.d.ts +249 -0
  344. package/dist/results/diff-output.d.ts.map +1 -0
  345. package/dist/results/fetch-result.d.ts +24 -1
  346. package/dist/results/fetch-result.d.ts.map +1 -1
  347. package/dist/results/index.d.ts +5 -0
  348. package/dist/results/index.d.ts.map +1 -1
  349. package/dist/results/index.js +2 -252
  350. package/dist/results/merge-result.d.ts +15 -1
  351. package/dist/results/merge-result.d.ts.map +1 -1
  352. package/dist/results/pull-result.d.ts +12 -3
  353. package/dist/results/pull-result.d.ts.map +1 -1
  354. package/dist/results/push-result.d.ts +42 -0
  355. package/dist/results/push-result.d.ts.map +1 -1
  356. package/dist/results/quote-path.d.ts +27 -0
  357. package/dist/results/quote-path.d.ts.map +1 -0
  358. package/dist/results/rebase-result.d.ts +28 -1
  359. package/dist/results/rebase-result.d.ts.map +1 -1
  360. package/dist/results/revert-result.d.ts +10 -0
  361. package/dist/results/revert-result.d.ts.map +1 -1
  362. package/dist/results/stash-result.d.ts +5 -0
  363. package/dist/results/stash-result.d.ts.map +1 -1
  364. package/dist/results/status-result.d.ts +143 -18
  365. package/dist/results/status-result.d.ts.map +1 -1
  366. package/dist/results-BZGa2Z3I.js +2934 -0
  367. package/dist/transport-command.d.ts +56 -1
  368. package/dist/transport-command.d.ts.map +1 -1
  369. package/package.json +15 -10
  370. package/src/commands/add-command.ts +1291 -224
  371. package/src/commands/add-patch/add-interactive.ts +941 -0
  372. package/src/commands/add-patch/add-patch.ts +1169 -0
  373. package/src/commands/add-patch/index.ts +5 -0
  374. package/src/commands/add-patch/patch-backend.ts +239 -0
  375. package/src/commands/add-patch/patch-modes.ts +249 -0
  376. package/src/commands/add-patch/patch-session.ts +159 -0
  377. package/src/commands/am/am-command.ts +1111 -0
  378. package/src/commands/am/index.ts +2 -0
  379. package/src/commands/am/mailinfo.ts +1015 -0
  380. package/src/commands/am/patch-format.ts +121 -0
  381. package/src/commands/apply/apply-command.ts +832 -0
  382. package/src/commands/apply/apply-engine.ts +1603 -0
  383. package/src/commands/apply/apply-parse.ts +1209 -0
  384. package/src/commands/apply/apply-types.ts +112 -0
  385. package/src/commands/apply/index.ts +5 -0
  386. package/src/commands/apply/latin1.ts +171 -0
  387. package/src/commands/apply/whitespace.ts +260 -0
  388. package/src/commands/attributes-source.ts +96 -0
  389. package/src/commands/backfill-command.ts +694 -0
  390. package/src/commands/bisect/bisect-checkout.ts +217 -0
  391. package/src/commands/bisect/bisect-command.ts +788 -0
  392. package/src/commands/bisect/bisect-engine.ts +1079 -0
  393. package/src/commands/bisect/bisect-graph.ts +595 -0
  394. package/src/commands/bisect/bisect-quote.ts +92 -0
  395. package/src/commands/bisect/index.ts +4 -0
  396. package/src/commands/blame-command.ts +711 -986
  397. package/src/commands/branch-command.ts +354 -32
  398. package/src/commands/branch-tracking.ts +331 -0
  399. package/src/commands/checkout-command.ts +1426 -297
  400. package/src/commands/checkout-paths.ts +784 -0
  401. package/src/commands/cherry-pick-command.ts +156 -396
  402. package/src/commands/clean-command.ts +532 -85
  403. package/src/commands/clone-command.ts +826 -55
  404. package/src/commands/commit-command.ts +1781 -166
  405. package/src/commands/core-config.ts +196 -0
  406. package/src/commands/date-format.ts +668 -0
  407. package/src/commands/describe-command.ts +2 -0
  408. package/src/commands/diff-command.ts +1898 -110
  409. package/src/commands/diff-textconv.ts +50 -0
  410. package/src/commands/fetch-command.ts +1038 -79
  411. package/src/commands/format-patch-command.ts +969 -0
  412. package/src/commands/fsck/fetch-fsck.ts +229 -0
  413. package/src/commands/fsck/fsck-command.ts +3347 -0
  414. package/src/commands/fsck/fsck-loose.ts +287 -0
  415. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  416. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  417. package/src/commands/fsck/fsck-object-table.ts +363 -0
  418. package/src/commands/fsck/fsck-pack.ts +604 -0
  419. package/src/commands/fsck/index.ts +5 -0
  420. package/src/commands/fsck/verify-pack-command.ts +249 -0
  421. package/src/commands/gc-command.ts +147 -1
  422. package/src/commands/git-date.ts +895 -0
  423. package/src/commands/git-describe.ts +316 -0
  424. package/src/commands/git-hooks.ts +1472 -0
  425. package/src/commands/git-ident.ts +344 -0
  426. package/src/commands/hook-command.ts +247 -0
  427. package/src/commands/index-adder.ts +706 -0
  428. package/src/commands/index-host.ts +291 -0
  429. package/src/commands/index.ts +83 -0
  430. package/src/commands/init-command.ts +60 -11
  431. package/src/commands/local-clone.ts +183 -0
  432. package/src/commands/local-transport.ts +762 -0
  433. package/src/commands/log-command.ts +1915 -170
  434. package/src/commands/log-graph.ts +671 -0
  435. package/src/commands/log-output.ts +1359 -0
  436. package/src/commands/ls-remote-command.ts +101 -58
  437. package/src/commands/mailmap.ts +129 -0
  438. package/src/commands/merge-bases.ts +296 -0
  439. package/src/commands/merge-command.ts +1386 -491
  440. package/src/commands/merge-config.ts +25 -0
  441. package/src/commands/merge-drivers.ts +306 -0
  442. package/src/commands/merge-support.ts +1198 -0
  443. package/src/commands/message-cleanup.ts +275 -0
  444. package/src/commands/mv-command.ts +976 -0
  445. package/src/commands/notes-command.ts +890 -0
  446. package/src/commands/notes-commands.ts +87 -0
  447. package/src/commands/notes-merge-command.ts +768 -0
  448. package/src/commands/notes-support.ts +402 -0
  449. package/src/commands/notes-tree.ts +602 -0
  450. package/src/commands/object-id-input.ts +27 -0
  451. package/src/commands/octopus-merge.ts +377 -0
  452. package/src/commands/ort-merge.ts +1660 -0
  453. package/src/commands/ort-recursive.ts +160 -0
  454. package/src/commands/pack-refs-command.ts +39 -22
  455. package/src/commands/patch-id.ts +196 -0
  456. package/src/commands/pathspec-attributes.ts +162 -0
  457. package/src/commands/pathspec.ts +1199 -0
  458. package/src/commands/post-index-change.ts +62 -0
  459. package/src/commands/pretty-format.ts +1431 -0
  460. package/src/commands/promisor-remote.ts +298 -0
  461. package/src/commands/pull-command.ts +207 -22
  462. package/src/commands/push-command.ts +236 -23
  463. package/src/commands/read-tree-command.ts +857 -0
  464. package/src/commands/rebase-command.ts +3808 -371
  465. package/src/commands/rebase-todo.ts +584 -0
  466. package/src/commands/ref-decoration-filter.ts +118 -0
  467. package/src/commands/reflog-messages.ts +177 -0
  468. package/src/commands/remote-command.ts +500 -19
  469. package/src/commands/remote-transport.ts +383 -0
  470. package/src/commands/reset-command.ts +828 -91
  471. package/src/commands/restore-command.ts +350 -0
  472. package/src/commands/rev-list-command.ts +167 -0
  473. package/src/commands/rev-parse-command.ts +277 -0
  474. package/src/commands/revert-command.ts +152 -399
  475. package/src/commands/revision-filenames.ts +254 -0
  476. package/src/commands/revision-range.ts +222 -0
  477. package/src/commands/revision-resolver.ts +1379 -0
  478. package/src/commands/rm-command.ts +613 -67
  479. package/src/commands/sequencer-pick.ts +869 -0
  480. package/src/commands/sequencer-support.ts +869 -0
  481. package/src/commands/serve-repository.ts +125 -0
  482. package/src/commands/sparse-checkout-command.ts +1389 -0
  483. package/src/commands/sparse-checkout-support.ts +793 -0
  484. package/src/commands/stash-apply-command.ts +692 -124
  485. package/src/commands/stash-create-command.ts +752 -89
  486. package/src/commands/stash-drop-command.ts +67 -6
  487. package/src/commands/stash-list-command.ts +10 -4
  488. package/src/commands/stash-working-tree.ts +387 -0
  489. package/src/commands/status-command.ts +1426 -97
  490. package/src/commands/status-format.ts +775 -0
  491. package/src/commands/status-header.ts +330 -0
  492. package/src/commands/strerror.ts +29 -0
  493. package/src/commands/submodule-config.ts +94 -0
  494. package/src/commands/submodule-summary-command.ts +334 -0
  495. package/src/commands/submodule-summary.ts +446 -0
  496. package/src/commands/switch-command.ts +402 -0
  497. package/src/commands/tag-command.ts +129 -41
  498. package/src/commands/tracking-info.ts +201 -0
  499. package/src/commands/trailers.ts +417 -0
  500. package/src/commands/tree-restore.ts +344 -15
  501. package/src/commands/untracked-cache-support.ts +194 -0
  502. package/src/commands/worktree-add-command.ts +458 -0
  503. package/src/commands/worktree-list-command.ts +208 -0
  504. package/src/commands/worktree-lock-command.ts +96 -0
  505. package/src/commands/worktree-overwrite-checks.ts +641 -0
  506. package/src/commands/worktree-prune-command.ts +99 -0
  507. package/src/commands/worktree-remove-command.ts +186 -0
  508. package/src/commands/worktree-repair-command.ts +59 -0
  509. package/src/commands/worktree-support.ts +214 -0
  510. package/src/core-commands/add.command.impl.ts +9 -5
  511. package/src/core-commands/index.ts +0 -8
  512. package/src/errors/add-errors.ts +45 -0
  513. package/src/errors/checkout-errors.ts +46 -2
  514. package/src/errors/command-errors.ts +101 -1
  515. package/src/errors/commit-errors.ts +18 -2
  516. package/src/errors/git-api-error.ts +82 -2
  517. package/src/errors/index.ts +1 -0
  518. package/src/errors/merge-errors.ts +2 -2
  519. package/src/errors/rebase-errors.ts +12 -0
  520. package/src/errors/ref-errors.ts +56 -2
  521. package/src/errors/remote-errors.ts +2 -2
  522. package/src/errors/stash-errors.ts +1 -1
  523. package/src/errors/transport-errors.ts +20 -4
  524. package/src/errors/worktree-errors.ts +49 -0
  525. package/src/git-command.ts +1218 -118
  526. package/src/git.ts +552 -11
  527. package/src/index.ts +1 -1
  528. package/src/remote-config/index.ts +1 -0
  529. package/src/remote-config/remote-config-store.ts +326 -16
  530. package/src/remote-config/remote-refs.ts +119 -0
  531. package/src/rename/detect-renames.ts +711 -0
  532. package/src/rename/git-similarity.ts +116 -0
  533. package/src/rename/index.ts +2 -0
  534. package/src/results/binary-patch.ts +401 -0
  535. package/src/results/blame-format.ts +239 -0
  536. package/src/results/cherry-pick-result.ts +10 -0
  537. package/src/results/clone-result.ts +18 -0
  538. package/src/results/combined-diff.ts +585 -0
  539. package/src/results/diff-entry.ts +35 -0
  540. package/src/results/diff-formatter.ts +152 -288
  541. package/src/results/diff-order.ts +64 -0
  542. package/src/results/diff-output.ts +1051 -0
  543. package/src/results/fetch-result.ts +24 -1
  544. package/src/results/index.ts +5 -0
  545. package/src/results/merge-result.ts +15 -1
  546. package/src/results/pull-result.ts +12 -3
  547. package/src/results/push-result.ts +43 -0
  548. package/src/results/quote-path.ts +103 -0
  549. package/src/results/rebase-result.ts +37 -0
  550. package/src/results/revert-result.ts +10 -0
  551. package/src/results/stash-result.ts +6 -0
  552. package/src/results/status-result.ts +288 -27
  553. package/src/transport-command.ts +139 -2
  554. package/dist/commands-BpeXZTC3.js +0 -10278
  555. package/dist/core-commands/checkout.command.d.ts +0 -103
  556. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  557. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  558. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  559. package/dist/status-result-BapZoQaR.js +0 -411
  560. package/src/core-commands/checkout.command.impl.ts +0 -564
  561. package/src/core-commands/checkout.command.ts +0 -125
@@ -0,0 +1,1472 @@
1
+ /**
2
+ * git's hooks (githooks(5), hook.c): finding a hook as `find_hook` does and running it
3
+ * through the host's {@link HookRunner}.
4
+ *
5
+ * ```typescript
6
+ * const hooks = new HookSession(workingCopy);
7
+ * const result = await hooks.run("pre-commit", { env: { GIT_INDEX_FILE: ".git/index" } });
8
+ * if (result && result.exitCode !== 0) throw new Error("pre-commit refused the commit");
9
+ * hooks.output; // what the hook wrote (git relays it on stderr), and any hints
10
+ * ```
11
+ *
12
+ * A hook is a file named after it in `core.hooksPath` (relative to the worktree top, the git
13
+ * directory when bare; `~/` the home directory) or else in `$GIT_DIR/hooks` (the common git
14
+ * directory of a linked worktree). It counts only when executable: a file that is not gets
15
+ * git's `advice.ignoredHook` hint, once per hook name. Without a runner on the host
16
+ * environment (`GitHostEnvironment.hookRunner`), nothing is looked up and no hook runs.
17
+ *
18
+ * Every hook runs in the worktree top (the git directory when bare) with `GIT_PREFIX` empty,
19
+ * as git's setup exports it, plus the variables of the call; its stdout goes to its stderr
20
+ * unless the call asks otherwise (`RUN_HOOKS_OPT_INIT`'s `stdout_to_stderr`).
21
+ */
22
+
23
+ import type { RefTransactionHook } from "@statewalker/vcs-core";
24
+ import { parseGitBool } from "@statewalker/vcs-utils";
25
+ import type { FilesApi } from "@statewalker/vcs-utils/files";
26
+ import {
27
+ expandUserPath,
28
+ type GitHostEnvironment,
29
+ type HookInvocation,
30
+ type HookOutcome,
31
+ type HookProcess,
32
+ type HookRunner,
33
+ type WorkingCopy,
34
+ } from "@statewalker/vcs-working-tree";
35
+ import { GitApiError, HookFailedError } from "../errors/index.js";
36
+ import { RemoteConfigStore } from "../remote-config/index.js";
37
+ import { hostEnvironmentOf } from "./git-ident.js";
38
+ import { configBool, configValue } from "./merge-config.js";
39
+
40
+ /** What a hook is given beyond its name. */
41
+ export interface HookCallOptions {
42
+ /** Arguments after the script */
43
+ args?: string[];
44
+ /** What the hook reads on stdin (text is written as UTF-8) */
45
+ stdin?: string | Uint8Array;
46
+ /** Variables set for the hook (GIT_INDEX_FILE, GIT_EDITOR, ...) */
47
+ env?: Record<string, string>;
48
+ /** Keep the hook's stdout apart (default false: sent to stderr, as git's hooks) */
49
+ keepStdout?: boolean;
50
+ /**
51
+ * The directory the hook runs in, a path of the repository's FilesApi, in place of the
52
+ * worktree top (git's `opt.dir`: `worktree add` runs post-checkout in the new worktree);
53
+ * the hook is then named by its absolute path, as git names it there
54
+ */
55
+ dir?: string;
56
+ /**
57
+ * Whether git's setup exported `GIT_PREFIX` (default true: the commands that run in a
58
+ * repository; `clone` and the receive side do not)
59
+ */
60
+ prefix?: boolean;
61
+ /**
62
+ * Variables the hook runs without, the host's own and the session's included (git's
63
+ * `opt.env` entries without a value: `worktree add` unsets `GIT_DIR` and `GIT_WORK_TREE`)
64
+ */
65
+ unsetEnv?: string[];
66
+ }
67
+
68
+ /** What running a hook gave: its exit code and output as text. */
69
+ export interface HookResult {
70
+ exitCode: number;
71
+ stdout: string;
72
+ stderr: string;
73
+ }
74
+
75
+ /**
76
+ * A hook started by {@link HookSession.start}: its stdin and stdout, and its exit. The shape
77
+ * of the transport's `ProcReceiveProcess`.
78
+ */
79
+ export interface StartedHook {
80
+ /** false: it takes its whole stdin before it runs (the runner has no `start`) */
81
+ readonly interactive: boolean;
82
+ write(data: Uint8Array): Promise<void>;
83
+ closeStdin(): Promise<void>;
84
+ readonly stdout: AsyncIterable<Uint8Array>;
85
+ closeStdout(): void;
86
+ /** Waits for it to exit (its stderr kept in the session's output): its exit code */
87
+ wait(): Promise<number>;
88
+ /** Stops it, where the runner can (`HookProcess.kill`) */
89
+ kill?(): void;
90
+ }
91
+
92
+ /** A hook found: where it is, for the runner and for git's messages. */
93
+ export interface FoundHook {
94
+ /** The path git names it by, relative to the hook's directory or absolute */
95
+ path: string;
96
+ /** Its path in the repository's FilesApi, when it lies there */
97
+ filesPath?: string;
98
+ /** Its absolute path on the host, when known */
99
+ hostPath?: string;
100
+ }
101
+
102
+ const decoder = new TextDecoder();
103
+ const encoder = new TextEncoder();
104
+
105
+ const trimSlashes = (path: string) => path.replace(/^\/+/, "").replace(/\/+$/, "");
106
+
107
+ /** `a` and `b` joined as FilesApi paths ("" is the root). */
108
+ function joinFilesPath(a: string, b: string): string {
109
+ const left = trimSlashes(a);
110
+ const right = trimSlashes(b);
111
+ if (!left) return right;
112
+ if (!right) return left;
113
+ return `${left}/${right}`;
114
+ }
115
+
116
+ /** A path with `.` and `..` components resolved (no leading slash). */
117
+ function normalizeFilesPath(path: string): string {
118
+ const out: string[] = [];
119
+ for (const part of path.split("/")) {
120
+ if (!part || part === ".") continue;
121
+ if (part === "..") out.pop();
122
+ else out.push(part);
123
+ }
124
+ return out.join("/");
125
+ }
126
+
127
+ /** Whether resolving `..` components of a FilesApi path climbs above the root. */
128
+ function leavesFilesRoot(path: string): boolean {
129
+ let depth = 0;
130
+ for (const part of path.split("/")) {
131
+ if (!part || part === ".") continue;
132
+ if (part === "..") {
133
+ if (depth === 0) return true;
134
+ depth--;
135
+ } else depth++;
136
+ }
137
+ return false;
138
+ }
139
+
140
+ /** `path` relative to `from` (both FilesApi paths). */
141
+ function relativeFilesPath(from: string, path: string): string {
142
+ const a = normalizeFilesPath(from).split("/").filter(Boolean);
143
+ const b = normalizeFilesPath(path).split("/").filter(Boolean);
144
+ let i = 0;
145
+ while (i < a.length && i < b.length && a[i] === b[i]) i++;
146
+ return [...a.slice(i).map(() => ".."), ...b.slice(i)].join("/") || ".";
147
+ }
148
+
149
+ /** The host's absolute path of a FilesApi path, where the FilesApi has a root directory. */
150
+ function hostPathOf(files: FilesApi, path: string): string | undefined {
151
+ const root = (files as { rootDirectory?: string }).rootDirectory;
152
+ if (!root) return undefined;
153
+ const base = root.replace(/\/+$/, "");
154
+ const rest = normalizeFilesPath(path);
155
+ return rest ? `${base}/${rest}` : base || "/";
156
+ }
157
+
158
+ /** The FilesApi path of an absolute host path inside the FilesApi's root directory. */
159
+ function filesPathOfHost(files: FilesApi, hostPath: string): string | undefined {
160
+ const root = (files as { rootDirectory?: string }).rootDirectory;
161
+ if (!root) return undefined;
162
+ const base = root.replace(/\/+$/, "");
163
+ if (hostPath === base) return "";
164
+ if (!hostPath.startsWith(`${base}/`)) return undefined;
165
+ return normalizeFilesPath(hostPath.slice(base.length + 1));
166
+ }
167
+
168
+ /** The hook runner of a working copy's host environment, if any. */
169
+ export function hookRunnerOf(workingCopy: WorkingCopy): HookRunner | undefined {
170
+ return hostEnvironmentOf(workingCopy)?.hookRunner;
171
+ }
172
+
173
+ /** Where the repository's files are, for hooks: its FilesApi, worktree top and git dirs. */
174
+ export interface HookLayout {
175
+ files: FilesApi;
176
+ /** The worktree top ("" for the FilesApi root) */
177
+ top: string;
178
+ /** The git directory */
179
+ gitDir: string;
180
+ /** Where the hook runs: the worktree top, the git directory when bare */
181
+ cwd: string;
182
+ bare: boolean;
183
+ /**
184
+ * The git directory as git exports it to hooks (`GIT_DIR`): where the worktree's `.git` is
185
+ * a gitfile (a linked worktree, a submodule), the real path of the git directory it names
186
+ * (setup.c, `read_gitfile_gently`'s `real_pathdup`); `.` in a bare repository (discovered
187
+ * from its top, where hooks run); absent for a `.git` directory, which git does not export
188
+ */
189
+ gitDirEnv?: string;
190
+ }
191
+
192
+ /**
193
+ * The repository a {@link HookSession} runs hooks of: where its files are, its settings and
194
+ * the host's environment (the runner). A working copy gives all three (see
195
+ * {@link hookHostOf}); the receive side of a local push gives the remote repository's.
196
+ */
197
+ export interface HookHost {
198
+ layout(): Promise<HookLayout | undefined>;
199
+ configValue(key: string): string | undefined;
200
+ environment(): GitHostEnvironment | undefined;
201
+ /**
202
+ * The `hook.<name>.<variable>` settings (event, command, enabled) in the configuration's
203
+ * order, for git 2.5x's configured hooks; absent: none are configured
204
+ */
205
+ hookSettings?(): HookSetting[];
206
+ /**
207
+ * Variables of the host every hook of this repository runs without unless a call sets them
208
+ * itself: the receive side of a local push, which git starts with `local_repo_env` cleared
209
+ * ({@link LOCAL_REPO_ENV}, connect.c)
210
+ */
211
+ unsetEnv?: readonly string[];
212
+ }
213
+
214
+ /**
215
+ * environment.c's `local_repo_env` (git 2.43 and 2.56): the variables naming the local
216
+ * repository, which connect.c removes from the environment of a receive-pack or upload-pack
217
+ * it starts for a local (or `ext::`, `ssh` on the same host) remote, so the remote's hooks
218
+ * never see the pushing repository's objects, config or index.
219
+ */
220
+ export const LOCAL_REPO_ENV: readonly string[] = [
221
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
222
+ "GIT_CONFIG",
223
+ "GIT_CONFIG_PARAMETERS",
224
+ "GIT_CONFIG_COUNT",
225
+ "GIT_OBJECT_DIRECTORY",
226
+ "GIT_DIR",
227
+ "GIT_WORK_TREE",
228
+ "GIT_IMPLICIT_WORK_TREE",
229
+ "GIT_GRAFT_FILE",
230
+ "GIT_INDEX_FILE",
231
+ "GIT_NO_REPLACE_OBJECTS",
232
+ "GIT_REPLACE_REF_BASE",
233
+ "GIT_PREFIX",
234
+ "GIT_SHALLOW_FILE",
235
+ "GIT_COMMON_DIR",
236
+ ];
237
+
238
+ /** One `hook.<name>.<variable>` setting (git 2.5x's configured hooks). */
239
+ export interface HookSetting {
240
+ /** The hook's friendly name (`<name>`) */
241
+ name: string;
242
+ variable: "event" | "command" | "enabled";
243
+ /** The value as git reads it (unquoted); undefined for a variable without `=` */
244
+ value: string | undefined;
245
+ /** The file it was read from, as the host names it (absent where the config cannot tell) */
246
+ file?: string;
247
+ /** Its line in that file, from 1 */
248
+ line?: number;
249
+ /** The scope of that file (git's `config_scope_name`: `local`, `global`, ...) */
250
+ scope?: string;
251
+ }
252
+
253
+ /** The hook host of a working copy. */
254
+ export function hookHostOf(workingCopy: WorkingCopy): HookHost {
255
+ return {
256
+ layout: () => hookLayout(workingCopy),
257
+ configValue: (key) => configValue(workingCopy, key),
258
+ environment: () => hostEnvironmentOf(workingCopy),
259
+ hookSettings: () => hookSettingsOf(workingCopy),
260
+ };
261
+ }
262
+
263
+ const HOOK_VARIABLES = ["event", "command", "enabled"] as const;
264
+
265
+ /**
266
+ * The `hook.*` settings of a working copy's configuration, in its order: by file (in the
267
+ * order the files are first met) and line where the configuration tells them, else as read.
268
+ */
269
+ function hookSettingsOf(workingCopy: WorkingCopy): HookSetting[] {
270
+ const store = RemoteConfigStore.from(workingCopy);
271
+ let names: string[];
272
+ try {
273
+ names = store.subsections("hook");
274
+ } catch {
275
+ return [];
276
+ }
277
+ const found: Array<HookSetting & { seq: number }> = [];
278
+ for (const name of names) {
279
+ for (const variable of HOOK_VARIABLES) {
280
+ const key = `hook.${name}.${variable}`;
281
+ // the values as git reads them (unquoted, unescaped; undefined without `=`) and where
282
+ // they were read, for the order and git's messages
283
+ for (const where of store.valuesWithOrigin(key)) {
284
+ found.push({
285
+ name,
286
+ variable,
287
+ value: where.text,
288
+ ...(where.file !== undefined ? { file: where.file } : {}),
289
+ ...(where.line !== undefined ? { line: where.line } : {}),
290
+ ...(where.scope !== undefined ? { scope: where.scope } : {}),
291
+ seq: found.length,
292
+ });
293
+ }
294
+ }
295
+ }
296
+ const fileOrder = new Map<string, number>();
297
+ for (const f of found)
298
+ if (f.file !== undefined && !fileOrder.has(f.file)) fileOrder.set(f.file, fileOrder.size);
299
+ const rank = (f: (typeof found)[number]) =>
300
+ f.file !== undefined && f.line !== undefined
301
+ ? [fileOrder.get(f.file) ?? 0, f.line]
302
+ : [Number.MAX_SAFE_INTEGER, f.seq];
303
+ return found
304
+ .sort((a, b) => {
305
+ const [fa, la] = rank(a);
306
+ const [fb, lb] = rank(b);
307
+ return (fa as number) - (fb as number) || (la as number) - (lb as number) || a.seq - b.seq;
308
+ })
309
+ .map(({ seq: _seq, ...setting }) => setting);
310
+ }
311
+
312
+ /**
313
+ * The `hook.<name>.<variable>` settings (event, command, enabled) among a configuration's
314
+ * entries in the order git reads them (an opened repository's `listWithOrigin`, else `list`
315
+ * without origins): the hook settings of a repository a push reaches.
316
+ */
317
+ export function hookSettingsFromEntries(
318
+ entries: ReadonlyArray<{
319
+ key: string;
320
+ value: string | null;
321
+ file?: string;
322
+ line?: number;
323
+ scope?: string;
324
+ }>,
325
+ ): HookSetting[] {
326
+ const out: HookSetting[] = [];
327
+ for (const e of entries) {
328
+ const first = e.key.indexOf(".");
329
+ const last = e.key.lastIndexOf(".");
330
+ if (first < 0 || last <= first) continue;
331
+ if (e.key.slice(0, first).toLowerCase() !== "hook") continue;
332
+ const variable = e.key.slice(last + 1).toLowerCase();
333
+ if (variable !== "event" && variable !== "command" && variable !== "enabled") continue;
334
+ out.push({
335
+ name: e.key.slice(first + 1, last),
336
+ variable,
337
+ value: e.value === null ? undefined : e.value,
338
+ ...(e.file !== undefined ? { file: e.file } : {}),
339
+ ...(e.line !== undefined ? { line: e.line } : {}),
340
+ ...(e.scope !== undefined ? { scope: e.scope } : {}),
341
+ });
342
+ }
343
+ return out;
344
+ }
345
+
346
+ /** git's hook names (hook-list.h, from githooks(5)): no friendly name may be one of them. */
347
+ const KNOWN_HOOKS = new Set([
348
+ "applypatch-msg",
349
+ "commit-msg",
350
+ "fsmonitor-watchman",
351
+ "p4-changelist",
352
+ "p4-post-changelist",
353
+ "p4-pre-submit",
354
+ "p4-prepare-changelist",
355
+ "post-applypatch",
356
+ "post-checkout",
357
+ "post-commit",
358
+ "post-index-change",
359
+ "post-merge",
360
+ "post-receive",
361
+ "post-rewrite",
362
+ "post-update",
363
+ "pre-applypatch",
364
+ "pre-auto-gc",
365
+ "pre-commit",
366
+ "pre-merge-commit",
367
+ "pre-push",
368
+ "pre-rebase",
369
+ "pre-receive",
370
+ "prepare-commit-msg",
371
+ "proc-receive",
372
+ "push-to-checkout",
373
+ "reference-transaction",
374
+ "sendemail-validate",
375
+ "update",
376
+ ]);
377
+
378
+ /** Whether `name` is one of git's hooks (hook.c `is_known_hook`, hook-list.h). */
379
+ export function isKnownHook(name: string): boolean {
380
+ return KNOWN_HOOKS.has(name);
381
+ }
382
+
383
+ /**
384
+ * What git 2.5x dies with (or warns of) on reading the configured hooks, which it does on
385
+ * looking up any hook (hook.c `hook_config_lookup_all`, `build_hook_config_map`): a
386
+ * variable without `=` (`error: missing value for ...`, then git's `bad config variable`), a
387
+ * friendly name that is a known hook name, a name of some event with no command (unless
388
+ * disabled). Returns the fatal message (undefined when none) and git's warnings (a friendly
389
+ * name equal to its event; a disabled one without a command).
390
+ */
391
+ export function hookSettingsCheck(settings: readonly HookSetting[]): {
392
+ fatal?: string;
393
+ warnings: string[];
394
+ } {
395
+ const warnings: string[] = [];
396
+ const events = new Map<string, string[]>();
397
+ const commands = new Set<string>();
398
+ const disabled = new Set<string>();
399
+ for (const s of settings) {
400
+ const key = `hook.${s.name}.${s.variable}`;
401
+ if (s.value === undefined) {
402
+ const fatal =
403
+ s.file !== undefined && s.line !== undefined
404
+ ? `fatal: bad config variable '${key}' in file '${s.file}' at line ${s.line}`
405
+ : `fatal: unable to parse '${key}' from command-line config`;
406
+ return { fatal: `error: missing value for '${key}'\n${fatal}`, warnings };
407
+ }
408
+ if (s.variable === "event") {
409
+ if (s.value === "") {
410
+ for (const list of events.values()) {
411
+ const at = list.indexOf(s.name);
412
+ if (at >= 0) list.splice(at, 1);
413
+ }
414
+ continue;
415
+ }
416
+ if (KNOWN_HOOKS.has(s.name)) {
417
+ return {
418
+ fatal: `fatal: hook friendly-name '${s.name}' collides with a known event name; please choose a different friendly-name`,
419
+ warnings,
420
+ };
421
+ }
422
+ if (s.name === s.value) {
423
+ warnings.push(
424
+ `warning: hook friendly-name '${s.name}' is the same as its event; this may cause ambiguity with hook.${s.name}.enabled`,
425
+ );
426
+ }
427
+ const list = events.get(s.value) ?? [];
428
+ const at = list.indexOf(s.name);
429
+ if (at >= 0) list.splice(at, 1);
430
+ list.push(s.name);
431
+ events.set(s.value, list);
432
+ } else if (s.variable === "command") {
433
+ commands.add(s.name);
434
+ } else {
435
+ const enabled = parseGitBool(s.value);
436
+ if (enabled === false) disabled.add(s.name);
437
+ else if (enabled === true) disabled.delete(s.name);
438
+ }
439
+ }
440
+ for (const list of events.values()) {
441
+ for (const name of list) {
442
+ if (commands.has(name)) continue;
443
+ if (disabled.has(name)) {
444
+ warnings.push(`warning: disabled hook '${name}' has no command configured`);
445
+ continue;
446
+ }
447
+ return {
448
+ fatal: `fatal: 'hook.${name}.command' must be configured or 'hook.${name}.event' must be removed; aborting.`,
449
+ warnings,
450
+ };
451
+ }
452
+ }
453
+ return { warnings };
454
+ }
455
+
456
+ /** One configured hook of an event, as git 2.5x's `list_hooks` keeps it (`git hook list`). */
457
+ export interface ConfiguredHookEntry {
458
+ /** Its friendly name (`hook.<name>`) */
459
+ name: string;
460
+ /** Its `hook.<name>.command` (absent: only a disabled hook may have none) */
461
+ command?: string;
462
+ /** `hook.<name>.enabled=false` */
463
+ disabled: boolean;
464
+ /** The whole event is disabled (`hook.<event>.enabled=false`, `<event>` no friendly name) */
465
+ eventDisabled: boolean;
466
+ /** The scope of its last event line (`local`, `global`, ...), where the config tells */
467
+ scope?: string;
468
+ }
469
+
470
+ /**
471
+ * git 2.5x's configured hooks of `event` (hook.c `build_hook_config_map`,
472
+ * `list_hooks_add_configured`): the friendly names whose `hook.<name>.event` names it, in the
473
+ * order of their last such line (an empty value drops the name from every event), each with
474
+ * its last `hook.<name>.command`, whether `hook.<name>.enabled=false` disables it and whether
475
+ * the event itself is disabled (`hook.<event>.enabled=false`, `<event>` not a friendly name).
476
+ * Disabled ones are kept, as `git hook list` shows them; none of them runs.
477
+ */
478
+ export function configuredHookEntries(
479
+ settings: readonly HookSetting[],
480
+ event: string,
481
+ ): ConfiguredHookEntry[] {
482
+ const events = new Map<string, Array<{ name: string; scope?: string }>>();
483
+ const commands = new Map<string, string>();
484
+ const disabled = new Set<string>();
485
+ const drop = (list: Array<{ name: string }>, name: string) => {
486
+ const at = list.findIndex((e) => e.name === name);
487
+ if (at >= 0) list.splice(at, 1);
488
+ };
489
+ for (const s of settings) {
490
+ if (s.variable === "event") {
491
+ if (s.value === undefined) continue;
492
+ if (s.value === "") {
493
+ // an empty value drops the name from every event
494
+ for (const list of events.values()) drop(list, s.name);
495
+ continue;
496
+ }
497
+ // moved to the end of its event's list (last-seen order)
498
+ const list = events.get(s.value) ?? [];
499
+ drop(list, s.name);
500
+ list.push({ name: s.name, ...(s.scope !== undefined ? { scope: s.scope } : {}) });
501
+ events.set(s.value, list);
502
+ } else if (s.variable === "command") {
503
+ if (s.value !== undefined) commands.set(s.name, s.value);
504
+ } else {
505
+ const enabled = parseGitBool(s.value ?? "true");
506
+ if (enabled === false) disabled.add(s.name);
507
+ else if (enabled === true) disabled.delete(s.name);
508
+ }
509
+ }
510
+ const friendly = (name: string) =>
511
+ commands.has(name) || [...events.values()].some((list) => list.some((e) => e.name === name));
512
+ const eventDisabled = disabled.has(event) && !friendly(event);
513
+ return (events.get(event) ?? []).map(({ name, scope }) => {
514
+ const command = commands.get(name);
515
+ return {
516
+ name,
517
+ ...(command !== undefined ? { command } : {}),
518
+ disabled: disabled.has(name),
519
+ eventDisabled,
520
+ ...(scope !== undefined ? { scope } : {}),
521
+ };
522
+ });
523
+ }
524
+
525
+ /**
526
+ * git 2.5x's configured hooks of `event` that run (see {@link configuredHookEntries}): those
527
+ * neither disabled nor of a disabled event. A name with no command is left out (git refuses
528
+ * to run any hook then, see {@link hookSettingsCheck}).
529
+ */
530
+ export function configuredHooks(
531
+ settings: readonly HookSetting[],
532
+ event: string,
533
+ ): Array<{ name: string; command: string }> {
534
+ const out: Array<{ name: string; command: string }> = [];
535
+ for (const e of configuredHookEntries(settings, event)) {
536
+ if (e.command === undefined || e.disabled || e.eventDisabled) continue;
537
+ out.push({ name: e.name, command: e.command });
538
+ }
539
+ return out;
540
+ }
541
+
542
+ /** One hook `git hook list` lists: a configured one or the hooks directory's script. */
543
+ export type HookListEntry =
544
+ | ({ kind: "configured" } & ConfiguredHookEntry)
545
+ | {
546
+ kind: "traditional";
547
+ /** The script's path as git names it (`.git/hooks/pre-commit`) */
548
+ path: string;
549
+ };
550
+
551
+ /** A hook to run: a script of the hooks directory or one the configuration defines. */
552
+ type HookToRun =
553
+ | { kind: "traditional"; found: FoundHook }
554
+ | { kind: "configured"; name: string; command: string };
555
+
556
+ async function hookLayout(workingCopy: WorkingCopy): Promise<HookLayout | undefined> {
557
+ let worktree:
558
+ | { getFiles?(): FilesApi; getGitDir?(): string | undefined; getRoot?(): string }
559
+ | undefined;
560
+ try {
561
+ worktree = workingCopy.worktree as typeof worktree;
562
+ } catch {
563
+ // a bare repository's working copy refuses its worktree: its hooks run in the
564
+ // repository's directory (`WorktreeAdmin.bareRepository`)
565
+ worktree = (workingCopy as { bareRepository?: typeof worktree }).bareRepository;
566
+ }
567
+ const files = worktree?.getFiles?.();
568
+ const gitDir = worktree?.getGitDir?.();
569
+ if (!files || gitDir === undefined) return undefined;
570
+ const top = normalizeFilesPath(worktree?.getRoot?.() ?? "");
571
+ const bareValue = configValue(workingCopy, "core.bare");
572
+ const bare = bareValue !== undefined && configBool(workingCopy, "core.bare", false);
573
+ const dir = normalizeFilesPath(gitDir);
574
+ const gitDirEnv = await gitDirEnvOf(files, top, bare, hostEnvironmentOf(workingCopy));
575
+ return {
576
+ files,
577
+ top,
578
+ gitDir: dir,
579
+ cwd: bare ? dir : top,
580
+ bare,
581
+ ...(gitDirEnv ? { gitDirEnv } : {}),
582
+ };
583
+ }
584
+
585
+ /**
586
+ * `GIT_DIR` as git's discovery exports it to hooks (see {@link HookLayout.gitDirEnv}): for a
587
+ * gitfile `<top>/.git`, the real path of the git directory it names (a linked worktree's own:
588
+ * the worktree's `getGitDir()` is the repository's common directory), as `read_gitfile_gently`
589
+ * resolves it; `.` for a bare repository; undefined otherwise.
590
+ */
591
+ async function gitDirEnvOf(
592
+ files: FilesApi,
593
+ top: string,
594
+ bare: boolean,
595
+ environment: GitHostEnvironment | undefined,
596
+ ): Promise<string | undefined> {
597
+ const dotGit = joinFilesPath(top, ".git");
598
+ const gitfile = await files
599
+ .stats(dotGit)
600
+ .then((s) => s?.kind === "file")
601
+ .catch(() => false);
602
+ if (!gitfile) return bare ? "." : undefined;
603
+ const host = await gitfileTarget(files, dotGit);
604
+ return host ? realHostPath(host, environment) : undefined;
605
+ }
606
+
607
+ /** `path` with its symbolic links followed where the host can tell (`realpath(3)`). */
608
+ async function realHostPath(
609
+ path: string,
610
+ environment: GitHostEnvironment | undefined,
611
+ ): Promise<string> {
612
+ return (await environment?.realPath?.(path).catch(() => undefined)) ?? path;
613
+ }
614
+
615
+ /**
616
+ * The host path of the git directory the gitfile at `path` names (relative to its
617
+ * directory, or absolute); undefined when it names none or the FilesApi has no host path.
618
+ */
619
+ async function gitfileTarget(files: FilesApi, path: string): Promise<string | undefined> {
620
+ const top = normalizeFilesPath(path.slice(0, Math.max(0, path.lastIndexOf("/"))));
621
+ try {
622
+ const chunks: Uint8Array[] = [];
623
+ for await (const chunk of files.read(path)) chunks.push(chunk);
624
+ const text = decoder.decode(chunks.length === 1 ? chunks[0] : concat(chunks));
625
+ const m = /^gitdir: (.*?)\r?\n?$/.exec(text.split("\n")[0] ?? "");
626
+ const target = m?.[1];
627
+ if (!target) return undefined;
628
+ if (target.startsWith("/")) return normalizeHostPath(target);
629
+ const topHost = hostPathOf(files, top);
630
+ return topHost ? normalizeHostPath(`${topHost}/${target}`) : undefined;
631
+ } catch {
632
+ return undefined;
633
+ }
634
+ }
635
+
636
+ /** An absolute host path with `.` and `..` components resolved. */
637
+ function normalizeHostPath(path: string): string {
638
+ return `/${normalizeFilesPath(path)}`;
639
+ }
640
+
641
+ /** The common git directory of `gitDir` (its `commondir` file), as a FilesApi path. */
642
+ async function commonDirOf(files: FilesApi, gitDir: string): Promise<string> {
643
+ const path = joinFilesPath(gitDir, "commondir");
644
+ try {
645
+ if ((await files.stats(path))?.kind !== "file") return gitDir;
646
+ const chunks: Uint8Array[] = [];
647
+ for await (const chunk of files.read(path)) chunks.push(chunk);
648
+ const text = decoder
649
+ .decode(chunks.length === 1 ? chunks[0] : concat(chunks))
650
+ .replace(/\r?\n$/, "");
651
+ if (!text) return gitDir;
652
+ if (text.startsWith("/")) return filesPathOfHost(files, text) ?? gitDir;
653
+ return normalizeFilesPath(joinFilesPath(gitDir, text));
654
+ } catch {
655
+ return gitDir;
656
+ }
657
+ }
658
+
659
+ function concat(chunks: Uint8Array[]): Uint8Array {
660
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
661
+ let at = 0;
662
+ for (const c of chunks) {
663
+ out.set(c, at);
664
+ at += c.length;
665
+ }
666
+ return out;
667
+ }
668
+
669
+ /** What `access(path, X_OK)` says: executable, present but not executable, or absent. */
670
+ async function accessOf(
671
+ files: FilesApi | undefined,
672
+ filesPath: string | undefined,
673
+ hostPath: string | undefined,
674
+ environment: GitHostEnvironment | undefined,
675
+ ): Promise<"executable" | "not-executable" | "absent"> {
676
+ if (files && filesPath !== undefined) {
677
+ try {
678
+ return await filesAccessOf(files, filesPath, environment);
679
+ } catch {
680
+ return "absent";
681
+ }
682
+ }
683
+ return hostAccessOf(hostPath, environment);
684
+ }
685
+
686
+ /** `access(X_OK)` of a host path, by its stat (links followed) through the host. */
687
+ async function hostAccessOf(
688
+ hostPath: string | undefined,
689
+ environment: GitHostEnvironment | undefined,
690
+ ): Promise<"executable" | "not-executable" | "absent"> {
691
+ if (!hostPath || !environment?.statFile) return "absent";
692
+ const stats = await environment.statFile(hostPath);
693
+ if (!stats) return "absent";
694
+ if (stats.kind === "directory" || stats.mode === undefined) return "executable";
695
+ return (stats.mode & 0o111) !== 0 ? "executable" : "not-executable";
696
+ }
697
+
698
+ /** The most links followed before giving up (the kernel's ELOOP limit). */
699
+ const MAX_LINK_HOPS = 40;
700
+
701
+ /**
702
+ * `access(X_OK)` of a FilesApi path: a symbolic link followed to its target (through the
703
+ * FilesApi while the target lies in it, else by its host path through the host), whose mode
704
+ * decides, as `access` follows links. A FilesApi without `lstat` gives no modes: present
705
+ * counts as executable.
706
+ */
707
+ async function filesAccessOf(
708
+ files: FilesApi,
709
+ start: string,
710
+ environment: GitHostEnvironment | undefined,
711
+ ): Promise<"executable" | "not-executable" | "absent"> {
712
+ const posix = files as {
713
+ lstat?(path: string): Promise<{ kind: string; mode?: number } | undefined>;
714
+ readlink?(path: string): Promise<Uint8Array | undefined>;
715
+ };
716
+ if (!posix.lstat) {
717
+ const stats = await files.stats(start);
718
+ return stats ? "executable" : "absent";
719
+ }
720
+ let path = normalizeFilesPath(start);
721
+ for (let hop = 0; hop <= MAX_LINK_HOPS; hop++) {
722
+ const link = await posix.lstat(path);
723
+ if (!link) return "absent";
724
+ if (link.kind !== "symlink") {
725
+ if (link.kind !== "file" || link.mode === undefined) return "executable";
726
+ return (link.mode & 0o111) !== 0 ? "executable" : "not-executable";
727
+ }
728
+ const raw = posix.readlink ? await posix.readlink(path) : undefined;
729
+ if (!raw) return "absent";
730
+ const target = decoder.decode(raw);
731
+ const slash = path.lastIndexOf("/");
732
+ const parent = slash < 0 ? "" : path.slice(0, slash);
733
+ if (target.startsWith("/")) {
734
+ const inside = filesPathOfHost(files, target);
735
+ if (inside === undefined) return hostAccessOf(target, environment);
736
+ path = inside;
737
+ continue;
738
+ }
739
+ // a relative target that climbs out of the FilesApi is reached through the host
740
+ if (escapesRoot(parent ? `${parent}/${target}` : target)) {
741
+ const parentHost = hostPathOf(files, parent);
742
+ return hostAccessOf(parentHost ? `${parentHost}/${target}` : undefined, environment);
743
+ }
744
+ path = normalizeFilesPath(joinFilesPath(parent, target));
745
+ }
746
+ return "absent";
747
+ }
748
+
749
+ /** Whether a relative path's `..` components climb above its root. */
750
+ function escapesRoot(path: string): boolean {
751
+ let depth = 0;
752
+ for (const part of path.split("/")) {
753
+ if (!part || part === ".") continue;
754
+ if (part === "..") {
755
+ depth--;
756
+ if (depth < 0) return true;
757
+ } else depth++;
758
+ }
759
+ return false;
760
+ }
761
+
762
+ /**
763
+ * The hooks one command runs, with git's per-process memory of the hints given and the
764
+ * output the hooks wrote (git relays it on its stderr, the hints included).
765
+ */
766
+ export class HookSession {
767
+ /** The hook names whose `advice.ignoredHook` hint was given (git's `advise_given`) */
768
+ private readonly advised = new Set<string>();
769
+ /** What the hooks wrote, and the hints, in order */
770
+ private readonly chunks: string[] = [];
771
+ /** What the hooks whose stdout git keeps apart (pre-push) wrote there */
772
+ private readonly stdoutChunks: string[] = [];
773
+
774
+ private readonly host: HookHost;
775
+ /** Variables every hook of this session gets, below each call's own (see {@link withEnv}) */
776
+ private processEnv: Record<string, string> = {};
777
+
778
+ constructor(source: WorkingCopy | HookHost) {
779
+ this.host = "layout" in source ? source : hookHostOf(source);
780
+ }
781
+
782
+ /**
783
+ * A session sharing this one's output and hints whose hooks all get `env` too (below each
784
+ * call's own variables): the hooks of a git command git runs as a child process with
785
+ * variables set, as a sequencer's `git commit` with GIT_REFLOG_ACTION.
786
+ */
787
+ withEnv(env: Record<string, string>): HookSession {
788
+ const derived = Object.create(HookSession.prototype) as HookSession;
789
+ Object.assign(derived, this);
790
+ derived.processEnv = { ...this.processEnv, ...env };
791
+ return derived;
792
+ }
793
+
794
+ private get runner(): HookRunner | undefined {
795
+ return this.host.environment()?.hookRunner;
796
+ }
797
+
798
+ /**
799
+ * The committer variables the host sets (`GIT_COMMITTER_NAME`, `GIT_COMMITTER_EMAIL`), as
800
+ * the host environment's `committer` gives them: what git's http-backend checks before
801
+ * naming the pushing user the committer of its children.
802
+ */
803
+ get hostCommitter(): { name?: string; email?: string } {
804
+ return this.host.environment()?.committer ?? {};
805
+ }
806
+
807
+ /**
808
+ * The host's `GIT_ALTERNATE_OBJECT_DIRECTORIES` (the host environment's
809
+ * `alternateObjectDirectories`): what a quarantined pre-receive gets the repository's
810
+ * objects appended to, as tmp-objdir.c's `env_append` appends them.
811
+ */
812
+ get hostAlternateObjectDirectories(): string | undefined {
813
+ // the receive side of a local push runs without them (local_repo_env)
814
+ if (this.host.unsetEnv?.includes("GIT_ALTERNATE_OBJECT_DIRECTORIES")) return undefined;
815
+ return this.host.environment()?.alternateObjectDirectories;
816
+ }
817
+
818
+ /** Whether hooks can run at all: the host environment has a runner. */
819
+ get enabled(): boolean {
820
+ return this.runner !== undefined;
821
+ }
822
+
823
+ /** The runner's git version (default 2.56). */
824
+ get compatibility(): "2.43" | "2.56" {
825
+ return this.runner?.compatibility ?? "2.56";
826
+ }
827
+
828
+ /** Everything the hooks wrote (stderr, and stdout sent there) and the hints, as git shows it. */
829
+ get output(): string {
830
+ return this.chunks.join("");
831
+ }
832
+
833
+ /** What the hooks whose stdout git keeps on its own stdout wrote there (pre-push). */
834
+ get stdout(): string {
835
+ return this.stdoutChunks.join("");
836
+ }
837
+
838
+ /** Text added to the output, as git writes its own messages between the hooks' output. */
839
+ append(text: string): void {
840
+ if (text) this.chunks.push(text);
841
+ }
842
+
843
+ /**
844
+ * A file of the git directory as git names it to hooks (`git_path`): relative to the
845
+ * directory the hooks run in (`.git/index`, `.git/COMMIT_EDITMSG`), else absolute.
846
+ * `absolute` names it by its host path where there is one, as git names a lock file
847
+ * (lockfile.c resolves the path it locks: `index.lock` of `commit -a`).
848
+ */
849
+ async gitPath(name: string, absolute = false): Promise<string> {
850
+ const layout = await this.host.layout();
851
+ if (!layout) return `.git/${name}`;
852
+ const filesPath = joinFilesPath(layout.gitDir, name);
853
+ if (absolute) {
854
+ const host = hostPathOf(layout.files, filesPath);
855
+ if (host) return host;
856
+ }
857
+ const relative = relativeFilesPath(layout.cwd, filesPath);
858
+ if (!relative.startsWith("../")) return relative;
859
+ return hostPathOf(layout.files, filesPath) ?? filesPath;
860
+ }
861
+
862
+ /** A file of the git directory as the repository's FilesApi names it (no layout: none). */
863
+ async gitFile(name: string): Promise<{ files: FilesApi; path: string } | undefined> {
864
+ const layout = await this.host.layout();
865
+ return layout ? { files: layout.files, path: joinFilesPath(layout.gitDir, name) } : undefined;
866
+ }
867
+
868
+ /**
869
+ * A file of the repository's common directory (the main git directory of a linked
870
+ * worktree: `objects/`, `packed-refs`) as the repository's FilesApi names it.
871
+ */
872
+ async commonGitFile(name: string): Promise<{ files: FilesApi; path: string } | undefined> {
873
+ const layout = await this.host.layout();
874
+ if (!layout) return undefined;
875
+ return {
876
+ files: layout.files,
877
+ path: joinFilesPath(await commonDirOf(layout.files, layout.gitDir), name),
878
+ };
879
+ }
880
+
881
+ /**
882
+ * A path of the repository's FilesApi as hooks are told it: its absolute host path where the
883
+ * files have one (as git names `GIT_QUARANTINE_PATH`), else relative to the directory the
884
+ * hooks run in; as given without a layout.
885
+ */
886
+ async hookPathOf(filesPath: string): Promise<string> {
887
+ const layout = await this.host.layout();
888
+ if (!layout) return filesPath;
889
+ return hostPathOf(layout.files, filesPath) ?? relativeFilesPath(layout.cwd, filesPath);
890
+ }
891
+
892
+ /**
893
+ * The bytes of a file a git option names (`git hook run --to-stdin=<path>`): a relative
894
+ * path from the directory git runs in (the worktree top, the git directory when bare),
895
+ * through the repository's FilesApi; an absolute one through it when it lies there, else
896
+ * through the host. Undefined when it cannot be read.
897
+ */
898
+ async readFileAt(path: string): Promise<Uint8Array | undefined> {
899
+ const layout = await this.host.layout();
900
+ const environment = this.host.environment();
901
+ // A relative path that climbs above the FilesApi's root names a host file outside it:
902
+ // resolve it against the host path of the directory git runs in, never clamp it.
903
+ let hostPath = path.startsWith("/") ? path : undefined;
904
+ let filesPath: string | undefined;
905
+ if (layout && !path.startsWith("/")) {
906
+ const joined = joinFilesPath(layout.cwd, path);
907
+ if (leavesFilesRoot(joined)) {
908
+ const hostCwd = hostPathOf(layout.files, layout.cwd);
909
+ if (!hostCwd) return undefined;
910
+ hostPath = `/${normalizeFilesPath(`${hostCwd}/${path}`)}`;
911
+ filesPath = filesPathOfHost(layout.files, hostPath);
912
+ } else {
913
+ filesPath = normalizeFilesPath(joined);
914
+ }
915
+ } else if (layout && hostPath) {
916
+ filesPath = filesPathOfHost(layout.files, hostPath);
917
+ }
918
+ try {
919
+ if (layout && filesPath !== undefined) {
920
+ if ((await layout.files.stats(filesPath))?.kind !== "file") return undefined;
921
+ const chunks: Uint8Array[] = [];
922
+ for await (const chunk of layout.files.read(filesPath)) chunks.push(chunk);
923
+ return chunks.length === 1 ? chunks[0] : concat(chunks);
924
+ }
925
+ if (hostPath && environment) return await environment.readFile(hostPath);
926
+ } catch {
927
+ return undefined;
928
+ }
929
+ return undefined;
930
+ }
931
+
932
+ /**
933
+ * The git directory's absolute host path, where the repository's files have one: its real
934
+ * path (symbolic links followed), as git names it after a `getcwd` (clone's GIT_DIR, the
935
+ * receive side's `absolute_path` in the git directory), or with `{ real: false }` as the
936
+ * host names it, as git's `absolute_path` of `.git` from the top keeps the logical `$PWD`
937
+ * (lockfile.c's "Unable to create" message).
938
+ */
939
+ async hostGitDir(options: { real?: boolean } = {}): Promise<string | undefined> {
940
+ const layout = await this.host.layout();
941
+ const host = layout ? hostPathOf(layout.files, layout.gitDir) : undefined;
942
+ if (!host || options.real === false) return host;
943
+ return realHostPath(host, this.host.environment());
944
+ }
945
+
946
+ /** Whether `name` exists as an executable hook (git's `hook_exists`), giving no hint. */
947
+ async exists(name: string): Promise<boolean> {
948
+ if (!this.enabled) return false;
949
+ return (await this.list(name, false)).length > 0;
950
+ }
951
+
952
+ /**
953
+ * The hooks of `name` git runs, in order (hook.c `list_hooks`): the configured ones (git
954
+ * 2.5x, see {@link configuredHooks}), then the hooks directory's script ({@link find}).
955
+ */
956
+ private async list(name: string, advise = true): Promise<HookToRun[]> {
957
+ const out: HookToRun[] = [];
958
+ if (this.compatibility !== "2.43") {
959
+ const settings = this.host.hookSettings?.() ?? [];
960
+ if (settings.length > 0) this.checkSettings(settings);
961
+ for (const hook of configuredHooks(settings, name)) out.push({ kind: "configured", ...hook });
962
+ }
963
+ const found = await this.find(name, advise);
964
+ if (found) out.push({ kind: "traditional", found });
965
+ return out;
966
+ }
967
+
968
+ /**
969
+ * Every hook of `name` git 2.5x's `list_hooks` keeps, in order (`git hook list`): the
970
+ * configured ones, disabled ones included (see {@link configuredHookEntries}; none under
971
+ * 2.43), then the hooks directory's script ({@link find}, its hint given). Throws git's
972
+ * fatal error for a broken `hook.*` configuration.
973
+ */
974
+ async listAll(name: string): Promise<HookListEntry[]> {
975
+ const out: HookListEntry[] = [];
976
+ if (this.compatibility !== "2.43") {
977
+ const settings = this.host.hookSettings?.() ?? [];
978
+ if (settings.length > 0) this.checkSettings(settings);
979
+ for (const entry of configuredHookEntries(settings, name)) {
980
+ out.push({ kind: "configured", ...entry });
981
+ }
982
+ }
983
+ const found = await this.find(name);
984
+ if (found) out.push({ kind: "traditional", path: found.path });
985
+ return out;
986
+ }
987
+
988
+ /** Whether the configured hooks' warnings were given (git gives them once per process). */
989
+ private settingsChecked = false;
990
+
991
+ /**
992
+ * git 2.5x's checks of the configured hooks on a hook's lookup ({@link hookSettingsCheck}):
993
+ * its warnings once, its fatal error thrown (on every lookup, as each git process dies).
994
+ */
995
+ private checkSettings(settings: readonly HookSetting[]): void {
996
+ const { fatal, warnings } = hookSettingsCheck(settings);
997
+ if (!this.settingsChecked) {
998
+ this.settingsChecked = true;
999
+ if (warnings.length > 0) this.append(`${warnings.join("\n")}\n`);
1000
+ }
1001
+ if (fatal) throw new GitApiError(fatal);
1002
+ }
1003
+
1004
+ /**
1005
+ * The hook `name` (git's `find_hook`): undefined when absent or not executable; the latter
1006
+ * gives the `advice.ignoredHook` hint (once per name) unless `advise` is false.
1007
+ */
1008
+ async find(name: string, advise = true): Promise<FoundHook | undefined> {
1009
+ const layout = await this.host.layout();
1010
+ if (!layout) return undefined;
1011
+ const environment = this.host.environment();
1012
+ const configured = this.host.configValue("core.hooksPath");
1013
+ let found: FoundHook;
1014
+ if (configured !== undefined && configured !== "") {
1015
+ const expanded = expandUserPath(configured, environment) ?? configured;
1016
+ const named = `${expanded.replace(/\/+$/, "")}/${name}`;
1017
+ if (named.startsWith("/")) {
1018
+ const filesPath = filesPathOfHost(layout.files, named);
1019
+ found = { path: named, hostPath: named, ...(filesPath !== undefined ? { filesPath } : {}) };
1020
+ } else {
1021
+ const filesPath = normalizeFilesPath(joinFilesPath(layout.cwd, named));
1022
+ const hostPath = hostPathOf(layout.files, filesPath);
1023
+ found = { path: named, filesPath, ...(hostPath ? { hostPath } : {}) };
1024
+ }
1025
+ } else {
1026
+ const commonDir = await commonDirOf(layout.files, layout.gitDir);
1027
+ const filesPath = joinFilesPath(commonDir, `hooks/${name}`);
1028
+ const hostPath = hostPathOf(layout.files, filesPath);
1029
+ // git names it from its git directory, which it reaches relative to the worktree top
1030
+ // when inside it (".git/hooks/pre-commit"), else by its absolute path
1031
+ const inside =
1032
+ !layout.top || filesPath.startsWith(`${layout.top}/`) || layout.bare
1033
+ ? relativeFilesPath(layout.cwd, filesPath)
1034
+ : undefined;
1035
+ const path = inside && !inside.startsWith("../") ? inside : (hostPath ?? filesPath);
1036
+ found = { path, filesPath, ...(hostPath ? { hostPath } : {}) };
1037
+ }
1038
+ const access = await accessOf(layout.files, found.filesPath, found.hostPath, environment);
1039
+ if (access === "executable") return found;
1040
+ if (
1041
+ access === "not-executable" &&
1042
+ advise &&
1043
+ (parseGitBool(this.host.configValue("advice.ignoredHook")) ?? true) &&
1044
+ !this.advised.has(name)
1045
+ ) {
1046
+ this.advised.add(name);
1047
+ const set = this.compatibility === "2.43" ? "" : " set";
1048
+ this.append(
1049
+ `hint: The '${found.path}' hook was ignored because it's not set as executable.\n` +
1050
+ `hint: You can disable this warning with \`git config${set} advice.ignoredHook false\`.\n`,
1051
+ );
1052
+ }
1053
+ return undefined;
1054
+ }
1055
+
1056
+ /**
1057
+ * Runs the hook `name` (git's `run_hooks_opt`): undefined when there is none (or no
1058
+ * runner), else its exit code and output. Its output is kept in {@link output}.
1059
+ */
1060
+ async run(name: string, options: HookCallOptions = {}): Promise<HookResult | undefined> {
1061
+ const runner = this.runner;
1062
+ if (!runner) return undefined;
1063
+ const hooks = await this.list(name);
1064
+ if (hooks.length === 0) return undefined;
1065
+ const layout = await this.host.layout();
1066
+ if (!layout) return undefined;
1067
+ // each in turn, their exit codes or'ed together (hook.c notify_hook_finished)
1068
+ let ran: HookResult | undefined;
1069
+ for (const hook of hooks) {
1070
+ const result = await this.runOne(runner, layout, name, hook, options);
1071
+ if (!result) continue;
1072
+ ran = ran
1073
+ ? {
1074
+ exitCode: ran.exitCode | result.exitCode,
1075
+ stdout: ran.stdout + result.stdout,
1076
+ stderr: ran.stderr + result.stderr,
1077
+ }
1078
+ : result;
1079
+ }
1080
+ return ran;
1081
+ }
1082
+
1083
+ /**
1084
+ * Starts the hook `name` found as git's `find_hook` finds it (the hooks directory's script
1085
+ * alone: no configured hook, as receive-pack's proc-receive), its stdin and stdout piped to
1086
+ * the caller. Undefined when there is none (or no runner). Its stderr is kept in
1087
+ * {@link output} and handed to `onStderr` as it comes where the runner streams it (git's
1088
+ * `copy_to_sideband`), else once it exited; either way all of it before `wait()` resolves.
1089
+ *
1090
+ * A runner that cannot start a hook it talks to (no `HookRunner.start`) gets a process that
1091
+ * takes the whole stdin first (`interactive: false`): the hook runs once its stdin is closed.
1092
+ */
1093
+ async start(
1094
+ name: string,
1095
+ options: HookCallOptions & { onStderr?: (text: string) => Promise<void> | void } = {},
1096
+ ): Promise<StartedHook | undefined> {
1097
+ const runner = this.runner;
1098
+ if (!runner) return undefined;
1099
+ const found = await this.find(name);
1100
+ if (!found) return undefined;
1101
+ const layout = await this.host.layout();
1102
+ if (!layout) return undefined;
1103
+ const { invocation, hook } = this.invocationOf(
1104
+ layout,
1105
+ name,
1106
+ { kind: "traditional", found },
1107
+ {
1108
+ ...options,
1109
+ keepStdout: true,
1110
+ },
1111
+ );
1112
+ const finish = async (outcome: HookOutcome | undefined): Promise<number> => {
1113
+ const stderr = outcome ? decoder.decode(outcome.stderr) : "";
1114
+ this.append(stderr);
1115
+ if (stderr) await options.onStderr?.(stderr);
1116
+ return outcome?.exitCode ?? 0;
1117
+ };
1118
+ if (runner.start) {
1119
+ // its stderr relayed chunk by chunk, in order, every chunk before wait() resolves
1120
+ const streamed = new TextDecoder();
1121
+ let relayed: Promise<void> = Promise.resolve();
1122
+ const relay = (text: string) => {
1123
+ if (!text) return;
1124
+ this.append(text);
1125
+ relayed = relayed.then(() => options.onStderr?.(text)).catch(() => {});
1126
+ };
1127
+ let process: HookProcess | undefined;
1128
+ try {
1129
+ process = await runner.start(invocation, {
1130
+ onStderr: (chunk) => relay(streamed.decode(chunk, { stream: true })),
1131
+ });
1132
+ } catch (error) {
1133
+ const text = `error: cannot run ${hook.path}: ${String((error as Error)?.message ?? error)}\n`;
1134
+ this.append(text);
1135
+ await options.onStderr?.(text);
1136
+ return undefined;
1137
+ }
1138
+ if (!process) return undefined;
1139
+ const started = process;
1140
+ return {
1141
+ interactive: true,
1142
+ write: (data) => started.write(data),
1143
+ closeStdin: () => started.closeStdin(),
1144
+ stdout: started.stdout,
1145
+ closeStdout: () => started.closeStdout(),
1146
+ wait: async () => {
1147
+ const outcome = await started.wait();
1148
+ relay(streamed.decode());
1149
+ await relayed;
1150
+ return finish(outcome);
1151
+ },
1152
+ ...(started.kill ? { kill: () => started.kill?.() } : {}),
1153
+ };
1154
+ }
1155
+ // the whole stdin first, then one run
1156
+ const chunks: Uint8Array[] = [];
1157
+ let ran: Promise<HookOutcome | undefined> | undefined;
1158
+ const runOnce = () => {
1159
+ ran ??= runner.run({ ...invocation, stdin: concat(chunks) }).catch(() => undefined);
1160
+ return ran;
1161
+ };
1162
+ return {
1163
+ interactive: false,
1164
+ write: async (data) => {
1165
+ if (ran) throw new Error("the hook's stdin is closed");
1166
+ chunks.push(data.slice());
1167
+ },
1168
+ closeStdin: async () => {
1169
+ void runOnce();
1170
+ },
1171
+ stdout: {
1172
+ async *[Symbol.asyncIterator]() {
1173
+ const outcome = await runOnce();
1174
+ if (outcome?.stdout.length) yield outcome.stdout;
1175
+ },
1176
+ },
1177
+ closeStdout: () => {},
1178
+ wait: async () => finish(await runOnce()),
1179
+ };
1180
+ }
1181
+
1182
+ /** The invocation of one hook of `name` (see {@link runOne}). */
1183
+ private invocationOf(
1184
+ layout: HookLayout,
1185
+ name: string,
1186
+ toRun: HookToRun,
1187
+ options: HookCallOptions,
1188
+ ): { invocation: HookInvocation; hook: FoundHook } {
1189
+ const cwd = options.dir !== undefined ? normalizeFilesPath(options.dir) : layout.cwd;
1190
+ const hostCwd = hostPathOf(layout.files, cwd);
1191
+ const hook: FoundHook = toRun.kind === "traditional" ? toRun.found : { path: toRun.command };
1192
+ // in another directory (git's opt.dir) the hook is named by its absolute path, else by
1193
+ // its path from that directory
1194
+ const path =
1195
+ toRun.kind === "configured" || options.dir === undefined || hook.path.startsWith("/")
1196
+ ? hook.path
1197
+ : (hook.hostPath ??
1198
+ relativeFilesPath(cwd, hook.filesPath ?? joinFilesPath(layout.cwd, hook.path)));
1199
+ const stdin =
1200
+ options.stdin === undefined
1201
+ ? undefined
1202
+ : typeof options.stdin === "string"
1203
+ ? encoder.encode(options.stdin)
1204
+ : options.stdin;
1205
+ const env: Record<string, string> = {
1206
+ ...(options.prefix === false ? {} : { GIT_PREFIX: "" }),
1207
+ ...(layout.gitDirEnv ? { GIT_DIR: layout.gitDirEnv } : {}),
1208
+ ...this.processEnv,
1209
+ ...(options.env ?? {}),
1210
+ };
1211
+ // the call's own unset variables, then the host's (local_repo_env) the call does not set
1212
+ const unsetEnv = [
1213
+ ...(options.unsetEnv ?? []),
1214
+ ...(this.host.unsetEnv ?? []).filter(
1215
+ (key) => options.env?.[key] === undefined && !options.unsetEnv?.includes(key),
1216
+ ),
1217
+ ];
1218
+ for (const key of unsetEnv) delete env[key];
1219
+ const invocation: HookInvocation = {
1220
+ name,
1221
+ path,
1222
+ ...(hook.hostPath ? { hostPath: hook.hostPath } : {}),
1223
+ args: options.args ?? [],
1224
+ ...(stdin ? { stdin } : {}),
1225
+ env,
1226
+ ...(unsetEnv.length > 0 ? { unsetEnv } : {}),
1227
+ cwd,
1228
+ ...(hostCwd ? { hostCwd } : {}),
1229
+ stdoutToStderr: !options.keepStdout,
1230
+ ...(toRun.kind === "configured" ? { command: toRun.command } : {}),
1231
+ };
1232
+ return { invocation, hook };
1233
+ }
1234
+
1235
+ /** Runs one hook of `name` (see {@link run}). */
1236
+ private async runOne(
1237
+ runner: HookRunner,
1238
+ layout: HookLayout,
1239
+ name: string,
1240
+ toRun: HookToRun,
1241
+ options: HookCallOptions,
1242
+ ): Promise<HookResult | undefined> {
1243
+ const { invocation, hook } = this.invocationOf(layout, name, toRun, options);
1244
+ let outcome: HookOutcome | undefined;
1245
+ try {
1246
+ outcome = await runner.run(invocation);
1247
+ } catch (error) {
1248
+ // git's notify_start_failure: the hook counts as failed
1249
+ this.append(
1250
+ `error: cannot run ${hook.path}: ${String((error as Error)?.message ?? error)}\n`,
1251
+ );
1252
+ return { exitCode: 1, stdout: "", stderr: "" };
1253
+ }
1254
+ if (!outcome) return undefined;
1255
+ const result = {
1256
+ exitCode: outcome.exitCode,
1257
+ stdout: decoder.decode(outcome.stdout),
1258
+ stderr: decoder.decode(outcome.stderr),
1259
+ };
1260
+ this.append(result.stderr);
1261
+ if (result.stdout) this.stdoutChunks.push(result.stdout);
1262
+ return result;
1263
+ }
1264
+ }
1265
+
1266
+ /** git's null object id of the length of `like` (sha1 when none is known). */
1267
+ export function nullIdLike(like?: string): string {
1268
+ return "0".repeat(like?.length === 64 ? 64 : 40);
1269
+ }
1270
+
1271
+ /**
1272
+ * The post-checkout hook (githooks(5)): the HEAD left and the one checked out (git's null id
1273
+ * for none) and `1` for a branch switch, `0` for a path checkout. Its exit code (0 when no
1274
+ * hook ran) becomes the command's exit status in git.
1275
+ */
1276
+ export async function runPostCheckoutHook(
1277
+ hooks: HookSession,
1278
+ oldId: string | undefined,
1279
+ newId: string | undefined,
1280
+ branchSwitch: boolean,
1281
+ env?: Record<string, string>,
1282
+ /** The directory it runs in (a FilesApi path), in place of the worktree top */
1283
+ dir?: string,
1284
+ /** Whether git's setup exported `GIT_PREFIX` (not for clone) */
1285
+ prefix = true,
1286
+ /** Variables the hook runs without (`worktree add`: `GIT_DIR`, `GIT_WORK_TREE`) */
1287
+ unsetEnv?: string[],
1288
+ ): Promise<number> {
1289
+ if (!hooks.enabled) return 0;
1290
+ const like = oldId ?? newId;
1291
+ const result = await hooks.run("post-checkout", {
1292
+ args: [oldId ?? nullIdLike(like), newId ?? nullIdLike(like), branchSwitch ? "1" : "0"],
1293
+ ...(env ? { env } : {}),
1294
+ ...(dir !== undefined ? { dir } : {}),
1295
+ prefix,
1296
+ ...(unsetEnv ? { unsetEnv } : {}),
1297
+ });
1298
+ return result?.exitCode ?? 0;
1299
+ }
1300
+
1301
+ /** What the sequencer's hooks write: `COMMIT_EDITMSG` and the rest of the git directory's state. */
1302
+ export interface SequencerHookState {
1303
+ read(path: string): Promise<string | undefined>;
1304
+ write(path: string, content: string): Promise<void>;
1305
+ }
1306
+
1307
+ /**
1308
+ * try_to_commit's prepare-commit-msg (sequencer.c `run_prepare_commit_msg_hook`): when the
1309
+ * hook exists, the message written to COMMIT_EDITMSG, the hook told `message`, and the file's
1310
+ * text taken back as the commit's message. A failing hook throws git's "'prepare-commit-msg'
1311
+ * hook failed". Without the hook, the message as it is.
1312
+ */
1313
+ export async function sequencerPrepareMessage(
1314
+ hooks: HookSession,
1315
+ state: SequencerHookState,
1316
+ message: string,
1317
+ ): Promise<string> {
1318
+ if (!hooks.enabled || !(await hooks.exists("prepare-commit-msg"))) return message;
1319
+ await state.write("COMMIT_EDITMSG", message);
1320
+ const file = await hooks.gitPath("COMMIT_EDITMSG");
1321
+ const result = await hooks.run("prepare-commit-msg", {
1322
+ args: [file, "message"],
1323
+ env: { GIT_INDEX_FILE: await hooks.gitPath("index"), GIT_EDITOR: ":" },
1324
+ });
1325
+ if (result && result.exitCode !== 0) {
1326
+ throw new HookFailedError(
1327
+ "prepare-commit-msg",
1328
+ result.exitCode,
1329
+ "error: 'prepare-commit-msg' hook failed",
1330
+ hooks.output,
1331
+ );
1332
+ }
1333
+ return (await state.read("COMMIT_EDITMSG")) ?? message;
1334
+ }
1335
+
1336
+ /** try_to_commit's post-commit hook (`run_commit_hook(0, index_file, ..., "post-commit")`). */
1337
+ export async function sequencerPostCommit(hooks: HookSession): Promise<void> {
1338
+ if (!hooks.enabled) return;
1339
+ await hooks.run("post-commit", {
1340
+ env: { GIT_INDEX_FILE: await hooks.gitPath("index"), GIT_EDITOR: ":" },
1341
+ });
1342
+ }
1343
+
1344
+ /**
1345
+ * git's reference-transaction hook (refs.c `run_transaction_hook`) for a ref store's
1346
+ * transactions: told `preparing` (2.5x), `prepared`, `committed` or `aborted` with an
1347
+ * `<old> <new> <ref>` line per update (git 2.43 lists a symbolic ref the update went
1348
+ * through, HEAD, ahead of the ref it names; 2.5x leaves it out); a refusal in `preparing`
1349
+ * or `prepared` aborts the transaction. Calls about a transaction only the other git
1350
+ * version makes (`context.only`) are left out.
1351
+ */
1352
+ export function refTransactionHookOf(
1353
+ hooks: HookSession,
1354
+ /** How the hook runs beyond its state and stdin (the receive side: GIT_DIR, no prefix) */
1355
+ runOptions: Pick<HookCallOptions, "env" | "prefix"> = {},
1356
+ ): RefTransactionHook {
1357
+ return async (state, updates, context) => {
1358
+ const legacy = hooks.compatibility === "2.43";
1359
+ if (context?.only && context.only !== hooks.compatibility) return true;
1360
+ if (state === "preparing" && legacy) return true;
1361
+ const lines: string[] = [];
1362
+ // git 2.43's log-only updates: the symbolic ref asked for keeps its place, the ref it
1363
+ // names and HEAD's line for a ref it names are appended, in order (split_symref_update,
1364
+ // split_head_update)
1365
+ const appended: string[] = [];
1366
+ for (const u of updates) {
1367
+ const zero = nullIdLike(u.new ?? u.old ?? undefined);
1368
+ const next = u.newTarget !== undefined ? `ref:${u.newTarget}` : (u.new ?? zero);
1369
+ const line = (name: string) => `${u.old ?? zero} ${next} ${name}\n`;
1370
+ if (state === "preparing" || context?.asAsked) lines.push(line(u.requested));
1371
+ else if (legacy && u.requested !== u.name) {
1372
+ lines.push(line(u.requested));
1373
+ for (const n of u.through ?? []) appended.push(line(n));
1374
+ appended.push(line(u.name));
1375
+ if (u.viaHead) appended.push(line("HEAD"));
1376
+ } else {
1377
+ lines.push(line(u.name));
1378
+ if (legacy && u.viaHead) appended.push(line("HEAD"));
1379
+ }
1380
+ }
1381
+ const result = await hooks.run("reference-transaction", {
1382
+ ...runOptions,
1383
+ args: [state],
1384
+ stdin: [...lines, ...appended].join(""),
1385
+ });
1386
+ if (!result || result.exitCode === 0 || state === "committed" || state === "aborted") {
1387
+ return true;
1388
+ }
1389
+ // 2.43 dies with one message for every state
1390
+ return legacy ? "ref updates aborted by hook" : false;
1391
+ };
1392
+ }
1393
+
1394
+ /** How a sequencer runs `git commit` (sequencer.c `run_git_commit`), for its hooks. */
1395
+ export interface GitCommitHookRun {
1396
+ /** VERIFY_MSG: pre-commit and commit-msg run (else `git commit -n`) */
1397
+ verify: boolean;
1398
+ /** EDIT_MSG (`-e`): an editor runs, so the hooks get no `GIT_EDITOR=:` */
1399
+ editor: boolean;
1400
+ /** prepare-commit-msg's arguments after the message file (`message`, `commit HEAD`) */
1401
+ hookArgs: string[];
1402
+ /** Variables of the `git commit` run (`GIT_REFLOG_ACTION`) */
1403
+ env?: Record<string, string>;
1404
+ }
1405
+
1406
+ /** The variables of the hooks of a `git commit` run (run_commit_hook). */
1407
+ async function gitCommitHookEnv(
1408
+ hooks: HookSession,
1409
+ run: GitCommitHookRun,
1410
+ index = true,
1411
+ ): Promise<Record<string, string>> {
1412
+ return {
1413
+ ...(index ? { GIT_INDEX_FILE: await hooks.gitPath("index") } : {}),
1414
+ ...(run.editor ? {} : { GIT_EDITOR: ":" }),
1415
+ ...(run.env ?? {}),
1416
+ };
1417
+ }
1418
+
1419
+ /**
1420
+ * The hooks of a `git commit` a sequencer runs, up to the commit (builtin/commit.c
1421
+ * `prepare_to_commit`): pre-commit (with VERIFY_MSG), `template` written to COMMIT_EDITMSG
1422
+ * for prepare-commit-msg, the editor over what it left (`edit`), then commit-msg (with
1423
+ * VERIFY_MSG). The file's text once they ran; a refusing hook throws {@link HookFailedError}.
1424
+ */
1425
+ export async function gitCommitMessageHooks(
1426
+ hooks: HookSession,
1427
+ state: SequencerHookState,
1428
+ template: string,
1429
+ run: GitCommitHookRun,
1430
+ edit: (text: string) => string | Promise<string>,
1431
+ ): Promise<string> {
1432
+ const env = await gitCommitHookEnv(hooks, run);
1433
+ const refuse = async (name: string, args: string[] = []) => {
1434
+ const result = await hooks.run(name, { args, env });
1435
+ if (result && result.exitCode !== 0) {
1436
+ throw new HookFailedError(
1437
+ name,
1438
+ result.exitCode,
1439
+ `the ${name} hook refused the commit (exit code ${result.exitCode})`,
1440
+ hooks.output,
1441
+ );
1442
+ }
1443
+ };
1444
+ if (run.verify) await refuse("pre-commit");
1445
+ await state.write("COMMIT_EDITMSG", template);
1446
+ const file = await hooks.gitPath("COMMIT_EDITMSG");
1447
+ await refuse("prepare-commit-msg", [file, ...run.hookArgs]);
1448
+ const edited = await edit((await state.read("COMMIT_EDITMSG")) ?? template);
1449
+ await state.write("COMMIT_EDITMSG", edited);
1450
+ if (run.verify) await refuse("commit-msg", [file]);
1451
+ return (await state.read("COMMIT_EDITMSG")) ?? edited;
1452
+ }
1453
+
1454
+ /**
1455
+ * The hooks of a `git commit` a sequencer runs, once HEAD has moved: post-commit, then for an
1456
+ * amend post-rewrite told `amend` with `<old> <new>` (commit_post_rewrite).
1457
+ */
1458
+ export async function gitCommitAfterHooks(
1459
+ hooks: HookSession,
1460
+ run: GitCommitHookRun,
1461
+ amended?: { from: string; to: string },
1462
+ ): Promise<void> {
1463
+ if (!hooks.enabled) return;
1464
+ await hooks.run("post-commit", { env: await gitCommitHookEnv(hooks, run) });
1465
+ if (amended) {
1466
+ await hooks.run("post-rewrite", {
1467
+ args: ["amend"],
1468
+ stdin: `${amended.from} ${amended.to}\n`,
1469
+ env: await gitCommitHookEnv(hooks, run, false),
1470
+ });
1471
+ }
1472
+ }