@statewalker/vcs-commands 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (546) 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 +117 -0
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +78 -1
  73. package/dist/commands/core-config.d.ts.map +1 -1
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +149 -10
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +54 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +31 -0
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +42 -8
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +155 -1
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +2 -0
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-working-tree.d.ts +23 -0
  237. package/dist/commands/stash-working-tree.d.ts.map +1 -1
  238. package/dist/commands/status-command.d.ts +300 -15
  239. package/dist/commands/status-command.d.ts.map +1 -1
  240. package/dist/commands/status-format.d.ts +155 -0
  241. package/dist/commands/status-format.d.ts.map +1 -0
  242. package/dist/commands/status-header.d.ts +64 -0
  243. package/dist/commands/status-header.d.ts.map +1 -0
  244. package/dist/commands/strerror.d.ts +7 -0
  245. package/dist/commands/strerror.d.ts.map +1 -0
  246. package/dist/commands/submodule-config.d.ts +38 -0
  247. package/dist/commands/submodule-config.d.ts.map +1 -0
  248. package/dist/commands/submodule-summary-command.d.ts +80 -0
  249. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary.d.ts +150 -0
  251. package/dist/commands/submodule-summary.d.ts.map +1 -0
  252. package/dist/commands/switch-command.d.ts +132 -0
  253. package/dist/commands/switch-command.d.ts.map +1 -0
  254. package/dist/commands/tag-command.d.ts +23 -2
  255. package/dist/commands/tag-command.d.ts.map +1 -1
  256. package/dist/commands/tracking-info.d.ts +64 -0
  257. package/dist/commands/tracking-info.d.ts.map +1 -0
  258. package/dist/commands/trailers.d.ts +73 -0
  259. package/dist/commands/trailers.d.ts.map +1 -0
  260. package/dist/commands/tree-restore.d.ts +85 -1
  261. package/dist/commands/tree-restore.d.ts.map +1 -1
  262. package/dist/commands/untracked-cache-support.d.ts +53 -0
  263. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  264. package/dist/commands/worktree-add-command.d.ts +108 -0
  265. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  266. package/dist/commands/worktree-list-command.d.ts +69 -0
  267. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-lock-command.d.ts +44 -0
  269. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-overwrite-checks.d.ts +146 -6
  271. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  272. package/dist/commands/worktree-prune-command.d.ts +48 -0
  273. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  274. package/dist/commands/worktree-remove-command.d.ts +59 -0
  275. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-repair-command.d.ts +35 -0
  277. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-support.d.ts +64 -0
  279. package/dist/commands/worktree-support.d.ts.map +1 -0
  280. package/dist/commands-DnmlfwGV.js +61620 -0
  281. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  282. package/dist/errors/add-errors.d.ts +55 -0
  283. package/dist/errors/add-errors.d.ts.map +1 -1
  284. package/dist/errors/checkout-errors.d.ts +16 -0
  285. package/dist/errors/checkout-errors.d.ts.map +1 -1
  286. package/dist/errors/command-errors.d.ts +77 -0
  287. package/dist/errors/command-errors.d.ts.map +1 -1
  288. package/dist/errors/commit-errors.d.ts +9 -0
  289. package/dist/errors/commit-errors.d.ts.map +1 -1
  290. package/dist/errors/git-api-error.d.ts +59 -2
  291. package/dist/errors/git-api-error.d.ts.map +1 -1
  292. package/dist/errors/index.d.ts +1 -0
  293. package/dist/errors/index.d.ts.map +1 -1
  294. package/dist/errors/index.js +354 -19
  295. package/dist/errors/rebase-errors.d.ts +9 -0
  296. package/dist/errors/rebase-errors.d.ts.map +1 -1
  297. package/dist/errors/ref-errors.d.ts +32 -0
  298. package/dist/errors/ref-errors.d.ts.map +1 -1
  299. package/dist/errors/transport-errors.d.ts +12 -2
  300. package/dist/errors/transport-errors.d.ts.map +1 -1
  301. package/dist/errors/worktree-errors.d.ts +35 -0
  302. package/dist/errors/worktree-errors.d.ts.map +1 -0
  303. package/dist/git-command-DxvwPrPB.js +7612 -0
  304. package/dist/git-command.d.ts +413 -32
  305. package/dist/git-command.d.ts.map +1 -1
  306. package/dist/git.d.ts +306 -3
  307. package/dist/git.d.ts.map +1 -1
  308. package/dist/index.d.ts +1 -1
  309. package/dist/index.d.ts.map +1 -1
  310. package/dist/index.js +5 -5
  311. package/dist/remote-config/remote-config-store.d.ts +105 -3
  312. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  313. package/dist/remote-config/remote-refs.d.ts +7 -3
  314. package/dist/remote-config/remote-refs.d.ts.map +1 -1
  315. package/dist/rename/detect-renames.d.ts +148 -0
  316. package/dist/rename/detect-renames.d.ts.map +1 -0
  317. package/dist/rename/git-similarity.d.ts +44 -0
  318. package/dist/rename/git-similarity.d.ts.map +1 -0
  319. package/dist/rename/index.d.ts +2 -0
  320. package/dist/rename/index.d.ts.map +1 -1
  321. package/dist/results/binary-patch.d.ts +11 -0
  322. package/dist/results/binary-patch.d.ts.map +1 -0
  323. package/dist/results/blame-format.d.ts +55 -0
  324. package/dist/results/blame-format.d.ts.map +1 -0
  325. package/dist/results/cherry-pick-result.d.ts +10 -0
  326. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  327. package/dist/results/clone-result.d.ts +10 -0
  328. package/dist/results/clone-result.d.ts.map +1 -1
  329. package/dist/results/combined-diff.d.ts +77 -0
  330. package/dist/results/combined-diff.d.ts.map +1 -0
  331. package/dist/results/diff-entry.d.ts +32 -0
  332. package/dist/results/diff-entry.d.ts.map +1 -1
  333. package/dist/results/diff-formatter.d.ts +34 -60
  334. package/dist/results/diff-formatter.d.ts.map +1 -1
  335. package/dist/results/diff-order.d.ts +25 -0
  336. package/dist/results/diff-order.d.ts.map +1 -0
  337. package/dist/results/diff-output.d.ts +249 -0
  338. package/dist/results/diff-output.d.ts.map +1 -0
  339. package/dist/results/fetch-result.d.ts +15 -0
  340. package/dist/results/fetch-result.d.ts.map +1 -1
  341. package/dist/results/index.d.ts +5 -0
  342. package/dist/results/index.d.ts.map +1 -1
  343. package/dist/results/index.js +2 -252
  344. package/dist/results/merge-result.d.ts +15 -1
  345. package/dist/results/merge-result.d.ts.map +1 -1
  346. package/dist/results/pull-result.d.ts +12 -3
  347. package/dist/results/pull-result.d.ts.map +1 -1
  348. package/dist/results/push-result.d.ts +42 -0
  349. package/dist/results/push-result.d.ts.map +1 -1
  350. package/dist/results/quote-path.d.ts +27 -0
  351. package/dist/results/quote-path.d.ts.map +1 -0
  352. package/dist/results/rebase-result.d.ts +28 -1
  353. package/dist/results/rebase-result.d.ts.map +1 -1
  354. package/dist/results/revert-result.d.ts +10 -0
  355. package/dist/results/revert-result.d.ts.map +1 -1
  356. package/dist/results/stash-result.d.ts +5 -0
  357. package/dist/results/stash-result.d.ts.map +1 -1
  358. package/dist/results/status-result.d.ts +60 -6
  359. package/dist/results/status-result.d.ts.map +1 -1
  360. package/dist/results-BZGa2Z3I.js +2934 -0
  361. package/dist/transport-command.d.ts +44 -1
  362. package/dist/transport-command.d.ts.map +1 -1
  363. package/package.json +15 -11
  364. package/src/commands/add-command.ts +1291 -226
  365. package/src/commands/add-patch/add-interactive.ts +941 -0
  366. package/src/commands/add-patch/add-patch.ts +1169 -0
  367. package/src/commands/add-patch/index.ts +5 -0
  368. package/src/commands/add-patch/patch-backend.ts +239 -0
  369. package/src/commands/add-patch/patch-modes.ts +249 -0
  370. package/src/commands/add-patch/patch-session.ts +159 -0
  371. package/src/commands/am/am-command.ts +1111 -0
  372. package/src/commands/am/index.ts +2 -0
  373. package/src/commands/am/mailinfo.ts +1015 -0
  374. package/src/commands/am/patch-format.ts +121 -0
  375. package/src/commands/apply/apply-command.ts +832 -0
  376. package/src/commands/apply/apply-engine.ts +1603 -0
  377. package/src/commands/apply/apply-parse.ts +1209 -0
  378. package/src/commands/apply/apply-types.ts +112 -0
  379. package/src/commands/apply/index.ts +5 -0
  380. package/src/commands/apply/latin1.ts +171 -0
  381. package/src/commands/apply/whitespace.ts +260 -0
  382. package/src/commands/attributes-source.ts +96 -0
  383. package/src/commands/backfill-command.ts +694 -0
  384. package/src/commands/bisect/bisect-checkout.ts +217 -0
  385. package/src/commands/bisect/bisect-command.ts +788 -0
  386. package/src/commands/bisect/bisect-engine.ts +1079 -0
  387. package/src/commands/bisect/bisect-graph.ts +595 -0
  388. package/src/commands/bisect/bisect-quote.ts +92 -0
  389. package/src/commands/bisect/index.ts +4 -0
  390. package/src/commands/blame-command.ts +711 -986
  391. package/src/commands/branch-command.ts +354 -32
  392. package/src/commands/branch-tracking.ts +331 -0
  393. package/src/commands/checkout-command.ts +1290 -243
  394. package/src/commands/checkout-paths.ts +784 -0
  395. package/src/commands/cherry-pick-command.ts +156 -396
  396. package/src/commands/clean-command.ts +504 -156
  397. package/src/commands/clone-command.ts +634 -67
  398. package/src/commands/commit-command.ts +1781 -166
  399. package/src/commands/core-config.ts +161 -6
  400. package/src/commands/date-format.ts +668 -0
  401. package/src/commands/describe-command.ts +2 -0
  402. package/src/commands/diff-command.ts +1898 -110
  403. package/src/commands/diff-textconv.ts +50 -0
  404. package/src/commands/fetch-command.ts +606 -66
  405. package/src/commands/format-patch-command.ts +969 -0
  406. package/src/commands/fsck/fetch-fsck.ts +229 -0
  407. package/src/commands/fsck/fsck-command.ts +3347 -0
  408. package/src/commands/fsck/fsck-loose.ts +287 -0
  409. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  410. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  411. package/src/commands/fsck/fsck-object-table.ts +363 -0
  412. package/src/commands/fsck/fsck-pack.ts +604 -0
  413. package/src/commands/fsck/index.ts +5 -0
  414. package/src/commands/fsck/verify-pack-command.ts +249 -0
  415. package/src/commands/gc-command.ts +147 -1
  416. package/src/commands/git-date.ts +895 -0
  417. package/src/commands/git-describe.ts +316 -0
  418. package/src/commands/git-hooks.ts +1472 -0
  419. package/src/commands/git-ident.ts +344 -0
  420. package/src/commands/hook-command.ts +247 -0
  421. package/src/commands/index-adder.ts +706 -0
  422. package/src/commands/index-host.ts +291 -0
  423. package/src/commands/index.ts +82 -0
  424. package/src/commands/init-command.ts +28 -4
  425. package/src/commands/local-clone.ts +183 -0
  426. package/src/commands/local-transport.ts +762 -0
  427. package/src/commands/log-command.ts +1915 -170
  428. package/src/commands/log-graph.ts +671 -0
  429. package/src/commands/log-output.ts +1359 -0
  430. package/src/commands/ls-remote-command.ts +101 -58
  431. package/src/commands/mailmap.ts +129 -0
  432. package/src/commands/merge-bases.ts +296 -0
  433. package/src/commands/merge-command.ts +1386 -491
  434. package/src/commands/merge-config.ts +25 -0
  435. package/src/commands/merge-drivers.ts +306 -0
  436. package/src/commands/merge-support.ts +1198 -0
  437. package/src/commands/message-cleanup.ts +275 -0
  438. package/src/commands/mv-command.ts +976 -0
  439. package/src/commands/notes-command.ts +890 -0
  440. package/src/commands/notes-commands.ts +87 -0
  441. package/src/commands/notes-merge-command.ts +768 -0
  442. package/src/commands/notes-support.ts +402 -0
  443. package/src/commands/notes-tree.ts +602 -0
  444. package/src/commands/object-id-input.ts +27 -0
  445. package/src/commands/octopus-merge.ts +377 -0
  446. package/src/commands/ort-merge.ts +1660 -0
  447. package/src/commands/ort-recursive.ts +160 -0
  448. package/src/commands/pack-refs-command.ts +39 -22
  449. package/src/commands/patch-id.ts +196 -0
  450. package/src/commands/pathspec-attributes.ts +162 -0
  451. package/src/commands/pathspec.ts +1199 -0
  452. package/src/commands/post-index-change.ts +62 -0
  453. package/src/commands/pretty-format.ts +1431 -0
  454. package/src/commands/promisor-remote.ts +298 -0
  455. package/src/commands/pull-command.ts +207 -22
  456. package/src/commands/push-command.ts +236 -23
  457. package/src/commands/read-tree-command.ts +857 -0
  458. package/src/commands/rebase-command.ts +3808 -371
  459. package/src/commands/rebase-todo.ts +584 -0
  460. package/src/commands/ref-decoration-filter.ts +118 -0
  461. package/src/commands/reflog-messages.ts +177 -0
  462. package/src/commands/remote-command.ts +93 -22
  463. package/src/commands/remote-transport.ts +383 -0
  464. package/src/commands/reset-command.ts +827 -103
  465. package/src/commands/restore-command.ts +350 -0
  466. package/src/commands/rev-list-command.ts +167 -0
  467. package/src/commands/rev-parse-command.ts +277 -0
  468. package/src/commands/revert-command.ts +152 -399
  469. package/src/commands/revision-filenames.ts +254 -0
  470. package/src/commands/revision-range.ts +222 -0
  471. package/src/commands/revision-resolver.ts +1379 -0
  472. package/src/commands/rm-command.ts +613 -67
  473. package/src/commands/sequencer-pick.ts +869 -0
  474. package/src/commands/sequencer-support.ts +869 -0
  475. package/src/commands/serve-repository.ts +125 -0
  476. package/src/commands/sparse-checkout-command.ts +1389 -0
  477. package/src/commands/sparse-checkout-support.ts +793 -0
  478. package/src/commands/stash-apply-command.ts +376 -343
  479. package/src/commands/stash-create-command.ts +625 -42
  480. package/src/commands/stash-drop-command.ts +15 -2
  481. package/src/commands/stash-working-tree.ts +168 -24
  482. package/src/commands/status-command.ts +1328 -105
  483. package/src/commands/status-format.ts +775 -0
  484. package/src/commands/status-header.ts +330 -0
  485. package/src/commands/strerror.ts +29 -0
  486. package/src/commands/submodule-config.ts +94 -0
  487. package/src/commands/submodule-summary-command.ts +334 -0
  488. package/src/commands/submodule-summary.ts +446 -0
  489. package/src/commands/switch-command.ts +402 -0
  490. package/src/commands/tag-command.ts +129 -41
  491. package/src/commands/tracking-info.ts +201 -0
  492. package/src/commands/trailers.ts +417 -0
  493. package/src/commands/tree-restore.ts +204 -4
  494. package/src/commands/untracked-cache-support.ts +194 -0
  495. package/src/commands/worktree-add-command.ts +458 -0
  496. package/src/commands/worktree-list-command.ts +208 -0
  497. package/src/commands/worktree-lock-command.ts +96 -0
  498. package/src/commands/worktree-overwrite-checks.ts +452 -26
  499. package/src/commands/worktree-prune-command.ts +99 -0
  500. package/src/commands/worktree-remove-command.ts +186 -0
  501. package/src/commands/worktree-repair-command.ts +59 -0
  502. package/src/commands/worktree-support.ts +214 -0
  503. package/src/core-commands/add.command.impl.ts +7 -1
  504. package/src/errors/add-errors.ts +45 -0
  505. package/src/errors/checkout-errors.ts +26 -2
  506. package/src/errors/command-errors.ts +101 -1
  507. package/src/errors/commit-errors.ts +18 -2
  508. package/src/errors/git-api-error.ts +82 -2
  509. package/src/errors/index.ts +1 -0
  510. package/src/errors/merge-errors.ts +2 -2
  511. package/src/errors/rebase-errors.ts +12 -0
  512. package/src/errors/ref-errors.ts +56 -2
  513. package/src/errors/remote-errors.ts +2 -2
  514. package/src/errors/stash-errors.ts +1 -1
  515. package/src/errors/transport-errors.ts +20 -4
  516. package/src/errors/worktree-errors.ts +49 -0
  517. package/src/git-command.ts +1177 -118
  518. package/src/git.ts +523 -10
  519. package/src/index.ts +1 -1
  520. package/src/remote-config/remote-config-store.ts +242 -8
  521. package/src/remote-config/remote-refs.ts +22 -6
  522. package/src/rename/detect-renames.ts +711 -0
  523. package/src/rename/git-similarity.ts +116 -0
  524. package/src/rename/index.ts +2 -0
  525. package/src/results/binary-patch.ts +401 -0
  526. package/src/results/blame-format.ts +239 -0
  527. package/src/results/cherry-pick-result.ts +10 -0
  528. package/src/results/clone-result.ts +12 -0
  529. package/src/results/combined-diff.ts +585 -0
  530. package/src/results/diff-entry.ts +35 -0
  531. package/src/results/diff-formatter.ts +152 -288
  532. package/src/results/diff-order.ts +64 -0
  533. package/src/results/diff-output.ts +1051 -0
  534. package/src/results/fetch-result.ts +15 -0
  535. package/src/results/index.ts +5 -0
  536. package/src/results/merge-result.ts +15 -1
  537. package/src/results/pull-result.ts +12 -3
  538. package/src/results/push-result.ts +43 -0
  539. package/src/results/quote-path.ts +103 -0
  540. package/src/results/rebase-result.ts +37 -0
  541. package/src/results/revert-result.ts +10 -0
  542. package/src/results/stash-result.ts +6 -0
  543. package/src/results/status-result.ts +123 -45
  544. package/src/transport-command.ts +121 -2
  545. package/dist/commands-CsLNyvZ1.js +0 -12587
  546. package/dist/status-result-BpyUK1Sg.js +0 -519
@@ -1,23 +1,28 @@
1
- import type { Commit, ObjectId, TreeEntry } from "@statewalker/vcs-core";
1
+ import type { Commit, ObjectId, PersonIdent } from "@statewalker/vcs-core";
2
+ import { DEFAULT_BIG_FILE_THRESHOLD, FileMode } from "@statewalker/vcs-core";
3
+ import { parseGitBool } from "@statewalker/vcs-utils";
4
+ import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
2
5
  import {
3
- DEFAULT_BIG_FILE_THRESHOLD,
4
- FileMode,
5
- isSymbolicRef,
6
- probeBlob,
7
- } from "@statewalker/vcs-core";
8
- import {
9
- merge3Way,
10
- MergeContentStrategy as UtilsMergeContentStrategy,
11
- } from "@statewalker/vcs-utils";
12
- import { MergeStage } from "@statewalker/vcs-working-tree";
13
-
6
+ attributesIndexOf,
7
+ type ContentAttributesContext,
8
+ cacheTreeOfTree,
9
+ entryStatOf,
10
+ getWorktreeEntries,
11
+ type IndexEntryOptions,
12
+ invalidateCacheTreePath,
13
+ type Worktree,
14
+ } from "@statewalker/vcs-working-tree";
15
+ import { InvalidArgumentError } from "../errors/command-errors.js";
16
+ import { GitApiError } from "../errors/git-api-error.js";
14
17
  import {
15
18
  InvalidMergeHeadsError,
19
+ MergeFailureReason,
16
20
  NoMergeBaseError,
17
21
  NotFastForwardError,
18
22
  } from "../errors/merge-errors.js";
19
- import { NoHeadError, RefNotFoundError } from "../errors/ref-errors.js";
23
+ import { NoHeadError, NotACommitError, RefNotFoundError } from "../errors/ref-errors.js";
20
24
  import { GitCommand } from "../git-command.js";
25
+ import { RemoteConfigStore } from "../remote-config/index.js";
21
26
  import {
22
27
  ContentMergeStrategy,
23
28
  FastForwardMode,
@@ -25,44 +30,104 @@ import {
25
30
  MergeStatus,
26
31
  MergeStrategy,
27
32
  } from "../results/merge-result.js";
33
+ import { CommitCommand, type CommitResult } from "./commit-command.js";
34
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
35
+ import { configBool, conflictStyleOf } from "./merge-config.js";
36
+ import { ortConfigOptions } from "./merge-drivers.js";
37
+ import {
38
+ conflictsComment,
39
+ flatTree,
40
+ indexChanges,
41
+ indexChangesFromTree,
42
+ OperationState,
43
+ readIndex,
44
+ rewriteIndex,
45
+ storeFlatTree,
46
+ storeFlatTreeOver,
47
+ switchTrees,
48
+ treeDelta,
49
+ writeIndexAsTree,
50
+ } from "./merge-support.js";
51
+ import {
52
+ type CleanupMode,
53
+ cleanupWith,
54
+ commitCleanupMode,
55
+ commitMessageFromOption,
56
+ } from "./message-cleanup.js";
57
+ import { octopusMerge } from "./octopus-merge.js";
58
+ import { ortResultEntries } from "./ort-merge.js";
59
+ import { mergeBaseTree, mergeStoredTrees } from "./ort-recursive.js";
60
+ import { reflogMessages, updateHead, updateHeadExpecting } from "./reflog-messages.js";
61
+ import {
62
+ applyAutostash,
63
+ cleanupMessage,
64
+ createAutostash,
65
+ removeMergeBranchState,
66
+ resetMerge,
67
+ saveAutostash,
68
+ squashMessage,
69
+ } from "./sequencer-support.js";
70
+ import { readSparseCheckoutPatterns, sparseCheckoutConfig } from "./sparse-checkout-support.js";
71
+ import { WorkingCopyStashProvider } from "./stash-working-tree.js";
72
+ import { readDiffSubmoduleConfig } from "./submodule-summary.js";
73
+ import {
74
+ type CheckedEntry,
75
+ pruneEmptyParents,
76
+ worktreeModified,
77
+ } from "./worktree-overwrite-checks.js";
78
+
79
+ /** What `git merge` is asked to do. */
80
+ export enum MergeOperation {
81
+ /** Merge the included commit (`git merge <commit>`) */
82
+ MERGE = "merge",
83
+ /** Give up the merge in progress (`git merge --abort`) */
84
+ ABORT = "abort",
85
+ /** Commit the resolved merge in progress (`git merge --continue`) */
86
+ CONTINUE = "continue",
87
+ /**
88
+ * Forget the merge in progress, leaving the index and the worktree as they are
89
+ * (`git merge --quit`); its autostash is kept on `refs/stash`.
90
+ */
91
+ QUIT = "quit",
92
+ }
93
+
94
+ /** git's refusal of a merge of histories with no common commit. */
95
+ export const UNRELATED_HISTORIES_MESSAGE = "fatal: refusing to merge unrelated histories";
96
+
97
+ /** git's refusal while the index has unmerged entries. */
98
+ export const UNMERGED_FILES_MESSAGE = (action: "Merging" | "Committing") =>
99
+ [
100
+ `error: ${action} is not possible because you have unmerged files.`,
101
+ "hint: Fix them up in the work tree, and then use 'git add/rm <file>'",
102
+ "hint: as appropriate to mark resolution and make a commit.",
103
+ "fatal: Exiting because of an unresolved conflict.",
104
+ ].join("\n");
28
105
 
29
106
  /**
30
107
  * Merge branches.
31
108
  *
32
- * Equivalent to `git merge`.
109
+ * Equivalent to `git merge`: a fast-forward, or git's merge-ort, written to the index and
110
+ * the working tree as git writes them. Before anything is written the merge is refused, with
111
+ * git's messages, where it would overwrite local changes or untracked files (or the index
112
+ * holds staged changes, or unmerged entries, or a merge is already in progress). A merge
113
+ * with conflicts leaves the files with git's conflict markers (`merge.conflictStyle`), the
114
+ * conflicts staged at stages 1-3, and git's state (`MERGE_HEAD`, `MERGE_MSG`, `MERGE_MODE`,
115
+ * `ORIG_HEAD`, `AUTO_MERGE`), so native git can `--continue` or `--abort` it and the other
116
+ * way round (`setOperation`).
33
117
  *
34
- * Based on JGit's MergeCommand.
118
+ * The result's `output` holds what git prints (`Auto-merging f`, `CONFLICT (...)`, ...)
119
+ * without the diffstat; a refused merge has status FAILED and git's error in `message`.
35
120
  *
36
121
  * @example
37
122
  * ```typescript
38
- * // Fast-forward merge
39
- * const result = await git.merge()
40
- * .include("feature-branch")
41
- * .call();
123
+ * const result = await git.merge().include("feature-branch").call();
124
+ * if (result.status === MergeStatus.CONFLICTING) {
125
+ * // resolve, `git add`, then
126
+ * await git.merge().setOperation(MergeOperation.CONTINUE).call();
127
+ * }
42
128
  *
43
129
  * // Force merge commit (no fast-forward)
44
- * const result = await git.merge()
45
- * .include("feature-branch")
46
- * .setFastForwardMode(FastForwardMode.NO_FF)
47
- * .call();
48
- *
49
- * // Fail if fast-forward not possible
50
- * const result = await git.merge()
51
- * .include("feature-branch")
52
- * .setFastForwardMode(FastForwardMode.FF_ONLY)
53
- * .call();
54
- *
55
- * // Use "ours" strategy (keep our tree, ignore theirs)
56
- * const result = await git.merge()
57
- * .include("feature-branch")
58
- * .setStrategy(MergeStrategy.OURS)
59
- * .call();
60
- *
61
- * // Use "theirs" strategy (replace our tree with theirs)
62
- * const result = await git.merge()
63
- * .include("feature-branch")
64
- * .setStrategy(MergeStrategy.THEIRS)
65
- * .call();
130
+ * await git.merge().include("feature").setFastForwardMode(FastForwardMode.NO_FF).call();
66
131
  * ```
67
132
  */
68
133
  export class MergeCommand extends GitCommand<MergeResult> {
@@ -73,7 +138,37 @@ export class MergeCommand extends GitCommand<MergeResult> {
73
138
  private squash = false;
74
139
  private commit = true;
75
140
  private message?: string;
141
+ private cleanupMode?: CleanupMode;
142
+ private inProcess = false;
143
+ private noVerify = false;
144
+
145
+ /**
146
+ * `--no-verify`: the `pre-merge-commit` and `commit-msg` hooks do not run
147
+ * (`prepare-commit-msg` and `post-merge` still do).
148
+ */
149
+ setNoVerify(noVerify: boolean): this {
150
+ this.checkCallable();
151
+ this.noVerify = noVerify;
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * A merge another command makes in process (a rebase's `merge`), which reads no `git
157
+ * merge` configuration of its own (`git_merge_config`).
158
+ *
159
+ * @internal
160
+ */
161
+ setInProcess(inProcess: boolean): this {
162
+ this.inProcess = inProcess;
163
+ return this;
164
+ }
76
165
  private bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD;
166
+ private operation = MergeOperation.MERGE;
167
+ private author?: PersonIdent;
168
+ private committer?: PersonIdent;
169
+ private autoStash?: boolean;
170
+ private renormalize?: boolean;
171
+ private allowUnrelated = false;
77
172
 
78
173
  /**
79
174
  * Add a commit/branch to merge.
@@ -104,10 +199,10 @@ export class MergeCommand extends GitCommand<MergeResult> {
104
199
  /**
105
200
  * Set merge strategy.
106
201
  *
107
- * - RECURSIVE (default): Standard three-way merge
202
+ * - RECURSIVE (default): git's merge-ort
108
203
  * - OURS: Keep our tree, ignore their changes (creates merge commit)
109
204
  * - THEIRS: Replace our tree with theirs (creates merge commit)
110
- * - RESOLVE: Simple resolve strategy
205
+ * - RESOLVE: as RECURSIVE
111
206
  *
112
207
  * @param strategy Merge strategy
113
208
  */
@@ -118,14 +213,9 @@ export class MergeCommand extends GitCommand<MergeResult> {
118
213
  }
119
214
 
120
215
  /**
121
- * Set content merge strategy for handling file-level conflicts.
122
- *
123
- * - OURS: Take our version for conflicts
124
- * - THEIRS: Take their version for conflicts
125
- * - UNION: Concatenate both sides (ours first, then theirs)
126
- *
127
- * When set, conflicts are resolved automatically using this strategy
128
- * instead of producing conflict markers.
216
+ * Set content merge strategy for handling file-level conflicts (git's `-X ours`,
217
+ * `-X theirs`, `merge=union`): conflicting hunks are resolved to that side instead of
218
+ * producing conflict markers.
129
219
  *
130
220
  * @param contentStrategy Content merge strategy
131
221
  */
@@ -140,8 +230,8 @@ export class MergeCommand extends GitCommand<MergeResult> {
140
230
  * `core.bigFileThreshold`, default 50 MiB).
141
231
  *
142
232
  * A binary file (over the threshold, or a NUL byte in its first 8000 bytes) is
143
- * never content-merged and never loaded: as git does, OURS and THEIRS take that
144
- * side's file whole, and UNION reports a conflict.
233
+ * never content-merged: as git does, OURS and THEIRS take that side's file whole, and
234
+ * otherwise ours stays with a conflict.
145
235
  *
146
236
  * @param threshold Size in bytes
147
237
  */
@@ -152,9 +242,8 @@ export class MergeCommand extends GitCommand<MergeResult> {
152
242
  }
153
243
 
154
244
  /**
155
- * Set squash mode.
156
- *
157
- * When true, changes are staged but not committed, and HEAD is not updated.
245
+ * Set squash mode (`git merge --squash`): the merge's result is written to the index and
246
+ * the worktree with `SQUASH_MSG`, and HEAD is not updated.
158
247
  *
159
248
  * @param squash Whether to squash
160
249
  */
@@ -165,7 +254,8 @@ export class MergeCommand extends GitCommand<MergeResult> {
165
254
  }
166
255
 
167
256
  /**
168
- * Set whether to commit after merge.
257
+ * Set whether to commit after merge (`--no-commit` when false: the merge stops before
258
+ * committing, with `MERGE_HEAD` and `MERGE_MSG` written for a later commit).
169
259
  *
170
260
  * @param commit Whether to commit (default: true)
171
261
  */
@@ -176,7 +266,10 @@ export class MergeCommand extends GitCommand<MergeResult> {
176
266
  }
177
267
 
178
268
  /**
179
- * Set the merge commit message.
269
+ * Set the merge commit message (default git's: `Merge branch 'feature'`), as git's
270
+ * `merge -m` takes it: cleaned up as a commit message (`whitespace`, which ends the last
271
+ * line, unless {@link setCleanupMode} or `commit.cleanup` says otherwise; `verbatim`
272
+ * stores it as given, without a newline added, unlike `commit -m`).
180
273
  *
181
274
  * @param message Commit message
182
275
  */
@@ -186,6 +279,94 @@ export class MergeCommand extends GitCommand<MergeResult> {
186
279
  return this;
187
280
  }
188
281
 
282
+ /**
283
+ * Add a paragraph to the message, as each further `-m` of `git merge` does: joined to
284
+ * the message so far by a blank line (`-m a -m b` is `"a\n\nb"` before its cleanup).
285
+ * The first call is {@link setMessage}.
286
+ *
287
+ * @param message One paragraph of the merge commit message
288
+ */
289
+ addMessage(message: string): this {
290
+ this.checkCallable();
291
+ // git's option_parse_message: "\n\n" before the next -m only after a non-empty one
292
+ this.message = !this.message ? message : `${this.message}\n\n${message}`;
293
+ return this;
294
+ }
295
+
296
+ /**
297
+ * How the merge commit's message is cleaned up (git's `merge --cleanup=<mode>`; default
298
+ * `commit.cleanup`, else `whitespace`, as without an editor).
299
+ */
300
+ setCleanupMode(mode: CleanupMode): this {
301
+ this.checkCallable();
302
+ this.cleanupMode = mode;
303
+ return this;
304
+ }
305
+
306
+ /**
307
+ * Merge (default), or `--abort` / `--continue` the merge in progress.
308
+ *
309
+ * @param operation What to do
310
+ */
311
+ setOperation(operation: MergeOperation): this {
312
+ this.checkCallable();
313
+ this.operation = operation;
314
+ return this;
315
+ }
316
+
317
+ /**
318
+ * Merge content as if checked out and checked in afresh (`-X renormalize`,
319
+ * `-X no-renormalize`; default `merge.renormalize`, false): a side whose change is only a
320
+ * change of line endings or filters does not conflict.
321
+ */
322
+ setRenormalize(renormalize: boolean): this {
323
+ this.checkCallable();
324
+ this.renormalize = renormalize;
325
+ return this;
326
+ }
327
+
328
+ /**
329
+ * Stash local changes away before the merge and apply them after it (`--autostash`;
330
+ * default `merge.autoStash`, false). A merge that stops (conflicts, `--no-commit`) keeps
331
+ * them in MERGE_AUTOSTASH until it is continued or aborted.
332
+ */
333
+ setAutoStash(autoStash: boolean): this {
334
+ this.checkCallable();
335
+ this.autoStash = autoStash;
336
+ return this;
337
+ }
338
+
339
+ /**
340
+ * Merge histories that share no commit (`--allow-unrelated-histories`): refused by
341
+ * default with git's "refusing to merge unrelated histories". A two-head merge then
342
+ * merges against the empty tree.
343
+ */
344
+ setAllowUnrelatedHistories(allow: boolean): this {
345
+ this.checkCallable();
346
+ this.allowUnrelated = allow;
347
+ return this;
348
+ }
349
+
350
+ /**
351
+ * The author of the merge commit (default: resolved as git resolves it, from
352
+ * `GIT_AUTHOR_*`, `author.*`, `user.*`).
353
+ */
354
+ setAuthor(author: PersonIdent): this {
355
+ this.checkCallable();
356
+ this.author = author;
357
+ return this;
358
+ }
359
+
360
+ /**
361
+ * The committer of the merge commit (default: resolved as git resolves it, from
362
+ * `GIT_COMMITTER_*`, `committer.*`, `user.*`).
363
+ */
364
+ setCommitter(committer: PersonIdent): this {
365
+ this.checkCallable();
366
+ this.committer = committer;
367
+ return this;
368
+ }
369
+
189
370
  /**
190
371
  * Execute the merge.
191
372
  *
@@ -194,14 +375,115 @@ export class MergeCommand extends GitCommand<MergeResult> {
194
375
  async call(): Promise<MergeResult> {
195
376
  this.checkCallable();
196
377
  this.setCallable(false);
378
+ // git_merge_config ends in git_diff_ui_config: a diff.submodule without a value dies
379
+ // (not for the merges a rebase makes in process)
380
+ if (!this.inProcess) readDiffSubmoduleConfig(this.workingCopy);
381
+ // the index as it is now, before the worktree or a ref is touched: one another writer
382
+ // replaced is read again (git reads the index at its start), unless this instance holds
383
+ // unwritten edits (refused)
384
+ await this.readCurrentIndex();
385
+ const worktree = this.worktreeAccess;
386
+ const run = () => this.run(worktree);
387
+ const result = await (worktree?.batch ? worktree.batch(run) : run());
388
+ // finish's post-merge hook, told whether the merge was squashed: after a fast-forward, a
389
+ // merge commit or a squash (not when already up to date, nor when stopped)
390
+ if (
391
+ this.operation === MergeOperation.MERGE &&
392
+ !this.inProcess &&
393
+ this.hooks.enabled &&
394
+ [
395
+ MergeStatus.FAST_FORWARD,
396
+ MergeStatus.FAST_FORWARD_SQUASHED,
397
+ MergeStatus.MERGED,
398
+ MergeStatus.MERGED_SQUASHED,
399
+ ].includes(result.status)
400
+ ) {
401
+ await this.hooks.run("post-merge", {
402
+ args: [this.squash ? "1" : "0"],
403
+ env: { GIT_REFLOG_ACTION: this.reflogActionValue() },
404
+ });
405
+ }
406
+ return this.sparseWarnings.length > 0 ? { ...result, warnings: this.sparseWarnings } : result;
407
+ }
408
+
409
+ /**
410
+ * git pull's `pull_into_void` on an unborn branch: `checkout_fast_forward` from the empty
411
+ * tree to `mergeHead` (a two-way switch, so a staged change the commit does not touch is
412
+ * kept, one it would overwrite refuses the pull), then HEAD's branch created at it with the
413
+ * reflog line `initial pull`. Used by {@link PullCommand}; a one-shot call like
414
+ * {@link call}.
415
+ */
416
+ async callIntoVoid(mergeHead: ObjectId): Promise<MergeResult> {
417
+ this.checkCallable();
418
+ this.setCallable(false);
419
+ await this.readCurrentIndex();
420
+ const worktree = this.worktreeAccess;
421
+ const run = async (): Promise<MergeResult> => {
422
+ const targetTree = await this.commits.getTree(mergeHead);
423
+ const target = await flatTree(this.trees, targetTree);
424
+ const refused = await switchTrees(this.context(worktree), new Map(), target, {
425
+ action: "merge",
426
+ operation: "merge",
427
+ targetTree,
428
+ });
429
+ if (refused) {
430
+ return {
431
+ status: MergeStatus.FAILED,
432
+ mergedCommits: [mergeHead],
433
+ message: refused.message,
434
+ failingPaths: failing(refused.paths),
435
+ output: [],
436
+ };
437
+ }
438
+ // refs_update_ref("HEAD", merge_head, curr_head): the message as it is, no action
439
+ const head = await this.refsStore.get("HEAD");
440
+ const name =
441
+ head && "target" in head && typeof head.target === "string" ? head.target : "HEAD";
442
+ await this.refsStore.set(name, mergeHead, this.reflogLine("initial pull", this.committer));
443
+ return {
444
+ status: MergeStatus.FAST_FORWARD,
445
+ newHead: mergeHead,
446
+ mergedCommits: [mergeHead],
447
+ output: [],
448
+ };
449
+ };
450
+ const result = await (worktree?.batch ? worktree.batch(run) : run());
451
+ return this.sparseWarnings.length > 0 ? { ...result, warnings: this.sparseWarnings } : result;
452
+ }
453
+
454
+ /** What the sparse checkout printed while the result was written (see MergeResult.warnings). */
455
+ private readonly sparseWarnings: string[] = [];
456
+
457
+ private async run(worktree: Worktree | undefined): Promise<MergeResult> {
458
+ const state = new OperationState(this.workingCopy.checkout, this.refsStore);
459
+ if (this.operation === MergeOperation.ABORT) return this.abort(state, worktree);
460
+ if (this.operation === MergeOperation.CONTINUE) return this.continueMerge(state);
461
+ if (this.operation === MergeOperation.QUIT) {
462
+ // git's `merge --quit`: remove_merge_branch_state, nothing else touched
463
+ return {
464
+ status: MergeStatus.ABORTED,
465
+ mergedCommits: [],
466
+ output: await removeMergeBranchState(this.context(worktree), state),
467
+ };
468
+ }
197
469
 
198
470
  // Validate parameters
199
471
  if (this.includes.length === 0) {
200
472
  throw new InvalidMergeHeadsError("No merge head specified");
201
473
  }
202
474
 
203
- if (this.includes.length > 1) {
204
- throw new InvalidMergeHeadsError("Only single-head merges are currently supported");
475
+ // git refuses on an index with unmerged entries, and while a merge is in progress
476
+ const { unmerged } = await readIndex(this.staging);
477
+ if (unmerged.length > 0) return failed(UNMERGED_FILES_MESSAGE("Merging"), unmerged);
478
+ if ((await this.mergeHeads(state)).length > 0) {
479
+ return failed(
480
+ "fatal: You have not concluded your merge (MERGE_HEAD exists).\nPlease, commit your changes before you merge.",
481
+ );
482
+ }
483
+ if (await state.ref("CHERRY_PICK_HEAD")) {
484
+ return failed(
485
+ "fatal: You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\nPlease, commit your changes before you merge.",
486
+ );
205
487
  }
206
488
 
207
489
  // Get HEAD
@@ -209,575 +491,1188 @@ export class MergeCommand extends GitCommand<MergeResult> {
209
491
  if (!head) {
210
492
  throw new NoHeadError("Cannot merge without HEAD");
211
493
  }
212
-
213
- const headId = await this.refsStore.resolve("HEAD");
214
- if (!headId?.objectId) {
494
+ const headResolved = await this.refsStore.resolve("HEAD");
495
+ if (!headResolved?.objectId) {
215
496
  throw new NoHeadError("HEAD does not point to a commit");
216
497
  }
498
+ const headId = headResolved.objectId;
499
+
500
+ // git refuses --squash with --no-ff before it looks at the heads
501
+ if (this.squash && this.fastForwardMode === FastForwardMode.NO_FF) {
502
+ throw new InvalidArgumentError(
503
+ "squash",
504
+ true,
505
+ "fatal: options '--squash' and '--no-ff.' cannot be used together",
506
+ );
507
+ }
217
508
 
218
509
  // Resolve merge source
219
- const srcRef = this.includes[0];
220
- const srcId = await this.resolveRef(srcRef);
510
+ let srcRef = this.includes[0];
511
+ let srcId = await this.mergeHeadOf(srcRef);
512
+ if (this.includes.length > 1) {
513
+ // several heads: the independent ones besides HEAD (git's reduce_heads); two or more
514
+ // are an octopus, one a merge of that head
515
+ const named: { id: ObjectId; name: string }[] = [];
516
+ for (const name of this.includes) named.push({ id: await this.mergeHeadOf(name), name });
517
+ const candidates = [{ id: headId, name: "HEAD" }, ...named].filter(
518
+ (c, k, all) => all.findIndex((x) => x.id === c.id) === k,
519
+ );
520
+ const independent: { id: ObjectId; name: string }[] = [];
521
+ for (const c of candidates) {
522
+ let reachable = false;
523
+ for (const other of candidates) {
524
+ if (other.id !== c.id && (await this.isAncestor(c.id, other.id))) reachable = true;
525
+ }
526
+ if (!reachable) independent.push(c);
527
+ }
528
+ const headSubsumed = !independent.some((c) => c.id === headId);
529
+ const remotes = independent.filter((c) => c.id !== headId);
530
+ if (remotes.length === 0) {
531
+ await state.setRef("ORIG_HEAD", headId);
532
+ return {
533
+ status: MergeStatus.ALREADY_UP_TO_DATE,
534
+ newHead: headId,
535
+ mergedCommits: named.map((n) => n.id),
536
+ output: [
537
+ this.squash ? "Already up to date. (nothing to squash)" : "Already up to date.",
538
+ ...(await removeMergeBranchState(this.context(worktree), state)),
539
+ ],
540
+ };
541
+ }
542
+ if (remotes.length > 1) {
543
+ // git has no strategy `theirs`: refused before anything is written
544
+ if (this.strategy === MergeStrategy.THEIRS) {
545
+ return failed(
546
+ "Could not find merge strategy 'theirs'.\nAvailable strategies are: octopus ours recursive resolve subtree.",
547
+ );
548
+ }
549
+ // the message names the heads left (fmt-merge-msg of the reduced heads)
550
+ const message = this.message ?? (await this.octopusMessage(remotes));
551
+ await state.setRef("ORIG_HEAD", headId);
552
+ const ids = remotes.map((r) => r.id);
553
+ if (!this.allowUnrelated && (await this.octopusBases(headId, ids)).length === 0) {
554
+ throw new NoMergeBaseError([headId, ...ids], UNRELATED_HISTORIES_MESSAGE);
555
+ }
556
+ if (this.ffMode() === FastForwardMode.FF_ONLY) {
557
+ throw new NotFastForwardError("fatal: Not possible to fast-forward, aborting.");
558
+ }
559
+ return this.withAutostash(state, worktree, headId, () =>
560
+ this.doOctopus(headId, head, remotes, headSubsumed, message, state, worktree),
561
+ );
562
+ }
563
+ srcRef = remotes[0].name;
564
+ srcId = remotes[0].id;
565
+ }
566
+
567
+ // git records where HEAD was before every merge
568
+ await state.setRef("ORIG_HEAD", headId);
569
+
570
+ // git's cmd_merge: the merge bases answer all three questions in one walk. src is an
571
+ // ancestor of HEAD exactly when it is their only merge base (already up to date), HEAD is
572
+ // one of src exactly when HEAD is (fast-forward); otherwise they are the merge's bases.
573
+ const bases = srcId === headId ? [headId] : await this.commits.findMergeBase(headId, srcId);
574
+ const onlyBase = bases.length === 1 ? bases[0] : undefined;
221
575
 
222
576
  // Check if already up to date (src is ancestor of HEAD)
223
- if (await this.isAncestor(srcId, headId.objectId)) {
577
+ if (onlyBase === srcId) {
578
+ // finish_up_to_date: remove_merge_branch_state (an AUTO_MERGE left behind goes)
224
579
  return {
225
580
  status: MergeStatus.ALREADY_UP_TO_DATE,
226
- newHead: headId.objectId,
581
+ newHead: headId,
227
582
  mergedCommits: [srcId],
583
+ output: [
584
+ this.squash ? "Already up to date. (nothing to squash)" : "Already up to date.",
585
+ // and a MERGE_AUTOSTASH left by a stopped merge is kept on refs/stash
586
+ ...(await removeMergeBranchState(this.context(worktree), state)),
587
+ ],
228
588
  };
229
589
  }
230
590
 
231
591
  // Check if fast-forward is possible (HEAD is ancestor of src)
232
- const canFastForward = await this.isAncestor(headId.objectId, srcId);
592
+ const canFastForward = onlyBase === headId;
593
+ const fastForward = canFastForward && this.ffMode() !== FastForwardMode.NO_FF;
233
594
 
234
- if (canFastForward && this.fastForwardMode !== FastForwardMode.NO_FF) {
235
- // Fast-forward merge
236
- return this.doFastForward(headId.objectId, srcId, head);
595
+ // git refuses unrelated histories before anything is stashed or written
596
+ const mergeBases = fastForward ? [] : bases;
597
+ if (!fastForward && mergeBases.length === 0 && !this.allowUnrelated) {
598
+ throw new NoMergeBaseError([headId, srcId], UNRELATED_HISTORIES_MESSAGE);
599
+ }
600
+ if (!fastForward && this.ffMode() === FastForwardMode.FF_ONLY) {
601
+ throw new NotFastForwardError("fatal: Not possible to fast-forward, aborting.");
237
602
  }
238
603
 
239
- if (this.fastForwardMode === FastForwardMode.FF_ONLY) {
240
- // Cannot fast-forward and FF_ONLY was requested
241
- throw new NotFastForwardError();
604
+ return this.withAutostash(state, worktree, headId, () =>
605
+ fastForward
606
+ ? this.doFastForward(headId, srcId, head, state, worktree)
607
+ : this.doMerge(headId, srcId, srcRef, head, state, worktree, mergeBases),
608
+ );
609
+ }
610
+
611
+ /**
612
+ * git's fast-forward setting as the strategy leaves it: `ours` (NO_FAST_FORWARD) always
613
+ * makes a merge commit, whatever was asked.
614
+ */
615
+ private ffMode(): FastForwardMode {
616
+ return this.strategy === MergeStrategy.OURS ? FastForwardMode.NO_FF : this.fastForwardMode;
617
+ }
618
+
619
+ /** git's get_octopus_merge_bases: the merge bases of HEAD and every head, folded. */
620
+ private async octopusBases(headId: ObjectId, heads: ObjectId[]): Promise<ObjectId[]> {
621
+ let bases = [headId];
622
+ for (const head of heads) {
623
+ const next = new Set<ObjectId>();
624
+ for (const base of bases) {
625
+ for (const id of await this.commits.findMergeBase(base, head)) next.add(id);
626
+ }
627
+ bases = [...next];
628
+ if (bases.length === 0) break;
242
629
  }
630
+ return bases;
631
+ }
243
632
 
244
- // Need to do a real merge
245
- return this.doMerge(headId.objectId, srcId, head);
633
+ /**
634
+ * The merge between git's `create_autostash_ref` and `apply_autostash_ref`
635
+ * (`merge.autoStash`): local changes stashed away first, applied again once the merge is
636
+ * done, kept in MERGE_AUTOSTASH while it stops for the user.
637
+ */
638
+ private async withAutostash(
639
+ state: OperationState,
640
+ worktree: Worktree | undefined,
641
+ headId: ObjectId,
642
+ merge: () => Promise<MergeResult>,
643
+ ): Promise<MergeResult> {
644
+ const created: string[] = [];
645
+ if (worktree && (this.autoStash ?? configBool(this.workingCopy, "merge.autoStash", false))) {
646
+ if (!state.supported) {
647
+ // the stash could be kept nowhere: refused rather than stranded
648
+ throw new InvalidArgumentError(
649
+ "autoStash",
650
+ true,
651
+ "merge --autostash needs a checkout that keeps state files (MERGE_AUTOSTASH)",
652
+ );
653
+ }
654
+ const autostash = await createAutostash(this.context(worktree), headId);
655
+ if (autostash) {
656
+ await state.write("MERGE_AUTOSTASH", `${autostash}\n`);
657
+ created.push(`Created autostash: ${await this.abbreviateObjectId(autostash)}`);
658
+ }
659
+ }
660
+ let result: MergeResult;
661
+ try {
662
+ result = await merge();
663
+ } catch (error) {
664
+ // nothing is stranded in the autostash: applied back as git's apply_autostash
665
+ await this.popAutostash(state, worktree).catch(() => undefined);
666
+ throw error;
667
+ }
668
+ const output = [...created, ...(result.output ?? [])];
669
+ // a merge stopped for the user (conflicts, --no-commit) keeps the autostash for later
670
+ if (
671
+ result.status !== MergeStatus.CONFLICTING &&
672
+ result.status !== MergeStatus.MERGED_NOT_COMMITTED
673
+ ) {
674
+ const applied = await this.popAutostash(state, worktree);
675
+ output.push(...applied);
676
+ // a merge that moved HEAD ends with git's remove_merge_branch_state, after the
677
+ // autostash was applied (whose own merge recorded AUTO_MERGE)
678
+ if (
679
+ applied.length > 0 &&
680
+ (result.status === MergeStatus.MERGED || result.status === MergeStatus.FAST_FORWARD)
681
+ ) {
682
+ await state.removeRef("AUTO_MERGE");
683
+ }
684
+ } else if (created.length > 0) {
685
+ output.push("When finished, apply stashed changes with `git stash pop`");
686
+ }
687
+ return { ...result, output };
688
+ }
689
+
690
+ /** Applies MERGE_AUTOSTASH back, if there is one. */
691
+ private async popAutostash(
692
+ state: OperationState,
693
+ worktree: Worktree | undefined,
694
+ ): Promise<string[]> {
695
+ const id = (await state.read("MERGE_AUTOSTASH"))?.trim();
696
+ if (!id) return [];
697
+ await state.remove("MERGE_AUTOSTASH");
698
+ return applyAutostash(this.context(worktree), id);
246
699
  }
247
700
 
248
701
  /**
249
- * Perform a fast-forward merge.
702
+ * Perform a fast-forward merge (git's checkout_fast_forward: a two-way switch).
250
703
  */
251
704
  private async doFastForward(
252
705
  headId: ObjectId,
253
706
  srcId: ObjectId,
254
707
  head: Awaited<ReturnType<typeof this.refsStore.get>>,
708
+ state: OperationState,
709
+ worktree: Worktree | undefined,
255
710
  ): Promise<MergeResult> {
256
- if (!this.squash) {
257
- // Update HEAD/branch to point to source commit
258
- if (head && isSymbolicRef(head)) {
259
- await this.refsStore.set(head.target, srcId);
260
- } else {
261
- await this.refsStore.set("HEAD", srcId);
262
- }
263
-
264
- // Update staging to match new HEAD
265
- const srcCommitFF = await this.commits.load(srcId);
266
- if (srcCommitFF) {
267
- await this.staging.readTree(this.trees, srcCommitFF.tree);
268
- await this.staging.write();
269
- }
270
-
711
+ const output = [
712
+ `Updating ${await this.abbreviateObjectId(headId)}..${await this.abbreviateObjectId(srcId)}`,
713
+ ];
714
+ const headTree = await flatTree(this.trees, await this.commits.getTree(headId));
715
+ const srcTreeId = await this.commits.getTree(srcId);
716
+ const srcTree = await flatTree(this.trees, srcTreeId);
717
+ const refused = await switchTrees(this.context(worktree), headTree, srcTree, {
718
+ action: "merge",
719
+ operation: "merge",
720
+ targetTree: srcTreeId,
721
+ });
722
+ if (refused) {
271
723
  return {
272
- status: MergeStatus.FAST_FORWARD,
273
- newHead: srcId,
724
+ status: MergeStatus.FAILED,
725
+ newHead: headId,
274
726
  mergedCommits: [headId, srcId],
727
+ message: refused.message,
728
+ failingPaths: failing(refused.paths),
729
+ output,
275
730
  };
276
731
  }
277
-
278
- // Squash: stage changes but don't update HEAD
279
- const srcCommitSquash = await this.commits.load(srcId);
280
- if (srcCommitSquash) {
281
- await this.staging.readTree(this.trees, srcCommitSquash.tree);
282
- await this.staging.write();
732
+ output.push("Fast-forward");
733
+ if (this.squash) {
734
+ await state.write(
735
+ "SQUASH_MSG",
736
+ await squashMessage(this.commits, headId, srcId, (id) => this.abbreviateObjectId(id)),
737
+ );
738
+ output.push("Squash commit -- not updating HEAD");
739
+ return {
740
+ status: MergeStatus.FAST_FORWARD_SQUASHED,
741
+ newHead: headId,
742
+ mergedCommits: [headId, srcId],
743
+ message: "Squashed commit of merged changes",
744
+ output,
745
+ };
283
746
  }
284
-
747
+ await this.updateHead(head, srcId, "Fast-forward");
285
748
  return {
286
- status: MergeStatus.FAST_FORWARD_SQUASHED,
287
- newHead: headId,
749
+ status: MergeStatus.FAST_FORWARD,
750
+ newHead: srcId,
288
751
  mergedCommits: [headId, srcId],
289
- message: "Squashed commit of merged changes",
752
+ output,
290
753
  };
291
754
  }
292
755
 
293
756
  /**
294
- * Perform a three-way merge.
757
+ * Perform a three-way merge (git's merge-ort).
295
758
  */
296
759
  private async doMerge(
297
760
  headId: ObjectId,
298
761
  srcId: ObjectId,
762
+ srcName: string,
299
763
  head: Awaited<ReturnType<typeof this.refsStore.get>>,
764
+ state: OperationState,
765
+ worktree: Worktree | undefined,
766
+ mergeBases: ObjectId[],
300
767
  ): Promise<MergeResult> {
301
- // Find merge base
302
- const mergeBases = await this.commits.findMergeBase(headId, srcId);
303
- if (mergeBases.length === 0) {
304
- // No common ancestor - shouldn't happen with connected histories
305
- throw new NoMergeBaseError([headId, srcId]);
306
- }
307
-
308
- const baseId = mergeBases[0]; // Use first merge base
309
-
310
- // Load commits
768
+ // no merge base (unrelated histories allowed): merge-ort merges against the empty tree
769
+ const baseId = mergeBases[0] as ObjectId | undefined;
311
770
  const headCommit = await this.commits.load(headId);
312
771
  const srcCommit = await this.commits.load(srcId);
313
-
314
772
  if (!headCommit || !srcCommit) {
315
773
  throw new RefNotFoundError(headId, "Failed to load commits for merge");
316
774
  }
775
+ const { index } = await readIndex(this.staging);
317
776
 
318
- // Handle strategy-specific merge
319
- let treeId: ObjectId;
320
-
777
+ const mergeName = await this.describeMergeSource(srcName, srcId);
778
+ const output: string[] = [];
779
+ let target: Map<string, { objectId: ObjectId; mode: number }>;
780
+ let merge: Awaited<ReturnType<typeof mergeStoredTrees>> | undefined;
321
781
  if (this.strategy === MergeStrategy.OURS) {
322
- // OURS strategy: keep our tree unchanged, completely ignore theirs
323
- treeId = headCommit.tree;
324
- await this.staging.readTree(this.trees, treeId);
325
- await this.staging.write();
782
+ target = await flatTree(this.trees, headCommit.tree);
326
783
  } else if (this.strategy === MergeStrategy.THEIRS) {
327
- // THEIRS strategy: replace our tree with theirs
328
- treeId = srcCommit.tree;
329
- await this.staging.readTree(this.trees, treeId);
330
- await this.staging.write();
784
+ target = await flatTree(this.trees, srcCommit.tree);
331
785
  } else {
332
- // RECURSIVE or RESOLVE strategy: do three-way merge
333
- const baseCommit = await this.commits.load(baseId);
334
- if (!baseCommit) {
335
- throw new RefNotFoundError(baseId, "Failed to load merge base commit");
336
- }
337
-
338
- // Perform tree-level merge
339
- const mergeResult = await this.mergeTreesThreeWay(
340
- baseCommit.tree,
786
+ const common = {
787
+ style: conflictStyleOf(this.workingCopy),
788
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
789
+ bigFileThreshold: this.bigFileThreshold,
790
+ ...ortConfigOptions(this.workingCopy, worktree, { renormalize: this.renormalize }),
791
+ };
792
+ // several merge bases: merge-ort's virtual merge base, built in memory
793
+ const base = await mergeBaseTree(
794
+ {
795
+ commits: this.commits,
796
+ trees: this.trees,
797
+ blobs: this.blobs,
798
+ abbreviate: (id) => this.abbreviateObjectId(id),
799
+ },
800
+ headId,
801
+ srcId,
802
+ mergeBases,
803
+ common,
804
+ );
805
+ merge = await mergeStoredTrees(
806
+ { trees: this.trees, blobs: this.blobs },
807
+ base,
341
808
  headCommit.tree,
342
809
  srcCommit.tree,
810
+ {
811
+ ...common,
812
+ oursLabel: "HEAD",
813
+ theirsLabel: srcName,
814
+ baseLabel: base.label,
815
+ favor: favorOf(this.contentStrategy),
816
+ },
343
817
  );
818
+ target = await ortResultEntries(this.blobs, merge);
819
+ }
820
+ // only the directories the merge changes are stored again
821
+ const treeId = merge
822
+ ? await storeFlatTreeOver(this.trees, headCommit.tree, merge.ours, target)
823
+ : await storeFlatTree(this.trees, target);
824
+ // merge-ort records its result tree (AUTO_MERGE) whether or not it can be written
825
+ if (merge) await state.setRef("AUTO_MERGE", treeId);
826
+
827
+ // merge-ort's sanity check: the index must match HEAD (merge-ort-wrappers' unclean())
828
+ const staged = await indexChangesFromTree(index, this.trees, headCommit.tree);
829
+ if (staged.length > 0) {
830
+ const restored = await this.restoreStateQuirk(state, headCommit.tree, worktree);
831
+ return {
832
+ status: MergeStatus.FAILED,
833
+ newHead: headId,
834
+ mergeBase: baseId,
835
+ mergedCommits: [headId, srcId],
836
+ message: `error: Your local changes to the following files would be overwritten by merge:\n ${staged.join(" ")}\n${restored}Merge with strategy ort failed.`,
837
+ failingPaths: new Map(staged.map((p) => [p, MergeFailureReason.DIRTY_INDEX])),
838
+ };
839
+ }
344
840
 
345
- if (mergeResult.conflicts.length > 0) {
346
- // Has conflicts - write conflict state to staging
347
- await this.writeConflictStaging(
348
- baseCommit.tree,
349
- headCommit.tree,
350
- srcCommit.tree,
351
- mergeResult,
841
+ const conflicts = merge ? [...merge.conflicts.values()] : [];
842
+ // only the paths HEAD and the result differ on are switched
843
+ const delta = await treeDelta(this.trees, headCommit.tree, treeId);
844
+ const refused = await switchTrees(this.context(worktree), delta.from, delta.to, {
845
+ action: "merge",
846
+ operation: "merge",
847
+ conflicts,
848
+ targetTree: treeId,
849
+ });
850
+ if (refused) {
851
+ const restored = await this.restoreStateQuirk(state, headCommit.tree, worktree);
852
+ return {
853
+ status: MergeStatus.FAILED,
854
+ newHead: headId,
855
+ mergeBase: baseId,
856
+ mergedCommits: [headId, srcId],
857
+ message: `${refused.message}\n${restored}Merge with strategy ort failed.`,
858
+ failingPaths: failing(refused.paths),
859
+ };
860
+ }
861
+ output.push(...(merge?.messages ?? []));
862
+ // a message given is the commit's as it is; git's default ends with a newline
863
+ const message = this.message ?? (await this.defaultMessage(mergeName));
864
+
865
+ if (conflicts.length > 0 || merge?.clean === false) {
866
+ const paths = [...new Set(conflicts.map((c) => c.stagePath))].sort(compareGitPaths);
867
+ if (this.squash) {
868
+ await state.write(
869
+ "SQUASH_MSG",
870
+ await squashMessage(this.commits, headId, srcId, (id) => this.abbreviateObjectId(id)),
871
+ );
872
+ await state.write("MERGE_MSG", conflictsComment(paths, true));
873
+ output.push("Squash commit -- not updating HEAD");
874
+ } else {
875
+ await this.writeMergeState(
876
+ state,
877
+ srcId,
878
+ `${this.stateMessage(message)}${conflictsComment(paths, true)}`,
352
879
  );
353
- await this.staging.write();
354
-
355
- return {
356
- status: MergeStatus.CONFLICTING,
357
- mergeBase: baseId,
358
- mergedCommits: [headId, srcId],
359
- conflicts: mergeResult.conflicts,
360
- };
361
880
  }
362
-
363
- // No conflicts - write merged tree to staging
364
- await this.writeMergedStaging(mergeResult);
365
- await this.staging.write();
366
- treeId = await this.staging.writeTree(this.trees);
881
+ output.push("Automatic merge failed; fix conflicts and then commit the result.");
882
+ return {
883
+ status: MergeStatus.CONFLICTING,
884
+ mergeBase: baseId,
885
+ mergedCommits: [headId, srcId],
886
+ conflicts: paths,
887
+ output,
888
+ };
367
889
  }
368
-
369
- if (!this.commit || this.squash) {
370
- // Don't commit
371
- const status = this.squash ? MergeStatus.MERGED_SQUASHED : MergeStatus.MERGED_NOT_COMMITTED;
890
+ if (this.squash) {
891
+ await state.write(
892
+ "SQUASH_MSG",
893
+ await squashMessage(this.commits, headId, srcId, (id) => this.abbreviateObjectId(id)),
894
+ );
895
+ output.push(
896
+ "Squash commit -- not updating HEAD",
897
+ "Automatic merge went well; stopped before committing as requested",
898
+ );
372
899
  return {
373
- status,
900
+ status: MergeStatus.MERGED_SQUASHED,
374
901
  newHead: headId,
375
902
  mergeBase: baseId,
376
903
  mergedCommits: [headId, srcId],
904
+ output,
377
905
  };
378
906
  }
379
-
380
- // Create merge commit
381
- const mergeMessage = this.message ?? `Merge commit '${srcId.slice(0, 7)}'`;
382
-
383
- const now = Math.floor(Date.now() / 1000); // Unix timestamp in seconds
384
- const mergeCommit: Commit = {
385
- tree: treeId,
386
- parents: [headId, srcId],
387
- author: {
388
- name: "Author",
389
- email: "author@example.com",
390
- timestamp: now,
391
- tzOffset: "+0000",
392
- },
393
- committer: {
394
- name: "Committer",
395
- email: "committer@example.com",
396
- timestamp: now,
397
- tzOffset: "+0000",
398
- },
399
- message: mergeMessage,
400
- };
401
-
402
- const newCommitId = await this.commits.store(mergeCommit);
403
-
404
- // Update HEAD/branch
405
- if (head && isSymbolicRef(head)) {
406
- await this.refsStore.set(head.target, newCommitId);
407
- } else {
408
- await this.refsStore.set("HEAD", newCommitId);
907
+ if (!this.commit) {
908
+ await this.writeMergeState(state, srcId, this.stateMessage(message));
909
+ output.push("Automatic merge went well; stopped before committing as requested");
910
+ return {
911
+ status: MergeStatus.MERGED_NOT_COMMITTED,
912
+ newHead: headId,
913
+ mergeBase: baseId,
914
+ mergedCommits: [headId, srcId],
915
+ output,
916
+ };
409
917
  }
410
918
 
919
+ const hooked = await this.mergeCommitHooks(state, message, (text) =>
920
+ this.writeMergeState(state, srcId, text),
921
+ );
922
+ if (hooked.refused !== undefined) {
923
+ return {
924
+ status: MergeStatus.FAILED,
925
+ newHead: headId,
926
+ mergeBase: baseId,
927
+ mergedCommits: [headId, srcId],
928
+ message: hooked.refused,
929
+ output,
930
+ };
931
+ }
932
+ const cleaned = hooked.message;
933
+ if (cleaned.length === 0) {
934
+ // git's prepare_to_commit: abort_commit, the merge left for `git commit`
935
+ await this.writeMergeState(state, srcId, this.stateMessage(message));
936
+ return {
937
+ status: MergeStatus.FAILED,
938
+ newHead: headId,
939
+ mergeBase: baseId,
940
+ mergedCommits: [headId, srcId],
941
+ message: EMPTY_MERGE_MESSAGE,
942
+ output,
943
+ };
944
+ }
945
+ const newCommitId = await this.storeCommit(treeId, [headId, srcId], cleaned);
946
+ await this.updateHead(head, newCommitId, reflogMessages.mergeMade(this.strategyName()));
947
+ // the commit ends the merge: git's remove_merge_branch_state
948
+ await state.removeRef("AUTO_MERGE");
949
+ output.push(`Merge made by the '${this.strategyName()}' strategy.`);
411
950
  return {
412
951
  status: MergeStatus.MERGED,
413
952
  newHead: newCommitId,
414
953
  mergeBase: baseId,
415
954
  mergedCommits: [headId, srcId],
955
+ output,
416
956
  };
417
957
  }
418
958
 
419
959
  /**
420
- * Check if commitA is an ancestor of commitB.
960
+ * A merge of several heads: git-merge-octopus (the heads merged one after the other) or,
961
+ * with strategy `ours`, git-merge-ours (HEAD's tree); written when it merged or left
962
+ * conflicts with the last head, nothing written when it gave up. As git's merge for any
963
+ * strategy: committed, or stopped before the commit (`--no-commit`), or squashed
964
+ * (`SQUASH_MSG`, HEAD left alone).
421
965
  */
422
- private async isAncestor(commitA: ObjectId, commitB: ObjectId): Promise<boolean> {
423
- if (commitA === commitB) return true;
424
-
425
- // Walk ancestors of B looking for A
426
- const visited = new Set<ObjectId>();
427
- const queue: ObjectId[] = [commitB];
428
-
429
- while (queue.length > 0) {
430
- const current = queue.shift();
431
- if (current === undefined) break;
432
-
433
- if (visited.has(current)) continue;
434
- visited.add(current);
435
-
436
- if (current === commitA) return true;
437
-
438
- try {
439
- const commit = await this.commits.load(current);
440
- if (commit) {
441
- for (const parent of commit.parents) {
442
- if (!visited.has(parent)) {
443
- queue.push(parent);
444
- }
445
- }
446
- }
447
- } catch {
448
- // Commit not found - continue
966
+ private async doOctopus(
967
+ headId: ObjectId,
968
+ head: Awaited<ReturnType<typeof this.refsStore.get>>,
969
+ remotes: { id: ObjectId; name: string }[],
970
+ headSubsumed: boolean,
971
+ message: string,
972
+ state: OperationState,
973
+ worktree: Worktree | undefined,
974
+ ): Promise<MergeResult> {
975
+ const mergedCommits = [headId, ...remotes.map((r) => r.id)];
976
+ const remoteIds = remotes.map((r) => r.id);
977
+ const headTree = await flatTree(this.trees, await this.commits.getTree(headId));
978
+ const { index } = await readIndex(this.staging);
979
+ const staged = indexChanges(index, headTree);
980
+ const strategy = this.strategy === MergeStrategy.OURS ? "ours" : "octopus";
981
+ // git restores the state it saved (reset --hard, stash apply): AUTO_MERGE as for ort
982
+ const giveUp = async (lines: string[], output: string[] = []): Promise<MergeResult> => {
983
+ const tree = (await this.commits.getTree(headId)) as ObjectId;
984
+ const restored = await this.restoreStateQuirk(state, tree, worktree);
985
+ return {
986
+ status: MergeStatus.FAILED,
987
+ newHead: headId,
988
+ mergedCommits,
989
+ message: [...lines, `${restored}Merge with strategy ${strategy} failed.`].join("\n"),
990
+ output,
991
+ };
992
+ };
993
+ // git-merge-resolve and merge-ort handle two heads only
994
+ if (this.strategy === MergeStrategy.RESOLVE) {
995
+ const tree = (await this.commits.getTree(headId)) as ObjectId;
996
+ const restored = await this.restoreStateQuirk(state, tree, worktree);
997
+ return failed(`${restored}Merge with strategy resolve failed.`);
998
+ }
999
+ let outcome: Awaited<ReturnType<typeof octopusMerge>>;
1000
+ if (this.strategy === MergeStrategy.OURS) {
1001
+ // git-merge-ours: refuses an index that differs from HEAD, else HEAD's tree
1002
+ if (staged.length > 0) return giveUp([]);
1003
+ outcome = {
1004
+ status: 0,
1005
+ output: [],
1006
+ errors: [],
1007
+ index: headTree,
1008
+ worktree: new Map(),
1009
+ conflicts: [],
1010
+ steps: [],
1011
+ };
1012
+ } else {
1013
+ outcome = await octopusMerge(
1014
+ {
1015
+ commits: this.commits,
1016
+ trees: this.trees,
1017
+ blobs: this.blobs,
1018
+ style: conflictStyleOf(this.workingCopy),
1019
+ },
1020
+ headId,
1021
+ remotes,
1022
+ staged,
1023
+ );
1024
+ }
1025
+ const output = [...outcome.output];
1026
+ if (outcome.status === 2) return giveUp(outcome.errors, output);
1027
+ const target = new Map(outcome.index);
1028
+ for (const [path, entry] of outcome.worktree) target.set(path, entry);
1029
+ const refused = await switchTrees(this.context(worktree), headTree, target, {
1030
+ action: "merge",
1031
+ operation: "merge",
1032
+ conflicts: outcome.conflicts,
1033
+ });
1034
+ if (refused) {
1035
+ // the script stopped at the first head whose read-tree met the local change
1036
+ const stop = outcome.steps.find((s) => refused.paths.some((p) => s.paths.has(p)));
1037
+ return giveUp([refused.message], stop ? output.slice(0, stop.output) : output);
1038
+ }
1039
+ const writeState = async (text: string) => {
1040
+ await state.write("MERGE_HEAD", remoteIds.map((id) => `${id}\n`).join(""));
1041
+ await state.write("MERGE_MSG", text);
1042
+ await state.write("MERGE_MODE", this.ffMode() === FastForwardMode.NO_FF ? "no-ff" : "");
1043
+ };
1044
+ if (outcome.status === 1) {
1045
+ const paths = [...new Set(outcome.conflicts.map((c) => c.stagePath))].sort(compareGitPaths);
1046
+ if (this.squash) {
1047
+ await state.write(
1048
+ "SQUASH_MSG",
1049
+ await squashMessage(this.commits, headId, remoteIds, (id) => this.abbreviateObjectId(id)),
1050
+ );
1051
+ await state.write("MERGE_MSG", conflictsComment(paths, true));
1052
+ output.push("Squash commit -- not updating HEAD");
1053
+ } else {
1054
+ await writeState(`${this.stateMessage(message)}${conflictsComment(paths, true)}`);
449
1055
  }
1056
+ output.push("Automatic merge failed; fix conflicts and then commit the result.");
1057
+ return {
1058
+ status: MergeStatus.CONFLICTING,
1059
+ mergedCommits,
1060
+ conflicts: paths,
1061
+ // what git-merge-one-file printed on stderr (`ERROR: content conflict in f`, ...)
1062
+ ...(outcome.errors.length > 0 ? { message: outcome.errors.join("\n") } : {}),
1063
+ output,
1064
+ };
450
1065
  }
451
-
452
- return false;
1066
+ if (this.squash) {
1067
+ await state.write(
1068
+ "SQUASH_MSG",
1069
+ await squashMessage(this.commits, headId, remoteIds, (id) => this.abbreviateObjectId(id)),
1070
+ );
1071
+ output.push(
1072
+ "Squash commit -- not updating HEAD",
1073
+ "Automatic merge went well; stopped before committing as requested",
1074
+ );
1075
+ return { status: MergeStatus.MERGED_SQUASHED, newHead: headId, mergedCommits, output };
1076
+ }
1077
+ if (!this.commit) {
1078
+ await writeState(this.stateMessage(message));
1079
+ output.push("Automatic merge went well; stopped before committing as requested");
1080
+ return { status: MergeStatus.MERGED_NOT_COMMITTED, newHead: headId, mergedCommits, output };
1081
+ }
1082
+ const treeId = await storeFlatTree(this.trees, outcome.index);
1083
+ // finish_automerge: HEAD a parent unless the heads contain it, or with --no-ff
1084
+ const keepHead = !headSubsumed || this.ffMode() === FastForwardMode.NO_FF;
1085
+ const parents = [...(keepHead ? [headId] : []), ...remoteIds];
1086
+ const hooked = await this.mergeCommitHooks(state, message, writeState);
1087
+ if (hooked.refused !== undefined) {
1088
+ return {
1089
+ status: MergeStatus.FAILED,
1090
+ newHead: headId,
1091
+ mergedCommits,
1092
+ message: hooked.refused,
1093
+ output,
1094
+ };
1095
+ }
1096
+ const cleaned = hooked.message;
1097
+ if (cleaned.length === 0) {
1098
+ // git's prepare_to_commit: abort_commit, the merge left for `git commit`
1099
+ await writeState(this.stateMessage(message));
1100
+ return {
1101
+ status: MergeStatus.FAILED,
1102
+ newHead: headId,
1103
+ mergedCommits,
1104
+ message: EMPTY_MERGE_MESSAGE,
1105
+ output,
1106
+ };
1107
+ }
1108
+ const newCommitId = await this.storeCommit(treeId, parents, cleaned);
1109
+ await this.updateHead(head, newCommitId, reflogMessages.mergeMade(strategy));
1110
+ output.push(`Merge made by the '${strategy}' strategy.`);
1111
+ return { status: MergeStatus.MERGED, newHead: newCommitId, mergedCommits, output };
453
1112
  }
454
1113
 
455
- /**
456
- * Perform three-way tree merge.
457
- *
458
- * Returns merged entries and conflicts.
459
- */
460
- private async mergeTreesThreeWay(
461
- baseTreeId: ObjectId,
462
- oursTreeId: ObjectId,
463
- theirsTreeId: ObjectId,
464
- ): Promise<TreeMergeResult> {
465
- const result: TreeMergeResult = {
466
- merged: [],
467
- conflicts: [],
1114
+ /** git's fmt-merge-msg title for several heads: `Merge branches 'a', 'b' and tag 'v1'`. */
1115
+ private async octopusMessage(heads: { id: ObjectId; name: string }[]): Promise<string> {
1116
+ const groups = new Map<string, string[]>();
1117
+ for (const { id, name } of heads) {
1118
+ const described = await this.describeMergeSource(name, id);
1119
+ const k = described.indexOf(" '");
1120
+ const kind = described.slice(0, k);
1121
+ const list = groups.get(kind) ?? [];
1122
+ list.push(described.slice(k + 1));
1123
+ groups.set(kind, list);
1124
+ }
1125
+ const plural: Record<string, string> = {
1126
+ branch: "branches",
1127
+ "remote-tracking branch": "remote-tracking branches",
1128
+ tag: "tags",
1129
+ commit: "commits",
468
1130
  };
469
-
470
- // Collect all paths from all three trees
471
- const allPaths = new Set<string>();
472
- const basePaths = new Map<string, TreeEntry>();
473
- const oursPaths = new Map<string, TreeEntry>();
474
- const theirsPaths = new Map<string, TreeEntry>();
475
-
476
- await this.collectTreeEntries(baseTreeId, "", basePaths, allPaths);
477
- await this.collectTreeEntries(oursTreeId, "", oursPaths, allPaths);
478
- await this.collectTreeEntries(theirsTreeId, "", theirsPaths, allPaths);
479
-
480
- // Process each unique path
481
- for (const path of allPaths) {
482
- const base = basePaths.get(path);
483
- const ours = oursPaths.get(path);
484
- const theirs = theirsPaths.get(path);
485
-
486
- const mergeEntry = this.mergeEntry(path, base, ours, theirs);
487
-
488
- if (mergeEntry.conflict) {
489
- // Try content-level merge if contentStrategy is set
490
- if (this.contentStrategy && ours && theirs) {
491
- const contentMergeResult = await this.tryContentMerge(path, base, ours, theirs);
492
- if (contentMergeResult) {
493
- result.merged.push({
494
- path,
495
- entry: contentMergeResult,
496
- });
497
- continue;
498
- }
499
- }
500
-
501
- // No content strategy or content merge not possible - mark as conflict
502
- result.conflicts.push(path);
503
- result.merged.push({
504
- path,
505
- base,
506
- ours,
507
- theirs,
508
- });
509
- } else if (mergeEntry.entry) {
510
- result.merged.push({
511
- path,
512
- entry: mergeEntry.entry,
513
- });
514
- }
515
- // If entry is undefined and no conflict, the file was deleted
1131
+ const parts: string[] = [];
1132
+ for (const kind of ["branch", "remote-tracking branch", "tag", "commit"]) {
1133
+ const list = groups.get(kind);
1134
+ if (!list) continue;
1135
+ const joined =
1136
+ list.length === 1
1137
+ ? list[0]
1138
+ : `${list.slice(0, -1).join(", ")} and ${list[list.length - 1]}`;
1139
+ parts.push(`${list.length === 1 ? kind : plural[kind]} ${joined}`);
516
1140
  }
1141
+ const branch = await this.getCurrentBranch();
1142
+ const short = branch?.startsWith("refs/heads/") ? branch.slice("refs/heads/".length) : "HEAD";
1143
+ const into = short === "main" || short === "master" ? "" : ` into ${short}`;
1144
+ return `Merge ${parts.join(", ")}${into}\n`;
1145
+ }
517
1146
 
518
- return result;
1147
+ /** The heads MERGE_HEAD names (one per line: several for an octopus). */
1148
+ private async mergeHeads(state: OperationState): Promise<ObjectId[]> {
1149
+ const text = await state.read("MERGE_HEAD");
1150
+ const lines = (text ?? "").split("\n").filter((l) => /^[0-9a-f]{40,64}$/.test(l));
1151
+ if (lines.length > 0) return lines;
1152
+ const single = await state.ref("MERGE_HEAD");
1153
+ return single ? [single] : [];
519
1154
  }
520
1155
 
521
- /**
522
- * Try to perform content-level merge using the configured strategy.
523
- *
524
- * @returns Merged tree entry if successful, undefined if content merge not applicable
525
- */
526
- private async tryContentMerge(
527
- _path: string,
528
- base: TreeEntry | undefined,
529
- ours: TreeEntry,
530
- theirs: TreeEntry,
531
- ): Promise<TreeEntry | undefined> {
532
- // Only merge regular files (not symlinks, executables, etc. for now)
533
- if (ours.mode !== FileMode.REGULAR_FILE || theirs.mode !== FileMode.REGULAR_FILE) {
534
- return undefined;
1156
+ /** `git merge --continue`: commits the resolved merge with MERGE_MSG. */
1157
+ private async continueMerge(state: OperationState): Promise<MergeResult> {
1158
+ const heads = await this.mergeHeads(state);
1159
+ const mergeHead = heads[0];
1160
+ if (!mergeHead) {
1161
+ return failed("fatal: There is no merge in progress (MERGE_HEAD missing).");
535
1162
  }
536
-
537
- // Content strategy must be set (caller should verify)
538
- if (!this.contentStrategy) {
539
- return undefined;
1163
+ const { unmerged } = await readIndex(this.staging);
1164
+ if (unmerged.length > 0) {
1165
+ return failed(UNMERGED_FILES_MESSAGE("Committing"), unmerged);
540
1166
  }
541
-
542
- try {
543
- // Binary or big files are never content-merged (git's ll_binary_merge)
544
- const contents = await this.loadTexts([base?.id, ours.id, theirs.id]);
545
- if (!contents) {
546
- switch (this.contentStrategy) {
547
- case ContentMergeStrategy.OURS:
548
- return ours;
549
- case ContentMergeStrategy.THEIRS:
550
- return { ...theirs, name: ours.name };
551
- default:
552
- return undefined;
553
- }
1167
+ if (this.message === undefined) {
1168
+ // `git merge --continue` runs `git commit`: its editor gets the whole template
1169
+ // (MERGE_MSG, the help and the status, written to COMMIT_EDITMSG), taken as the editor
1170
+ // leaves it
1171
+ const commit = new CommitCommand(this.workingCopy).shareHooksOf(this);
1172
+ if (this.author) commit.setAuthorIdent(this.author);
1173
+ if (this.committer) commit.setCommitterIdent(this.committer);
1174
+ if (this.cleanupMode) commit.setCleanupMode(this.cleanupMode);
1175
+ // the status in the template as `commit.status` says (git's editor gets it)
1176
+ const status = RemoteConfigStore.from(this.workingCopy).value("commit.status");
1177
+ commit.setIncludeStatus(status === undefined ? true : (parseGitBool(status) ?? true));
1178
+ // the autostash applied here, with its output (the commit would apply it silently)
1179
+ const autostash = await state.read("MERGE_AUTOSTASH");
1180
+ if (autostash !== undefined) await state.remove("MERGE_AUTOSTASH");
1181
+ let made: CommitResult;
1182
+ try {
1183
+ made = await commit.call();
1184
+ } catch (error) {
1185
+ if (autostash !== undefined) await state.write("MERGE_AUTOSTASH", autostash);
1186
+ if (error instanceof GitApiError) return failed(error.message);
1187
+ throw error;
554
1188
  }
555
-
556
- // Load content from all three versions (text under the threshold)
557
- // (read once, by the probe)
558
- const [baseContent, oursContent, theirsContent] = contents;
559
-
560
- // Convert ContentMergeStrategy to utils MergeContentStrategy
561
- const strategy = this.convertContentStrategy(this.contentStrategy);
562
-
563
- // Perform content-level merge
564
- const mergeResult = merge3Way(baseContent, oursContent, theirsContent, { strategy });
565
-
566
- // If using OURS/THEIRS/UNION, conflicts are auto-resolved
567
- // Store the merged content
568
- const mergedBlobId = await this.blobs.store(
569
- [mergeResult.content],
570
- mergeResult.content.length,
571
- );
572
-
1189
+ if (autostash !== undefined) await state.write("MERGE_AUTOSTASH", autostash);
573
1190
  return {
574
- name: ours.name,
575
- mode: ours.mode,
576
- id: mergedBlobId,
1191
+ status: MergeStatus.MERGED,
1192
+ newHead: made.id,
1193
+ mergedCommits: made.parents,
1194
+ output: await this.popAutostash(state, this.worktreeAccess),
577
1195
  };
578
- } catch {
579
- // Content merge failed - fall back to conflict
580
- return undefined;
581
1196
  }
1197
+ const headId = await this.resolveHead();
1198
+ const head = await this.refsStore.get("HEAD");
1199
+ const treeId = await this.staging.writeTree(this.trees);
1200
+ // a message given is `git commit -m`'s; MERGE_MSG is taken as an editor leaves it
1201
+ const message =
1202
+ this.message !== undefined
1203
+ ? commitMessageFromOption(this.message, this.cleanupMode, this.workingCopy)
1204
+ : cleanupMessage((await state.read("MERGE_MSG")) ?? `Merge commit '${mergeHead}'\n`);
1205
+ const newCommitId = await this.storeCommit(treeId, [headId, ...heads], message);
1206
+ // `git merge --continue` is `git commit`: "commit (merge): <subject>"
1207
+ await this.updateHead(head, newCommitId, undefined, reflogMessages.commit("merge", message));
1208
+ await state.removeRef("MERGE_HEAD", "AUTO_MERGE");
1209
+ await state.remove("MERGE_MSG", "MERGE_MODE", "SQUASH_MSG");
1210
+ return {
1211
+ status: MergeStatus.MERGED,
1212
+ newHead: newCommitId,
1213
+ mergedCommits: [headId, ...heads],
1214
+ output: await this.popAutostash(state, this.worktreeAccess),
1215
+ };
1216
+ }
1217
+
1218
+ /** `git merge --abort`: `git reset --merge`, the merge's state removed. */
1219
+ private async abort(state: OperationState, worktree: Worktree | undefined): Promise<MergeResult> {
1220
+ const mergeHead = (await this.mergeHeads(state))[0];
1221
+ if (!mergeHead) {
1222
+ return failed("fatal: There is no merge to abort (MERGE_HEAD missing).");
1223
+ }
1224
+ const headId = await this.resolveHead();
1225
+ const refused = await resetMerge(this.context(worktree), headId, "HEAD");
1226
+ if (refused) {
1227
+ // git has taken MERGE_AUTOSTASH away by now (and dies in the reset): ours is kept on
1228
+ // refs/stash rather than lost
1229
+ const autostash = (await state.read("MERGE_AUTOSTASH"))?.trim();
1230
+ if (autostash) {
1231
+ await state.remove("MERGE_AUTOSTASH");
1232
+ await saveAutostash(this.context(worktree), autostash);
1233
+ }
1234
+ return failed(refused.message, refused.paths);
1235
+ }
1236
+ await state.setRef("ORIG_HEAD", headId);
1237
+ // `git reset --merge` moves HEAD where it is: "reset: moving to HEAD" (git's merge sets
1238
+ // GIT_REFLOG_ACTION only after the abort, so a caller's action reads "<action>: updating HEAD")
1239
+ const message = this.hasReflogAction()
1240
+ ? `${this.reflogAction("merge")}: updating HEAD`
1241
+ : reflogMessages.reset("HEAD");
1242
+ await updateHead(this.refsStore, headId, this.reflogLine(message));
1243
+ await state.removeRef("MERGE_HEAD", "AUTO_MERGE");
1244
+ await state.remove("MERGE_MSG", "MERGE_MODE", "SQUASH_MSG");
1245
+ return {
1246
+ status: MergeStatus.ABORTED,
1247
+ newHead: headId,
1248
+ mergedCommits: [mergeHead],
1249
+ output: await this.popAutostash(state, worktree),
1250
+ };
582
1251
  }
583
1252
 
584
1253
  /**
585
- * The blobs' contents, each read once; nothing when one is binary or over the
586
- * threshold (then the rest are not read). A missing id is empty content.
1254
+ * A failed strategy leaves AUTO_MERGE as git leaves it: git's merge restores the local
1255
+ * changes it saved (`restore_state`, a stash of them applied by merge-ort), so AUTO_MERGE
1256
+ * ends up the tree of the index and the tracked files' worktree content, and is absent
1257
+ * when there was nothing to save. Returns the warning lines the reset printed (each ending
1258
+ * with a newline).
587
1259
  */
588
- private async loadTexts(
589
- ids: [ObjectId | undefined, ObjectId, ObjectId],
590
- ): Promise<[Uint8Array, Uint8Array, Uint8Array] | undefined> {
591
- const out: Uint8Array[] = [];
592
- for (const id of ids) {
593
- if (!id) {
594
- out.push(new Uint8Array(0));
1260
+ private async restoreStateQuirk(
1261
+ state: OperationState,
1262
+ headTree: ObjectId,
1263
+ worktree: Worktree | undefined,
1264
+ ): Promise<string> {
1265
+ await state.removeRef("AUTO_MERGE");
1266
+ if (!worktree) return "";
1267
+ const provider = new WorkingCopyStashProvider({
1268
+ workingCopy: this.workingCopy,
1269
+ trees: this.trees,
1270
+ blobs: this.blobs,
1271
+ staging: this.staging,
1272
+ worktree,
1273
+ headTree: async () => headTree,
1274
+ });
1275
+ // save_state's `stash create`, then the reset. The stash writes the index's tree first
1276
+ // (write_index_as_tree, the index file written with its cache-tree), and fails before
1277
+ // the reset where it cannot save the worktree (an intent-to-add entry)
1278
+ let savedTree: ObjectId | undefined;
1279
+ let indexTree: ObjectId | undefined;
1280
+ if (await provider.hasLocalChanges()) {
1281
+ indexTree = await writeIndexAsTree(this.staging, this.trees);
1282
+ savedTree = await provider.getWorkingTree();
1283
+ }
1284
+ // nothing saved: the reset alone, which leaves the index exactly HEAD (read-tree's
1285
+ // prime_cache_tree: a fully valid cache-tree)
1286
+ await this.resetAssumeUnchanged(worktree, savedTree ? undefined : headTree);
1287
+ if (!savedTree) return "";
1288
+ let warnings = "";
1289
+ // a sparse checkout: the reset leaves what is outside its patterns to unpack-trees, which
1290
+ // unlinks a file leaving it (its skip-worktree bit cleared on reading, the path present)
1291
+ const sparseConfig = sparseCheckoutConfig(this.workingCopy);
1292
+ const patterns = sparseConfig.expectFilesOutside
1293
+ ? undefined
1294
+ : await readSparseCheckoutPatterns(this.workingCopy);
1295
+ // stash apply's merge_ort_nonrecursive: a stash whose worktree tree is HEAD's ("Already
1296
+ // up to date", e.g. a tracked file replaced by a directory, which stash create passes
1297
+ // over) merges nothing and records no AUTO_MERGE
1298
+ if (savedTree !== headTree) await state.setRef("AUTO_MERGE", savedTree);
1299
+ // restore_state's `reset --hard` and `stash apply --index`: every changed file is
1300
+ // written again from what was saved, through the checkout filters (eol, smudge)
1301
+ const saved = await flatTree(this.trees, savedTree);
1302
+ const head = await flatTree(this.trees, headTree);
1303
+ const { index } = await readIndex(this.staging);
1304
+ const attributes: ContentAttributesContext = {
1305
+ direction: "checkout",
1306
+ index: attributesIndexOf([...index].map(([p, e]) => [p, e.objectId] as const)),
1307
+ };
1308
+ const symlinks = worktreeModeTrust(this.workingCopy, worktree).symlinks;
1309
+ const restaged = new Map<string, IndexEntryOptions[]>();
1310
+ // the reset --hard (read-tree --reset -u, untracked files overwritten): checkout_entry
1311
+ // finds a directory (never a symlink to one) at each of HEAD's files and removes it with
1312
+ // everything in it, a nested repository too (remove_subtree), before the file is written;
1313
+ // stash create passed such a path over, or saved the index's content for it. HEAD's
1314
+ // files are stat'ed in one batch. Outside the sparse patterns the reset unlinks instead,
1315
+ // which fails on the directory with git's warning, and the path is left alone.
1316
+ const headFiles = [...head]
1317
+ .filter(([, entry]) => entry.mode !== FileMode.GITLINK)
1318
+ .map(([path]) => path);
1319
+ const headStats = await getWorktreeEntries(worktree, headFiles);
1320
+ const replaced = new Set<string>();
1321
+ const blocked = new Set<string>();
1322
+ for (let i = 0; i < headFiles.length; i++) {
1323
+ const path = headFiles[i] as string;
1324
+ const current = headStats[i];
1325
+ if (!current?.isDirectory || current.mode === FileMode.SYMLINK) continue;
1326
+ if (patterns && !patterns.includes(path)) {
1327
+ warnings += `warning: unable to unlink '${path}': Is a directory\n`;
1328
+ blocked.add(path);
595
1329
  continue;
596
1330
  }
597
- const probe = await probeBlob(this.blobs, id, {
598
- bigFileThreshold: this.bigFileThreshold,
599
- loadText: true,
600
- });
601
- if (probe.binary || !probe.content) return undefined;
602
- out.push(probe.content);
1331
+ await worktree.remove(path, { recursive: true });
1332
+ replaced.add(path);
1333
+ }
1334
+ for (const [path, entry] of saved) {
1335
+ if (entry.mode === FileMode.GITLINK || blocked.has(path)) continue;
1336
+ // `stash apply` writes what changed; the reset wrote HEAD's content where it replaced
1337
+ // a directory
1338
+ const before = head.get(path);
1339
+ if (
1340
+ before?.objectId === entry.objectId &&
1341
+ before.mode === entry.mode &&
1342
+ !replaced.has(path)
1343
+ ) {
1344
+ continue;
1345
+ }
1346
+ const content = await this.blobs.load(entry.objectId);
1347
+ if (!content) continue;
1348
+ const mode =
1349
+ entry.mode === FileMode.SYMLINK && !symlinks ? FileMode.REGULAR_FILE : entry.mode;
1350
+ try {
1351
+ await worktree.writeContent(path, content, {
1352
+ mode,
1353
+ ...(mode !== entry.mode ? { raw: true } : {}),
1354
+ createParents: true,
1355
+ replaceInTheWay: true,
1356
+ attributes,
1357
+ });
1358
+ } catch (error) {
1359
+ // checkout_entry's error: the file is not written, the rest goes on
1360
+ warnings += `error: unable to create file ${path}: ${(error as Error).message}\n`;
1361
+ continue;
1362
+ }
1363
+ // `stash apply --index` stages again what was staged: the index entry takes the stat
1364
+ // of the file just written where the file holds its blob
1365
+ const staged = index.get(path);
1366
+ const stats = await worktree.getEntry(path);
1367
+ if (staged && stats && !stats.isDirectory) {
1368
+ if ((await worktree.computeHash(path)) === staged.objectId) {
1369
+ restaged.set(path, [
1370
+ { path, objectId: staged.objectId, mode: staged.mode, ...entryStatOf(stats) },
1371
+ ]);
1372
+ }
1373
+ }
603
1374
  }
604
- return out as [Uint8Array, Uint8Array, Uint8Array];
1375
+ // the reset --hard wrote a new index: no resolve-undo left
1376
+ this.staging.clearResolveUndo?.();
1377
+ if (this.staging.setCacheTree && indexTree) {
1378
+ // `stash apply --index` of staged changes ends reading the index's tree (fully valid);
1379
+ // with none, HEAD's cache-tree (the reset) has the paths the apply wrote invalid
1380
+ const staged = indexTree !== headTree;
1381
+ const cacheTree = await cacheTreeOfTree(this.trees, staged ? indexTree : headTree);
1382
+ if (!staged) {
1383
+ const differs = (a: CheckedEntry | undefined, b: CheckedEntry | undefined) =>
1384
+ a?.objectId !== b?.objectId || a?.mode !== b?.mode;
1385
+ for (const path of new Set([...saved.keys(), ...head.keys()])) {
1386
+ if (differs(saved.get(path), head.get(path))) invalidateCacheTreePath(cacheTree, path);
1387
+ }
1388
+ }
1389
+ this.staging.setCacheTree(cacheTree);
1390
+ }
1391
+ await rewriteIndex(this.staging, restaged);
1392
+ // a file deleted in what was saved: `reset --hard` wrote it, `stash apply` removed it
1393
+ // again with the directories it leaves empty
1394
+ for (const path of head.keys()) {
1395
+ if (saved.has(path) || (await worktree.getEntry(path))) continue;
1396
+ await pruneEmptyParents(worktree, path);
1397
+ }
1398
+ return warnings;
605
1399
  }
606
1400
 
607
1401
  /**
608
- * Convert ContentMergeStrategy to utils MergeContentStrategy.
1402
+ * restore_state's `reset --hard` over a file the index marks assume-unchanged: `stash
1403
+ * create` did not save its change (the flag hides it), and the reset writes it again from
1404
+ * the index when it no longer matches (oneway_merge compares with CE_MATCH_IGNORE_VALID),
1405
+ * so the local change is lost, as in git. The entry keeps its flag and takes the new stat.
1406
+ * With `cacheTree` (the index is that tree's), the index is written with its cache-tree.
609
1407
  */
610
- private convertContentStrategy(strategy: ContentMergeStrategy): UtilsMergeContentStrategy {
611
- switch (strategy) {
612
- case ContentMergeStrategy.OURS:
613
- return UtilsMergeContentStrategy.OURS;
614
- case ContentMergeStrategy.THEIRS:
615
- return UtilsMergeContentStrategy.THEIRS;
616
- case ContentMergeStrategy.UNION:
617
- return UtilsMergeContentStrategy.UNION;
1408
+ private async resetAssumeUnchanged(worktree: Worktree, cacheTree?: ObjectId): Promise<void> {
1409
+ const marked: IndexEntryOptions[] = [];
1410
+ for await (const entry of this.staging.entries()) {
1411
+ if (entry.stage === 0 && entry.assumeValid && entry.mode !== FileMode.GITLINK) {
1412
+ marked.push(entry);
1413
+ }
1414
+ }
1415
+ if (marked.length === 0 && !cacheTree) return;
1416
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
1417
+ const indexTime = this.staging.getUpdateTime();
1418
+ const { index } = await readIndex(this.staging);
1419
+ const attributes: ContentAttributesContext = {
1420
+ direction: "checkout",
1421
+ index: attributesIndexOf([...index].map(([p, e]) => [p, e.objectId] as const)),
1422
+ };
1423
+ const rewritten = new Map<string, IndexEntryOptions[]>();
1424
+ for (const entry of marked) {
1425
+ if (!(await worktreeModified(worktree, entry.path, entry, trust, indexTime))) continue;
1426
+ const content = await this.blobs.load(entry.objectId);
1427
+ if (!content) continue;
1428
+ const mode =
1429
+ entry.mode === FileMode.SYMLINK && !trust.symlinks ? FileMode.REGULAR_FILE : entry.mode;
1430
+ await worktree.writeContent(entry.path, content, {
1431
+ mode,
1432
+ ...(mode !== entry.mode ? { raw: true } : {}),
1433
+ createParents: true,
1434
+ replaceInTheWay: true,
1435
+ attributes,
1436
+ });
1437
+ const stats = await worktree.getEntry(entry.path);
1438
+ rewritten.set(entry.path, [
1439
+ {
1440
+ ...entry,
1441
+ ...(stats && !stats.isDirectory ? entryStatOf(stats) : {}),
1442
+ },
1443
+ ]);
618
1444
  }
1445
+ if (cacheTree && this.staging.setCacheTree) {
1446
+ this.staging.setCacheTree(await cacheTreeOfTree(this.trees, cacheTree));
1447
+ } else if (rewritten.size === 0) {
1448
+ return;
1449
+ }
1450
+ await rewriteIndex(this.staging, rewritten);
1451
+ }
1452
+
1453
+ private context(worktree: Worktree | undefined) {
1454
+ return {
1455
+ workingCopy: this.workingCopy,
1456
+ worktree,
1457
+ staging: this.staging,
1458
+ blobs: this.blobs,
1459
+ trees: this.trees,
1460
+ commits: this.commits,
1461
+ refs: this.refsStore,
1462
+ sparseWarnings: this.sparseWarnings,
1463
+ };
619
1464
  }
620
1465
 
621
1466
  /**
622
- * Collect all blob entries from a tree recursively.
1467
+ * MERGE_MSG's text before any conflicts hint (git's `write_merge_state`): the message as
1468
+ * given with a newline added, always (`-m "x\n"` gives `x` and a blank line), or git's
1469
+ * default message (already one line ended).
623
1470
  */
624
- private async collectTreeEntries(
625
- treeId: ObjectId,
626
- prefix: string,
627
- entries: Map<string, TreeEntry>,
628
- allPaths: Set<string>,
629
- ): Promise<void> {
630
- for await (const entry of this.trees.loadTree(treeId)) {
631
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
1471
+ private stateMessage(message: string): string {
1472
+ return this.message !== undefined ? `${this.message}\n` : message;
1473
+ }
632
1474
 
633
- if (entry.mode === FileMode.TREE) {
634
- // Recurse into subtree
635
- await this.collectTreeEntries(entry.id, path, entries, allPaths);
636
- } else {
637
- // Blob entry
638
- entries.set(path, entry);
639
- allPaths.add(path);
640
- }
641
- }
1475
+ /** git's merge exports GIT_REFLOG_ACTION before it writes a ref (see reflogActionValue). */
1476
+ protected override refTransactionHookEnv(): Record<string, string> | undefined {
1477
+ return { GIT_REFLOG_ACTION: this.reflogActionValue() };
1478
+ }
1479
+
1480
+ /** `GIT_REFLOG_ACTION` as git's merge exports it (`merge <names>`, `pull` for a pull). */
1481
+ private reflogActionValue(): string {
1482
+ return this.reflogAction(reflogMessages.mergeAction(this.includes));
642
1483
  }
643
1484
 
644
1485
  /**
645
- * Merge a single entry using three-way merge logic.
1486
+ * prepare_to_commit of git's merge, around the hooks: `pre-merge-commit` (not with
1487
+ * --no-verify; the index read again after it), then MERGE_HEAD and MERGE_MSG written,
1488
+ * `prepare-commit-msg` (`merge`) and `commit-msg` (not with --no-verify) over MERGE_MSG,
1489
+ * whose text, cleaned up, is the commit's. A refusing hook stops the merge before its
1490
+ * commit, its state written (abort_commit); `refused` is git's message then. Without
1491
+ * hooks: the message cleaned up.
646
1492
  */
647
- private mergeEntry(
648
- _path: string,
649
- base: TreeEntry | undefined,
650
- ours: TreeEntry | undefined,
651
- theirs: TreeEntry | undefined,
652
- ): { entry?: TreeEntry; conflict?: boolean } {
653
- // Case 1: All same (or all undefined)
654
- if (this.sameEntry(base, ours) && this.sameEntry(base, theirs)) {
655
- return { entry: ours };
1493
+ private async mergeCommitHooks(
1494
+ state: OperationState,
1495
+ message: string,
1496
+ writeState: (text: string) => Promise<void>,
1497
+ ): Promise<{ message: string; refused?: string }> {
1498
+ // (a merge a rebase makes in process runs no hooks of its own)
1499
+ if (!this.hooks.enabled || this.inProcess) return { message: this.cleanup(message) };
1500
+ const env = {
1501
+ GIT_INDEX_FILE: await this.hooks.gitPath("index"),
1502
+ GIT_EDITOR: ":",
1503
+ GIT_REFLOG_ACTION: this.reflogActionValue(),
1504
+ };
1505
+ const abort = async () => {
1506
+ await writeState(this.stateMessage(message));
1507
+ return {
1508
+ message: "",
1509
+ refused: "Not committing merge; use 'git commit' to complete the merge.",
1510
+ };
1511
+ };
1512
+ if (!this.noVerify) {
1513
+ const pre = await this.hooks.run("pre-merge-commit", { env });
1514
+ if (pre && pre.exitCode !== 0) return abort();
1515
+ if (pre) await this.staging.read();
656
1516
  }
657
-
658
- // Case 2: Only we changed
659
- if (this.sameEntry(base, theirs)) {
660
- return { entry: ours };
1517
+ // prepare_to_commit writes merge_msg as it is (`-m`'s text without a newline added)
1518
+ await writeState(this.message ?? message);
1519
+ const file = await this.hooks.gitPath("MERGE_MSG");
1520
+ const prepare = await this.hooks.run("prepare-commit-msg", { args: [file, "merge"], env });
1521
+ if (prepare && prepare.exitCode !== 0) return abort();
1522
+ if (!this.noVerify) {
1523
+ const check = await this.hooks.run("commit-msg", { args: [file], env });
1524
+ if (check && check.exitCode !== 0) return abort();
661
1525
  }
1526
+ const text = (await state.read("MERGE_MSG")) ?? "";
1527
+ // the commit ends the merge (remove_merge_branch_state)
1528
+ await state.removeRef("MERGE_HEAD");
1529
+ await state.remove("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE");
1530
+ return { message: this.cleanup(text) };
1531
+ }
662
1532
 
663
- // Case 3: Only they changed
664
- if (this.sameEntry(base, ours)) {
665
- return { entry: theirs };
666
- }
1533
+ /** MERGE_HEAD, MERGE_MSG and MERGE_MODE of a merge stopped before its commit. */
1534
+ private async writeMergeState(
1535
+ state: OperationState,
1536
+ srcId: ObjectId,
1537
+ message: string,
1538
+ ): Promise<void> {
1539
+ await state.setRef("MERGE_HEAD", srcId);
1540
+ await state.write("MERGE_MSG", message);
1541
+ await state.write("MERGE_MODE", this.ffMode() === FastForwardMode.NO_FF ? "no-ff" : "");
1542
+ }
667
1543
 
668
- // Case 4: Both changed - check if same change
669
- if (this.sameEntry(ours, theirs)) {
670
- return { entry: ours };
1544
+ private strategyName(): string {
1545
+ switch (this.strategy) {
1546
+ case MergeStrategy.OURS:
1547
+ return "ours";
1548
+ case MergeStrategy.THEIRS:
1549
+ return "theirs";
1550
+ default:
1551
+ return "ort";
671
1552
  }
1553
+ }
672
1554
 
673
- // Case 5: Both changed differently - conflict
674
- return { conflict: true };
1555
+ /** git's `cleanup_message` of a merge commit's message (prepare_to_commit, no editor). */
1556
+ private cleanup(message: string): string {
1557
+ const mode = commitCleanupMode(this.workingCopy, this.cleanupMode);
1558
+ return cleanupWith(this.workingCopy, message, mode);
675
1559
  }
676
1560
 
677
- /**
678
- * Check if two tree entries are the same.
679
- */
680
- private sameEntry(a: TreeEntry | undefined, b: TreeEntry | undefined): boolean {
681
- if (a === undefined && b === undefined) return true;
682
- if (a === undefined || b === undefined) return false;
683
- return a.id === b.id && a.mode === b.mode;
1561
+ private async storeCommit(tree: ObjectId, parents: ObjectId[], message: string) {
1562
+ // git's merge commit: the author and the committer as git resolves them (GIT_AUTHOR_* /
1563
+ // GIT_COMMITTER_*, author.* / committer.*, user.*), unless given
1564
+ const author = this.author ?? this.resolveAuthor(this.committer);
1565
+ const committer = this.committer ?? this.resolveCommitter(author);
1566
+ const commit: Commit = { tree, parents, author, committer, message };
1567
+ return this.commits.store(commit);
684
1568
  }
685
1569
 
686
1570
  /**
687
- * Write conflict state to staging area.
1571
+ * HEAD (its branch, when attached) moved to `id`, logged as git's merge logs it:
1572
+ * `<action>: <outcome>`, the action being `merge <names as given>` (`pull` for a pull);
1573
+ * or with `message` as it is.
688
1574
  */
689
- private async writeConflictStaging(
690
- _baseTreeId: ObjectId,
691
- _oursTreeId: ObjectId,
692
- _theirsTreeId: ObjectId,
693
- mergeResult: TreeMergeResult,
1575
+ private async updateHead(
1576
+ head: Awaited<ReturnType<typeof this.refsStore.get>>,
1577
+ id: ObjectId,
1578
+ outcome: string | undefined,
1579
+ message?: string,
694
1580
  ): Promise<void> {
695
- const builder = this.staging.createBuilder();
696
-
697
- // Add merged entries (stage 0)
698
- for (const item of mergeResult.merged) {
699
- if (item.entry) {
700
- builder.add({
701
- path: item.path,
702
- mode: item.entry.mode,
703
- objectId: item.entry.id,
704
- stage: MergeStage.MERGED,
705
- });
706
- } else if (item.base || item.ours || item.theirs) {
707
- // Conflict entry - add all stages
708
- if (item.base) {
709
- builder.add({
710
- path: item.path,
711
- mode: item.base.mode,
712
- objectId: item.base.id,
713
- stage: MergeStage.BASE,
714
- });
715
- }
716
- if (item.ours) {
717
- builder.add({
718
- path: item.path,
719
- mode: item.ours.mode,
720
- objectId: item.ours.id,
721
- stage: MergeStage.OURS,
722
- });
723
- }
724
- if (item.theirs) {
725
- builder.add({
726
- path: item.path,
727
- mode: item.theirs.mode,
728
- objectId: item.theirs.id,
729
- stage: MergeStage.THEIRS,
730
- });
731
- }
732
- }
1581
+ const action = this.reflogAction(reflogMessages.mergeAction(this.includes));
1582
+ const log = this.reflogLine(
1583
+ message ?? reflogMessages.merge(action, outcome ?? ""),
1584
+ this.committer,
1585
+ );
1586
+ // finish()'s update_ref("HEAD", new_head, head): one transaction on HEAD expecting the
1587
+ // commit it left, as the reference-transaction hook sees it
1588
+ const old = (await this.refsStore.resolve("HEAD").catch(() => undefined))?.objectId;
1589
+ if (head === undefined && old === undefined) {
1590
+ await this.refsStore.set("HEAD", id, log);
1591
+ return;
733
1592
  }
1593
+ await updateHeadExpecting(this.refsStore, id, old, log);
1594
+ }
1595
+
1596
+ /** How git's merge message names what is merged: `branch 'x'`, `tag 'v1'`, ... */
1597
+ private async describeMergeSource(name: string, id: ObjectId): Promise<string> {
1598
+ const strip = (prefix: string) => (name.startsWith(prefix) ? name.slice(prefix.length) : name);
1599
+ if (name.startsWith("refs/heads/")) return `branch '${strip("refs/heads/")}'`;
1600
+ if (name.startsWith("refs/remotes/"))
1601
+ return `remote-tracking branch '${strip("refs/remotes/")}'`;
1602
+ if (name.startsWith("refs/tags/")) return `tag '${strip("refs/tags/")}'`;
1603
+ if (await this.refsStore.has(`refs/heads/${name}`)) return `branch '${name}'`;
1604
+ if (await this.refsStore.has(`refs/tags/${name}`)) return `tag '${name}'`;
1605
+ if (await this.refsStore.has(`refs/remotes/${name}`)) return `remote-tracking branch '${name}'`;
1606
+ return `commit '${name || id}'`;
1607
+ }
734
1608
 
735
- await builder.finish();
1609
+ /** git's default merge message: `Merge branch 'x'` (`into <branch>` off main/master). */
1610
+ private async defaultMessage(description: string): Promise<string> {
1611
+ const branch = await this.getCurrentBranch();
1612
+ const short = branch?.startsWith("refs/heads/") ? branch.slice("refs/heads/".length) : "HEAD";
1613
+ const into = short === "main" || short === "master" ? "" : ` into ${short}`;
1614
+ return `Merge ${description}${into}\n`;
736
1615
  }
737
1616
 
738
1617
  /**
739
- * Write successfully merged entries to staging.
1618
+ * Check if commitA is an ancestor of commitB.
740
1619
  */
741
- private async writeMergedStaging(mergeResult: TreeMergeResult): Promise<void> {
742
- const builder = this.staging.createBuilder();
1620
+ private async isAncestor(commitA: ObjectId, commitB: ObjectId): Promise<boolean> {
1621
+ // the store's walk (git's repo_in_merge_bases): commit-graph generations cut it short
1622
+ return this.commits.isAncestor(commitA, commitB);
1623
+ }
743
1624
 
744
- for (const item of mergeResult.merged) {
745
- if (item.entry) {
746
- builder.add({
747
- path: item.path,
748
- mode: item.entry.mode,
749
- objectId: item.entry.id,
750
- stage: MergeStage.MERGED,
751
- });
752
- }
1625
+ /**
1626
+ * The commit a head to merge names (git's `get_merge_parent`, `peel_to_type` commit): a
1627
+ * tree or a blob is `error: <name>: expected commit type, but the object dereferences to
1628
+ * tree type` and `merge: <name> - not something we can merge`.
1629
+ */
1630
+ private async mergeHeadOf(name: string): Promise<ObjectId> {
1631
+ try {
1632
+ return await this.resolveRef(name);
1633
+ } catch (error) {
1634
+ if (!(error instanceof NotACommitError)) throw error;
1635
+ const lines = error.objectType
1636
+ ? [
1637
+ `error: ${name}: expected commit type, but the object dereferences to ${error.objectType} type`,
1638
+ ]
1639
+ : [];
1640
+ lines.push(`merge: ${name} - not something we can merge`);
1641
+ throw new NotACommitError(name, error.objectId, error.objectType, lines.join("\n"));
753
1642
  }
754
-
755
- await builder.finish();
756
1643
  }
757
1644
  }
758
1645
 
759
- /**
760
- * Result of tree-level merge.
761
- */
762
- interface TreeMergeResult {
763
- /** Merged entries (both clean merges and conflicts) */
764
- merged: MergedEntry[];
765
- /** Paths with conflicts */
766
- conflicts: string[];
1646
+ /** git's abort_commit after a message that cleans up to nothing (MERGE_HEAD etc. kept). */
1647
+ const EMPTY_MERGE_MESSAGE =
1648
+ "error: Empty commit message.\nNot committing merge; use 'git commit' to complete the merge.";
1649
+
1650
+ /** A refused merge: git's message, nothing changed. */
1651
+ function failed(message: string, paths: string[] = []): MergeResult {
1652
+ return {
1653
+ status: MergeStatus.FAILED,
1654
+ mergedCommits: [],
1655
+ message,
1656
+ ...(paths.length > 0 ? { failingPaths: failing(paths) } : {}),
1657
+ };
767
1658
  }
768
1659
 
769
- /**
770
- * A merged entry from three-way merge.
771
- */
772
- interface MergedEntry {
773
- /** File path */
774
- path: string;
775
- /** Merged entry (for clean merges) */
776
- entry?: TreeEntry;
777
- /** Base entry (for conflicts) */
778
- base?: TreeEntry;
779
- /** Our entry (for conflicts) */
780
- ours?: TreeEntry;
781
- /** Their entry (for conflicts) */
782
- theirs?: TreeEntry;
1660
+ function failing(paths: string[]): Map<string, MergeFailureReason> {
1661
+ return new Map(paths.map((p) => [p, MergeFailureReason.DIRTY_WORKTREE]));
1662
+ }
1663
+
1664
+ /** The content strategy as merge-ort's favor (`-X ours`, `-X theirs`, union). */
1665
+ export function favorOf(
1666
+ strategy: ContentMergeStrategy | undefined,
1667
+ ): "ours" | "theirs" | "union" | undefined {
1668
+ switch (strategy) {
1669
+ case ContentMergeStrategy.OURS:
1670
+ return "ours";
1671
+ case ContentMergeStrategy.THEIRS:
1672
+ return "theirs";
1673
+ case ContentMergeStrategy.UNION:
1674
+ return "union";
1675
+ default:
1676
+ return undefined;
1677
+ }
783
1678
  }