@statewalker/vcs-commands 0.5.0 → 0.7.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 +300 -18
  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 +49 -16
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +134 -0
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/comment-char-config.d.ts +35 -0
  71. package/dist/commands/comment-char-config.d.ts.map +1 -0
  72. package/dist/commands/commit-command.d.ts +311 -17
  73. package/dist/commands/commit-command.d.ts.map +1 -1
  74. package/dist/commands/core-config.d.ts +78 -1
  75. package/dist/commands/core-config.d.ts.map +1 -1
  76. package/dist/commands/date-format.d.ts +58 -0
  77. package/dist/commands/date-format.d.ts.map +1 -0
  78. package/dist/commands/default-branch.d.ts +70 -0
  79. package/dist/commands/default-branch.d.ts.map +1 -0
  80. package/dist/commands/describe-command.d.ts.map +1 -1
  81. package/dist/commands/diff-command.d.ts +377 -30
  82. package/dist/commands/diff-command.d.ts.map +1 -1
  83. package/dist/commands/diff-textconv.d.ts +40 -0
  84. package/dist/commands/diff-textconv.d.ts.map +1 -0
  85. package/dist/commands/fetch-command.d.ts +149 -10
  86. package/dist/commands/fetch-command.d.ts.map +1 -1
  87. package/dist/commands/format-patch-command.d.ts +164 -0
  88. package/dist/commands/format-patch-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  90. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-command.d.ts +227 -0
  92. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-loose.d.ts +71 -0
  94. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  96. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-object-checks.d.ts +159 -0
  98. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  99. package/dist/commands/fsck/fsck-object-table.d.ts +140 -0
  100. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  101. package/dist/commands/fsck/fsck-pack.d.ts +122 -0
  102. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  103. package/dist/commands/fsck/index.d.ts +6 -0
  104. package/dist/commands/fsck/index.d.ts.map +1 -0
  105. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  106. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  107. package/dist/commands/gc-command.d.ts +106 -39
  108. package/dist/commands/gc-command.d.ts.map +1 -1
  109. package/dist/commands/git-date.d.ts +2 -0
  110. package/dist/commands/git-date.d.ts.map +1 -0
  111. package/dist/commands/git-describe.d.ts +67 -0
  112. package/dist/commands/git-describe.d.ts.map +1 -0
  113. package/dist/commands/git-hooks.d.ts +424 -0
  114. package/dist/commands/git-hooks.d.ts.map +1 -0
  115. package/dist/commands/git-ident.d.ts +128 -0
  116. package/dist/commands/git-ident.d.ts.map +1 -0
  117. package/dist/commands/hook-command.d.ts +96 -0
  118. package/dist/commands/hook-command.d.ts.map +1 -0
  119. package/dist/commands/index-adder.d.ts +233 -0
  120. package/dist/commands/index-adder.d.ts.map +1 -0
  121. package/dist/commands/index-host.d.ts +86 -0
  122. package/dist/commands/index-host.d.ts.map +1 -0
  123. package/dist/commands/index.d.ts +56 -0
  124. package/dist/commands/index.d.ts.map +1 -1
  125. package/dist/commands/index.js +3 -2
  126. package/dist/commands/init-command.d.ts +62 -4
  127. package/dist/commands/init-command.d.ts.map +1 -1
  128. package/dist/commands/legacy-remotes.d.ts +55 -0
  129. package/dist/commands/legacy-remotes.d.ts.map +1 -0
  130. package/dist/commands/local-clone.d.ts +60 -0
  131. package/dist/commands/local-clone.d.ts.map +1 -0
  132. package/dist/commands/local-transport.d.ts +117 -0
  133. package/dist/commands/local-transport.d.ts.map +1 -0
  134. package/dist/commands/log-command.d.ts +216 -24
  135. package/dist/commands/log-command.d.ts.map +1 -1
  136. package/dist/commands/log-graph.d.ts +120 -0
  137. package/dist/commands/log-graph.d.ts.map +1 -0
  138. package/dist/commands/log-output.d.ts +323 -0
  139. package/dist/commands/log-output.d.ts.map +1 -0
  140. package/dist/commands/ls-remote-command.d.ts +23 -7
  141. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  142. package/dist/commands/mailmap.d.ts +31 -0
  143. package/dist/commands/mailmap.d.ts.map +1 -0
  144. package/dist/commands/merge-bases.d.ts +85 -0
  145. package/dist/commands/merge-bases.d.ts.map +1 -0
  146. package/dist/commands/merge-command.d.ts +221 -74
  147. package/dist/commands/merge-command.d.ts.map +1 -1
  148. package/dist/commands/merge-config.d.ts +13 -0
  149. package/dist/commands/merge-config.d.ts.map +1 -0
  150. package/dist/commands/merge-drivers.d.ts +130 -0
  151. package/dist/commands/merge-drivers.d.ts.map +1 -0
  152. package/dist/commands/merge-support.d.ts +260 -0
  153. package/dist/commands/merge-support.d.ts.map +1 -0
  154. package/dist/commands/message-cleanup.d.ts +86 -0
  155. package/dist/commands/message-cleanup.d.ts.map +1 -0
  156. package/dist/commands/mv-command.d.ts +94 -0
  157. package/dist/commands/mv-command.d.ts.map +1 -0
  158. package/dist/commands/notes-command.d.ts +256 -0
  159. package/dist/commands/notes-command.d.ts.map +1 -0
  160. package/dist/commands/notes-commands.d.ts +41 -0
  161. package/dist/commands/notes-commands.d.ts.map +1 -0
  162. package/dist/commands/notes-merge-command.d.ts +105 -0
  163. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  164. package/dist/commands/notes-support.d.ts +125 -0
  165. package/dist/commands/notes-support.d.ts.map +1 -0
  166. package/dist/commands/notes-tree.d.ts +116 -0
  167. package/dist/commands/notes-tree.d.ts.map +1 -0
  168. package/dist/commands/object-id-input.d.ts +20 -0
  169. package/dist/commands/object-id-input.d.ts.map +1 -0
  170. package/dist/commands/octopus-merge.d.ts +59 -0
  171. package/dist/commands/octopus-merge.d.ts.map +1 -0
  172. package/dist/commands/ort-merge.d.ts +126 -0
  173. package/dist/commands/ort-merge.d.ts.map +1 -0
  174. package/dist/commands/ort-recursive.d.ts +53 -0
  175. package/dist/commands/ort-recursive.d.ts.map +1 -0
  176. package/dist/commands/pack-refs-command.d.ts +20 -0
  177. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  178. package/dist/commands/patch-id.d.ts +44 -0
  179. package/dist/commands/patch-id.d.ts.map +1 -0
  180. package/dist/commands/pathspec-attributes.d.ts +64 -0
  181. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  182. package/dist/commands/pathspec.d.ts +324 -0
  183. package/dist/commands/pathspec.d.ts.map +1 -0
  184. package/dist/commands/post-index-change.d.ts +33 -0
  185. package/dist/commands/post-index-change.d.ts.map +1 -0
  186. package/dist/commands/pretty-format.d.ts +222 -0
  187. package/dist/commands/pretty-format.d.ts.map +1 -0
  188. package/dist/commands/promisor-remote.d.ts +80 -0
  189. package/dist/commands/promisor-remote.d.ts.map +1 -0
  190. package/dist/commands/pull-command.d.ts +59 -8
  191. package/dist/commands/pull-command.d.ts.map +1 -1
  192. package/dist/commands/push-command.d.ts +24 -8
  193. package/dist/commands/push-command.d.ts.map +1 -1
  194. package/dist/commands/read-tree-command.d.ts +112 -0
  195. package/dist/commands/read-tree-command.d.ts.map +1 -0
  196. package/dist/commands/rebase-command.d.ts +507 -75
  197. package/dist/commands/rebase-command.d.ts.map +1 -1
  198. package/dist/commands/rebase-todo.d.ts +130 -0
  199. package/dist/commands/rebase-todo.d.ts.map +1 -0
  200. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  201. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  202. package/dist/commands/reflog-messages.d.ts +98 -0
  203. package/dist/commands/reflog-messages.d.ts.map +1 -0
  204. package/dist/commands/remote-command.d.ts +31 -0
  205. package/dist/commands/remote-command.d.ts.map +1 -1
  206. package/dist/commands/remote-transport.d.ts +120 -0
  207. package/dist/commands/remote-transport.d.ts.map +1 -0
  208. package/dist/commands/reset-command.d.ts +161 -7
  209. package/dist/commands/reset-command.d.ts.map +1 -1
  210. package/dist/commands/restore-command.d.ts +103 -0
  211. package/dist/commands/restore-command.d.ts.map +1 -0
  212. package/dist/commands/rev-list-command.d.ts +78 -0
  213. package/dist/commands/rev-list-command.d.ts.map +1 -0
  214. package/dist/commands/rev-parse-command.d.ts +89 -0
  215. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  216. package/dist/commands/revert-command.d.ts +46 -38
  217. package/dist/commands/revert-command.d.ts.map +1 -1
  218. package/dist/commands/revision-filenames.d.ts +95 -0
  219. package/dist/commands/revision-filenames.d.ts.map +1 -0
  220. package/dist/commands/revision-range.d.ts +67 -0
  221. package/dist/commands/revision-range.d.ts.map +1 -0
  222. package/dist/commands/revision-resolver.d.ts +325 -0
  223. package/dist/commands/revision-resolver.d.ts.map +1 -0
  224. package/dist/commands/rm-command.d.ts +69 -7
  225. package/dist/commands/rm-command.d.ts.map +1 -1
  226. package/dist/commands/sequencer-pick.d.ts +191 -0
  227. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  228. package/dist/commands/sequencer-support.d.ts +125 -0
  229. package/dist/commands/sequencer-support.d.ts.map +1 -0
  230. package/dist/commands/serve-repository.d.ts +52 -0
  231. package/dist/commands/serve-repository.d.ts.map +1 -0
  232. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  233. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  234. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  235. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  236. package/dist/commands/stash-apply-command.d.ts +42 -8
  237. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  238. package/dist/commands/stash-create-command.d.ts +156 -2
  239. package/dist/commands/stash-create-command.d.ts.map +1 -1
  240. package/dist/commands/stash-drop-command.d.ts +2 -0
  241. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  242. package/dist/commands/stash-working-tree.d.ts +23 -0
  243. package/dist/commands/stash-working-tree.d.ts.map +1 -1
  244. package/dist/commands/status-command.d.ts +300 -15
  245. package/dist/commands/status-command.d.ts.map +1 -1
  246. package/dist/commands/status-format.d.ts +155 -0
  247. package/dist/commands/status-format.d.ts.map +1 -0
  248. package/dist/commands/status-header.d.ts +64 -0
  249. package/dist/commands/status-header.d.ts.map +1 -0
  250. package/dist/commands/strerror.d.ts +7 -0
  251. package/dist/commands/strerror.d.ts.map +1 -0
  252. package/dist/commands/submodule-config.d.ts +38 -0
  253. package/dist/commands/submodule-config.d.ts.map +1 -0
  254. package/dist/commands/submodule-summary-command.d.ts +80 -0
  255. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  256. package/dist/commands/submodule-summary.d.ts +150 -0
  257. package/dist/commands/submodule-summary.d.ts.map +1 -0
  258. package/dist/commands/switch-command.d.ts +132 -0
  259. package/dist/commands/switch-command.d.ts.map +1 -0
  260. package/dist/commands/tag-command.d.ts +23 -2
  261. package/dist/commands/tag-command.d.ts.map +1 -1
  262. package/dist/commands/tracking-info.d.ts +64 -0
  263. package/dist/commands/tracking-info.d.ts.map +1 -0
  264. package/dist/commands/trailers.d.ts +73 -0
  265. package/dist/commands/trailers.d.ts.map +1 -0
  266. package/dist/commands/tree-restore.d.ts +85 -1
  267. package/dist/commands/tree-restore.d.ts.map +1 -1
  268. package/dist/commands/untracked-cache-support.d.ts +54 -0
  269. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  270. package/dist/commands/worktree-add-command.d.ts +108 -0
  271. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-list-command.d.ts +69 -0
  273. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  274. package/dist/commands/worktree-lock-command.d.ts +44 -0
  275. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-overwrite-checks.d.ts +146 -6
  277. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  278. package/dist/commands/worktree-prune-command.d.ts +48 -0
  279. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-remove-command.d.ts +59 -0
  281. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  282. package/dist/commands/worktree-repair-command.d.ts +35 -0
  283. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  284. package/dist/commands/worktree-support.d.ts +64 -0
  285. package/dist/commands/worktree-support.d.ts.map +1 -0
  286. package/dist/commands-DIJ91NnD.js +62225 -0
  287. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  288. package/dist/errors/add-errors.d.ts +55 -0
  289. package/dist/errors/add-errors.d.ts.map +1 -1
  290. package/dist/errors/checkout-errors.d.ts +16 -0
  291. package/dist/errors/checkout-errors.d.ts.map +1 -1
  292. package/dist/errors/command-errors.d.ts +77 -0
  293. package/dist/errors/command-errors.d.ts.map +1 -1
  294. package/dist/errors/commit-errors.d.ts +9 -0
  295. package/dist/errors/commit-errors.d.ts.map +1 -1
  296. package/dist/errors/git-api-error.d.ts +59 -2
  297. package/dist/errors/git-api-error.d.ts.map +1 -1
  298. package/dist/errors/index.d.ts +1 -0
  299. package/dist/errors/index.d.ts.map +1 -1
  300. package/dist/errors/index.js +354 -19
  301. package/dist/errors/rebase-errors.d.ts +9 -0
  302. package/dist/errors/rebase-errors.d.ts.map +1 -1
  303. package/dist/errors/ref-errors.d.ts +32 -0
  304. package/dist/errors/ref-errors.d.ts.map +1 -1
  305. package/dist/errors/transport-errors.d.ts +12 -2
  306. package/dist/errors/transport-errors.d.ts.map +1 -1
  307. package/dist/errors/worktree-errors.d.ts +35 -0
  308. package/dist/errors/worktree-errors.d.ts.map +1 -0
  309. package/dist/git-command-BGiOJ8Zk.js +7246 -0
  310. package/dist/git-command.d.ts +428 -32
  311. package/dist/git-command.d.ts.map +1 -1
  312. package/dist/git.d.ts +315 -5
  313. package/dist/git.d.ts.map +1 -1
  314. package/dist/index.d.ts +1 -1
  315. package/dist/index.d.ts.map +1 -1
  316. package/dist/index.js +5 -5
  317. package/dist/remote-config/index.d.ts +1 -1
  318. package/dist/remote-config/index.d.ts.map +1 -1
  319. package/dist/remote-config/remote-config-store.d.ts +167 -6
  320. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  321. package/dist/remote-config/remote-refs.d.ts +7 -3
  322. package/dist/remote-config/remote-refs.d.ts.map +1 -1
  323. package/dist/rename/detect-renames.d.ts +148 -0
  324. package/dist/rename/detect-renames.d.ts.map +1 -0
  325. package/dist/rename/git-similarity.d.ts +44 -0
  326. package/dist/rename/git-similarity.d.ts.map +1 -0
  327. package/dist/rename/index.d.ts +2 -0
  328. package/dist/rename/index.d.ts.map +1 -1
  329. package/dist/results/binary-patch.d.ts +11 -0
  330. package/dist/results/binary-patch.d.ts.map +1 -0
  331. package/dist/results/blame-format.d.ts +55 -0
  332. package/dist/results/blame-format.d.ts.map +1 -0
  333. package/dist/results/cherry-pick-result.d.ts +10 -0
  334. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  335. package/dist/results/clone-result.d.ts +18 -0
  336. package/dist/results/clone-result.d.ts.map +1 -1
  337. package/dist/results/combined-diff.d.ts +77 -0
  338. package/dist/results/combined-diff.d.ts.map +1 -0
  339. package/dist/results/diff-entry.d.ts +32 -0
  340. package/dist/results/diff-entry.d.ts.map +1 -1
  341. package/dist/results/diff-formatter.d.ts +34 -60
  342. package/dist/results/diff-formatter.d.ts.map +1 -1
  343. package/dist/results/diff-order.d.ts +25 -0
  344. package/dist/results/diff-order.d.ts.map +1 -0
  345. package/dist/results/diff-output.d.ts +249 -0
  346. package/dist/results/diff-output.d.ts.map +1 -0
  347. package/dist/results/fetch-result.d.ts +15 -0
  348. package/dist/results/fetch-result.d.ts.map +1 -1
  349. package/dist/results/index.d.ts +5 -0
  350. package/dist/results/index.d.ts.map +1 -1
  351. package/dist/results/index.js +2 -252
  352. package/dist/results/init-result.d.ts +7 -0
  353. package/dist/results/init-result.d.ts.map +1 -1
  354. package/dist/results/merge-result.d.ts +15 -1
  355. package/dist/results/merge-result.d.ts.map +1 -1
  356. package/dist/results/pull-result.d.ts +17 -3
  357. package/dist/results/pull-result.d.ts.map +1 -1
  358. package/dist/results/push-result.d.ts +47 -0
  359. package/dist/results/push-result.d.ts.map +1 -1
  360. package/dist/results/quote-path.d.ts +27 -0
  361. package/dist/results/quote-path.d.ts.map +1 -0
  362. package/dist/results/rebase-result.d.ts +28 -1
  363. package/dist/results/rebase-result.d.ts.map +1 -1
  364. package/dist/results/revert-result.d.ts +10 -0
  365. package/dist/results/revert-result.d.ts.map +1 -1
  366. package/dist/results/stash-result.d.ts +5 -0
  367. package/dist/results/stash-result.d.ts.map +1 -1
  368. package/dist/results/status-result.d.ts +60 -6
  369. package/dist/results/status-result.d.ts.map +1 -1
  370. package/dist/results-WVlBhVb1.js +2935 -0
  371. package/dist/transport-command.d.ts +44 -1
  372. package/dist/transport-command.d.ts.map +1 -1
  373. package/package.json +15 -11
  374. package/src/commands/add-command.ts +1291 -226
  375. package/src/commands/add-patch/add-interactive.ts +941 -0
  376. package/src/commands/add-patch/add-patch.ts +1169 -0
  377. package/src/commands/add-patch/index.ts +5 -0
  378. package/src/commands/add-patch/patch-backend.ts +239 -0
  379. package/src/commands/add-patch/patch-modes.ts +249 -0
  380. package/src/commands/add-patch/patch-session.ts +159 -0
  381. package/src/commands/am/am-command.ts +1111 -0
  382. package/src/commands/am/index.ts +2 -0
  383. package/src/commands/am/mailinfo.ts +1015 -0
  384. package/src/commands/am/patch-format.ts +121 -0
  385. package/src/commands/apply/apply-command.ts +842 -0
  386. package/src/commands/apply/apply-engine.ts +1602 -0
  387. package/src/commands/apply/apply-parse.ts +1210 -0
  388. package/src/commands/apply/apply-types.ts +112 -0
  389. package/src/commands/apply/index.ts +5 -0
  390. package/src/commands/apply/latin1.ts +171 -0
  391. package/src/commands/apply/whitespace.ts +260 -0
  392. package/src/commands/attributes-source.ts +96 -0
  393. package/src/commands/backfill-command.ts +694 -0
  394. package/src/commands/bisect/bisect-checkout.ts +217 -0
  395. package/src/commands/bisect/bisect-command.ts +788 -0
  396. package/src/commands/bisect/bisect-engine.ts +1080 -0
  397. package/src/commands/bisect/bisect-graph.ts +595 -0
  398. package/src/commands/bisect/bisect-quote.ts +92 -0
  399. package/src/commands/bisect/index.ts +4 -0
  400. package/src/commands/blame-command.ts +711 -986
  401. package/src/commands/branch-command.ts +354 -32
  402. package/src/commands/branch-tracking.ts +331 -0
  403. package/src/commands/checkout-command.ts +1290 -243
  404. package/src/commands/checkout-paths.ts +784 -0
  405. package/src/commands/cherry-pick-command.ts +156 -396
  406. package/src/commands/clean-command.ts +504 -156
  407. package/src/commands/clone-command.ts +748 -69
  408. package/src/commands/comment-char-config.ts +160 -0
  409. package/src/commands/commit-command.ts +1782 -166
  410. package/src/commands/core-config.ts +166 -6
  411. package/src/commands/date-format.ts +668 -0
  412. package/src/commands/default-branch.ts +196 -0
  413. package/src/commands/describe-command.ts +2 -0
  414. package/src/commands/diff-command.ts +1916 -110
  415. package/src/commands/diff-textconv.ts +50 -0
  416. package/src/commands/fetch-command.ts +622 -68
  417. package/src/commands/format-patch-command.ts +974 -0
  418. package/src/commands/fsck/fetch-fsck.ts +229 -0
  419. package/src/commands/fsck/fsck-command.ts +3464 -0
  420. package/src/commands/fsck/fsck-loose.ts +297 -0
  421. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  422. package/src/commands/fsck/fsck-object-checks.ts +1085 -0
  423. package/src/commands/fsck/fsck-object-table.ts +373 -0
  424. package/src/commands/fsck/fsck-pack.ts +634 -0
  425. package/src/commands/fsck/index.ts +5 -0
  426. package/src/commands/fsck/verify-pack-command.ts +252 -0
  427. package/src/commands/gc-command.ts +324 -77
  428. package/src/commands/git-date.ts +9 -0
  429. package/src/commands/git-describe.ts +316 -0
  430. package/src/commands/git-hooks.ts +1483 -0
  431. package/src/commands/git-ident.ts +344 -0
  432. package/src/commands/hook-command.ts +247 -0
  433. package/src/commands/index-adder.ts +711 -0
  434. package/src/commands/index-host.ts +291 -0
  435. package/src/commands/index.ts +84 -0
  436. package/src/commands/init-command.ts +194 -14
  437. package/src/commands/legacy-remotes.ts +224 -0
  438. package/src/commands/local-clone.ts +183 -0
  439. package/src/commands/local-transport.ts +762 -0
  440. package/src/commands/log-command.ts +1930 -170
  441. package/src/commands/log-graph.ts +671 -0
  442. package/src/commands/log-output.ts +1359 -0
  443. package/src/commands/ls-remote-command.ts +105 -58
  444. package/src/commands/mailmap.ts +129 -0
  445. package/src/commands/merge-bases.ts +296 -0
  446. package/src/commands/merge-command.ts +1416 -491
  447. package/src/commands/merge-config.ts +25 -0
  448. package/src/commands/merge-drivers.ts +306 -0
  449. package/src/commands/merge-support.ts +1219 -0
  450. package/src/commands/message-cleanup.ts +275 -0
  451. package/src/commands/mv-command.ts +976 -0
  452. package/src/commands/notes-command.ts +890 -0
  453. package/src/commands/notes-commands.ts +87 -0
  454. package/src/commands/notes-merge-command.ts +777 -0
  455. package/src/commands/notes-support.ts +402 -0
  456. package/src/commands/notes-tree.ts +617 -0
  457. package/src/commands/object-id-input.ts +27 -0
  458. package/src/commands/octopus-merge.ts +378 -0
  459. package/src/commands/ort-merge.ts +1660 -0
  460. package/src/commands/ort-recursive.ts +160 -0
  461. package/src/commands/pack-refs-command.ts +39 -22
  462. package/src/commands/patch-id.ts +204 -0
  463. package/src/commands/pathspec-attributes.ts +162 -0
  464. package/src/commands/pathspec.ts +1199 -0
  465. package/src/commands/post-index-change.ts +62 -0
  466. package/src/commands/pretty-format.ts +1432 -0
  467. package/src/commands/promisor-remote.ts +298 -0
  468. package/src/commands/pull-command.ts +326 -33
  469. package/src/commands/push-command.ts +257 -29
  470. package/src/commands/read-tree-command.ts +861 -0
  471. package/src/commands/rebase-command.ts +3820 -372
  472. package/src/commands/rebase-todo.ts +584 -0
  473. package/src/commands/ref-decoration-filter.ts +118 -0
  474. package/src/commands/reflog-messages.ts +177 -0
  475. package/src/commands/remote-command.ts +124 -23
  476. package/src/commands/remote-transport.ts +383 -0
  477. package/src/commands/reset-command.ts +821 -104
  478. package/src/commands/restore-command.ts +350 -0
  479. package/src/commands/rev-list-command.ts +167 -0
  480. package/src/commands/rev-parse-command.ts +299 -0
  481. package/src/commands/revert-command.ts +152 -399
  482. package/src/commands/revision-filenames.ts +254 -0
  483. package/src/commands/revision-range.ts +222 -0
  484. package/src/commands/revision-resolver.ts +1397 -0
  485. package/src/commands/rm-command.ts +613 -67
  486. package/src/commands/sequencer-pick.ts +874 -0
  487. package/src/commands/sequencer-support.ts +876 -0
  488. package/src/commands/serve-repository.ts +125 -0
  489. package/src/commands/sparse-checkout-command.ts +1389 -0
  490. package/src/commands/sparse-checkout-support.ts +793 -0
  491. package/src/commands/stash-apply-command.ts +376 -343
  492. package/src/commands/stash-create-command.ts +625 -42
  493. package/src/commands/stash-drop-command.ts +15 -2
  494. package/src/commands/stash-working-tree.ts +168 -24
  495. package/src/commands/status-command.ts +1326 -105
  496. package/src/commands/status-format.ts +775 -0
  497. package/src/commands/status-header.ts +332 -0
  498. package/src/commands/strerror.ts +29 -0
  499. package/src/commands/submodule-config.ts +94 -0
  500. package/src/commands/submodule-summary-command.ts +333 -0
  501. package/src/commands/submodule-summary.ts +446 -0
  502. package/src/commands/switch-command.ts +402 -0
  503. package/src/commands/tag-command.ts +129 -41
  504. package/src/commands/tracking-info.ts +201 -0
  505. package/src/commands/trailers.ts +417 -0
  506. package/src/commands/tree-restore.ts +204 -4
  507. package/src/commands/untracked-cache-support.ts +198 -0
  508. package/src/commands/worktree-add-command.ts +458 -0
  509. package/src/commands/worktree-list-command.ts +206 -0
  510. package/src/commands/worktree-lock-command.ts +96 -0
  511. package/src/commands/worktree-overwrite-checks.ts +452 -26
  512. package/src/commands/worktree-prune-command.ts +99 -0
  513. package/src/commands/worktree-remove-command.ts +186 -0
  514. package/src/commands/worktree-repair-command.ts +59 -0
  515. package/src/commands/worktree-support.ts +214 -0
  516. package/src/core-commands/add.command.impl.ts +8 -2
  517. package/src/errors/add-errors.ts +45 -0
  518. package/src/errors/checkout-errors.ts +26 -2
  519. package/src/errors/command-errors.ts +101 -1
  520. package/src/errors/commit-errors.ts +18 -2
  521. package/src/errors/git-api-error.ts +82 -2
  522. package/src/errors/index.ts +1 -0
  523. package/src/errors/merge-errors.ts +2 -2
  524. package/src/errors/rebase-errors.ts +12 -0
  525. package/src/errors/ref-errors.ts +56 -2
  526. package/src/errors/remote-errors.ts +2 -2
  527. package/src/errors/stash-errors.ts +1 -1
  528. package/src/errors/transport-errors.ts +20 -4
  529. package/src/errors/worktree-errors.ts +49 -0
  530. package/src/git-command.ts +1207 -118
  531. package/src/git.ts +538 -12
  532. package/src/index.ts +1 -1
  533. package/src/remote-config/index.ts +2 -0
  534. package/src/remote-config/remote-config-store.ts +378 -18
  535. package/src/remote-config/remote-refs.ts +22 -6
  536. package/src/rename/detect-renames.ts +715 -0
  537. package/src/rename/git-similarity.ts +116 -0
  538. package/src/rename/index.ts +2 -0
  539. package/src/results/binary-patch.ts +401 -0
  540. package/src/results/blame-format.ts +239 -0
  541. package/src/results/cherry-pick-result.ts +10 -0
  542. package/src/results/clone-result.ts +21 -0
  543. package/src/results/combined-diff.ts +585 -0
  544. package/src/results/diff-entry.ts +35 -0
  545. package/src/results/diff-formatter.ts +152 -288
  546. package/src/results/diff-order.ts +64 -0
  547. package/src/results/diff-output.ts +1053 -0
  548. package/src/results/fetch-result.ts +15 -0
  549. package/src/results/index.ts +5 -0
  550. package/src/results/init-result.ts +9 -0
  551. package/src/results/merge-result.ts +15 -1
  552. package/src/results/pull-result.ts +17 -3
  553. package/src/results/push-result.ts +48 -0
  554. package/src/results/quote-path.ts +103 -0
  555. package/src/results/rebase-result.ts +37 -0
  556. package/src/results/revert-result.ts +10 -0
  557. package/src/results/stash-result.ts +6 -0
  558. package/src/results/status-result.ts +127 -46
  559. package/src/transport-command.ts +121 -2
  560. package/dist/commands-CsLNyvZ1.js +0 -12587
  561. package/dist/status-result-BpyUK1Sg.js +0 -519
@@ -1,10 +1,29 @@
1
- import type { Commit, ObjectId, PersonIdent } from "@statewalker/vcs-core";
2
- import { isSymbolicRef } from "@statewalker/vcs-core";
3
- import type { Worktree } from "@statewalker/vcs-working-tree";
1
+ import {
2
+ type Commit,
3
+ FileMode,
4
+ type ObjectId,
5
+ type PersonIdent,
6
+ type TreeEntry,
7
+ } from "@statewalker/vcs-core";
8
+ import { FileStagingStore } from "@statewalker/vcs-store-files";
9
+ import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
10
+ import type { FilesApi } from "@statewalker/vcs-utils/files";
11
+ import {
12
+ expandUserPath,
13
+ type Staging,
14
+ type StagingEntry,
15
+ type StagingIndexLock,
16
+ type Worktree,
17
+ type WorktreeEntry,
18
+ } from "@statewalker/vcs-working-tree";
4
19
 
5
20
  import {
6
21
  EmptyCommitError,
22
+ GitApiError,
23
+ HookFailedError,
7
24
  IncompatibleOptionsError,
25
+ IndexLockFailedError,
26
+ InvalidArgumentError,
8
27
  NoHeadError,
9
28
  NoMessageError,
10
29
  RefNotFoundError,
@@ -12,7 +31,49 @@ import {
12
31
  UnmergedPathsError,
13
32
  } from "../errors/index.js";
14
33
  import { GitCommand } from "../git-command.js";
34
+ import { RemoteConfigStore } from "../remote-config/index.js";
15
35
  import { AddCommand } from "./add-command.js";
36
+ import { worktreeModeTrust } from "./core-config.js";
37
+ import { DEFAULT_DATE_MODE, showDate } from "./date-format.js";
38
+ import { hostEnvironmentOf, withoutCrud } from "./git-ident.js";
39
+ import { IndexAdder, readGitlinkHead } from "./index-adder.js";
40
+ import {
41
+ flatTree,
42
+ OperationState,
43
+ updateIndexCacheTree,
44
+ writeIndexAsTree,
45
+ } from "./merge-support.js";
46
+ import {
47
+ CleanupMode,
48
+ cleanupWith,
49
+ commentPrefixOf,
50
+ commitCleanupMode,
51
+ completeLine,
52
+ editorCleanupMode,
53
+ stripspace,
54
+ } from "./message-cleanup.js";
55
+ import { copyNotesForAmend } from "./notes-support.js";
56
+ import { canonicalObjectId } from "./object-id-input.js";
57
+ import {
58
+ DO_MATCH_DIRECTORY,
59
+ matchPathspecSeen,
60
+ type PathspecItem,
61
+ parsePathspec,
62
+ pathspecErrors,
63
+ pathspecItemMayMatch,
64
+ } from "./pathspec.js";
65
+ import { PathspecAttributes } from "./pathspec-attributes.js";
66
+ import { type CommitReflogKind, reflogMessages, updateHead } from "./reflog-messages.js";
67
+ import { applyAutostash } from "./sequencer-support.js";
68
+ import {
69
+ cutLine,
70
+ readShowUntrackedFiles,
71
+ StatusCommand,
72
+ type StatusTextResult,
73
+ type UntrackedFilesMode,
74
+ } from "./status-command.js";
75
+ import { type CommitWhence, StatusPrinter } from "./status-format.js";
76
+ import { readDiffSubmoduleConfig } from "./submodule-summary.js";
16
77
 
17
78
  /**
18
79
  * Result of a commit operation.
@@ -25,20 +86,6 @@ export interface CommitResult extends Commit {
25
86
  id: ObjectId;
26
87
  }
27
88
 
28
- /**
29
- * Get current timezone offset as string (+HHMM or -HHMM).
30
- */
31
- function getTimezoneOffset(): string {
32
- const offset = new Date().getTimezoneOffset();
33
- const sign = offset <= 0 ? "+" : "-";
34
- const absOffset = Math.abs(offset);
35
- const hours = Math.floor(absOffset / 60)
36
- .toString()
37
- .padStart(2, "0");
38
- const minutes = (absOffset % 60).toString().padStart(2, "0");
39
- return `${sign}${hours}${minutes}`;
40
- }
41
-
42
89
  /**
43
90
  * Create a commit from staged changes.
44
91
  *
@@ -89,15 +136,38 @@ export class CommitCommand extends GitCommand<CommitResult> {
89
136
  private message?: string;
90
137
  private author?: PersonIdent;
91
138
  private committer?: PersonIdent;
139
+ /** `--author=<name> <email>`: dated when the commit is made */
140
+ private authorName?: { name: string; email: string };
141
+ /** A committer named without a date, dated when the commit is made */
142
+ private committerName?: { name: string; email: string };
143
+ private resetAuthor = false;
92
144
  private amend = false;
145
+ private noPostRewrite = false;
146
+ private noVerify = false;
93
147
  private allowEmpty = false;
94
148
  private parents: ObjectId[] = [];
95
149
  private onlyPaths: string[] = [];
96
150
  private all = false;
151
+ private include = false;
152
+ private includePaths: string[] = [];
97
153
  private worktreeIterator: Worktree | undefined;
154
+ private cleanupMode?: CleanupMode;
155
+ private allowEmptyMessage = false;
156
+ private editor?: CommitEditor;
157
+ private edit?: boolean;
158
+ private includeStatus?: boolean;
159
+ private verbose?: number;
160
+ private untrackedMode?: UntrackedFilesMode;
161
+ private statusFormat?: "long" | "short" | "porcelain";
162
+ private showBranch?: boolean;
163
+ private nullTermination = false;
164
+ private aheadBehind?: boolean;
165
+ private templateFile?: string;
98
166
 
99
167
  /**
100
- * Set the commit message.
168
+ * Set the commit message, as git's `commit -m` takes it: its last line is ended and it is
169
+ * cleaned up (`whitespace` by default, see {@link setCleanupMode}), so `"Fix"` is stored
170
+ * as `"Fix\n"` and the commit gets native git's id.
101
171
  *
102
172
  * @param message Commit message
103
173
  */
@@ -107,6 +177,49 @@ export class CommitCommand extends GitCommand<CommitResult> {
107
177
  return this;
108
178
  }
109
179
 
180
+ /**
181
+ * Add a paragraph to the message, as each further `-m` of `git commit` does: the
182
+ * message so far gets its last line ended and a blank line, then this one (`-m a -m b`
183
+ * is `"a\n\nb\n"`). The first call is {@link setMessage}.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * await git.commit().addMessage("Subject").addMessage("Body paragraph.").call();
188
+ * ```
189
+ *
190
+ * @param message One paragraph of the commit message
191
+ */
192
+ addMessage(message: string): this {
193
+ this.checkCallable();
194
+ // git's opt_parse_m: a newline before the next -m only when the buffer holds something
195
+ this.message = !this.message
196
+ ? message
197
+ : `${this.message}${this.message.endsWith("\n") ? "" : "\n"}\n${message}`;
198
+ return this;
199
+ }
200
+
201
+ /**
202
+ * How the message is cleaned up (git's `--cleanup=<mode>`; default `commit.cleanup`, else
203
+ * `default`, which without an editor is `whitespace`: trailing whitespace and surrounding
204
+ * blank lines dropped, blank runs collapsed). `strip` also drops comment lines;
205
+ * `verbatim` keeps the message as given (with its last line ended, as `-m` does).
206
+ */
207
+ setCleanupMode(mode: CleanupMode): this {
208
+ this.checkCallable();
209
+ this.cleanupMode = mode;
210
+ return this;
211
+ }
212
+
213
+ /**
214
+ * Allow a message that is empty after its cleanup (git's `--allow-empty-message`);
215
+ * without it such a commit is refused: `Aborting commit due to empty commit message.`
216
+ */
217
+ setAllowEmptyMessage(allow: boolean): this {
218
+ this.checkCallable();
219
+ this.allowEmptyMessage = allow;
220
+ return this;
221
+ }
222
+
110
223
  /**
111
224
  * Set the author identity.
112
225
  *
@@ -115,12 +228,10 @@ export class CommitCommand extends GitCommand<CommitResult> {
115
228
  */
116
229
  setAuthor(name: string, email: string): this {
117
230
  this.checkCallable();
118
- this.author = {
119
- name,
120
- email,
121
- timestamp: Math.floor(Date.now() / 1000),
122
- tzOffset: getTimezoneOffset(),
123
- };
231
+ // git's --author: the name and email; the date is the amended commit's, the picked
232
+ // commit's, else GIT_AUTHOR_DATE or now
233
+ this.author = undefined;
234
+ this.authorName = { name, email };
124
235
  return this;
125
236
  }
126
237
 
@@ -131,6 +242,7 @@ export class CommitCommand extends GitCommand<CommitResult> {
131
242
  */
132
243
  setAuthorIdent(author: PersonIdent): this {
133
244
  this.checkCallable();
245
+ this.authorName = undefined;
134
246
  this.author = author;
135
247
  return this;
136
248
  }
@@ -143,12 +255,9 @@ export class CommitCommand extends GitCommand<CommitResult> {
143
255
  */
144
256
  setCommitter(name: string, email: string): this {
145
257
  this.checkCallable();
146
- this.committer = {
147
- name,
148
- email,
149
- timestamp: Math.floor(Date.now() / 1000),
150
- tzOffset: getTimezoneOffset(),
151
- };
258
+ // dated as git dates the committer: GIT_COMMITTER_DATE, else now
259
+ this.committer = undefined;
260
+ this.committerName = { name, email };
152
261
  return this;
153
262
  }
154
263
 
@@ -159,10 +268,44 @@ export class CommitCommand extends GitCommand<CommitResult> {
159
268
  */
160
269
  setCommitterIdent(committer: PersonIdent): this {
161
270
  this.checkCallable();
271
+ this.committerName = undefined;
162
272
  this.committer = committer;
163
273
  return this;
164
274
  }
165
275
 
276
+ /**
277
+ * `--reset-author`: an amended commit, or the commit that concludes a cherry-pick, is
278
+ * authored as a new one (the author resolved as git resolves it, dated now) instead of
279
+ * keeping the earlier commit's author.
280
+ *
281
+ * @param reset Whether to reset the author
282
+ */
283
+ setResetAuthor(reset: boolean): this {
284
+ this.checkCallable();
285
+ this.resetAuthor = reset;
286
+ return this;
287
+ }
288
+
289
+ /**
290
+ * `--no-post-rewrite`: an amend does not carry the amended commit's notes over to the new
291
+ * one (`notes.rewriteRef`, `notes.rewrite.amend`), as git skips its post-rewrite step.
292
+ */
293
+ setNoPostRewrite(noPostRewrite: boolean): this {
294
+ this.checkCallable();
295
+ this.noPostRewrite = noPostRewrite;
296
+ return this;
297
+ }
298
+
299
+ /**
300
+ * `-n` / `--no-verify`: the `pre-commit` and `commit-msg` hooks do not run
301
+ * (`prepare-commit-msg` and `post-commit` still do, as in git).
302
+ */
303
+ setNoVerify(noVerify: boolean): this {
304
+ this.checkCallable();
305
+ this.noVerify = noVerify;
306
+ return this;
307
+ }
308
+
166
309
  /**
167
310
  * Set whether to amend the previous commit.
168
311
  *
@@ -195,16 +338,30 @@ export class CommitCommand extends GitCommand<CommitResult> {
195
338
  */
196
339
  setParentIds(...parents: ObjectId[]): this {
197
340
  this.checkCallable();
198
- this.parents = parents;
341
+ this.parents = parents.map(canonicalObjectId);
199
342
  return this;
200
343
  }
201
344
 
202
345
  /**
203
- * Set paths to commit (--only mode).
346
+ * Set paths to commit (`git commit --only <paths>`, git's partial commit).
204
347
  *
205
- * When set, only the specified paths are taken from the staging area.
206
- * All other paths are taken from the parent commit's tree. This allows
207
- * partial commits without affecting unstaged changes to other files.
348
+ * The paths are a pathspec, as git reads it (`d/`, `*.md`, `:(glob)d/**`, `:!d/x`,
349
+ * `./a`). As git's `prepare_index`: the index entries (any stage) and HEAD's files the
350
+ * pathspec matches are listed (`list_paths`); an element that matches none of them fails
351
+ * with git's "error: pathspec '<path>' did not match any file(s) known to git". The index
352
+ * lock is then held until HEAD has moved. Each listed path is taken from the worktree
353
+ * literally (`add_remove_files`): a file (ignored or not) is staged as `git add` stages it
354
+ * (cleaned by the content filters; an intent-to-add entry gets the content, a conflicted
355
+ * path is resolved to the file, the entries it clashes with as a file or a directory
356
+ * replaced), a path gone is removed, a submodule takes the commit checked out in it, and a
357
+ * path that is now a directory holding no commit refuses the commit before anything
358
+ * changes ("'<path>' does not have a commit checked out"). The index is
359
+ * written into the lock with the paths updated, and the commit records HEAD's tree with
360
+ * only these paths changed, whatever else is staged. The lock is renamed over the index
361
+ * once the commit is made; on any failure it is removed and the index (and this instance's
362
+ * staging, unwritten edits included) stays as it was. A skip-worktree path keeps its HEAD
363
+ * version. A partial commit during a merge, a cherry-pick or a rebase is refused; other
364
+ * unmerged paths do not stop it (they stay unmerged in the index).
208
365
  *
209
366
  * Cannot be combined with setAll().
210
367
  *
@@ -213,10 +370,8 @@ export class CommitCommand extends GitCommand<CommitResult> {
213
370
  */
214
371
  setOnly(...paths: string[]): this {
215
372
  this.checkCallable();
216
- // JGit: --all and --only are mutually exclusive
217
- if (this.all && paths.length > 0) {
218
- throw new IncompatibleOptionsError(["--only", "--all"]);
219
- }
373
+ // git's parse_and_validate_options: paths and -a do not go together
374
+ if (this.all && paths.length > 0) throw pathsWithAllError(paths);
220
375
  this.onlyPaths = paths;
221
376
  return this;
222
377
  }
@@ -225,7 +380,9 @@ export class CommitCommand extends GitCommand<CommitResult> {
225
380
  * Set whether to auto-stage modified tracked files before committing.
226
381
  *
227
382
  * If true, stages all modified and deleted tracked files before
228
- * creating the commit. Requires a working tree iterator.
383
+ * creating the commit. Requires a working tree iterator. As git's: the index lock is held
384
+ * from before the files are staged until HEAD has moved, and the index is left as it was
385
+ * when the commit fails.
229
386
  *
230
387
  * Cannot be combined with setOnly().
231
388
  *
@@ -237,14 +394,39 @@ export class CommitCommand extends GitCommand<CommitResult> {
237
394
  */
238
395
  setAll(all: boolean): this {
239
396
  this.checkCallable();
240
- // JGit: --all and --only are mutually exclusive
241
- if (all && this.onlyPaths.length > 0) {
242
- throw new IncompatibleOptionsError(["--all", "--only"]);
243
- }
397
+ // git's parse_and_validate_options: paths and -a do not go together
398
+ if (all && this.onlyPaths.length > 0) throw pathsWithAllError(this.onlyPaths);
244
399
  this.all = all;
245
400
  return this;
246
401
  }
247
402
 
403
+ /**
404
+ * Commit the index with the tracked files `paths` names staged first (`git commit -i
405
+ * <paths>` / `--include`, git's `prepare_index` "non partial, non as-is commit"): the index
406
+ * lock is taken, the tracked paths the pathspec matches are staged from the worktree as
407
+ * `git add -u <paths>` stages them (`add_files_to_cache`; untracked files are not added),
408
+ * an element that matches no index entry fails with git's "error: pathspec '<path>' did
409
+ * not match any file(s) known to git" (git 2.5x; 2.43 commits what is staged), and the
410
+ * whole index, written into the lock, is committed; the lock is renamed over the index
411
+ * once HEAD has moved, or removed on failure (the index stays as it was).
412
+ *
413
+ * As git: refused with {@link setOnly} paths ("options '-i/--include' and '-o/--only'
414
+ * cannot be used together"), with {@link setAll} ("options '-i/--include' and
415
+ * '-a/--all' cannot be used together"), and without paths ("No paths with
416
+ * --include/--only does not make sense."), when the commit runs.
417
+ *
418
+ * @example
419
+ * ```typescript
420
+ * await git.commit().setInclude("src/a.ts").setMessage("Fix a").call();
421
+ * ```
422
+ */
423
+ setInclude(...paths: string[]): this {
424
+ this.checkCallable();
425
+ this.include = true;
426
+ this.includePaths = paths;
427
+ return this;
428
+ }
429
+
248
430
  /**
249
431
  * Whether --all mode is enabled.
250
432
  */
@@ -261,6 +443,511 @@ export class CommitCommand extends GitCommand<CommitResult> {
261
443
  * @param iterator Custom working tree iterator
262
444
  * @returns this for chaining
263
445
  */
446
+ /**
447
+ * The editor of the commit message (git's `core.editor` / `GIT_EDITOR`, which a library
448
+ * cannot launch): called with the path of `COMMIT_EDITMSG` in the git directory and the
449
+ * text written there, the template git prepares (the message so far, then, unless
450
+ * {@link setIncludeStatus} is false, the commented help and status, and with
451
+ * {@link setVerbose} the diff below the scissors line). It returns the edited text, or
452
+ * nothing once it changed the file itself; the result is cleaned up as git cleans up an
453
+ * edited message (`default` strips comments, `scissors` cuts at the scissors line). It is
454
+ * used when no message is given, or with {@link setEdit}.
455
+ *
456
+ * @example
457
+ * ```typescript
458
+ * await git.commit().setEditor(async (_path, template) => `Subject\n\n${template}`).call();
459
+ * ```
460
+ */
461
+ setEditor(editor: CommitEditor): this {
462
+ this.checkCallable();
463
+ this.editor = editor;
464
+ return this;
465
+ }
466
+
467
+ /**
468
+ * `-t <file>` / `--template=<file>`: the editor starts from this file's text (default
469
+ * `commit.template`) when no message is given and nothing is in progress; a message the
470
+ * editor leaves as the template was is refused (`Aborting commit; you did not edit the
471
+ * message.`). A relative path is read from the worktree's top, through the host.
472
+ *
473
+ * @example
474
+ * ```typescript
475
+ * await git.commit().setTemplate("/home/me/.gitmessage").setEditor(edit).call();
476
+ * ```
477
+ */
478
+ setTemplate(path: string): this {
479
+ this.checkCallable();
480
+ this.templateFile = path;
481
+ return this;
482
+ }
483
+
484
+ /** `-e` / `--no-edit`: edit a given message too, or never edit (default: edit when none is given). */
485
+ setEdit(edit: boolean): this {
486
+ this.checkCallable();
487
+ this.edit = edit;
488
+ return this;
489
+ }
490
+
491
+ /** `--status` / `--no-status`: the status in the editor's template (default `commit.status`, true). */
492
+ setIncludeStatus(include: boolean): this {
493
+ this.checkCallable();
494
+ this.includeStatus = include;
495
+ return this;
496
+ }
497
+
498
+ /**
499
+ * `-v` (1) / `-vv` (2): the staged diff below the template's scissors line (and the
500
+ * unstaged one), or in {@link callDryRun}'s output (default `commit.verbose`)
501
+ */
502
+ setVerbose(level: number): this {
503
+ this.checkCallable();
504
+ this.verbose = level;
505
+ return this;
506
+ }
507
+
508
+ /** `-u<mode>` / `--untracked-files=<mode>` of the template and the dry run */
509
+ setUntrackedFiles(mode: UntrackedFilesMode): this {
510
+ this.checkCallable();
511
+ this.untrackedMode = mode;
512
+ return this;
513
+ }
514
+
515
+ /** `--short`, `--porcelain`, `--long`: the format of {@link callDryRun} (git's commit has no v2) */
516
+ setStatusFormat(format: "long" | "short" | "porcelain"): this {
517
+ this.checkCallable();
518
+ this.statusFormat = format;
519
+ return this;
520
+ }
521
+
522
+ /** `--branch`: the branch header of the short and porcelain dry runs (default `status.branch`) */
523
+ setShowBranch(show: boolean): this {
524
+ this.checkCallable();
525
+ this.showBranch = show;
526
+ return this;
527
+ }
528
+
529
+ /** `-z`: NUL-terminated dry-run output (porcelain unless another format is set) */
530
+ setNullTermination(z: boolean): this {
531
+ this.checkCallable();
532
+ this.nullTermination = z;
533
+ return this;
534
+ }
535
+
536
+ /** `--[no-]ahead-behind` of the dry run (default `status.aheadBehind` for the human formats) */
537
+ setAheadBehind(full: boolean): this {
538
+ this.checkCallable();
539
+ this.aheadBehind = full;
540
+ return this;
541
+ }
542
+
543
+ /**
544
+ * `git commit --dry-run` (and `--short`, `--porcelain`, `--long`, `-z`, which imply it):
545
+ * the status of what would be committed, in the format set, with git's exit code (0
546
+ * when there is something to commit, else 1). The index is prepared as the commit would
547
+ * prepare it (`-a` stages the tracked changes, {@link setInclude} the named tracked paths,
548
+ * {@link setOnly} builds the index of HEAD with the named paths), then left as it was
549
+ * (rollback_index_files).
550
+ *
551
+ * @example
552
+ * ```typescript
553
+ * const { text, exitCode } = await git.commit().setAll(true).callDryRun();
554
+ * ```
555
+ */
556
+ async callDryRun(): Promise<CommitDryRunResult> {
557
+ this.checkCallable();
558
+ this.setCallable(false);
559
+ readShowUntrackedFiles(this.workingCopy);
560
+ // ... and git_diff_ui_config: a diff.submodule without a value dies
561
+ readDiffSubmoduleConfig(this.workingCopy);
562
+ await this.readCurrentIndex();
563
+ // `-i` refuses what it refuses for a commit, before anything is read
564
+ if (this.include) this.checkIncludeOptions();
565
+ const state = new OperationState(this.workingCopy.checkout, this.refsStore);
566
+ const mergeHeads = await this.mergeHeads(state);
567
+ const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
568
+ await this.checkAmend(state, mergeHeads, headId);
569
+ const partial = this.onlyPaths.length > 0;
570
+ const z = this.nullTermination;
571
+ const format = this.statusFormat ?? (z ? "porcelain" : "long");
572
+ const run = async (): Promise<StatusTextResult> =>
573
+ this.commitStatus({
574
+ format,
575
+ z,
576
+ ...(this.showBranch !== undefined ? { branch: this.showBranch } : {}),
577
+ ...(this.aheadBehind !== undefined ? { aheadBehind: this.aheadBehind } : {}),
578
+ verbose: this.verboseLevel(),
579
+ commitTemplate: true,
580
+ amend: this.amend,
581
+ });
582
+ let result: StatusTextResult;
583
+ if (this.include) {
584
+ // `-i <paths>`: the tracked paths staged on the held index, shown, then rolled back
585
+ const index = await this.holdIndex();
586
+ try {
587
+ await this.stageTrackedChanges(this.includePaths);
588
+ result = await run();
589
+ } finally {
590
+ await index.release();
591
+ }
592
+ } else if (this.all) {
593
+ const index = await this.holdIndex();
594
+ try {
595
+ await this.stageTrackedChanges();
596
+ result = await run();
597
+ } finally {
598
+ await index.release();
599
+ }
600
+ } else if (partial) {
601
+ const paths = await this.listPartialPaths(state, mergeHeads, headId);
602
+ const index = await this.holdIndex();
603
+ try {
604
+ // the false index shown, its tree never stored (git writes it into a lock only)
605
+ const falseIndex = await this.preparePartialCommit(paths, headId, index);
606
+ result = await this.withFalseIndex(await this.falseIndexFiles(falseIndex), run);
607
+ } finally {
608
+ await index.release();
609
+ }
610
+ } else {
611
+ // an as-is commit (prepare_index): the index lock taken (git dies when another
612
+ // process holds it), then the status of the index as it is
613
+ const index = await this.holdIndex();
614
+ await index.release();
615
+ result = await run();
616
+ }
617
+ return { ...result, exitCode: result.committable ? 0 : 1 };
618
+ }
619
+
620
+ /** git's use_editor: an editor is set, and no message is given or `-e` asks for it. */
621
+ private usesEditor(): boolean {
622
+ if (!this.editor || this.edit === false) return false;
623
+ return this.edit === true || this.message === undefined;
624
+ }
625
+
626
+ /**
627
+ * prepare_to_commit with an editor: COMMIT_EDITMSG written with the message so far and
628
+ * (`commit.status`) the commented help, identities and status of the template, the
629
+ * editor run over it, and what it left cleaned up as the commit message.
630
+ */
631
+ private async editMessage(
632
+ ctx: {
633
+ state: OperationState;
634
+ mergeHeads: ObjectId[];
635
+ pickHead: ObjectId | undefined;
636
+ partialTree: ObjectId | undefined;
637
+ /** The tree the commit records */
638
+ treeId: ObjectId;
639
+ /** HEAD, or HEAD^1 when amending (none: an initial commit, or a root amended) */
640
+ firstParent: ObjectId | undefined;
641
+ previousCommit: Commit | undefined;
642
+ author: PersonIdent;
643
+ committer: PersonIdent;
644
+ authorKept: boolean;
645
+ /** The variables of the commit hooks */
646
+ hookEnv: Record<string, string>;
647
+ },
648
+ editor: CommitEditor,
649
+ ): Promise<{ message: string; cleanup: CleanupMode; untouched: boolean }> {
650
+ const { state } = ctx;
651
+ const config = RemoteConfigStore.from(this.workingCopy);
652
+ const mode = editorCleanupMode(this.workingCopy, this.cleanupMode);
653
+ const templateText = await this.readTemplate(config);
654
+ const rebasing = (await state.read("rebase-merge/head-name")) !== undefined;
655
+ const whence: CommitWhence =
656
+ ctx.mergeHeads.length > 0
657
+ ? "merge"
658
+ : ctx.pickHead
659
+ ? rebasing && (await state.ref("REBASE_HEAD")) === ctx.pickHead
660
+ ? "rebase-pick"
661
+ : "cherry-pick"
662
+ : "commit";
663
+ // the message so far
664
+ let sb = "";
665
+ let cutLineAdded = false;
666
+ const mergeMsg = await state.read("MERGE_MSG");
667
+ const squashMsg = await state.read("SQUASH_MSG");
668
+ if (this.message !== undefined) sb = completeLine(this.message);
669
+ else if (this.amend && ctx.previousCommit) {
670
+ sb = ctx.previousCommit.message.replace(/^(?:[ \t\r]*\n)+/, "");
671
+ } else if (mergeMsg !== undefined) {
672
+ sb = `${squashMsg ?? ""}${mergeMsg}`;
673
+ if (mode === CleanupMode.SCISSORS) {
674
+ const cut = `${commentPrefixOf(this.workingCopy)} ------------------------ >8 ------------------------\n`;
675
+ if (mergeMsg.startsWith(cut) || mergeMsg.includes(`\n${cut}`)) cutLineAdded = true;
676
+ }
677
+ } else if (squashMsg !== undefined) sb = squashMsg;
678
+ else if (templateText !== undefined) sb = templateText;
679
+ // clean_message_contents: not for a template, which goes in as it is
680
+ const fromTemplate =
681
+ this.message === undefined &&
682
+ !(this.amend && ctx.previousCommit) &&
683
+ mergeMsg === undefined &&
684
+ squashMsg === undefined &&
685
+ templateText !== undefined;
686
+ if (mode !== CleanupMode.VERBATIM && !fromTemplate) sb = stripspace(sb);
687
+ // core.commentChar=auto: a character the message does not start a line with
688
+ const comment = commentPrefixOf(this.workingCopy, sb);
689
+ // (a prepared message taken without an editor: as `--no-status`, unless asked for)
690
+ const includeStatus =
691
+ this.includeStatus ??
692
+ (this.usesEditor() ? parseBool(config.value("commit.status"), true) : false);
693
+ const verbose = this.verboseLevel();
694
+ let template = sb;
695
+ let committable: boolean;
696
+ const p = new StatusPrinter(comment);
697
+ if (includeStatus) {
698
+ if (whence !== "commit") {
699
+ if (mode === CleanupMode.SCISSORS && !cutLineAdded) {
700
+ p.raw(cutLine(comment));
701
+ cutLineAdded = true;
702
+ }
703
+ const what = whence === "merge" ? "a merge" : "a cherry-pick";
704
+ const ref = whence === "merge" ? "MERGE_HEAD" : "CHERRY_PICK_HEAD";
705
+ p.ln(
706
+ `\nIt looks like you may be committing ${what}.\nIf this is not correct, please run\n\tgit update-ref -d ${ref}\nand try again.\n`,
707
+ );
708
+ }
709
+ p.raw("\n");
710
+ if (mode === CleanupMode.STRIP) {
711
+ p.printf(
712
+ this.allowEmptyMessage
713
+ ? `Please enter the commit message for your changes. Lines starting\nwith '${comment}' will be ignored.\n`
714
+ : `Please enter the commit message for your changes. Lines starting\nwith '${comment}' will be ignored, and an empty message aborts the commit.\n`,
715
+ );
716
+ } else if (mode === CleanupMode.SCISSORS) {
717
+ if (whence === "commit" && !cutLineAdded) {
718
+ p.raw(cutLine(comment));
719
+ cutLineAdded = true;
720
+ }
721
+ } else {
722
+ p.printf(
723
+ this.allowEmptyMessage
724
+ ? `Please enter the commit message for your changes. Lines starting\nwith '${comment}' will be kept; you may remove them yourself if you want to.\n`
725
+ : `Please enter the commit message for your changes. Lines starting\nwith '${comment}' will be kept; you may remove them yourself if you want to.\nAn empty message aborts the commit.\n`,
726
+ );
727
+ }
728
+ let identShown = 0;
729
+ const { author, committer } = ctx;
730
+ if (author.name !== committer.name || author.email !== committer.email) {
731
+ p.ln(`${identShown++ ? "" : "\n"}Author: ${author.name} <${author.email}>`);
732
+ }
733
+ if (ctx.authorKept) {
734
+ const date = showDate(author.timestamp, author.tzOffset, DEFAULT_DATE_MODE);
735
+ p.ln(`${identShown++ ? "" : "\n"}Date: ${date}`);
736
+ }
737
+ if (!this.committerIdentGiven()) {
738
+ p.ln(`${identShown++ ? "" : "\n"}Committer: ${committer.name} <${committer.email}>`);
739
+ }
740
+ p.ln("");
741
+ const run = () =>
742
+ this.commitStatus({
743
+ format: "long",
744
+ commentPrefix: comment,
745
+ hints: false,
746
+ nowarn: true,
747
+ commitTemplate: true,
748
+ amend: this.amend,
749
+ verbose,
750
+ toFile: true,
751
+ cutLineAdded,
752
+ whence,
753
+ });
754
+ const status = ctx.partialTree
755
+ ? await this.withIndexOfTree(ctx.partialTree, run)
756
+ : await run();
757
+ committable = status.committable;
758
+ template += p.out + status.text;
759
+ } else {
760
+ // no status in the template: prepare_to_commit's index_differs_from against HEAD
761
+ // (HEAD^1 when amending), intent-to-add entries invisible; without that parent,
762
+ // `cache_nr - ita_nr > 0`. The recorded tree says both without a status run.
763
+ const parentTree = ctx.firstParent
764
+ ? (await this.commits.load(ctx.firstParent))?.tree
765
+ : this.objectFormat.emptyTreeId;
766
+ committable = ctx.treeId !== parentTree;
767
+ }
768
+ // COMMIT_EDITMSG written in full, then an empty commit refused before the editor runs
769
+ await state.write("COMMIT_EDITMSG", template);
770
+ const isMerge = (ctx.previousCommit?.parents.length ?? 0) > 1;
771
+ if (!committable && whence !== "merge" && !this.allowEmpty && !(this.amend && isMerge)) {
772
+ throw new EmptyCommitError();
773
+ }
774
+ // prepare-commit-msg, the editor over what it left, then commit-msg
775
+ let text = "";
776
+ let edited: unknown;
777
+ const hookArgs = this.prepareMessageHookArgs(
778
+ mergeMsg,
779
+ squashMsg,
780
+ fromTemplate ? templateText : undefined,
781
+ ctx.mergeHeads,
782
+ ctx.pickHead,
783
+ );
784
+ const ran = await this.runMessageHooks(ctx.hookEnv, hookArgs, async () => {
785
+ const current = this.hooks.enabled
786
+ ? ((await state.read("COMMIT_EDITMSG")) ?? template)
787
+ : template;
788
+ edited = await editor("COMMIT_EDITMSG", current);
789
+ if (typeof edited === "string") await state.write("COMMIT_EDITMSG", edited);
790
+ });
791
+ if (typeof edited === "string" && !ran) text = edited;
792
+ else text = (await state.read("COMMIT_EDITMSG")) ?? "";
793
+ // cleanup_message
794
+ if (verbose > 0 || mode === CleanupMode.SCISSORS) {
795
+ const cut = `${comment} ------------------------ >8 ------------------------\n`;
796
+ if (text.startsWith(cut)) text = "";
797
+ else {
798
+ const at = text.indexOf(`\n${cut}`);
799
+ if (at >= 0) text = text.slice(0, at + 1);
800
+ }
801
+ }
802
+ if (mode !== CleanupMode.VERBATIM) {
803
+ text = stripspace(text, mode === CleanupMode.STRIP ? comment : undefined);
804
+ }
805
+ return {
806
+ message: text,
807
+ cleanup: mode === CleanupMode.VERBATIM ? mode : CleanupMode.STRIP,
808
+ untouched: templateUntouched(text, templateText, mode, comment),
809
+ };
810
+ }
811
+
812
+ /**
813
+ * The commit template (`-t`, else `commit.template`, `~/` expanded) read through the host,
814
+ * undefined when none is set; one that cannot be read fails as git's `die_errno`.
815
+ */
816
+ private async readTemplate(config: RemoteConfigStore): Promise<string | undefined> {
817
+ const configured = config.value("commit.template");
818
+ const file =
819
+ this.templateFile ?? (configured !== undefined && configured !== "" ? configured : undefined);
820
+ if (file === undefined) return undefined;
821
+ const environment = hostEnvironmentOf(this.workingCopy);
822
+ const expanded = expandUserPath(file, environment);
823
+ let bytes: Uint8Array | undefined;
824
+ if (expanded !== undefined && environment) {
825
+ let path = expanded;
826
+ if (!path.startsWith("/")) {
827
+ const base = (this.worktreeAccess as { hostPath?: string } | undefined)?.hostPath;
828
+ if (base) path = `${base.replace(/\/+$/, "")}/${path}`;
829
+ }
830
+ bytes = await environment.readFile(path).catch(() => undefined);
831
+ }
832
+ if (!bytes) {
833
+ throw new GitApiError(`fatal: could not read '${file}': No such file or directory`);
834
+ }
835
+ return new TextDecoder().decode(bytes);
836
+ }
837
+
838
+ /** committer_ident_sufficiently_given: a name and an email named, not guessed. */
839
+ private committerIdentGiven(): boolean {
840
+ const env = hostEnvironmentOf(this.workingCopy);
841
+ const config = RemoteConfigStore.from(this.workingCopy);
842
+ const name =
843
+ env?.committer?.name !== undefined ||
844
+ config.value("committer.name") !== undefined ||
845
+ config.value("user.name") !== undefined;
846
+ const email =
847
+ env?.committer?.email !== undefined ||
848
+ config.value("committer.email") !== undefined ||
849
+ config.value("user.email") !== undefined ||
850
+ !!env?.defaultEmail;
851
+ return name && email;
852
+ }
853
+
854
+ /** parse_and_validate_options' checks of `--amend`. */
855
+ private async checkAmend(
856
+ state: OperationState,
857
+ mergeHeads: ObjectId[],
858
+ headId: ObjectId | undefined,
859
+ ): Promise<void> {
860
+ if (!this.amend) return;
861
+ if (!headId) {
862
+ throw new InvalidArgumentError("amend", true, "fatal: You have nothing to amend.");
863
+ }
864
+ if (mergeHeads.length > 0) {
865
+ throw new InvalidArgumentError(
866
+ "amend",
867
+ true,
868
+ "fatal: You are in the middle of a merge -- cannot amend.",
869
+ );
870
+ }
871
+ if (await state.ref("CHERRY_PICK_HEAD")) {
872
+ throw new InvalidArgumentError(
873
+ "amend",
874
+ true,
875
+ "fatal: You are in the middle of a cherry-pick -- cannot amend.",
876
+ );
877
+ }
878
+ }
879
+
880
+ /** `-v` as given, else `commit.verbose` (a boolean or a level), else 0. */
881
+ private verboseLevel(): number {
882
+ if (this.verbose !== undefined) return this.verbose;
883
+ const value = RemoteConfigStore.from(this.workingCopy).value("commit.verbose");
884
+ if (value === undefined) return 0;
885
+ if (/^\s*-?\d+\s*$/.test(value)) return Number.parseInt(value, 10);
886
+ const v = value.toLowerCase();
887
+ return v === "" || v === "false" || v === "no" || v === "off" ? 0 : 1;
888
+ }
889
+
890
+ /**
891
+ * run_status for the commit: the status of the prepared index against HEAD (HEAD^1 for
892
+ * `--amend`), its stats not written back (the commit holds the index).
893
+ */
894
+ private async commitStatus(
895
+ options: Parameters<StatusCommand["callText"]>[0] & object,
896
+ ): Promise<StatusTextResult> {
897
+ const status = new StatusCommand(this.workingCopy).setWriteIndex(false);
898
+ if (this.untrackedMode) status.setUntrackedFiles(this.untrackedMode);
899
+ if (this.amend) {
900
+ const headId = await this.resolveHead();
901
+ const head = await this.commits.load(headId);
902
+ status.setReferenceCommit(head?.parents[0] ?? null);
903
+ }
904
+ return status.callText(options);
905
+ }
906
+
907
+ /** {@link withFalseIndex} with the files of `tree` (a partial commit's stored tree). */
908
+ private async withIndexOfTree<T>(tree: ObjectId, fn: () => Promise<T>): Promise<T> {
909
+ return this.withFalseIndex(await flatTree(this.trees, tree), fn);
910
+ }
911
+
912
+ /**
913
+ * Runs `fn` while the staging holds the entries `flat` names (a partial commit's false
914
+ * index: HEAD with the named paths), each with the stat of the staging's same entry,
915
+ * then puts the staging back exactly as it was: the same entry objects, so the ones kept
916
+ * as read are still checked for racy-git smudging when the index is written
917
+ * (`saveState`; a staging without it gets its entries rebuilt).
918
+ */
919
+ private async withFalseIndex<T>(
920
+ flat: Map<string, { objectId: ObjectId; mode: number }>,
921
+ fn: () => Promise<T>,
922
+ ): Promise<T> {
923
+ const staging = this.staging;
924
+ const saved = staging.saveState?.();
925
+ const before = (staging.entryList?.() ?? (await collectEntries(staging))).slice();
926
+ const cacheTree = saved ? undefined : staging.getCacheTree?.();
927
+ const known = new Map(before.filter((e) => e.stage === 0).map((e) => [e.path, e]));
928
+ const builder = staging.createBuilder();
929
+ for (const [path, entry] of flat) {
930
+ const same = known.get(path);
931
+ builder.add(
932
+ same && same.objectId === entry.objectId && same.mode === entry.mode
933
+ ? same
934
+ : { path, mode: entry.mode, objectId: entry.objectId, stage: 0, size: 0, mtime: 0 },
935
+ );
936
+ }
937
+ await builder.finish();
938
+ try {
939
+ return await fn();
940
+ } finally {
941
+ if (saved) staging.restoreState?.(saved);
942
+ else {
943
+ const restore = staging.createBuilder();
944
+ for (const entry of before) restore.add(entry);
945
+ await restore.finish();
946
+ staging.setCacheTree?.(cacheTree);
947
+ }
948
+ }
949
+ }
950
+
264
951
  setWorktree(iterator: Worktree): this {
265
952
  this.checkCallable();
266
953
  this.worktreeIterator = iterator;
@@ -277,65 +964,248 @@ export class CommitCommand extends GitCommand<CommitResult> {
277
964
  */
278
965
  async call(): Promise<CommitResult> {
279
966
  this.checkCallable();
967
+ // git commit reads the status configuration first (git_status_config): a bad
968
+ // status.showUntrackedFiles fails it before anything is done
969
+ readShowUntrackedFiles(this.workingCopy);
970
+ // ... and git_diff_ui_config: a diff.submodule without a value dies
971
+ readDiffSubmoduleConfig(this.workingCopy);
972
+ // the index as it is now: one another writer replaced is read again (git reads the
973
+ // index at its start), unless this instance holds unwritten edits (refused)
974
+ await this.readCurrentIndex();
975
+ if (this.include) return this.commitIncluded();
976
+ const partial = this.onlyPaths.length > 0;
977
+ if (!this.all) return this.commitWith(partial, undefined);
978
+ // `-a` (git's COMMIT_NORMAL): the index lock held from before the tracked changes are
979
+ // staged until HEAD has moved
980
+ const index = await this.holdIndex();
981
+ try {
982
+ // git writes the lock once (prepare_index): one post-index-change run, the lock held
983
+ return await this.withOneIndexWrite("first", async () => {
984
+ // Handle --all flag: auto-stage modified tracked files
985
+ await this.stageTrackedChanges();
986
+ return await this.commitWith(partial, index);
987
+ });
988
+ } catch (error) {
989
+ await index.release();
990
+ throw error;
991
+ }
992
+ }
280
993
 
281
- // Handle --all flag: auto-stage modified tracked files
282
- if (this.all) {
283
- await this.stageTrackedChanges();
994
+ /**
995
+ * `-i <paths>` (git's prepare_index for `also`): the option checks of
996
+ * parse_and_validate_options and prepare_index, then the index lock held from before the
997
+ * tracked paths are staged until HEAD has moved.
998
+ */
999
+ private async commitIncluded(): Promise<CommitResult> {
1000
+ this.checkIncludeOptions();
1001
+ const index = await this.holdIndex();
1002
+ try {
1003
+ await this.stageTrackedChanges(this.includePaths);
1004
+ return await this.commitWith(false, index);
1005
+ } catch (error) {
1006
+ await index.release();
1007
+ throw error;
284
1008
  }
1009
+ }
285
1010
 
286
- // Check message
287
- if (!this.message && !this.amend) {
288
- throw new NoMessageError();
1011
+ /** `-i <paths>`: parse_and_validate_options' and prepare_index's refusals. */
1012
+ private checkIncludeOptions(): void {
1013
+ if (this.onlyPaths.length > 0) {
1014
+ throw new IncompatibleOptionsError(
1015
+ ["-i/--include", "-o/--only"],
1016
+ "fatal: options '-i/--include' and '-o/--only' cannot be used together",
1017
+ );
1018
+ }
1019
+ if (this.all) {
1020
+ throw new IncompatibleOptionsError(
1021
+ ["-i/--include", "-a/--all"],
1022
+ "fatal: options '-i/--include' and '-a/--all' cannot be used together",
1023
+ );
1024
+ }
1025
+ if (this.includePaths.length === 0) {
1026
+ throw new InvalidArgumentError(
1027
+ "include",
1028
+ [],
1029
+ "fatal: No paths with --include/--only does not make sense.",
1030
+ );
289
1031
  }
1032
+ }
290
1033
 
291
- // Check for conflicts
292
- if (await this.staging.hasConflicts()) {
1034
+ /**
1035
+ * The commit, once `-a` staged the tracked changes (`index`: the index lock it holds).
1036
+ * A partial commit takes the lock itself.
1037
+ */
1038
+ private async commitWith(partial: boolean, held: HeldIndex | undefined): Promise<CommitResult> {
1039
+ let index = held;
1040
+
1041
+ // Check for conflicts (a partial commit records HEAD and the named paths: other
1042
+ // unmerged paths stay in the index, as git's)
1043
+ if (!partial && (await this.staging.hasConflicts())) {
293
1044
  const conflictPaths = await this.staging.getConflictedPaths();
294
- throw new UnmergedPathsError(conflictPaths);
1045
+ throw new UnmergedPathsError(
1046
+ conflictPaths,
1047
+ [
1048
+ "error: Committing is not possible because you have unmerged files.",
1049
+ "hint: Fix them up in the work tree, and then use 'git add/rm <file>'",
1050
+ "hint: as appropriate to mark resolution and make a commit.",
1051
+ "fatal: Exiting because of an unresolved conflict.",
1052
+ ].join("\n"),
1053
+ );
295
1054
  }
296
1055
 
297
- // Get message (from amend or new)
298
- let finalMessage = this.message;
299
- let previousCommit: Commit | undefined;
300
-
301
- if (this.amend) {
302
- const headId = await this.resolveHead();
303
- previousCommit = await this.commits.load(headId);
304
- if (!previousCommit) {
305
- throw new NoHeadError("Cannot amend: HEAD commit not found");
306
- }
307
- if (!finalMessage) {
308
- finalMessage = previousCommit.message;
1056
+ // a merge, cherry-pick or revert in progress (git's whence: MERGE_HEAD,
1057
+ // CHERRY_PICK_HEAD, REVERT_HEAD), and the message it prepared
1058
+ const state = new OperationState(this.workingCopy.checkout, this.refsStore);
1059
+ const mergeHeads = await this.mergeHeads(state);
1060
+ const pickHead = await state.ref("CHERRY_PICK_HEAD");
1061
+ if (this.amend && mergeHeads.length > 0) {
1062
+ throw new InvalidArgumentError(
1063
+ "amend",
1064
+ true,
1065
+ "fatal: You are in the middle of a merge -- cannot amend.",
1066
+ );
1067
+ }
1068
+ // a partial commit: the paths named, from the index and HEAD (git's list_paths)
1069
+ const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
1070
+ let partialTree: ObjectId | undefined;
1071
+ let falseIndexFile: FalseIndexFile | undefined;
1072
+ const partialPaths = partial
1073
+ ? await this.listPartialPaths(state, mergeHeads, headId)
1074
+ : undefined;
1075
+ if (partialPaths) {
1076
+ // git's partial commit (prepare_index): the index lock taken once the paths are
1077
+ // listed, the named paths taken from the worktree into the index and written into
1078
+ // the lock (renamed over the index once HEAD has moved), the commit's tree HEAD's with
1079
+ // the same paths taken; any failure leaves the index as it was
1080
+ index = await this.holdIndex();
1081
+ try {
1082
+ const falseIndex = await this.preparePartialCommit(partialPaths, headId, index);
1083
+ partialTree = await this.storeFalseIndex(falseIndex);
1084
+ // the hooks are given the false index as a file (git's next-index-<pid>.lock),
1085
+ // removed once the commit is made or given up
1086
+ if (this.hooks.enabled) {
1087
+ falseIndexFile = await this.writeFalseIndexFile(falseIndex);
1088
+ if (falseIndexFile) index = withCleanup(index, falseIndexFile.remove);
1089
+ }
1090
+ } catch (error) {
1091
+ await falseIndexFile?.remove();
1092
+ await index.release();
1093
+ throw error;
309
1094
  }
310
1095
  }
311
-
312
- if (!finalMessage) {
313
- throw new NoMessageError();
1096
+ try {
1097
+ return await this.commitPrepared(
1098
+ partialTree,
1099
+ state,
1100
+ mergeHeads,
1101
+ pickHead,
1102
+ index,
1103
+ falseIndexFile,
1104
+ );
1105
+ } catch (error) {
1106
+ await index?.release();
1107
+ throw error;
314
1108
  }
1109
+ }
315
1110
 
316
- // Determine author and committer
317
- const defaultIdent: PersonIdent = {
318
- name: "Unknown",
319
- email: "unknown@example.com",
320
- timestamp: Math.floor(Date.now() / 1000),
321
- tzOffset: getTimezoneOffset(),
322
- };
323
-
324
- let author = this.author;
325
- let committer = this.committer;
326
-
327
- if (this.amend && previousCommit) {
328
- // Keep original author when amending unless explicitly set
329
- if (!author) {
330
- author = previousCommit.author;
1111
+ /**
1112
+ * A partial commit's false index written as git's `prepare_index` writes it for the hooks
1113
+ * (`$GIT_DIR/next-index-<pid>.lock`): HEAD's tree with the named paths taken, each entry
1114
+ * the index has unchanged keeping its stat data (create_base_index's one-way merge), the
1115
+ * others none. Undefined where the repository's files cannot hold it.
1116
+ */
1117
+ private async writeFalseIndexFile(falseIndex: FalseIndex): Promise<FalseIndexFile | undefined> {
1118
+ // git names it by its process id; any number no file has will do here
1119
+ let name = "";
1120
+ let target: { files: FilesApi; path: string } | undefined;
1121
+ for (let attempt = 0; attempt < 100; attempt++) {
1122
+ name = `next-index-${10000 + Math.floor(Math.random() * 90000)}.lock`;
1123
+ target = await this.hooks.gitFile(name);
1124
+ if (!target) return undefined;
1125
+ if ((await target.files.stats(target.path)) === undefined) break;
1126
+ target = undefined;
1127
+ }
1128
+ if (!target) throw new Error("could not choose a name for the false index file");
1129
+ const lock = target;
1130
+ const files = await this.falseIndexFiles(falseIndex);
1131
+ const current = new Map<string, StagingEntry>();
1132
+ for await (const entry of this.staging.entries()) {
1133
+ if (entry.stage === 0) current.set(entry.path, entry);
1134
+ }
1135
+ const temp = new FileStagingStore(lock.files, lock.path);
1136
+ const builder = temp.createBuilder();
1137
+ for (const path of [...files.keys()].sort(compareGitPaths)) {
1138
+ const file = files.get(path) as { objectId: ObjectId; mode: number };
1139
+ const kept = current.get(path);
1140
+ if (kept && kept.objectId === file.objectId && kept.mode === file.mode && !kept.intentToAdd) {
1141
+ builder.add(kept);
1142
+ } else {
1143
+ builder.add({ path, mode: file.mode, objectId: file.objectId, size: 0, mtime: 0 });
331
1144
  }
332
1145
  }
1146
+ await builder.finish();
1147
+ const remove = async () => {
1148
+ await lock.files.remove(lock.path).catch(() => false);
1149
+ };
1150
+ // the file is ours from its first byte: a failure before it is handed over removes it
1151
+ try {
1152
+ await temp.write();
1153
+ return {
1154
+ hostPath: await this.hooks.gitPath(name, true),
1155
+ reread: async () => {
1156
+ await temp.read();
1157
+ return writeIndexAsTree(temp, this.trees, this.objectFormat, { write: false });
1158
+ },
1159
+ remove,
1160
+ };
1161
+ } catch (error) {
1162
+ await remove();
1163
+ throw error;
1164
+ }
1165
+ }
333
1166
 
334
- if (!author) {
335
- author = committer ?? defaultIdent;
1167
+ /** The commit made from the index (or the partial commit's tree), after the index is ready. */
1168
+ private async commitPrepared(
1169
+ partialTreeIn: ObjectId | undefined,
1170
+ state: OperationState,
1171
+ mergeHeads: ObjectId[],
1172
+ pickHead: ObjectId | undefined,
1173
+ index: HeldIndex | undefined,
1174
+ falseIndexFile?: FalseIndexFile,
1175
+ ): Promise<CommitResult> {
1176
+ let partialTree = partialTreeIn;
1177
+ // an editor edits the message (git's use_editor): no message given, or -e; without an
1178
+ // editor set, a merge's or a pick's prepared message (MERGE_MSG, SQUASH_MSG) is taken as
1179
+ // `git commit --no-status` takes it once the editor leaves it as it is (the template
1180
+ // written to COMMIT_EDITMSG; the status too with setIncludeStatus(true)), unless
1181
+ // setEdit(false) (`--no-edit`)
1182
+ const mergeMsgPresent =
1183
+ (await state.read("MERGE_MSG")) !== undefined ||
1184
+ (await state.read("SQUASH_MSG")) !== undefined;
1185
+ const editorLike =
1186
+ this.usesEditor() ||
1187
+ (this.message === undefined && !this.amend && this.edit !== false && mergeMsgPresent);
1188
+ const editor: CommitEditor = this.usesEditor()
1189
+ ? (this.editor as CommitEditor)
1190
+ : async () => undefined;
1191
+ const message = this.message;
1192
+ if (!editorLike && message === undefined && !this.amend && !mergeMsgPresent) {
1193
+ throw new NoMessageError();
336
1194
  }
337
- if (!committer) {
338
- committer = author;
1195
+
1196
+ // prepare_to_commit's pre-commit hook (not with --no-verify), over the index the commit
1197
+ // records (the lock `-a` and a partial commit wrote); a hook that ran may have changed
1198
+ // the index, which is read again (git's discard_index + read_index_from)
1199
+ // (a partial commit's hooks see its false index; `-a` the index lock, read back from
1200
+ // the lock; a plain commit the index)
1201
+ const hookEnv = await this.commitHookEnv(editorLike, index, falseIndexFile?.hostPath);
1202
+ if (!this.noVerify && this.hooks.enabled) {
1203
+ if (index) await index.write();
1204
+ if (await this.runCommitHook("pre-commit", hookEnv)) {
1205
+ if (falseIndexFile) partialTree = await falseIndexFile.reread();
1206
+ else if (index) await index.reread();
1207
+ else await this.staging.read();
1208
+ }
339
1209
  }
340
1210
 
341
1211
  // Determine parents
@@ -359,27 +1229,213 @@ export class CommitCommand extends GitCommand<CommitResult> {
359
1229
  // Initial commit
360
1230
  parents = [];
361
1231
  }
1232
+ if (mergeHeads.length > 0) {
1233
+ // a merge commit: HEAD and MERGE_HEAD's commits; reduced to the independent ones
1234
+ // unless MERGE_MODE says no-ff (git's reduce_heads_replace)
1235
+ parents = [...parents, ...mergeHeads.filter((id) => !parents.includes(id))];
1236
+ const mode = (await state.read("MERGE_MODE")) ?? "";
1237
+ if (!/\bno-ff\b/.test(mode)) parents = await this.reduceHeads(parents);
1238
+ }
362
1239
  }
363
1240
 
364
1241
  // Generate tree from staging area
365
1242
  let treeId: ObjectId;
366
-
367
- if (this.onlyPaths.length > 0 && parents.length > 0) {
368
- // --only mode: combine parent tree with specified paths from staging
369
- treeId = await this.buildOnlyTree(parents[0]);
1243
+ if (partialTree) {
1244
+ treeId = partialTree;
1245
+ } else if (index) {
1246
+ // `-a`: the index with a fully valid cache-tree (cache_tree_update), written into the
1247
+ // lock
1248
+ treeId = await writeIndexAsTree(this.staging, this.trees, this.objectFormat, {
1249
+ write: false,
1250
+ });
1251
+ await index.write();
370
1252
  } else {
371
- // Normal mode: use full staging area
372
- treeId = await this.staging.writeTree(this.trees);
1253
+ // Normal mode: use full staging area; as git's prepare_index, the index is written
1254
+ // again with a fully valid cache-tree (cache_tree_update, which keeps the valid nodes:
1255
+ // a stored subtree no edit touched stays the one stored)
1256
+ treeId = await writeIndexAsTree(this.staging, this.trees, this.objectFormat);
373
1257
  }
1258
+ let previousCommit: Commit | undefined;
1259
+ let amendedId: ObjectId | undefined;
374
1260
 
375
- // Check for empty commit
376
- if (!this.allowEmpty && parents.length > 0) {
377
- const parentCommit = await this.commits.load(parents[0]);
378
- if (parentCommit && parentCommit.tree === treeId) {
379
- throw new EmptyCommitError();
1261
+ if (this.amend) {
1262
+ const headId = await this.resolveHead();
1263
+ amendedId = headId;
1264
+ previousCommit = await this.commits.load(headId);
1265
+ if (!previousCommit) {
1266
+ throw new NoHeadError("Cannot amend: HEAD commit not found");
380
1267
  }
381
1268
  }
382
1269
 
1270
+ // The author (git's determine_author_info): the one given; else an amended commit's or
1271
+ // a concluded cherry-pick's author (its date too; `--author` replaces only the name and
1272
+ // email), unless --reset-author; else resolved as git does (GIT_AUTHOR_*, author.*,
1273
+ // user.*, GIT_AUTHOR_DATE or now)
1274
+ let author = this.author;
1275
+ if (!author) {
1276
+ const kept = this.resetAuthor
1277
+ ? undefined
1278
+ : this.amend && previousCommit
1279
+ ? previousCommit.author
1280
+ : pickHead
1281
+ ? (await this.commits.load(pickHead))?.author
1282
+ : undefined;
1283
+ if (kept) {
1284
+ author = this.authorName
1285
+ ? {
1286
+ ...kept,
1287
+ name: withoutCrud(this.authorName.name),
1288
+ email: withoutCrud(this.authorName.email),
1289
+ }
1290
+ : kept;
1291
+ } else if (this.authorName) author = this.datedIdent("author", this.authorName);
1292
+ else author = this.resolveAuthor(this.committer ?? this.committerName);
1293
+ }
1294
+ // the committer: always resolved (GIT_COMMITTER_*, committer.*, user.*), unless given
1295
+ const committer =
1296
+ this.committer ??
1297
+ (this.committerName
1298
+ ? this.datedIdent("committer", this.committerName)
1299
+ : this.resolveCommitter(author));
1300
+
1301
+ let finalMessage: string;
1302
+ let cleanup: CleanupMode;
1303
+ let untouched = false;
1304
+ if (editorLike) {
1305
+ const edited = await this.editMessage(
1306
+ {
1307
+ state,
1308
+ mergeHeads,
1309
+ pickHead,
1310
+ partialTree,
1311
+ treeId,
1312
+ firstParent: parents[0],
1313
+ previousCommit,
1314
+ author,
1315
+ committer,
1316
+ authorKept: !this.author && !this.resetAuthor && (!!previousCommit || !!pickHead),
1317
+ hookEnv,
1318
+ },
1319
+ editor,
1320
+ );
1321
+ finalMessage = edited.message;
1322
+ cleanup = edited.cleanup;
1323
+ untouched = edited.untouched;
1324
+ } else {
1325
+ // prepare_to_commit without an editor: the message so far (`-m`, the amended commit's,
1326
+ // else MERGE_MSG after SQUASH_MSG, or SQUASH_MSG) with its whitespace cleaned up
1327
+ // unless verbatim (`get_cleanup_mode` without an editor: default and scissors are
1328
+ // whitespace) is written to COMMIT_EDITMSG; then a commit with nothing to commit is
1329
+ // refused; then the file's text is cleaned up (cleanup_message) and checked
1330
+ cleanup = commitCleanupMode(this.workingCopy, this.cleanupMode);
1331
+ let sb: string;
1332
+ if (message !== undefined) sb = completeLine(message);
1333
+ else if (previousCommit) sb = previousCommit.message.replace(/^(?:[ \t\r]*\n)+/, "");
1334
+ else {
1335
+ const mergeMsg = await state.read("MERGE_MSG");
1336
+ const squashMsg = await state.read("SQUASH_MSG");
1337
+ sb = mergeMsg !== undefined ? `${squashMsg ?? ""}${mergeMsg}` : (squashMsg ?? "");
1338
+ }
1339
+ if (cleanup !== CleanupMode.VERBATIM) sb = stripspace(sb);
1340
+ await state.write("COMMIT_EDITMSG", sb);
1341
+ await this.refuseNothingToCommit(treeId, parents, mergeHeads, previousCommit);
1342
+ // prepare-commit-msg and commit-msg, which may rewrite COMMIT_EDITMSG: the commit
1343
+ // takes the file's text (cmd_commit reads it back)
1344
+ // (git's hook arguments: read only when hooks can run)
1345
+ const hookArgs = this.hooks.enabled
1346
+ ? this.prepareMessageHookArgs(
1347
+ await state.read("MERGE_MSG"),
1348
+ await state.read("SQUASH_MSG"),
1349
+ undefined,
1350
+ mergeHeads,
1351
+ pickHead,
1352
+ )
1353
+ : [];
1354
+ let text = sb;
1355
+ if (await this.runMessageHooks(hookEnv, hookArgs, undefined)) {
1356
+ text = (await state.read("COMMIT_EDITMSG")) ?? "";
1357
+ }
1358
+ // cleanup_message: cut at the scissors line with -v (commit.verbose)
1359
+ if (this.verboseLevel() > 0) {
1360
+ const comment = commentPrefixOf(this.workingCopy, sb);
1361
+ const cut = `${comment} ------------------------ >8 ------------------------\n`;
1362
+ if (text.startsWith(cut)) text = "";
1363
+ else {
1364
+ const at = text.indexOf(`\n${cut}`);
1365
+ if (at >= 0) text = text.slice(0, at + 1);
1366
+ }
1367
+ }
1368
+ finalMessage = cleanupWith(this.workingCopy, text, cleanup, true);
1369
+ }
1370
+
1371
+ // git's message_is_empty: nothing but whitespace and sign-offs (any text, verbatim);
1372
+ // then template_untouched (only an editor's message: -m, -F and -C drop the template)
1373
+ if (
1374
+ !this.allowEmptyMessage &&
1375
+ (cleanup !== CleanupMode.VERBATIM || finalMessage.length === 0) &&
1376
+ isEmptyMessage(finalMessage)
1377
+ ) {
1378
+ throw new NoMessageError("Aborting commit due to empty commit message.");
1379
+ }
1380
+ if (untouched && !this.allowEmptyMessage) {
1381
+ throw new NoMessageError("Aborting commit; you did not edit the message.");
1382
+ }
1383
+
1384
+ return this.finishCommit(treeId, parents, mergeHeads, pickHead, {
1385
+ author,
1386
+ committer,
1387
+ finalMessage,
1388
+ state,
1389
+ amendedId,
1390
+ commitIndex: index ? () => index.commit() : undefined,
1391
+ editorUsed: editorLike,
1392
+ });
1393
+ }
1394
+
1395
+ /**
1396
+ * prepare_to_commit's refusal of a commit with nothing to commit: the tree is its first
1397
+ * parent's (HEAD's, HEAD^1's when amending), or empty without a first parent, unless a merge is concluded, empty commits are
1398
+ * allowed, or a merge commit is amended.
1399
+ */
1400
+ private async refuseNothingToCommit(
1401
+ treeId: ObjectId,
1402
+ parents: ObjectId[],
1403
+ mergeHeads: ObjectId[],
1404
+ previousCommit: Commit | undefined,
1405
+ ): Promise<void> {
1406
+ if (this.allowEmpty || mergeHeads.length > 0) return;
1407
+ if (parents.length === 0) {
1408
+ // no first parent (an initial commit, or --amend of a root commit): git counts the
1409
+ // index, `cache_nr - ita_nr > 0`; only intent-to-add entries (or none) leave the tree
1410
+ // empty
1411
+ if (treeId === this.objectFormat.emptyTreeId) throw new EmptyCommitError();
1412
+ return;
1413
+ }
1414
+ if (this.amend && (previousCommit?.parents.length ?? 0) > 1) return;
1415
+ const parentCommit = await this.commits.load(parents[0] as ObjectId);
1416
+ if (parentCommit && parentCommit.tree === treeId) throw new EmptyCommitError();
1417
+ }
1418
+
1419
+ /** The commit of `treeId` made, HEAD moved to it, and what was in progress ended. */
1420
+ private async finishCommit(
1421
+ treeId: ObjectId,
1422
+ parents: ObjectId[],
1423
+ mergeHeads: ObjectId[],
1424
+ pickHead: ObjectId | undefined,
1425
+ info: {
1426
+ author: PersonIdent;
1427
+ committer: PersonIdent;
1428
+ finalMessage: string;
1429
+ state: OperationState;
1430
+ amendedId: ObjectId | undefined;
1431
+ /** Renames the index lock over the index, once HEAD has moved (git's commit_index_files) */
1432
+ commitIndex?: () => Promise<void>;
1433
+ /** An editor edited the message (git's use_editor): hooks get no `GIT_EDITOR=:` */
1434
+ editorUsed?: boolean;
1435
+ },
1436
+ ): Promise<CommitResult> {
1437
+ const { author, committer, finalMessage, state, amendedId } = info;
1438
+
383
1439
  // Create commit
384
1440
  const commit: Commit = {
385
1441
  tree: treeId,
@@ -391,103 +1447,525 @@ export class CommitCommand extends GitCommand<CommitResult> {
391
1447
 
392
1448
  const commitId = await this.commits.store(commit);
393
1449
 
394
- // Update HEAD/branch ref
395
- const head = await this.refsStore.get("HEAD");
396
- if (head && isSymbolicRef(head)) {
397
- // HEAD points to a branch - update the branch
398
- await this.refsStore.set(head.target, commitId);
399
- } else {
400
- // Detached HEAD - update HEAD directly
401
- await this.refsStore.set("HEAD", commitId);
402
- }
1450
+ // Update HEAD/branch ref, with git's reflog line in the branch's log and HEAD's
1451
+ // (builtin/commit.c: initial, amend, merge, cherry-pick, else plain)
1452
+ const initial = !(await this.refsStore.resolve("HEAD"))?.objectId;
1453
+ const kind: CommitReflogKind = initial
1454
+ ? "initial"
1455
+ : this.amend
1456
+ ? "amend"
1457
+ : mergeHeads.length > 0
1458
+ ? "merge"
1459
+ : pickHead
1460
+ ? "cherry-pick"
1461
+ : undefined;
1462
+ const action = this.hasReflogAction() ? this.reflogAction("commit") : undefined;
1463
+ const log = this.reflogLine(reflogMessages.commit(kind, finalMessage, action), committer);
1464
+ if (this.hooks.enabled) {
1465
+ // update_head_with_reflog: one transaction on HEAD expecting the commit's parent (none
1466
+ // for an initial commit), as the reference-transaction hook sees it
1467
+ const current = (await this.refsStore.resolve("HEAD"))?.objectId;
1468
+ const result = await this.refsStore.batch(
1469
+ [{ name: "HEAD", old: current ?? null, new: commitId }],
1470
+ log,
1471
+ );
1472
+ if (!result.ok) {
1473
+ throw new GitApiError(
1474
+ `fatal: cannot lock ref 'HEAD': ${result.rejected.map((r) => r.reason).join(", ")}`,
1475
+ );
1476
+ }
1477
+ } else await updateHead(this.refsStore, commitId, log);
403
1478
 
404
1479
  this.setCallable(false);
405
1480
 
1481
+ // the commit ends what was in progress (git's sequencer_post_commit_cleanup and the
1482
+ // state files cmd_commit unlinks), then the new index (commit_index_files), then applies
1483
+ // a merge's autostash
1484
+ await this.cleanupAfterCommit(state, info.commitIndex);
1485
+
1486
+ // the post-commit hook, over the index (whatever the commit recorded)
1487
+ if (this.hooks.enabled) {
1488
+ await this.hooks.run("post-commit", {
1489
+ env: await this.commitHookEnv(info.editorUsed ?? false, undefined),
1490
+ });
1491
+ }
1492
+
1493
+ // commit_post_rewrite: the amended commit's notes carried over (notes.rewriteRef), then
1494
+ // the post-rewrite hook told "amend" with "<old> <new>" on stdin
1495
+ if (amendedId && !this.noPostRewrite) {
1496
+ // git exports the amend's author (determine_author_info): the notes commit's too
1497
+ await copyNotesForAmend(this.notesContext(), amendedId, commitId, commit.author);
1498
+ if (this.hooks.enabled) {
1499
+ await this.hooks.run("post-rewrite", {
1500
+ args: ["amend"],
1501
+ stdin: `${amendedId} ${commitId}\n`,
1502
+ });
1503
+ }
1504
+ }
1505
+
406
1506
  // Return commit with its ID (like JGit's RevCommit)
407
1507
  return { ...commit, id: commitId };
408
1508
  }
409
1509
 
410
1510
  /**
411
- * Build tree for --only mode.
412
- *
413
- * Combines parent tree with specified paths from staging area.
414
- *
415
- * @param parentCommitId Parent commit ID
416
- * @returns Tree ObjectId
1511
+ * The variables of the commit hooks (git's `run_commit_hook`): `GIT_INDEX_FILE` names the
1512
+ * index the commit records (the lock `-a` and a partial commit write; git's false index of
1513
+ * a partial commit is not kept as a file here), and `GIT_EDITOR=:` tells a hook that no
1514
+ * editor runs.
417
1515
  */
418
- private async buildOnlyTree(parentCommitId: ObjectId): Promise<ObjectId> {
419
- const parentCommit = await this.commits.load(parentCommitId);
420
- if (!parentCommit) {
421
- throw new RefNotFoundError(parentCommitId, "Parent commit not found");
1516
+ private async commitHookEnv(
1517
+ editorUsed: boolean,
1518
+ index: HeldIndex | undefined,
1519
+ /** A partial commit's false index (its host path), which the hooks see in its place */
1520
+ falseIndexPath?: string,
1521
+ ): Promise<Record<string, string>> {
1522
+ if (!this.hooks.enabled) return {};
1523
+ return {
1524
+ GIT_INDEX_FILE:
1525
+ falseIndexPath ??
1526
+ (index ? await this.hooks.gitPath("index.lock", true) : await this.hooks.gitPath("index")),
1527
+ ...(editorUsed ? {} : { GIT_EDITOR: ":" }),
1528
+ };
1529
+ }
1530
+
1531
+ /** Runs a hook that can refuse the commit; whether it ran. */
1532
+ private async runCommitHook(
1533
+ name: string,
1534
+ env: Record<string, string>,
1535
+ args: string[] = [],
1536
+ ): Promise<boolean> {
1537
+ const result = await this.hooks.run(name, { args, env });
1538
+ if (result && result.exitCode !== 0) {
1539
+ throw new HookFailedError(
1540
+ name,
1541
+ result.exitCode,
1542
+ `the ${name} hook refused the commit (exit code ${result.exitCode})`,
1543
+ this.hooks.output,
1544
+ );
422
1545
  }
1546
+ return result !== undefined;
1547
+ }
423
1548
 
424
- // Collect staging entries for onlyPaths
425
- const onlyPathSet = new Set(this.onlyPaths);
426
- const stagingEntriesMap = new Map<string, { objectId: ObjectId; mode: number }>();
1549
+ /**
1550
+ * The arguments of prepare-commit-msg after the message file (prepare_to_commit's
1551
+ * hook_arg1 and hook_arg2): where the message came from.
1552
+ */
1553
+ private prepareMessageHookArgs(
1554
+ mergeMsg: string | undefined,
1555
+ squashMsg: string | undefined,
1556
+ templateText: string | undefined,
1557
+ mergeHeads: ObjectId[],
1558
+ pickHead: ObjectId | undefined,
1559
+ ): string[] {
1560
+ if (this.message !== undefined) return ["message"];
1561
+ // --amend without a message reuses HEAD's (git's use_message = "HEAD")
1562
+ if (this.amend) return ["commit", "HEAD"];
1563
+ if (mergeMsg !== undefined) return [squashMsg !== undefined ? "squash" : "merge"];
1564
+ if (squashMsg !== undefined) return ["squash"];
1565
+ if (templateText !== undefined) return ["template"];
1566
+ if (mergeHeads.length > 0) return ["merge"];
1567
+ if (pickHead) return ["commit", "CHERRY_PICK_HEAD"];
1568
+ return [];
1569
+ }
427
1570
 
428
- for await (const entry of this.staging.entries()) {
429
- if (onlyPathSet.has(entry.path) && entry.stage === 0) {
430
- stagingEntriesMap.set(entry.path, {
431
- objectId: entry.objectId,
432
- mode: entry.mode,
433
- });
434
- }
1571
+ /**
1572
+ * prepare-commit-msg, the editor (when one runs) and commit-msg (not with --no-verify)
1573
+ * over COMMIT_EDITMSG, in prepare_to_commit's order; whether any hook ran (the file is then
1574
+ * to be read back). A non-zero commit-msg refuses the commit, as does prepare-commit-msg.
1575
+ */
1576
+ private async runMessageHooks(
1577
+ env: Record<string, string>,
1578
+ args: string[],
1579
+ edit: (() => Promise<void>) | undefined,
1580
+ ): Promise<boolean> {
1581
+ if (!this.hooks.enabled) {
1582
+ await edit?.();
1583
+ return false;
435
1584
  }
1585
+ const file = await this.hooks.gitPath("COMMIT_EDITMSG");
1586
+ let ran = await this.runCommitHook("prepare-commit-msg", env, [file, ...args]);
1587
+ await edit?.();
1588
+ if (!this.noVerify) ran = (await this.runCommitHook("commit-msg", env, [file])) || ran;
1589
+ return ran;
1590
+ }
436
1591
 
437
- // Create builder and populate with filtered tree
438
- const builder = this.staging.createBuilder();
439
-
440
- // Walk parent tree and add entries NOT in onlyPaths
441
- await this.addTreeFiltered(builder, parentCommit.tree, "", onlyPathSet);
1592
+ /** The commits MERGE_HEAD names (one per line), none without a merge in progress. */
1593
+ private async mergeHeads(state: OperationState): Promise<ObjectId[]> {
1594
+ const text = await state.read("MERGE_HEAD");
1595
+ if (text !== undefined) {
1596
+ return text
1597
+ .split("\n")
1598
+ .map((l) => l.trim())
1599
+ .filter((l) => /^[0-9a-f]{40,64}$/.test(l));
1600
+ }
1601
+ const id = await state.ref("MERGE_HEAD");
1602
+ return id ? [id] : [];
1603
+ }
442
1604
 
443
- // Add staging entries for onlyPaths
444
- for (const [path, { objectId, mode }] of stagingEntriesMap) {
445
- builder.add({
446
- path,
447
- mode,
448
- objectId,
449
- size: 0,
450
- mtime: Date.now(),
451
- });
1605
+ /** The heads none of the others reaches (git's reduce_heads), in their order. */
1606
+ private async reduceHeads(heads: ObjectId[]): Promise<ObjectId[]> {
1607
+ const out: ObjectId[] = [];
1608
+ for (const head of heads) {
1609
+ let reached = false;
1610
+ for (const other of heads) {
1611
+ if (other === head) continue;
1612
+ if (await this.commits.isAncestor(head, other)) {
1613
+ reached = true;
1614
+ break;
1615
+ }
1616
+ }
1617
+ if (!reached) out.push(head);
452
1618
  }
1619
+ return out.length > 0 ? out : heads.slice(0, 1);
1620
+ }
453
1621
 
454
- await builder.finish();
1622
+ /**
1623
+ * After the commit: the merge state removed (MERGE_HEAD, MERGE_MSG, MERGE_MODE,
1624
+ * SQUASH_MSG, AUTO_MERGE), a stopped cherry-pick or revert ended (its sequencer state
1625
+ * too once it was the last pick), and MERGE_AUTOSTASH applied back, as `git commit`.
1626
+ */
1627
+ private async cleanupAfterCommit(
1628
+ state: OperationState,
1629
+ commitIndex: (() => Promise<void>) | undefined,
1630
+ ): Promise<void> {
1631
+ if (!state.supported) {
1632
+ await commitIndex?.();
1633
+ return;
1634
+ }
1635
+ const picking =
1636
+ (await state.ref("CHERRY_PICK_HEAD")) !== undefined ||
1637
+ (await state.ref("REVERT_HEAD")) !== undefined;
1638
+ // sequencer_post_commit_cleanup: CHERRY_PICK_HEAD and REVERT_HEAD when there, AUTO_MERGE
1639
+ // in any case (git 2.5x's reference-transaction hook hears of it)
1640
+ await state.removeRef("CHERRY_PICK_HEAD", "REVERT_HEAD");
1641
+ await state.deleteRef("AUTO_MERGE");
1642
+ await state.removeRef("MERGE_HEAD");
1643
+ await state.remove("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "SQUASH_MSG");
1644
+ if (picking) {
1645
+ // have_finished_the_last_pick: the todo holds no more than the pick just committed
1646
+ const todo = (await state.read("sequencer/todo")) ?? "";
1647
+ const left = todo.split("\n").filter((l) => l.trim() && !l.trim().startsWith("#"));
1648
+ if (left.length <= 1) await state.remove("sequencer");
1649
+ }
1650
+ await commitIndex?.();
1651
+ const autostash = (await state.read("MERGE_AUTOSTASH"))?.trim();
1652
+ if (autostash) {
1653
+ await state.remove("MERGE_AUTOSTASH");
1654
+ await applyAutostash(
1655
+ {
1656
+ workingCopy: this.workingCopy,
1657
+ worktree: this.worktreeIterator ?? this.worktreeAccess,
1658
+ staging: this.staging,
1659
+ blobs: this.blobs,
1660
+ trees: this.trees,
1661
+ commits: this.commits,
1662
+ refs: this.refsStore,
1663
+ },
1664
+ autostash,
1665
+ );
1666
+ }
1667
+ }
455
1668
 
456
- // Now write tree from staging
457
- return await this.staging.writeTree(this.trees);
1669
+ /**
1670
+ * The index held for a commit that changes it (git's `repo_hold_locked_index`): the
1671
+ * index lock taken now (a staging with an index file), released on failure with the
1672
+ * staging as it was before (read again, or its unwritten edits put back).
1673
+ */
1674
+ private async holdIndex(): Promise<HeldIndex> {
1675
+ const staging = this.staging;
1676
+ const unwritten = staging.hasUnwrittenChanges?.() !== false;
1677
+ // what the staging held, for a staging that cannot read it back (no index file) or that
1678
+ // holds edits not yet written
1679
+ let lock: StagingIndexLock | undefined;
1680
+ try {
1681
+ lock = staging.lockIndex ? await staging.lockIndex() : undefined;
1682
+ } catch (error) {
1683
+ throw indexLockError(error, this.workingCopy);
1684
+ }
1685
+ // the staging as it is, put back exactly (the entry objects kept as read included)
1686
+ const saved = !lock || unwritten ? staging.saveState?.() : undefined;
1687
+ const snapshot =
1688
+ (!lock || unwritten) && !saved
1689
+ ? {
1690
+ entries: (staging.entryList?.() ?? (await collectEntries(staging))).slice(),
1691
+ cacheTree: staging.getCacheTree?.(),
1692
+ }
1693
+ : undefined;
1694
+ let done = false;
1695
+ return {
1696
+ write: async () => {
1697
+ await lock?.write();
1698
+ },
1699
+ reread: async () => {
1700
+ if (lock?.reread) await lock.reread();
1701
+ else if (lock) await staging.read();
1702
+ },
1703
+ commit: async () => {
1704
+ if (lock) await lock.commit();
1705
+ else await staging.write();
1706
+ done = true;
1707
+ },
1708
+ release: async () => {
1709
+ if (done) return;
1710
+ done = true;
1711
+ await lock?.rollback();
1712
+ if (saved) {
1713
+ staging.restoreState?.(saved);
1714
+ return;
1715
+ }
1716
+ if (!snapshot) {
1717
+ await staging.read();
1718
+ return;
1719
+ }
1720
+ const builder = staging.createBuilder();
1721
+ for (const entry of snapshot.entries) builder.add(entry);
1722
+ await builder.finish();
1723
+ staging.setCacheTree?.(snapshot.cacheTree);
1724
+ },
1725
+ };
458
1726
  }
459
1727
 
460
1728
  /**
461
- * Recursively walk tree and add entries to builder, excluding specified paths.
1729
+ * The paths a partial commit takes (git's `list_paths`): those of the index (any stage)
1730
+ * and of HEAD's tree the pathspec matches (`ce_path_match`, magic and globs as git's), in
1731
+ * git's order, each with whether its index entry is skip-worktree. Refused during a
1732
+ * merge, a cherry-pick or a rebase (git's whence), and when an element of the pathspec
1733
+ * matches nothing (`report_path_error`).
462
1734
  */
463
- private async addTreeFiltered(
464
- builder: ReturnType<typeof this.staging.createBuilder>,
1735
+ private async listPartialPaths(
1736
+ state: OperationState,
1737
+ mergeHeads: ObjectId[],
1738
+ headId: ObjectId | undefined,
1739
+ ): Promise<Map<string, boolean>> {
1740
+ if (mergeHeads.length > 0) {
1741
+ throw new InvalidArgumentError(
1742
+ "only",
1743
+ this.onlyPaths,
1744
+ "fatal: cannot do a partial commit during a merge.",
1745
+ );
1746
+ }
1747
+ const pick = await state.ref("CHERRY_PICK_HEAD");
1748
+ if (pick) {
1749
+ // sequencer_determine_whence: a rebase stopped at this pick, else a cherry-pick
1750
+ const rebasing =
1751
+ (await state.read("rebase-merge/head-name")) !== undefined &&
1752
+ (await state.ref("REBASE_HEAD")) === pick;
1753
+ throw new InvalidArgumentError(
1754
+ "only",
1755
+ this.onlyPaths,
1756
+ `fatal: cannot do a partial commit during a ${rebasing ? "rebase" : "cherry-pick"}.`,
1757
+ );
1758
+ }
1759
+
1760
+ let items: PathspecItem[];
1761
+ try {
1762
+ items = parsePathspec(this.onlyPaths, { attr: true });
1763
+ } catch (error) {
1764
+ throw new InvalidArgumentError("only", this.onlyPaths, `fatal: ${(error as Error).message}`);
1765
+ }
1766
+ // the elements as given (and the "." git adds when every element excludes)
1767
+ const originals =
1768
+ items.length > this.onlyPaths.length ? [...this.onlyPaths, "."] : [...this.onlyPaths];
1769
+ // git's overlay_tree_on_index: HEAD's files at stage 1, among the index's entries (its
1770
+ // conflict stages hoisted to 3), a HEAD file the index has at stage 0 left out; matched
1771
+ // in that order (the order decides what an element matched exactly skips, as in git)
1772
+ type Listed = { path: string; key: number; mode: number; skipWorktree: boolean };
1773
+ const listed: Listed[] = [];
1774
+ const stage0 = new Set<string>();
1775
+ for await (const entry of this.staging.entries()) {
1776
+ if (entry.stage === 0) stage0.add(entry.path);
1777
+ listed.push({
1778
+ path: entry.path,
1779
+ key: entry.stage === 0 ? 0 : 3,
1780
+ mode: entry.mode,
1781
+ skipWorktree: entry.skipWorktree === true,
1782
+ });
1783
+ }
1784
+ if (headId) {
1785
+ const head = await this.commits.load(headId);
1786
+ if (!head) throw new RefNotFoundError(headId, "HEAD commit not found");
1787
+ // only the directories a positive element can match something in are read
1788
+ const positive = items.filter((i) => !i.exclude);
1789
+ const mayMatch = (dir: string) => positive.some((item) => pathspecItemMayMatch(item, dir));
1790
+ const files: Array<{ path: string; mode: number }> = [];
1791
+ await this.collectTreeFiles(head.tree, "", mayMatch, files);
1792
+ for (const file of files) {
1793
+ if (!stage0.has(file.path)) listed.push({ ...file, key: 1, skipWorktree: false });
1794
+ }
1795
+ listed.sort((a, b) => compareGitPaths(a.path, b.path) || a.key - b.key);
1796
+ }
1797
+ // `:(attr:...)`: the attributes of the listed paths (match_pathspec_attrs)
1798
+ const attributes = PathspecAttributes.forWorktree(items, this.getWorktreeIterator());
1799
+ await attributes?.load(listed.map((entry) => entry.path));
1800
+ const seen = items.map(() => 0);
1801
+ const paths = new Map<string, boolean>();
1802
+ for (const entry of listed) {
1803
+ const flags = isGitlink(entry.mode) ? DO_MATCH_DIRECTORY : 0;
1804
+ if (!matchPathspecSeen(items, entry.path, flags, seen)) continue;
1805
+ paths.set(entry.path, (paths.get(entry.path) ?? false) || entry.skipWorktree);
1806
+ }
1807
+ const errors = pathspecErrors(originals, seen);
1808
+ if (errors.length > 0) {
1809
+ // report_path_error: list_paths fails, prepare_index exits 1
1810
+ throw new InvalidArgumentError(
1811
+ "only",
1812
+ originals.filter((_, i) => !seen[i]),
1813
+ errors.join("\n"),
1814
+ );
1815
+ }
1816
+ // git's string_list: sorted by the paths' bytes
1817
+ return new Map([...paths].sort(([a], [b]) => compareGitPaths(a, b)));
1818
+ }
1819
+
1820
+ /** The files (and gitlinks) of a tree, in the directories `mayMatch` lets in. */
1821
+ private async collectTreeFiles(
465
1822
  treeId: ObjectId,
466
1823
  prefix: string,
467
- excludePaths: Set<string>,
1824
+ mayMatch: (dir: string) => boolean,
1825
+ files: Array<{ path: string; mode: number }>,
468
1826
  ): Promise<void> {
469
1827
  for await (const entry of this.trees.loadTree(treeId)) {
470
- const fullPath = prefix ? `${prefix}/${entry.name}` : entry.name;
1828
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
1829
+ if (entry.mode === FileMode.TREE) {
1830
+ if (mayMatch(path)) await this.collectTreeFiles(entry.id, path, mayMatch, files);
1831
+ } else {
1832
+ files.push({ path, mode: entry.mode });
1833
+ }
1834
+ }
1835
+ }
1836
+
1837
+ /**
1838
+ * git's partial commit (`prepare_index`, `add_remove_files`): each listed path (but the
1839
+ * skip-worktree ones) as git's `add_remove_files` takes it, literally: a file (ignored or
1840
+ * not) hashed and staged, a path gone removed, a submodule staged at the commit checked
1841
+ * out in it, a directory without one refused before anything changes ("'<path>' does not
1842
+ * have a commit checked out"); the index then gets its
1843
+ * cache-tree (none while it holds conflicts) and is written into the lock. The tree
1844
+ * committed is HEAD's with the same paths taken (git's false index), returned as HEAD's
1845
+ * tree and those edits: stored by {@link storeFalseIndex}, never by a dry run.
1846
+ */
1847
+ private async preparePartialCommit(
1848
+ paths: Map<string, boolean>,
1849
+ headId: ObjectId | undefined,
1850
+ index: HeldIndex,
1851
+ ): Promise<FalseIndex> {
1852
+ const taken = [...paths].filter(([, skipWorktree]) => !skipWorktree).map(([path]) => path);
1853
+ // the lstat of each path, before the index is touched
1854
+ const found = new Map<string, WorktreeEntry | undefined>();
1855
+ let worktree: Worktree | undefined;
1856
+ if (taken.length > 0) {
1857
+ worktree = this.getWorktreeIterator();
1858
+ if (!worktree) {
1859
+ throw new StoreNotAvailableError(
1860
+ "Worktree",
1861
+ "Working tree iterator required for a partial commit. " +
1862
+ "Ensure WorkingCopy has worktree or call setWorktreeStore().",
1863
+ );
1864
+ }
1865
+ }
1866
+ if (worktree) {
1867
+ for (const path of taken) {
1868
+ const entry = await worktree.getEntry(path);
1869
+ // add_to_index of a directory: a gitlink to the commit checked out in the repository
1870
+ // there (index_path's resolve_gitlink_ref, a gitfile followed), refused before
1871
+ // anything changes when there is none; git 2.5x adds the "unable to index file" line
1872
+ if (entry?.isDirectory && !(await readGitlinkHead(worktree, path))) {
1873
+ throw new GitApiError(
1874
+ `error: '${path}' does not have a commit checked out\n` +
1875
+ `error: unable to index file '${path}'\nfatal: updating files failed`,
1876
+ );
1877
+ }
1878
+ found.set(path, entry);
1879
+ }
1880
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
1881
+ const adder = await IndexAdder.open(this.staging, this.blobs, trust);
1882
+ for (const path of taken) {
1883
+ const entry = found.get(path);
1884
+ if (entry) await adder.add(worktree, path, entry);
1885
+ else adder.remove(path);
1886
+ }
1887
+ await adder.finish();
1888
+ }
1889
+ // the real index, with a cache-tree made valid as git's cache_tree_update before
1890
+ // write_locked_index (none while it holds conflicts: the edits' invalidations stay)
1891
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
1892
+ await index.write();
471
1893
 
472
- // Check if this is a tree (directory)
473
- const isTree = (entry.mode & 0o170000) === 0o040000;
1894
+ // the false index: HEAD's tree with the same paths as the index now has them
1895
+ const edits = new Map<string, { mode: number; id: ObjectId } | null>();
1896
+ for (const path of taken) {
1897
+ const entry = found.get(path) ? await this.staging.getEntry(path) : undefined;
1898
+ edits.set(
1899
+ path,
1900
+ entry && !entry.intentToAdd ? { mode: entry.mode, id: entry.objectId } : null,
1901
+ );
1902
+ }
1903
+ const head = headId ? await this.commits.load(headId) : undefined;
1904
+ if (headId && !head) throw new RefNotFoundError(headId, "HEAD commit not found");
1905
+ return { headTree: head?.tree, edits: [...edits] };
1906
+ }
474
1907
 
475
- if (isTree) {
476
- // Recursively process subtree
477
- await this.addTreeFiltered(builder, entry.id, fullPath, excludePaths);
478
- } else {
479
- // Only add if not in excluded paths
480
- if (!excludePaths.has(fullPath)) {
481
- builder.add({
482
- path: fullPath,
483
- mode: entry.mode,
484
- objectId: entry.id,
485
- size: 0,
486
- mtime: Date.now(),
487
- });
1908
+ /** The tree of a partial commit's false index, stored (with the directories it changes). */
1909
+ private async storeFalseIndex(falseIndex: FalseIndex): Promise<ObjectId> {
1910
+ return (await this.editTree(falseIndex.headTree, falseIndex.edits)) ?? this.trees.store([]);
1911
+ }
1912
+
1913
+ /** The files of a partial commit's false index, without storing a tree. */
1914
+ private async falseIndexFiles(
1915
+ falseIndex: FalseIndex,
1916
+ ): Promise<Map<string, { objectId: ObjectId; mode: number }>> {
1917
+ const flat: Map<string, { objectId: ObjectId; mode: number }> = await flatTree(
1918
+ this.trees,
1919
+ falseIndex.headTree,
1920
+ );
1921
+ for (const [path, edit] of falseIndex.edits) {
1922
+ if (edit) {
1923
+ // a file in place of a directory of HEAD (or the reverse) replaces it
1924
+ for (const key of [...flat.keys()]) if (key.startsWith(`${path}/`)) flat.delete(key);
1925
+ for (let at = path.indexOf("/"); at >= 0; at = path.indexOf("/", at + 1)) {
1926
+ flat.delete(path.slice(0, at));
488
1927
  }
1928
+ flat.set(path, { objectId: edit.id, mode: edit.mode });
1929
+ } else flat.delete(path);
1930
+ }
1931
+ return flat;
1932
+ }
1933
+
1934
+ /**
1935
+ * A tree with the given files set (or removed, for null), only the directories on their
1936
+ * paths stored again; undefined when nothing is left in it.
1937
+ */
1938
+ private async editTree(
1939
+ treeId: ObjectId | undefined,
1940
+ edits: Array<[string, { mode: number; id: ObjectId } | null]>,
1941
+ ): Promise<ObjectId | undefined> {
1942
+ const entries = new Map<string, TreeEntry>();
1943
+ if (treeId) {
1944
+ for await (const entry of this.trees.loadTree(treeId)) entries.set(entry.name, entry);
1945
+ }
1946
+ const subdirs = new Map<string, Array<[string, { mode: number; id: ObjectId } | null]>>();
1947
+ for (const [path, edit] of edits) {
1948
+ const slash = path.indexOf("/");
1949
+ if (slash >= 0) {
1950
+ const dir = path.slice(0, slash);
1951
+ const list = subdirs.get(dir) ?? [];
1952
+ list.push([path.slice(slash + 1), edit]);
1953
+ subdirs.set(dir, list);
1954
+ } else if (edit) {
1955
+ entries.set(path, { name: path, mode: edit.mode, id: edit.id });
1956
+ } else if (entries.get(path)?.mode !== FileMode.TREE) {
1957
+ entries.delete(path);
489
1958
  }
490
1959
  }
1960
+ for (const [dir, list] of subdirs) {
1961
+ const existing = entries.get(dir);
1962
+ const base = existing?.mode === FileMode.TREE ? existing.id : undefined;
1963
+ const id = await this.editTree(base, list);
1964
+ if (id) entries.set(dir, { name: dir, mode: FileMode.TREE, id });
1965
+ else if (base) entries.delete(dir);
1966
+ }
1967
+ if (entries.size === 0) return undefined;
1968
+ return this.trees.store([...entries.values()]);
491
1969
  }
492
1970
 
493
1971
  /**
@@ -496,7 +1974,7 @@ export class CommitCommand extends GitCommand<CommitResult> {
496
1974
  * Uses AddCommand with setUpdate(true) to stage changes,
497
1975
  * equivalent to `git add -u .` which JGit does for --all.
498
1976
  */
499
- private async stageTrackedChanges(): Promise<void> {
1977
+ private async stageTrackedChanges(paths: string[] = []): Promise<void> {
500
1978
  // Get working tree iterator
501
1979
  const worktree = this.getWorktreeIterator();
502
1980
  if (!worktree) {
@@ -508,9 +1986,15 @@ export class CommitCommand extends GitCommand<CommitResult> {
508
1986
  }
509
1987
 
510
1988
  // Use AddCommand to stage all modified tracked files
1989
+ // git's add_files_to_cache without a pathspec (`commit -a`): no element to report
511
1990
  const addCommand = new AddCommand(this._workingCopy);
512
- addCommand.addFilepattern(".");
513
1991
  addCommand.setUpdate(true);
1992
+ // `-i <paths>`: the tracked paths they match (report_path_error: an element matching no
1993
+ // index entry fails, exit status 128)
1994
+ for (const path of paths) addCommand.addFilepattern(path);
1995
+ if (paths.length > 0) addCommand.setFilesToCache(true);
1996
+ // into the index lock the commit holds, once the commit's tree is made
1997
+ addCommand.setWriteIndex(false);
514
1998
  addCommand.setWorktreeStore(worktree);
515
1999
  await addCommand.call();
516
2000
  }
@@ -527,3 +2011,135 @@ export class CommitCommand extends GitCommand<CommitResult> {
527
2011
  return this.worktreeAccess;
528
2012
  }
529
2013
  }
2014
+
2015
+ /** git's "paths '<first> ...' with -a does not make sense". */
2016
+ function pathsWithAllError(paths: readonly string[]): IncompatibleOptionsError {
2017
+ return new IncompatibleOptionsError(
2018
+ ["--all", "--only"],
2019
+ `fatal: paths '${paths[0]} ...' with -a does not make sense`,
2020
+ );
2021
+ }
2022
+
2023
+ /** A partial commit's false index written for the hooks (see `writeFalseIndexFile`). */
2024
+ interface FalseIndexFile {
2025
+ /** Its absolute host path (else its path from the worktree top): `GIT_INDEX_FILE` */
2026
+ hostPath: string;
2027
+ /** Reads it back as a hook left it: the tree to commit */
2028
+ reread(): Promise<ObjectId>;
2029
+ /** Removes it (git's rollback of `false_lock`) */
2030
+ remove(): Promise<void>;
2031
+ }
2032
+
2033
+ /** A held index whose commit or release also runs `cleanup` (after the index's own). */
2034
+ function withCleanup(index: HeldIndex, cleanup: () => Promise<void>): HeldIndex {
2035
+ return {
2036
+ write: () => index.write(),
2037
+ reread: () => index.reread(),
2038
+ commit: async () => {
2039
+ try {
2040
+ await index.commit();
2041
+ } finally {
2042
+ await cleanup();
2043
+ }
2044
+ },
2045
+ release: async () => {
2046
+ try {
2047
+ await index.release();
2048
+ } finally {
2049
+ await cleanup();
2050
+ }
2051
+ },
2052
+ };
2053
+ }
2054
+
2055
+ /** A partial commit's false index: HEAD's tree with the named paths set or removed. */
2056
+ interface FalseIndex {
2057
+ headTree: ObjectId | undefined;
2058
+ edits: Array<[string, { mode: number; id: ObjectId } | null]>;
2059
+ }
2060
+
2061
+ /**
2062
+ * The index lock another process holds, as git's `unable_to_lock_die` reports it (git 2.5x's
2063
+ * wording: 2.43 adds "e.g. an editor opened by 'git commit'..." instead); other errors as
2064
+ * they are.
2065
+ */
2066
+ function indexLockError(error: unknown, workingCopy: unknown): unknown {
2067
+ if (!(error instanceof Error) || error.name !== "IndexLockedError") return error;
2068
+ const gitDir = (workingCopy as { config?: { hostGitDir?: string } }).config?.hostGitDir;
2069
+ const lockPath = gitDir ? `${gitDir.replace(/\/+$/, "")}/index.lock` : ".git/index.lock";
2070
+ return new IndexLockFailedError(
2071
+ lockPath,
2072
+ `fatal: Unable to create '${lockPath}': File exists.\n\n` +
2073
+ "Another git process seems to be running in this repository, or the lock file may be stale",
2074
+ { cause: error },
2075
+ );
2076
+ }
2077
+
2078
+ /** The index a commit holds while it changes it (see `CommitCommand.holdIndex`). */
2079
+ interface HeldIndex {
2080
+ /** Writes the staging's entries into the index lock (nothing without an index file). */
2081
+ write(): Promise<void>;
2082
+ /** Reads the index lock back into the staging, as a hook left it (git's read_index_from). */
2083
+ reread(): Promise<void>;
2084
+ /** The index lock renamed over the index (a staging without one: written). */
2085
+ commit(): Promise<void>;
2086
+ /** On failure: the lock removed, the staging as it was before. Idempotent. */
2087
+ release(): Promise<void>;
2088
+ }
2089
+
2090
+ /** Every entry of the staging, in its order. */
2091
+ async function collectEntries(staging: Staging): Promise<StagingEntry[]> {
2092
+ const out: StagingEntry[] = [];
2093
+ for await (const entry of staging.entries()) out.push(entry);
2094
+ return out;
2095
+ }
2096
+
2097
+ const isGitlink = (mode: number) => (mode & 0o170000) === 0o160000;
2098
+
2099
+ /**
2100
+ * git's `template_untouched`: the cleaned-up message is the template (cleaned up the same
2101
+ * way, comments kept unless the mode strips them) followed by nothing but whitespace and
2102
+ * sign-offs. A verbatim message that is not empty is never untouched; nor is any without a
2103
+ * template (or with an empty one).
2104
+ */
2105
+ function templateUntouched(
2106
+ message: string,
2107
+ template: string | undefined,
2108
+ mode: CleanupMode,
2109
+ comment: string,
2110
+ ): boolean {
2111
+ if (mode === CleanupMode.VERBATIM && message.length > 0) return false;
2112
+ if (!template) return false;
2113
+ const tmpl = stripspace(template, mode === CleanupMode.STRIP ? comment : undefined);
2114
+ const rest = message.startsWith(tmpl) ? message.slice(tmpl.length) : message;
2115
+ return isEmptyMessage(rest);
2116
+ }
2117
+
2118
+ /** git's `rest_is_empty`: only whitespace and `Signed-off-by:` lines. */
2119
+ function isEmptyMessage(message: string): boolean {
2120
+ return message
2121
+ .split("\n")
2122
+ .every((line) => line.startsWith("Signed-off-by: ") || /^[ \t\r]*$/.test(line));
2123
+ }
2124
+
2125
+ /** A git boolean (`fallback` when unset or not one). */
2126
+ function parseBool(value: string | undefined, fallback: boolean): boolean {
2127
+ if (value === undefined) return fallback;
2128
+ const v = value.trim().toLowerCase();
2129
+ if (v === "" || v === "false" || v === "no" || v === "off" || v === "0") return false;
2130
+ if (v === "true" || v === "yes" || v === "on" || v === "1") return true;
2131
+ return fallback;
2132
+ }
2133
+
2134
+ /**
2135
+ * The editor of a commit message (`CommitCommand.setEditor`): the path of the message file
2136
+ * within the git directory (`COMMIT_EDITMSG`) and its text; it returns the edited text, or
2137
+ * nothing (anything but a string) when it edited the file in place.
2138
+ */
2139
+ export type CommitEditor = (path: string, text: string) => Promise<unknown>;
2140
+
2141
+ /** What `CommitCommand.callDryRun` gives: the status text and git's exit code. */
2142
+ export interface CommitDryRunResult extends StatusTextResult {
2143
+ /** 0 when there is something to commit, 1 when not (dry_run_commit) */
2144
+ exitCode: number;
2145
+ }