@statewalker/vcs-commands 0.5.0 → 0.7.0

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