@statewalker/vcs-commands 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (561) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +299 -34
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +67 -4
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +179 -7
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +93 -0
  73. package/dist/commands/core-config.d.ts.map +1 -0
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +244 -23
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +55 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +146 -6
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +69 -13
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +214 -26
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +10 -2
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-list-command.d.ts +2 -4
  237. package/dist/commands/stash-list-command.d.ts.map +1 -1
  238. package/dist/commands/stash-working-tree.d.ts +95 -0
  239. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  240. package/dist/commands/status-command.d.ts +320 -28
  241. package/dist/commands/status-command.d.ts.map +1 -1
  242. package/dist/commands/status-format.d.ts +155 -0
  243. package/dist/commands/status-format.d.ts.map +1 -0
  244. package/dist/commands/status-header.d.ts +64 -0
  245. package/dist/commands/status-header.d.ts.map +1 -0
  246. package/dist/commands/strerror.d.ts +7 -0
  247. package/dist/commands/strerror.d.ts.map +1 -0
  248. package/dist/commands/submodule-config.d.ts +38 -0
  249. package/dist/commands/submodule-config.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary-command.d.ts +80 -0
  251. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  252. package/dist/commands/submodule-summary.d.ts +150 -0
  253. package/dist/commands/submodule-summary.d.ts.map +1 -0
  254. package/dist/commands/switch-command.d.ts +132 -0
  255. package/dist/commands/switch-command.d.ts.map +1 -0
  256. package/dist/commands/tag-command.d.ts +23 -2
  257. package/dist/commands/tag-command.d.ts.map +1 -1
  258. package/dist/commands/tracking-info.d.ts +64 -0
  259. package/dist/commands/tracking-info.d.ts.map +1 -0
  260. package/dist/commands/trailers.d.ts +73 -0
  261. package/dist/commands/trailers.d.ts.map +1 -0
  262. package/dist/commands/tree-restore.d.ts +137 -6
  263. package/dist/commands/tree-restore.d.ts.map +1 -1
  264. package/dist/commands/untracked-cache-support.d.ts +53 -0
  265. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  266. package/dist/commands/worktree-add-command.d.ts +108 -0
  267. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-list-command.d.ts +69 -0
  269. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-lock-command.d.ts +44 -0
  271. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-overwrite-checks.d.ts +204 -0
  273. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  274. package/dist/commands/worktree-prune-command.d.ts +48 -0
  275. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-remove-command.d.ts +59 -0
  277. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-repair-command.d.ts +35 -0
  279. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-support.d.ts +64 -0
  281. package/dist/commands/worktree-support.d.ts.map +1 -0
  282. package/dist/commands-DnmlfwGV.js +61620 -0
  283. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  284. package/dist/core-commands/index.d.ts +0 -3
  285. package/dist/core-commands/index.d.ts.map +1 -1
  286. package/dist/errors/add-errors.d.ts +55 -0
  287. package/dist/errors/add-errors.d.ts.map +1 -1
  288. package/dist/errors/checkout-errors.d.ts +29 -0
  289. package/dist/errors/checkout-errors.d.ts.map +1 -1
  290. package/dist/errors/command-errors.d.ts +77 -0
  291. package/dist/errors/command-errors.d.ts.map +1 -1
  292. package/dist/errors/commit-errors.d.ts +9 -0
  293. package/dist/errors/commit-errors.d.ts.map +1 -1
  294. package/dist/errors/git-api-error.d.ts +59 -2
  295. package/dist/errors/git-api-error.d.ts.map +1 -1
  296. package/dist/errors/index.d.ts +1 -0
  297. package/dist/errors/index.d.ts.map +1 -1
  298. package/dist/errors/index.js +371 -19
  299. package/dist/errors/rebase-errors.d.ts +9 -0
  300. package/dist/errors/rebase-errors.d.ts.map +1 -1
  301. package/dist/errors/ref-errors.d.ts +32 -0
  302. package/dist/errors/ref-errors.d.ts.map +1 -1
  303. package/dist/errors/transport-errors.d.ts +12 -2
  304. package/dist/errors/transport-errors.d.ts.map +1 -1
  305. package/dist/errors/worktree-errors.d.ts +35 -0
  306. package/dist/errors/worktree-errors.d.ts.map +1 -0
  307. package/dist/git-command-DxvwPrPB.js +7612 -0
  308. package/dist/git-command.d.ts +422 -32
  309. package/dist/git-command.d.ts.map +1 -1
  310. package/dist/git.d.ts +326 -5
  311. package/dist/git.d.ts.map +1 -1
  312. package/dist/index.d.ts +1 -1
  313. package/dist/index.d.ts.map +1 -1
  314. package/dist/index.js +5 -5
  315. package/dist/remote-config/index.d.ts +1 -0
  316. package/dist/remote-config/index.d.ts.map +1 -1
  317. package/dist/remote-config/remote-config-store.d.ts +123 -3
  318. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  319. package/dist/remote-config/remote-refs.d.ts +41 -0
  320. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  321. package/dist/rename/detect-renames.d.ts +148 -0
  322. package/dist/rename/detect-renames.d.ts.map +1 -0
  323. package/dist/rename/git-similarity.d.ts +44 -0
  324. package/dist/rename/git-similarity.d.ts.map +1 -0
  325. package/dist/rename/index.d.ts +2 -0
  326. package/dist/rename/index.d.ts.map +1 -1
  327. package/dist/results/binary-patch.d.ts +11 -0
  328. package/dist/results/binary-patch.d.ts.map +1 -0
  329. package/dist/results/blame-format.d.ts +55 -0
  330. package/dist/results/blame-format.d.ts.map +1 -0
  331. package/dist/results/cherry-pick-result.d.ts +10 -0
  332. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  333. package/dist/results/clone-result.d.ts +16 -0
  334. package/dist/results/clone-result.d.ts.map +1 -1
  335. package/dist/results/combined-diff.d.ts +77 -0
  336. package/dist/results/combined-diff.d.ts.map +1 -0
  337. package/dist/results/diff-entry.d.ts +32 -0
  338. package/dist/results/diff-entry.d.ts.map +1 -1
  339. package/dist/results/diff-formatter.d.ts +34 -60
  340. package/dist/results/diff-formatter.d.ts.map +1 -1
  341. package/dist/results/diff-order.d.ts +25 -0
  342. package/dist/results/diff-order.d.ts.map +1 -0
  343. package/dist/results/diff-output.d.ts +249 -0
  344. package/dist/results/diff-output.d.ts.map +1 -0
  345. package/dist/results/fetch-result.d.ts +24 -1
  346. package/dist/results/fetch-result.d.ts.map +1 -1
  347. package/dist/results/index.d.ts +5 -0
  348. package/dist/results/index.d.ts.map +1 -1
  349. package/dist/results/index.js +2 -252
  350. package/dist/results/merge-result.d.ts +15 -1
  351. package/dist/results/merge-result.d.ts.map +1 -1
  352. package/dist/results/pull-result.d.ts +12 -3
  353. package/dist/results/pull-result.d.ts.map +1 -1
  354. package/dist/results/push-result.d.ts +42 -0
  355. package/dist/results/push-result.d.ts.map +1 -1
  356. package/dist/results/quote-path.d.ts +27 -0
  357. package/dist/results/quote-path.d.ts.map +1 -0
  358. package/dist/results/rebase-result.d.ts +28 -1
  359. package/dist/results/rebase-result.d.ts.map +1 -1
  360. package/dist/results/revert-result.d.ts +10 -0
  361. package/dist/results/revert-result.d.ts.map +1 -1
  362. package/dist/results/stash-result.d.ts +5 -0
  363. package/dist/results/stash-result.d.ts.map +1 -1
  364. package/dist/results/status-result.d.ts +143 -18
  365. package/dist/results/status-result.d.ts.map +1 -1
  366. package/dist/results-BZGa2Z3I.js +2934 -0
  367. package/dist/transport-command.d.ts +56 -1
  368. package/dist/transport-command.d.ts.map +1 -1
  369. package/package.json +15 -10
  370. package/src/commands/add-command.ts +1291 -224
  371. package/src/commands/add-patch/add-interactive.ts +941 -0
  372. package/src/commands/add-patch/add-patch.ts +1169 -0
  373. package/src/commands/add-patch/index.ts +5 -0
  374. package/src/commands/add-patch/patch-backend.ts +239 -0
  375. package/src/commands/add-patch/patch-modes.ts +249 -0
  376. package/src/commands/add-patch/patch-session.ts +159 -0
  377. package/src/commands/am/am-command.ts +1111 -0
  378. package/src/commands/am/index.ts +2 -0
  379. package/src/commands/am/mailinfo.ts +1015 -0
  380. package/src/commands/am/patch-format.ts +121 -0
  381. package/src/commands/apply/apply-command.ts +832 -0
  382. package/src/commands/apply/apply-engine.ts +1603 -0
  383. package/src/commands/apply/apply-parse.ts +1209 -0
  384. package/src/commands/apply/apply-types.ts +112 -0
  385. package/src/commands/apply/index.ts +5 -0
  386. package/src/commands/apply/latin1.ts +171 -0
  387. package/src/commands/apply/whitespace.ts +260 -0
  388. package/src/commands/attributes-source.ts +96 -0
  389. package/src/commands/backfill-command.ts +694 -0
  390. package/src/commands/bisect/bisect-checkout.ts +217 -0
  391. package/src/commands/bisect/bisect-command.ts +788 -0
  392. package/src/commands/bisect/bisect-engine.ts +1079 -0
  393. package/src/commands/bisect/bisect-graph.ts +595 -0
  394. package/src/commands/bisect/bisect-quote.ts +92 -0
  395. package/src/commands/bisect/index.ts +4 -0
  396. package/src/commands/blame-command.ts +711 -986
  397. package/src/commands/branch-command.ts +354 -32
  398. package/src/commands/branch-tracking.ts +331 -0
  399. package/src/commands/checkout-command.ts +1426 -297
  400. package/src/commands/checkout-paths.ts +784 -0
  401. package/src/commands/cherry-pick-command.ts +156 -396
  402. package/src/commands/clean-command.ts +532 -85
  403. package/src/commands/clone-command.ts +826 -55
  404. package/src/commands/commit-command.ts +1781 -166
  405. package/src/commands/core-config.ts +196 -0
  406. package/src/commands/date-format.ts +668 -0
  407. package/src/commands/describe-command.ts +2 -0
  408. package/src/commands/diff-command.ts +1898 -110
  409. package/src/commands/diff-textconv.ts +50 -0
  410. package/src/commands/fetch-command.ts +1038 -79
  411. package/src/commands/format-patch-command.ts +969 -0
  412. package/src/commands/fsck/fetch-fsck.ts +229 -0
  413. package/src/commands/fsck/fsck-command.ts +3347 -0
  414. package/src/commands/fsck/fsck-loose.ts +287 -0
  415. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  416. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  417. package/src/commands/fsck/fsck-object-table.ts +363 -0
  418. package/src/commands/fsck/fsck-pack.ts +604 -0
  419. package/src/commands/fsck/index.ts +5 -0
  420. package/src/commands/fsck/verify-pack-command.ts +249 -0
  421. package/src/commands/gc-command.ts +147 -1
  422. package/src/commands/git-date.ts +895 -0
  423. package/src/commands/git-describe.ts +316 -0
  424. package/src/commands/git-hooks.ts +1472 -0
  425. package/src/commands/git-ident.ts +344 -0
  426. package/src/commands/hook-command.ts +247 -0
  427. package/src/commands/index-adder.ts +706 -0
  428. package/src/commands/index-host.ts +291 -0
  429. package/src/commands/index.ts +83 -0
  430. package/src/commands/init-command.ts +60 -11
  431. package/src/commands/local-clone.ts +183 -0
  432. package/src/commands/local-transport.ts +762 -0
  433. package/src/commands/log-command.ts +1915 -170
  434. package/src/commands/log-graph.ts +671 -0
  435. package/src/commands/log-output.ts +1359 -0
  436. package/src/commands/ls-remote-command.ts +101 -58
  437. package/src/commands/mailmap.ts +129 -0
  438. package/src/commands/merge-bases.ts +296 -0
  439. package/src/commands/merge-command.ts +1386 -491
  440. package/src/commands/merge-config.ts +25 -0
  441. package/src/commands/merge-drivers.ts +306 -0
  442. package/src/commands/merge-support.ts +1198 -0
  443. package/src/commands/message-cleanup.ts +275 -0
  444. package/src/commands/mv-command.ts +976 -0
  445. package/src/commands/notes-command.ts +890 -0
  446. package/src/commands/notes-commands.ts +87 -0
  447. package/src/commands/notes-merge-command.ts +768 -0
  448. package/src/commands/notes-support.ts +402 -0
  449. package/src/commands/notes-tree.ts +602 -0
  450. package/src/commands/object-id-input.ts +27 -0
  451. package/src/commands/octopus-merge.ts +377 -0
  452. package/src/commands/ort-merge.ts +1660 -0
  453. package/src/commands/ort-recursive.ts +160 -0
  454. package/src/commands/pack-refs-command.ts +39 -22
  455. package/src/commands/patch-id.ts +196 -0
  456. package/src/commands/pathspec-attributes.ts +162 -0
  457. package/src/commands/pathspec.ts +1199 -0
  458. package/src/commands/post-index-change.ts +62 -0
  459. package/src/commands/pretty-format.ts +1431 -0
  460. package/src/commands/promisor-remote.ts +298 -0
  461. package/src/commands/pull-command.ts +207 -22
  462. package/src/commands/push-command.ts +236 -23
  463. package/src/commands/read-tree-command.ts +857 -0
  464. package/src/commands/rebase-command.ts +3808 -371
  465. package/src/commands/rebase-todo.ts +584 -0
  466. package/src/commands/ref-decoration-filter.ts +118 -0
  467. package/src/commands/reflog-messages.ts +177 -0
  468. package/src/commands/remote-command.ts +500 -19
  469. package/src/commands/remote-transport.ts +383 -0
  470. package/src/commands/reset-command.ts +828 -91
  471. package/src/commands/restore-command.ts +350 -0
  472. package/src/commands/rev-list-command.ts +167 -0
  473. package/src/commands/rev-parse-command.ts +277 -0
  474. package/src/commands/revert-command.ts +152 -399
  475. package/src/commands/revision-filenames.ts +254 -0
  476. package/src/commands/revision-range.ts +222 -0
  477. package/src/commands/revision-resolver.ts +1379 -0
  478. package/src/commands/rm-command.ts +613 -67
  479. package/src/commands/sequencer-pick.ts +869 -0
  480. package/src/commands/sequencer-support.ts +869 -0
  481. package/src/commands/serve-repository.ts +125 -0
  482. package/src/commands/sparse-checkout-command.ts +1389 -0
  483. package/src/commands/sparse-checkout-support.ts +793 -0
  484. package/src/commands/stash-apply-command.ts +692 -124
  485. package/src/commands/stash-create-command.ts +752 -89
  486. package/src/commands/stash-drop-command.ts +67 -6
  487. package/src/commands/stash-list-command.ts +10 -4
  488. package/src/commands/stash-working-tree.ts +387 -0
  489. package/src/commands/status-command.ts +1426 -97
  490. package/src/commands/status-format.ts +775 -0
  491. package/src/commands/status-header.ts +330 -0
  492. package/src/commands/strerror.ts +29 -0
  493. package/src/commands/submodule-config.ts +94 -0
  494. package/src/commands/submodule-summary-command.ts +334 -0
  495. package/src/commands/submodule-summary.ts +446 -0
  496. package/src/commands/switch-command.ts +402 -0
  497. package/src/commands/tag-command.ts +129 -41
  498. package/src/commands/tracking-info.ts +201 -0
  499. package/src/commands/trailers.ts +417 -0
  500. package/src/commands/tree-restore.ts +344 -15
  501. package/src/commands/untracked-cache-support.ts +194 -0
  502. package/src/commands/worktree-add-command.ts +458 -0
  503. package/src/commands/worktree-list-command.ts +208 -0
  504. package/src/commands/worktree-lock-command.ts +96 -0
  505. package/src/commands/worktree-overwrite-checks.ts +641 -0
  506. package/src/commands/worktree-prune-command.ts +99 -0
  507. package/src/commands/worktree-remove-command.ts +186 -0
  508. package/src/commands/worktree-repair-command.ts +59 -0
  509. package/src/commands/worktree-support.ts +214 -0
  510. package/src/core-commands/add.command.impl.ts +9 -5
  511. package/src/core-commands/index.ts +0 -8
  512. package/src/errors/add-errors.ts +45 -0
  513. package/src/errors/checkout-errors.ts +46 -2
  514. package/src/errors/command-errors.ts +101 -1
  515. package/src/errors/commit-errors.ts +18 -2
  516. package/src/errors/git-api-error.ts +82 -2
  517. package/src/errors/index.ts +1 -0
  518. package/src/errors/merge-errors.ts +2 -2
  519. package/src/errors/rebase-errors.ts +12 -0
  520. package/src/errors/ref-errors.ts +56 -2
  521. package/src/errors/remote-errors.ts +2 -2
  522. package/src/errors/stash-errors.ts +1 -1
  523. package/src/errors/transport-errors.ts +20 -4
  524. package/src/errors/worktree-errors.ts +49 -0
  525. package/src/git-command.ts +1218 -118
  526. package/src/git.ts +552 -11
  527. package/src/index.ts +1 -1
  528. package/src/remote-config/index.ts +1 -0
  529. package/src/remote-config/remote-config-store.ts +326 -16
  530. package/src/remote-config/remote-refs.ts +119 -0
  531. package/src/rename/detect-renames.ts +711 -0
  532. package/src/rename/git-similarity.ts +116 -0
  533. package/src/rename/index.ts +2 -0
  534. package/src/results/binary-patch.ts +401 -0
  535. package/src/results/blame-format.ts +239 -0
  536. package/src/results/cherry-pick-result.ts +10 -0
  537. package/src/results/clone-result.ts +18 -0
  538. package/src/results/combined-diff.ts +585 -0
  539. package/src/results/diff-entry.ts +35 -0
  540. package/src/results/diff-formatter.ts +152 -288
  541. package/src/results/diff-order.ts +64 -0
  542. package/src/results/diff-output.ts +1051 -0
  543. package/src/results/fetch-result.ts +24 -1
  544. package/src/results/index.ts +5 -0
  545. package/src/results/merge-result.ts +15 -1
  546. package/src/results/pull-result.ts +12 -3
  547. package/src/results/push-result.ts +43 -0
  548. package/src/results/quote-path.ts +103 -0
  549. package/src/results/rebase-result.ts +37 -0
  550. package/src/results/revert-result.ts +10 -0
  551. package/src/results/stash-result.ts +6 -0
  552. package/src/results/status-result.ts +288 -27
  553. package/src/transport-command.ts +139 -2
  554. package/dist/commands-BpeXZTC3.js +0 -10278
  555. package/dist/core-commands/checkout.command.d.ts +0 -103
  556. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  557. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  558. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  559. package/dist/status-result-BapZoQaR.js +0 -411
  560. package/src/core-commands/checkout.command.impl.ts +0 -564
  561. package/src/core-commands/checkout.command.ts +0 -125
@@ -1,125 +1,250 @@
1
- import type { ObjectId, PersonIdent } from "@statewalker/vcs-core";
1
+ import {
2
+ type Commit,
3
+ EMPTY_TREE_ID,
4
+ isSymbolicRef,
5
+ listObjectsWithPrefix,
6
+ type ObjectId,
7
+ type PersonIdent,
8
+ type RefLogOptions,
9
+ type TreeEntry,
10
+ } from "@statewalker/vcs-core";
11
+ import { parseGitBool } from "@statewalker/vcs-utils";
12
+ import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
13
+ import { isIndexUnborn, type Worktree } from "@statewalker/vcs-working-tree";
2
14
 
3
15
  import {
4
16
  CommitNotFoundError,
5
17
  InvalidArgumentError,
6
18
  NoHeadError,
7
19
  NoRebaseInProgressError,
20
+ RebaseTodoMissingError,
21
+ RefNotFoundError,
8
22
  UpstreamRequiredError,
9
23
  } from "../errors/index.js";
10
24
  import { GitCommand } from "../git-command.js";
11
- import { type ContentMergeStrategy, MergeStrategy } from "../results/merge-result.js";
25
+ import { RemoteConfigStore } from "../remote-config/index.js";
26
+ import {
27
+ type ContentMergeStrategy,
28
+ FastForwardMode,
29
+ type MergeResult,
30
+ MergeStatus,
31
+ MergeStrategy,
32
+ } from "../results/merge-result.js";
12
33
  import type { RebaseResult, RebaseTodoLine } from "../results/rebase-result.js";
13
34
  import { RebaseAction, RebaseStatus } from "../results/rebase-result.js";
14
- import { mergeTreesThreeWay } from "../tree-merge/index.js";
15
-
16
- /**
17
- * Get timezone offset string in Git format (+HHMM or -HHMM).
18
- */
19
- function getTimezoneOffset(): string {
20
- const offset = new Date().getTimezoneOffset();
21
- const sign = offset <= 0 ? "+" : "-";
22
- const absOffset = Math.abs(offset);
23
- const hours = Math.floor(absOffset / 60)
24
- .toString()
25
- .padStart(2, "0");
26
- const minutes = (absOffset % 60).toString().padStart(2, "0");
27
- return `${sign}${hours}${minutes}`;
28
- }
35
+ import { coreBool, createIdAbbreviator, worktreeModeTrust } from "./core-config.js";
36
+ import { createDescriber, type DescribeOptions } from "./git-describe.js";
37
+ import {
38
+ type GitCommitHookRun,
39
+ gitCommitAfterHooks,
40
+ gitCommitMessageHooks,
41
+ runPostCheckoutHook,
42
+ sequencerPostCommit,
43
+ sequencerPrepareMessage,
44
+ } from "./git-hooks.js";
45
+ import { hostEnvironmentOf, localTimezoneOffset } from "./git-ident.js";
46
+ import { favorOf, MergeCommand } from "./merge-command.js";
47
+ import { configBool, configValue, conflictStyleOf } from "./merge-config.js";
48
+ import { ortConfigOptions } from "./merge-drivers.js";
49
+ import {
50
+ conflictsComment,
51
+ FlatTreeCache,
52
+ flatTree,
53
+ indexChanges,
54
+ OperationState,
55
+ readIndex,
56
+ refsWatched,
57
+ storeFlatTreeOver,
58
+ subjectOf,
59
+ switchTrees,
60
+ treeDelta,
61
+ } from "./merge-support.js";
62
+ import { CleanupMode, commentPrefixOf, stripspace } from "./message-cleanup.js";
63
+ import { copyNotesForAmend, copyNotesForRebase } from "./notes-support.js";
64
+ import { ortResultEntries } from "./ort-merge.js";
65
+ import { mergeBaseTree, mergeStoredTrees, storedBase } from "./ort-recursive.js";
66
+ import { type PatchIdTrees, patchId } from "./patch-id.js";
67
+ import { formatCommitPretty, loadRefDecorations, type RefDecorations } from "./pretty-format.js";
68
+ import {
69
+ addExecCommands,
70
+ combinedMessage,
71
+ commentLines,
72
+ countTodoCommands,
73
+ formatTodo,
74
+ isFinalFixup,
75
+ isFixup,
76
+ isNoop,
77
+ isPickLike,
78
+ messageBody,
79
+ parseTodo,
80
+ peekCommand,
81
+ rearrangeSquash,
82
+ squashMessageForFixup,
83
+ squashTexts,
84
+ subjectLength,
85
+ type TodoItem,
86
+ takesCommit,
87
+ todoHelp,
88
+ } from "./rebase-todo.js";
89
+ import { reflogMessages, updateHeadExpecting } from "./reflog-messages.js";
90
+ import { revisionMergeBases } from "./rev-parse-command.js";
91
+ import { expandCommitId } from "./sequencer-pick.js";
92
+ import {
93
+ applyAutostash,
94
+ cleanupMessage,
95
+ createAutostash,
96
+ moveHeadAsReset,
97
+ removeBranchState,
98
+ resetMerge,
99
+ } from "./sequencer-support.js";
100
+ import { appendSignoff, trailerConfigOf } from "./trailers.js";
101
+ import { worktreeModified } from "./worktree-overwrite-checks.js";
102
+ import { usesBranch } from "./worktree-support.js";
29
103
 
30
104
  /**
31
- * The available rebase operations.
32
- *
33
- * Based on JGit's RebaseCommand.Operation.
105
+ * Rebase operation types.
34
106
  */
35
107
  export enum RebaseOperation {
36
- /** Initiates rebase */
108
+ /** Start a new rebase */
37
109
  BEGIN = "begin",
38
-
39
- /** Continues after conflict resolution */
110
+ /** Continue after resolving conflicts */
40
111
  CONTINUE = "continue",
41
-
42
- /** Skips the current commit */
112
+ /** Skip the current commit */
43
113
  SKIP = "skip",
44
-
45
- /** Aborts and resets the current rebase */
114
+ /** Abort and restore original state */
46
115
  ABORT = "abort",
47
-
48
- /** Process steps (internal) */
116
+ /** Process steps (for interactive rebase) */
49
117
  PROCESS_STEPS = "process-steps",
118
+ /** `--edit-todo`: the rest of the todo list edited (the interactive handler's editTodo) */
119
+ EDIT_TODO = "edit-todo",
50
120
  }
51
121
 
52
122
  /**
53
- * Interactive rebase handler interface.
54
- *
55
- * Based on JGit's RebaseCommand.InteractiveHandler.
123
+ * Handler for interactive rebase (`git rebase -i`): it plays the editors git runs.
56
124
  */
57
125
  export interface InteractiveHandler {
58
126
  /**
59
- * Prepare the list of steps before rebase starts.
60
- * Can reorder, remove, or change actions.
127
+ * The sequence editor: the todo list as git shows it in the editor (abbreviated ids, the
128
+ * help after it), returned edited. Run before {@link prepareSteps}.
61
129
  */
62
- prepareSteps(steps: RebaseTodoLine[]): void;
130
+ editTodo?(todo: string): string | Promise<string>;
63
131
 
64
132
  /**
65
- * Modify commit message during reword/squash.
133
+ * Modify the steps before execution (the todo list's commands, comments left out).
134
+ * @param steps List of rebase steps to modify
66
135
  */
67
- modifyCommitMessage(message: string): string;
136
+ prepareSteps?(steps: RebaseTodoLine[]): void;
137
+
138
+ /**
139
+ * The commit message editor (`reword`, the end of a `squash` chain, `fixup -c`, `merge
140
+ * -c`): the text git puts in the editor (the message, or the chain's `# This is a
141
+ * combination of N commits.` text), returned edited; git then strips the comments.
142
+ * Without it the text is kept (as with an editor that changes nothing).
143
+ */
144
+ modifyCommitMessage?(message: string): string;
145
+ }
146
+
147
+ /** What an `exec` command did (git runs it in a shell). */
148
+ export interface RebaseExecResult {
149
+ /** The exit status (0: success; 127, command not found, counts as 1) */
150
+ exitCode: number;
151
+ /** What the command printed, put in the result's output */
152
+ output?: string[];
153
+ }
154
+
155
+ /**
156
+ * Runs the command of an `exec` todo line (`exec <command>`, `--exec <command>`): git runs it
157
+ * with the shell in the worktree; a portable rebase leaves that to its host. The index and
158
+ * the worktree are read again after it, as git reads them.
159
+ */
160
+ export type RebaseExecHandler = (command: string) => RebaseExecResult | Promise<RebaseExecResult>;
161
+
162
+ /** `--empty`: what becomes of a commit that becomes empty when picked. */
163
+ export type RebaseEmptyMode = "drop" | "keep" | "stop";
164
+
165
+ /** One entry of `rebase-merge/update-refs`: the ref, its value at the start, the new one. */
166
+ interface UpdateRefRecord {
167
+ ref: string;
168
+ before: ObjectId;
169
+ after: ObjectId;
68
170
  }
69
171
 
172
+ /** What a pick (do_pick_commit) did. */
173
+ type PickOutcome =
174
+ | { kind: "ok" }
175
+ | { kind: "dropped" }
176
+ | {
177
+ kind: "conflicts";
178
+ /** do_pick_commit's lines (`error: could not apply ...` and hints, git commit's refusal) */
179
+ lines: string[];
180
+ conflicts: string[];
181
+ /** What error_with_patch writes to `rebase-merge/message` */
182
+ message?: string;
183
+ }
184
+ | { kind: "reschedule"; result: RebaseResult & { reschedule?: boolean } };
185
+
186
+ const ZERO_ID = "0000000000000000000000000000000000000000";
187
+
70
188
  /**
71
- * In-memory rebase state.
189
+ * What a todo command came to: nothing (go on), `checkTodo` (go on, the list read again if
190
+ * it changed), or a result that stops the rebase (`reschedule`: the command goes back).
72
191
  */
73
- interface RebaseState {
74
- /** Original HEAD ref name */
75
- headName: string;
192
+ type StepOutcome =
193
+ | (Partial<RebaseResult> & { reschedule?: boolean; checkTodo?: boolean })
194
+ | undefined;
76
195
 
77
- /** Original HEAD commit ID */
78
- originalHead: ObjectId;
196
+ /** sequencer.c's staged_changes_advice (no `-S`). */
197
+ const STAGED_CHANGES_ADVICE = `error: you have staged changes in your working tree
198
+ If these changes are meant to be squashed into the previous commit, run:
79
199
 
80
- /** Onto commit (upstream) */
81
- onto: ObjectId;
200
+ git commit --amend
82
201
 
83
- /** Onto name for messages */
84
- ontoName: string;
202
+ If they are meant to go into a new commit, run:
85
203
 
86
- /** Commits to cherry-pick in order */
87
- todoSteps: RebaseTodoLine[];
204
+ git commit
88
205
 
89
- /** Completed steps */
90
- doneSteps: RebaseTodoLine[];
206
+ In both cases, once you're done, continue with:
91
207
 
92
- /** Whether rebase is in progress */
93
- inProgress: boolean;
208
+ git rebase --continue`;
94
209
 
95
- /** Current commit being processed (for stop/conflict) */
96
- currentCommit?: ObjectId;
97
- }
210
+ /** rebase-interactive.c's edit_todo_list_advice. */
211
+ const EDIT_TODO_ADVICE = [
212
+ "You can fix this with 'git rebase --edit-todo' and then run 'git rebase --continue'.",
213
+ "Or you can abort the rebase with 'git rebase --abort'.",
214
+ ];
215
+
216
+ /** Tracked files checked at once against the worktree (stats and hashes in flight). */
217
+ const WORKTREE_CHECK_BATCH = 32;
218
+
219
+ /** The state directory of git's merge backend. */
220
+ const DIR = "rebase-merge";
221
+
222
+ /** sequencer.c's GIT_MAX_LABEL_LENGTH (NAME_MAX - ".lock" - 16) */
223
+ const MAX_LABEL_LENGTH = 255 - 5 - 16;
224
+
225
+ /** git's quoting of a value in `author-script` (`'...'`, a quote as `'\''`). */
226
+ const sq = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
98
227
 
99
228
  /**
100
- * Rebase command for replaying commits on top of another branch.
101
- *
102
- * Equivalent to `git rebase`.
229
+ * Rebase the current branch onto another commit.
103
230
  *
104
- * Based on JGit's RebaseCommand.
231
+ * Equivalent to `git rebase <upstream>` with git's merge backend: the commits HEAD has that
232
+ * upstream has not (merges dropped) are picked one by one onto upstream by git's merge-ort,
233
+ * the working tree and the index written as git writes them. A conflict stops the rebase
234
+ * with git's markers (`<<<<<<< HEAD` / `>>>>>>> <abbrev> (<subject>)`), stages 1-3 and
235
+ * git's state (`.git/rebase-merge/`, `REBASE_HEAD`, `MERGE_MSG`, `AUTO_MERGE`), so native
236
+ * `git rebase --continue / --skip / --abort` resumes what we started, and we resume what
237
+ * native git started. A rebase is refused on unstaged or staged changes, as git refuses it.
238
+ * With {@link RebaseCommand.setRebaseMerges} (`--rebase-merges`) the merges are kept: git's
239
+ * todo list of `label`, `reset` and `merge -C` commands, run as git's sequencer runs them.
105
240
  *
106
241
  * @example
107
242
  * ```typescript
108
- * // Basic rebase onto main
109
- * const result = await git.rebase()
110
- * .setUpstream("main")
111
- * .call();
112
- *
113
- * // Abort ongoing rebase
114
- * const result = await git.rebase()
115
- * .setOperation(RebaseOperation.ABORT)
116
- * .call();
117
- *
118
- * // Rebase with merge strategy
119
- * const result = await git.rebase()
120
- * .setUpstream("main")
121
- * .setStrategy(MergeStrategy.OURS)
122
- * .call();
243
+ * const result = await git.rebase().setUpstream(mainId).call();
244
+ * if (result.status === RebaseStatus.STOPPED) {
245
+ * // resolve, `git add`, then
246
+ * await git.rebase().setOperation(RebaseOperation.CONTINUE).call();
247
+ * }
123
248
  * ```
124
249
  */
125
250
  export class RebaseCommand extends GitCommand<RebaseResult> {
@@ -130,16 +255,65 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
130
255
  private contentStrategy?: ContentMergeStrategy;
131
256
  private preserveMerges = false;
132
257
  private interactiveHandler?: InteractiveHandler;
258
+ private committer?: PersonIdent;
259
+ /** `--committer-date-is-author-date` (kept in `rebase-merge/cdate_is_adate`) */
260
+ private committerDateIsAuthorDate = false;
261
+ /** `--ignore-date` / `--reset-author-date` (kept in `rebase-merge/ignore_date`) */
262
+ private ignoreDate = false;
263
+ /** `--signoff` (kept in `rebase-merge/signoff`) */
264
+ private signoff = false;
265
+ private autoStash?: boolean;
266
+ private reapplyCherryPicks = false;
267
+ /** `--rebase-merges` (undefined: `rebase.rebaseMerges`) */
268
+ private rebaseMerges?: boolean;
269
+ /** `--rebase-merges=rebase-cousins` */
270
+ private rebaseCousins = false;
271
+ /** The commits read by the walks that make the todo list */
272
+ private loadedCommits = new Map<ObjectId, Commit>();
273
+ /** The flat trees the picks read (each pick's result is the next one's HEAD) */
274
+ private flatTrees?: FlatTreeCache;
275
+ /** Commit subjects, for the todo and done lines */
276
+ private readonly subjects = new Map<ObjectId, string>();
277
+ /** The refs' decorations, for `%d` in rebase.instructionFormat (loaded once) */
278
+ private decorations?: RefDecorations;
279
+ /** What loading the decorations printed (`warning: invalid replace ref <name>`) */
280
+ private decorationWarnings: string[] = [];
281
+ /** `--exec <command>` (each run after every pick) */
282
+ private execCommands: string[] = [];
283
+ /** Runs the `exec` commands */
284
+ private execHandler?: RebaseExecHandler;
285
+ /** `--[no-]reschedule-failed-exec` (undefined: rebase.rescheduleFailedExec) */
286
+ private rescheduleFailedExec?: boolean;
287
+ /** `--empty=drop|keep|stop` (undefined: git's default for the kind of rebase) */
288
+ private emptyMode?: RebaseEmptyMode;
289
+ /** `--[no-]keep-empty`: commits empty from the start are picked (default) */
290
+ private keepEmpty = true;
291
+ /** `--[no-]update-refs` (undefined: rebase.updateRefs) */
292
+ private updateRefs?: boolean;
293
+ /** `--[no-]autosquash` (undefined: rebase.autoSquash with an interactive rebase) */
294
+ private autosquash?: boolean;
295
+ /** `--root`: every commit of the branch rebased (onto the upstream given, else a new root) */
296
+ private root = false;
297
+ private noVerify = false;
133
298
 
134
- // In-memory state for tracking rebase progress
135
- private static rebaseStates = new WeakMap<object, RebaseState>();
299
+ /** `--no-verify`: the pre-rebase hook does not run. */
300
+ setNoVerify(noVerify: boolean): this {
301
+ this.checkCallable();
302
+ this.noVerify = noVerify;
303
+ return this;
304
+ }
305
+ /** The command after the one running (git's peek_command), for record_in_rewritten */
306
+ private nextCommand?: RebaseAction;
136
307
 
137
308
  /**
138
- * Set the upstream branch or commit to rebase onto.
309
+ * Set the upstream to rebase onto: a commit id or any revision (`main`, `HEAD~2`,
310
+ * `v1.0`), resolved to a commit when the rebase starts (git's `lookup_commit_reference`
311
+ * of `<upstream>`; "fatal: invalid upstream '<name>'" when it names none). The name given
312
+ * is kept for the reflog and the messages (`checkout main`).
139
313
  *
140
- * @param upstream The upstream commit ID
314
+ * @param upstream Upstream commit ID or revision
141
315
  */
142
- setUpstream(upstream: ObjectId): this {
316
+ setUpstream(upstream: ObjectId | string): this {
143
317
  this.checkCallable();
144
318
  this.upstreamCommit = upstream;
145
319
  this.upstreamCommitName = upstream;
@@ -147,25 +321,41 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
147
321
  }
148
322
 
149
323
  /**
150
- * Set the upstream branch name to rebase onto.
324
+ * Set the upstream by branch name.
151
325
  *
152
- * @param upstream The upstream branch name
326
+ * @param upstream Branch name to rebase onto
153
327
  */
154
328
  async setUpstreamBranch(upstream: string): Promise<this> {
155
329
  this.checkCallable();
156
- this.upstreamCommit = await this.resolveRef(upstream);
330
+ this.upstreamCommit = await this.resolveUpstream(upstream);
157
331
  this.upstreamCommitName = upstream;
158
332
  return this;
159
333
  }
160
334
 
161
335
  /**
162
- * Override the upstream name for conflict messages.
336
+ * builtin/rebase.c's `lookup_commit_reference_by_name(options.upstream_name)`: the commit
337
+ * an upstream names, or git's "fatal: invalid upstream '<name>'" (exit 128).
338
+ */
339
+ private async resolveUpstream(name: string): Promise<ObjectId> {
340
+ const fatal = (n: string) => `fatal: invalid upstream '${n}'`;
341
+ try {
342
+ return await this.resolveRef(name, fatal);
343
+ } catch (error) {
344
+ if (error instanceof RefNotFoundError) {
345
+ throw new RefNotFoundError(name, fatal(name)).withExitCode(128);
346
+ }
347
+ throw error;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Set the upstream name for messages.
163
353
  *
164
- * @param name The name to use for upstream in messages
354
+ * @param name Display name for upstream
165
355
  */
166
356
  setUpstreamName(name: string): this {
167
357
  this.checkCallable();
168
- if (!this.upstreamCommit) {
358
+ if (this.upstreamCommit === undefined) {
169
359
  throw new InvalidArgumentError(
170
360
  "upstreamName",
171
361
  name,
@@ -176,10 +366,15 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
176
366
  return this;
177
367
  }
178
368
 
369
+ /** The upstream's name (the branch given, else its id). */
370
+ getUpstreamName(): string | undefined {
371
+ return this.upstreamCommitName;
372
+ }
373
+
179
374
  /**
180
375
  * Set the operation to perform.
181
376
  *
182
- * @param operation BEGIN, CONTINUE, SKIP, or ABORT
377
+ * @param operation Rebase operation
183
378
  */
184
379
  setOperation(operation: RebaseOperation): this {
185
380
  this.checkCallable();
@@ -195,9 +390,9 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
195
390
  }
196
391
 
197
392
  /**
198
- * Set the merge strategy to use.
393
+ * Set the merge strategy (only git's merge-ort is run; kept for compatibility).
199
394
  *
200
- * @param strategy The merge strategy
395
+ * @param strategy Merge strategy
201
396
  */
202
397
  setStrategy(strategy: MergeStrategy): this {
203
398
  this.checkCallable();
@@ -213,9 +408,9 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
213
408
  }
214
409
 
215
410
  /**
216
- * Set the content merge strategy for file-level conflicts.
411
+ * Set content merge strategy for conflicts (`-X ours`, `-X theirs`).
217
412
  *
218
- * @param strategy The content merge strategy
413
+ * @param strategy Content merge strategy
219
414
  */
220
415
  setContentMergeStrategy(strategy: ContentMergeStrategy): this {
221
416
  this.checkCallable();
@@ -231,9 +426,10 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
231
426
  }
232
427
 
233
428
  /**
234
- * Set whether to preserve merges during rebase.
429
+ * Set whether to preserve merge commits (not supported: merges are dropped, as git's
430
+ * default rebase drops them).
235
431
  *
236
- * @param preserve true to re-create merges
432
+ * @param preserve Whether to preserve merges
237
433
  */
238
434
  setPreserveMerges(preserve: boolean): this {
239
435
  this.checkCallable();
@@ -249,9 +445,9 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
249
445
  }
250
446
 
251
447
  /**
252
- * Enable interactive rebase with the given handler.
448
+ * Enable interactive mode with handler.
253
449
  *
254
- * @param handler The interactive handler
450
+ * @param handler Interactive handler
255
451
  */
256
452
  runInteractively(handler: InteractiveHandler): this {
257
453
  this.checkCallable();
@@ -260,406 +456,3647 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
260
456
  }
261
457
 
262
458
  /**
263
- * Execute the rebase command.
459
+ * Pick commits whose change upstream already has (`--reapply-cherry-picks`); by default
460
+ * (`--no-reapply-cherry-picks`) they are left out, with git's "skipped previously applied
461
+ * commit" warnings, as their patch-id is found upstream.
264
462
  */
265
- async call(): Promise<RebaseResult> {
463
+ setReapplyCherryPicks(reapply: boolean): this {
266
464
  this.checkCallable();
267
- this.setCallable(false);
465
+ this.reapplyCherryPicks = reapply;
466
+ return this;
467
+ }
268
468
 
269
- switch (this.operation) {
270
- case RebaseOperation.ABORT:
271
- return this.abort();
469
+ /**
470
+ * `--rebase-merges[=rebase-cousins|no-rebase-cousins]`: the branch's merges are kept. The
471
+ * todo list (git's make_script_with_merges) labels each side branch's tip (`label`),
472
+ * starts each branch from where it forked (`reset`), and recreates each merge with its
473
+ * original message (`merge -C <merge> <label> # <oneline>`); a side branch that forked
474
+ * off below the merge base stays on its fork point unless `rebase-cousins`. `false`
475
+ * (`--no-rebase-merges`) drops the merges; default `rebase.rebaseMerges`.
476
+ */
477
+ setRebaseMerges(mode: boolean | "rebase-cousins" | "no-rebase-cousins"): this {
478
+ this.checkCallable();
479
+ this.rebaseMerges = mode !== false;
480
+ this.rebaseCousins = mode === "rebase-cousins";
481
+ return this;
482
+ }
272
483
 
273
- case RebaseOperation.CONTINUE:
274
- return this.continueRebase();
484
+ /**
485
+ * Stash local changes away for the rebase and apply them after it (`--autostash`;
486
+ * default `rebase.autoStash`, false).
487
+ */
488
+ setAutoStash(autoStash: boolean): this {
489
+ this.checkCallable();
490
+ this.autoStash = autoStash;
491
+ return this;
492
+ }
275
493
 
276
- case RebaseOperation.SKIP:
277
- return this.skip();
494
+ /**
495
+ * The committer of the rebased commits (default: resolved as git resolves it,
496
+ * `GIT_COMMITTER_*`, `committer.*`, `user.*`). The picks keep their authors.
497
+ */
498
+ setCommitter(committer: PersonIdent): this {
499
+ this.checkCallable();
500
+ this.committer = committer;
501
+ return this;
502
+ }
278
503
 
279
- case RebaseOperation.BEGIN:
280
- case RebaseOperation.PROCESS_STEPS:
281
- return this.begin();
282
- }
504
+ /**
505
+ * `--committer-date-is-author-date`: each rebased commit's committer date is its author
506
+ * date. Like git, it implies `--force-rebase`: a branch already on its upstream is
507
+ * rebased all the same.
508
+ */
509
+ setCommitterDateIsAuthorDate(value: boolean): this {
510
+ this.checkCallable();
511
+ this.committerDateIsAuthorDate = value;
512
+ return this;
283
513
  }
284
514
 
285
515
  /**
286
- * Begin the rebase operation.
516
+ * `--ignore-date` (`--reset-author-date`): each rebased commit's author date is the
517
+ * current time (git's `ignore_author_date`: the clock, not `GIT_AUTHOR_DATE`). Implies
518
+ * `--force-rebase`, as in git.
287
519
  */
288
- private async begin(): Promise<RebaseResult> {
289
- if (!this.upstreamCommit) {
290
- throw new UpstreamRequiredError("Upstream commit is required for rebase BEGIN operation");
291
- }
520
+ setIgnoreDate(value: boolean): this {
521
+ this.checkCallable();
522
+ this.ignoreDate = value;
523
+ return this;
524
+ }
292
525
 
293
- // Get current HEAD
294
- const headResolved = await this.refsStore.resolve("HEAD");
295
- if (!headResolved?.objectId) {
296
- throw new NoHeadError("HEAD cannot be resolved");
297
- }
526
+ /**
527
+ * `--signoff`: each rebased commit gets git's `Signed-off-by: <committer>` trailer
528
+ * (append_signoff: added unless the message's trailer block already ends with it), its
529
+ * message cleaned up as git's `--signoff` commits clean it (whitespace). Like git, it
530
+ * implies `--force-rebase`; the recreated merges are not signed off (git commits them
531
+ * without `--signoff`).
532
+ */
533
+ setSignoff(value: boolean): this {
534
+ this.checkCallable();
535
+ this.signoff = value;
536
+ return this;
537
+ }
298
538
 
299
- const headCommit = headResolved.objectId;
539
+ /**
540
+ * `--exec <command>` (`-x`): an `exec <command>` line after each pick (after its fixup and
541
+ * squash chain) and each merge; implies an interactive list (no fast-forward shortcut) and
542
+ * `--empty=keep` unless given. The commands run through {@link setExecHandler}.
543
+ */
544
+ setExec(commands: string[]): this {
545
+ this.checkCallable();
546
+ this.execCommands = [...commands];
547
+ return this;
548
+ }
300
549
 
301
- // Get HEAD's target branch name (if symbolic)
302
- const headRef = await this.refsStore.get("HEAD");
303
- const headName = headRef && "target" in headRef ? headRef.target : headCommit;
550
+ /**
551
+ * Runs the `exec` commands (git runs them with the shell). Without one an `exec` fails as a
552
+ * command not found does.
553
+ */
554
+ setExecHandler(handler: RebaseExecHandler): this {
555
+ this.checkCallable();
556
+ this.execHandler = handler;
557
+ return this;
558
+ }
304
559
 
305
- // Check if already up to date
306
- const isAncestor = await this.isAncestor(this.upstreamCommit, headCommit);
307
- if (isAncestor) {
308
- return {
309
- status: RebaseStatus.UP_TO_DATE,
310
- newHead: headCommit,
311
- };
312
- }
560
+ /**
561
+ * `--reschedule-failed-exec`: an `exec` that fails goes back to the todo list's head, so
562
+ * `--continue` runs it again (kept in `rebase-merge/reschedule-failed-exec`); default
563
+ * `rebase.rescheduleFailedExec`, false.
564
+ */
565
+ setRescheduleFailedExec(value: boolean): this {
566
+ this.checkCallable();
567
+ this.rescheduleFailedExec = value;
568
+ return this;
569
+ }
313
570
 
314
- // Check if can fast-forward
315
- const canFastForward = await this.isAncestor(headCommit, this.upstreamCommit);
316
- if (canFastForward) {
317
- // Fast-forward HEAD to upstream
318
- await this.updateHead(headName, this.upstreamCommit);
319
- return {
320
- status: RebaseStatus.FAST_FORWARD,
321
- newHead: this.upstreamCommit,
322
- };
323
- }
571
+ /**
572
+ * `--empty=drop|keep|stop`: a pick that becomes empty (its change already in HEAD) is
573
+ * dropped (`drop_redundant_commits`), kept as an empty commit (`keep_redundant_commits`) or
574
+ * stops the rebase (git commit's "The previous cherry-pick is now empty"). git 2.5x's
575
+ * default: `stop` for an interactive rebase, `keep` with `--exec`, else `drop`.
576
+ */
577
+ setEmpty(mode: RebaseEmptyMode): this {
578
+ this.checkCallable();
579
+ this.emptyMode = mode;
580
+ return this;
581
+ }
324
582
 
325
- // Calculate commits to cherry-pick
326
- const commitsToRebase = await this.calculateCommitsToRebase(headCommit, this.upstreamCommit);
583
+ /**
584
+ * `--keep-empty` (default) / `--no-keep-empty`: commits that are empty from the start are
585
+ * picked (` # empty` in the todo list) or left out.
586
+ */
587
+ setKeepEmpty(value: boolean): this {
588
+ this.checkCallable();
589
+ this.keepEmpty = value;
590
+ return this;
591
+ }
327
592
 
328
- if (commitsToRebase.length === 0) {
329
- return {
330
- status: RebaseStatus.UP_TO_DATE,
331
- newHead: headCommit,
332
- };
333
- }
593
+ /**
594
+ * `--update-refs`: the other branches that point at rebased commits move with them
595
+ * (`update-ref <ref>` lines, `rebase-merge/update-refs`, written at the end); branches
596
+ * checked out in other worktrees are left alone. Default `rebase.updateRefs`.
597
+ */
598
+ setUpdateRefs(value: boolean): this {
599
+ this.checkCallable();
600
+ this.updateRefs = value;
601
+ return this;
602
+ }
334
603
 
335
- // Build todo list
336
- const todoSteps: RebaseTodoLine[] = [];
337
- for (const commitId of commitsToRebase) {
338
- const commit = await this.commits.load(commitId);
339
- if (!commit) continue;
340
- const shortMessage = commit.message.split("\n")[0].substring(0, 50);
341
- todoSteps.push({
342
- action: RebaseAction.PICK,
343
- commit: commitId.substring(0, 7),
344
- shortMessage,
345
- });
346
- }
604
+ /**
605
+ * `--autosquash`: `fixup! `, `amend! ` and `squash! ` commits moved after the commit they
606
+ * name, as `fixup`, `fixup -C` and `squash`. Default: `rebase.autoSquash` for an
607
+ * interactive rebase.
608
+ */
609
+ setAutosquash(value: boolean): this {
610
+ this.checkCallable();
611
+ this.autosquash = value;
612
+ return this;
613
+ }
614
+
615
+ /**
616
+ * `--root`: all the commits of the branch are rebased, its root commit too. With an
617
+ * upstream set ({@link setUpstream}) that is `--root --onto <upstream>`; without one the
618
+ * commits go onto a new root (git's squash_onto, a commit of the empty tree kept in
619
+ * `rebase-merge/squash-onto`), so an unchanged list keeps the history as it is.
620
+ */
621
+ setRoot(value: boolean): this {
622
+ this.checkCallable();
623
+ this.root = value;
624
+ return this;
625
+ }
626
+
627
+ async call(): Promise<RebaseResult> {
628
+ this.checkCallable();
629
+ this.setCallable(false);
630
+ // the index as it is now, before the worktree or a ref is touched: one another writer
631
+ // replaced is read again (git reads the index at its start), unless this instance holds
632
+ // unwritten edits (refused)
633
+ await this.readCurrentIndex();
634
+ const worktree = this.worktreeAccess;
635
+ const run = () => this.run(worktree);
636
+ return worktree?.batch ? worktree.batch(run) : run();
637
+ }
347
638
 
348
- // Let interactive handler modify steps
349
- if (this.interactiveHandler) {
350
- this.interactiveHandler.prepareSteps(todoSteps);
639
+ private async run(worktree: Worktree | undefined): Promise<RebaseResult> {
640
+ const state = new OperationState(this.workingCopy.checkout, this.refsStore);
641
+ // git's rebase_config, read before anything else (any operation): a rebase.rebaseMerges
642
+ // that is neither a boolean nor a cousins mode dies
643
+ for (const value of RemoteConfigStore.from(this.workingCopy).values("rebase.rebaseMerges")) {
644
+ if (
645
+ parseGitBool(value) === undefined &&
646
+ value !== "rebase-cousins" &&
647
+ value !== "no-rebase-cousins"
648
+ ) {
649
+ return {
650
+ status: RebaseStatus.FAILED,
651
+ message: `fatal: Unknown rebase-merges mode: ${value}`,
652
+ };
653
+ }
654
+ }
655
+ switch (this.operation) {
656
+ case RebaseOperation.ABORT:
657
+ return this.abort(state, worktree);
658
+ case RebaseOperation.CONTINUE:
659
+ return this.continueRebase(state, worktree);
660
+ case RebaseOperation.SKIP:
661
+ return this.skip(state, worktree);
662
+ case RebaseOperation.EDIT_TODO:
663
+ return this.editTodo(state);
664
+ default:
665
+ return this.begin(state, worktree);
351
666
  }
667
+ }
352
668
 
353
- // Save rebase state
354
- const state: RebaseState = {
355
- headName,
356
- originalHead: headCommit,
357
- onto: this.upstreamCommit,
358
- ontoName: this.upstreamCommitName ?? this.upstreamCommit,
359
- todoSteps,
360
- doneSteps: [],
361
- inProgress: true,
669
+ private context(worktree: Worktree | undefined) {
670
+ return {
671
+ workingCopy: this.workingCopy,
672
+ worktree,
673
+ staging: this.staging,
674
+ blobs: this.blobs,
675
+ trees: this.trees,
676
+ commits: this.commits,
677
+ refs: this.refsStore,
362
678
  };
363
- RebaseCommand.rebaseStates.set(this._workingCopy, state);
364
-
365
- // Reset HEAD to onto
366
- await this.updateHead(headName, this.upstreamCommit);
679
+ }
367
680
 
368
- // Process steps
369
- return this.processSteps(state, commitsToRebase);
681
+ private async inProgress(state: OperationState): Promise<boolean> {
682
+ return (
683
+ (await state.read(`${DIR}/head-name`)) !== undefined ||
684
+ (await state.read(`${DIR}/onto`)) !== undefined ||
685
+ (await state.listDir(DIR)).length > 0
686
+ );
370
687
  }
371
688
 
372
- /**
373
- * Process the rebase steps (cherry-pick each commit).
374
- */
375
- private async processSteps(
376
- state: RebaseState,
377
- commitsToRebase: ObjectId[],
689
+ private async begin(
690
+ state: OperationState,
691
+ worktree: Worktree | undefined,
378
692
  ): Promise<RebaseResult> {
379
- let newHead = state.onto;
380
-
381
- for (let i = 0; i < state.todoSteps.length; i++) {
382
- const step = state.todoSteps[i];
383
-
384
- if (step.action === RebaseAction.COMMENT) {
385
- continue;
693
+ if (this.upstreamCommit === undefined && !this.root) {
694
+ throw new UpstreamRequiredError("Upstream commit is required for rebase BEGIN operation");
695
+ }
696
+ // the upstream as given (setUpstream takes a name too) peeled to the commit it names
697
+ // before anything is written, so HEAD is never set to a name ("main\n" in .git/HEAD)
698
+ // an empty name too: "fatal: invalid upstream ''"
699
+ if (this.upstreamCommit !== undefined) {
700
+ this.upstreamCommit = await this.resolveUpstream(this.upstreamCommit);
701
+ }
702
+ if (await this.inProgress(state)) {
703
+ return {
704
+ status: RebaseStatus.FAILED,
705
+ message:
706
+ "fatal: It seems that there is already a rebase-merge directory, and\nI wonder if you are in the middle of another rebase.",
707
+ };
708
+ }
709
+ // check_exec_cmd
710
+ for (const command of this.execCommands) {
711
+ if (command.includes("\n")) {
712
+ return {
713
+ status: RebaseStatus.FAILED,
714
+ message: "error: exec commands cannot contain newlines",
715
+ };
386
716
  }
717
+ if (command === "")
718
+ return { status: RebaseStatus.FAILED, message: "error: empty exec command" };
719
+ }
720
+ const headResolved = await this.refsStore.resolve("HEAD");
721
+ if (!headResolved?.objectId) throw new NoHeadError("HEAD cannot be resolved");
722
+ const headId = headResolved.objectId;
723
+ const headRef = await this.refsStore.get("HEAD");
724
+ const headName = headRef && isSymbolicRef(headRef) ? headRef.target : "detached HEAD";
725
+ // --root without --onto: the commits go onto git's squash_onto, a commit of the empty
726
+ // tree with no parent (their root is then a root again)
727
+ let squashOnto: ObjectId | undefined;
728
+ if (!this.upstreamCommit) {
729
+ squashOnto = await this.createSquashOnto();
730
+ this.upstreamCommitName = squashOnto;
731
+ }
732
+ const onto = (this.upstreamCommit ?? squashOnto) as ObjectId;
387
733
 
388
- // Find the full commit ID
389
- const commitId = commitsToRebase.find((c) => c.startsWith(step.commit));
390
- if (!commitId) {
391
- throw new CommitNotFoundError(step.commit);
734
+ // git's require_clean_work_tree: no unstaged, no staged changes, unless they are
735
+ // stashed away for the rebase (rebase.autoStash) and applied again after it
736
+ const output: string[] = [];
737
+ let autostash: ObjectId | undefined;
738
+ const refusal = await this.uncleanWorktree(headId, worktree);
739
+ if (refusal) {
740
+ if (!(this.autoStash ?? configBool(this.workingCopy, "rebase.autoStash", false))) {
741
+ return refusal;
742
+ }
743
+ if (!state.supported) {
744
+ // the stash could be kept nowhere: refused rather than stranded
745
+ throw new InvalidArgumentError(
746
+ "autoStash",
747
+ true,
748
+ "rebase --autostash needs a checkout that keeps state files (rebase-merge/autostash)",
749
+ );
392
750
  }
751
+ autostash = await createAutostash(this.context(worktree), headId);
752
+ if (autostash) {
753
+ output.push(`Created autostash: ${await this.abbreviateObjectId(autostash)}`);
754
+ }
755
+ }
756
+ const unstash = async () => {
757
+ if (autostash) output.push(...(await applyAutostash(this.context(worktree), autostash)));
758
+ };
393
759
 
394
- // Cherry-pick the commit
395
- const result = await this.cherryPickCommit(commitId, newHead, state);
760
+ // builtin/rebase.c's options as cmd_rebase settles them
761
+ const config = this.workingCopy;
762
+ const interactive = this.interactiveHandler !== undefined;
763
+ const execs = this.execCommands;
764
+ const autosquash =
765
+ this.autosquash ?? (interactive && configBool(config, "rebase.autoSquash", false));
766
+ const updateRefs = this.updateRefs ?? configBool(config, "rebase.updateRefs", false);
767
+ const emptyMode: RebaseEmptyMode =
768
+ this.emptyMode ?? (interactive ? "stop" : execs.length > 0 ? "keep" : "drop");
769
+ const reschedule =
770
+ this.rescheduleFailedExec ?? configBool(config, "rebase.rescheduleFailedExec", false);
771
+ const abbreviate = configBool(config, "rebase.abbreviateCommands", false);
772
+ const comment = commentPrefixOf(config);
396
773
 
397
- if (result.status === RebaseStatus.STOPPED) {
398
- state.currentCommit = commitId;
399
- state.doneSteps = state.todoSteps.slice(0, i);
400
- state.todoSteps = state.todoSteps.slice(i);
401
- return result;
774
+ // git's can_fast_forward: HEAD already on upstream with a linear history since, nothing
775
+ // to do (unless forced, as the date options and --signoff do); an interactive rebase,
776
+ // --exec and --autosquash never take the shortcut (allow_preemptive_ff)
777
+ const forced = this.committerDateIsAuthorDate || this.ignoreDate || this.signoff;
778
+ const preemptive = !interactive && execs.length === 0 && this.autosquash !== true;
779
+ if (preemptive && !this.root && (await this.canFastForward(onto, headId))) {
780
+ const upToDate = headName.startsWith("refs/")
781
+ ? `Current branch ${headName.replace(/^refs\/heads\//, "")} is up to date`
782
+ : "HEAD is up to date";
783
+ if (!forced) {
784
+ output.push(`${upToDate}.`);
785
+ // finish_rebase: what an earlier rebase left removed
786
+ await state.removeRef("REBASE_HEAD", "AUTO_MERGE");
787
+ await unstash();
788
+ return { status: RebaseStatus.UP_TO_DATE, newHead: headId, output };
402
789
  }
790
+ output.push(`${upToDate}, rebase forced.`);
791
+ }
403
792
 
404
- if (result.newHead) {
405
- newHead = result.newHead;
793
+ // the pre-rebase hook, told the upstream as given (`--root` with --root), may refuse
794
+ if (!this.noVerify) {
795
+ const upstreamArg =
796
+ this.root && !this.upstreamCommit ? "--root" : (this.upstreamCommitName ?? onto);
797
+ const pre = await this.hooks.run("pre-rebase", { args: [upstreamArg] });
798
+ if (pre && pre.exitCode !== 0) {
799
+ await unstash();
800
+ return {
801
+ status: RebaseStatus.FAILED,
802
+ // 2.43 dies (exit 128), 2.5x returns an error (exit 1)
803
+ message: `${this.hooks.compatibility === "2.43" ? "fatal" : "error"}: The pre-rebase hook refused to rebase.`,
804
+ output,
805
+ };
406
806
  }
807
+ }
407
808
 
408
- // Handle EDIT action - stop after successful pick
409
- if (step.action === RebaseAction.EDIT) {
410
- state.currentCommit = commitId;
411
- state.doneSteps = state.todoSteps.slice(0, i + 1);
412
- state.todoSteps = state.todoSteps.slice(i + 1);
809
+ const headTree = await flatTree(this.trees, await this.commits.getTree(headId));
810
+ const ontoTreeId = await this.commits.getTree(onto);
811
+ const ontoTree = await flatTree(this.trees, ontoTreeId);
812
+ // HEAD moved to upstream with nothing replayed: HEAD detached at upstream ("(start)"),
813
+ // then the branch moved, as git's rebase does for an empty (noop) todo
814
+ const moveToOnto = async (status: RebaseStatus): Promise<RebaseResult> => {
815
+ const refused = await switchTrees(this.context(worktree), headTree, ontoTree, {
816
+ action: "checkout",
817
+ operation: "rebase",
818
+ targetTree: ontoTreeId,
819
+ });
820
+ if (refused) {
821
+ await unstash();
822
+ // the merge backend's checkout_onto, a fast-forward included
413
823
  return {
414
- status: RebaseStatus.EDIT,
415
- newHead,
416
- currentCommit: commitId,
824
+ status: RebaseStatus.FAILED,
825
+ message: `${refused.message}\nerror: could not detach HEAD`,
826
+ output,
417
827
  };
418
828
  }
829
+ await state.setRef("ORIG_HEAD", headId);
830
+ await this.refsStore.set("HEAD", onto, this.startLog());
831
+ await runPostCheckoutHook(this.hooks, headId, onto, true);
832
+ await this.finishBranch(headName, onto, onto);
833
+ await unstash();
834
+ return { status, newHead: onto, output };
835
+ };
836
+ // nothing of HEAD's to replay: HEAD moves to upstream
837
+ if (await this.isAncestor(headId, onto)) return moveToOnto(RebaseStatus.FAST_FORWARD);
419
838
 
420
- state.doneSteps.push(step);
839
+ // `--rebase-merges` (else `rebase.rebaseMerges`, a boolean or a cousins mode)
840
+ let rebaseMerges = this.rebaseMerges;
841
+ let rebaseCousins = this.rebaseCousins;
842
+ if (rebaseMerges === undefined) {
843
+ const value = configValue(this.workingCopy, "rebase.rebaseMerges");
844
+ if (value !== undefined) {
845
+ const bool = parseGitBool(value);
846
+ rebaseMerges = bool ?? true;
847
+ rebaseCousins = bool === undefined && value === "rebase-cousins";
848
+ }
421
849
  }
850
+ // the commits to pick: HEAD's, not upstream's, merges dropped (kept with
851
+ // --rebase-merges), oldest first
852
+ const range = await this.commitsToRebase(headId, onto, !!rebaseMerges);
853
+ // only merges since upstream (dropped without --rebase-merges): git's todo is a `noop`,
854
+ // and the branch still moves to upstream
855
+ if (range.length === 0) return moveToOnto(RebaseStatus.OK);
856
+ // commits whose change upstream has already (`--cherry-mark`): left out, with git's
857
+ // warnings (`make_script`), unless --reapply-cherry-picks
858
+ const skipped = this.reapplyCherryPicks
859
+ ? new Set<ObjectId>()
860
+ : await this.appliedUpstream(headId, onto, range);
861
+ const ids = range.filter((id) => !skipped.has(id));
862
+ if (skipped.size > 0) {
863
+ for (const id of range) {
864
+ if (skipped.has(id))
865
+ output.push(
866
+ `warning: skipped previously applied commit ${await this.abbreviateObjectId(id)}`,
867
+ );
868
+ }
869
+ if (configBool(this.workingCopy, "advice.skippedCherryPicks", true)) {
870
+ output.push(
871
+ "hint: use --reapply-cherry-picks to include skipped commits",
872
+ 'hint: Disable this message with "git config set advice.skippedCherryPicks false"',
873
+ );
874
+ }
875
+ }
876
+ // sequencer_make_script: a commit empty from the start says so (` # empty`), or is left
877
+ // out with --no-keep-empty
878
+ let script = "";
879
+ if (rebaseMerges) {
880
+ script = await this.makeScriptWithMerges(
881
+ headId,
882
+ onto,
883
+ range,
884
+ skipped,
885
+ rebaseCousins,
886
+ this.keepEmpty,
887
+ );
888
+ } else {
889
+ for (const id of ids) {
890
+ const empty = await this.originallyEmpty(id);
891
+ if (empty && !this.keepEmpty) continue;
892
+ script += `pick ${id} ${await this.instructionText(id)}${empty ? ` ${comment} empty` : ""}\n`;
893
+ }
894
+ }
895
+ let items = parseTodo(script, comment).items;
896
+ // complete_action: a list with nothing is a `noop`, then --update-refs, --autosquash
897
+ // and --exec rework it before it is edited
898
+ if (items.length === 0) items = [{ action: RebaseAction.NOOP, id: "", rest: "" }];
899
+ // load_ref_decorations' warnings, printed while the todo list is made
900
+ output.push(...this.decorationWarnings.splice(0));
422
901
 
423
- // Rebase complete - clean up state
424
- state.inProgress = false;
425
- RebaseCommand.rebaseStates.delete(this._workingCopy);
902
+ // init_basic_state / write_basic_state
903
+ await state.write(`${DIR}/head-name`, `${headName}\n`);
904
+ await state.write(`${DIR}/onto`, `${onto}\n`);
905
+ await state.write(`${DIR}/orig-head`, `${headId}\n`);
906
+ if (this.signoff) await state.write(`${DIR}/signoff`, "--signoff\n");
907
+ if (emptyMode === "drop") await state.write(`${DIR}/drop_redundant_commits`, "");
908
+ if (emptyMode === "keep") await state.write(`${DIR}/keep_redundant_commits`, "");
909
+ if (this.committerDateIsAuthorDate) await state.write(`${DIR}/cdate_is_adate`, "");
910
+ if (this.ignoreDate) await state.write(`${DIR}/ignore_date`, "");
911
+ await state.write(
912
+ `${DIR}/${reschedule ? "reschedule-failed-exec" : "no-reschedule-failed-exec"}`,
913
+ "",
914
+ );
915
+ await state.write(`${DIR}/interactive`, "");
916
+ if (autostash) await state.write(`${DIR}/autostash`, `${autostash}\n`);
917
+ if (squashOnto) await state.write(`${DIR}/squash-onto`, `${squashOnto}\n`);
426
918
 
427
- // Update branch ref to point to new head
428
- await this.updateHead(state.headName, newHead);
919
+ if (updateRefs) items = await this.addUpdateRefCommands(state, items, comment);
920
+ // the list's commits abbreviated once (the rearrangements below keep the same commits):
921
+ // for the editor, and to read the names back without a look at the store
922
+ const shorts = await this.shortIds(items);
923
+ if (autosquash) {
924
+ const rearranged = await rearrangeSquash(
925
+ items,
926
+ async (id) => subjectOf((await this.loadCommit(id))?.message ?? ""),
927
+ (name) => this.autosquashTarget(name, shorts),
928
+ );
929
+ if (!rearranged) {
930
+ await state.remove(DIR);
931
+ await unstash();
932
+ return {
933
+ status: RebaseStatus.FAILED,
934
+ message: "error: the script was already rearranged.",
935
+ output,
936
+ };
937
+ }
938
+ items = rearranged;
939
+ }
940
+ if (execs.length > 0) items = addExecCommands(items, execs);
429
941
 
430
- return {
431
- status: RebaseStatus.OK,
432
- newHead,
942
+ // edit_todo_list: the list (abbreviated ids, git's help) in the editor, the backup with
943
+ // the full ids
944
+ const missingCheck = this.missingCommitsCheckLevel(output);
945
+ const commandTotal = countTodoCommands(items);
946
+ const shortOnto = await this.abbreviateObjectId(onto);
947
+ const help = todoHelp(
948
+ commandTotal,
949
+ comment,
950
+ {
951
+ shortRevisions: this.root
952
+ ? await this.abbreviateObjectId(headId)
953
+ : `${shortOnto}..${await this.abbreviateObjectId(headId)}`,
954
+ shortOnto,
955
+ },
956
+ missingCheck === "error",
957
+ );
958
+ const editorText = `${formatTodo(items, { abbreviate, idOf: (id) => shorts.get(id) ?? id })}${help}`;
959
+ await state.write(`${DIR}/git-rebase-todo`, editorText);
960
+ await state.write(
961
+ `${DIR}/git-rebase-todo.backup`,
962
+ `${formatTodo(items, { abbreviate })}${help}`,
963
+ );
964
+ let edited: string;
965
+ try {
966
+ edited = await this.runSequenceEditor(editorText, shorts);
967
+ } catch (error) {
968
+ // complete_action's -2 (launch_sequence_editor failed): the autostash applied, the
969
+ // state removed, HEAD where it was
970
+ await state.remove(DIR);
971
+ await unstash();
972
+ return { status: RebaseStatus.FAILED, message: sequenceEditorFailure(error), output };
973
+ }
974
+ await state.write(`${DIR}/git-rebase-todo`, edited);
975
+ const strippedTodo = stripspace(edited, comment);
976
+ if (strippedTodo === "") {
977
+ // an empty list aborts the rebase (complete_action's "nothing to do")
978
+ await state.remove(DIR);
979
+ await unstash();
980
+ return { status: RebaseStatus.FAILED, message: "error: nothing to do", output };
981
+ }
982
+ // HEAD detached at upstream, the rebase left for `--edit-todo` (complete_action's -4)
983
+ const fixTodo = async (lines: string[]): Promise<RebaseResult> => {
984
+ const refused = await switchTrees(this.context(worktree), headTree, ontoTree, {
985
+ action: "checkout",
986
+ operation: "rebase",
987
+ targetTree: ontoTreeId,
988
+ });
989
+ if (!refused) {
990
+ await state.setRef("ORIG_HEAD", headId);
991
+ await this.refsStore.set("HEAD", onto, this.startLog());
992
+ }
993
+ return { status: RebaseStatus.FAILED, message: lines.join("\n"), output };
433
994
  };
434
- }
435
-
436
- /**
437
- * Cherry-pick a single commit.
438
- */
439
- private async cherryPickCommit(
440
- commitId: ObjectId,
441
- ontoCommit: ObjectId,
442
- _state: RebaseState,
443
- ): Promise<RebaseResult> {
444
- const commit = await this.commits.load(commitId);
445
- if (!commit) {
446
- throw new CommitNotFoundError(commitId);
995
+ const parsed = await this.resolveTodo(parseTodo(strippedTodo, comment).items, {
996
+ known: shorts,
997
+ });
998
+ output.push(...parsed.warnings);
999
+ if (parsed.errors.length > 0) return fixTodo([...parsed.errors, ...EDIT_TODO_ADVICE]);
1000
+ const missing = await this.missingCommits(items, parsed.items, missingCheck);
1001
+ if (missing.length > 0) {
1002
+ if (missingCheck === "error") {
1003
+ await state.write(`${DIR}/dropped`, "");
1004
+ return fixTodo(missing);
1005
+ }
1006
+ output.push(...missing);
447
1007
  }
1008
+ await this.filterUpdateRefs(state, parsed.items);
1009
+ // the ids expanded, the list written again as git writes it
1010
+ let todo = parsed.items.map(({ line: _, ...item }) => item as TodoItem);
448
1011
 
449
- // Skip merge commits unless preserveMerges is set
450
- if (commit.parents.length > 1 && !this.preserveMerges) {
451
- // Return success without creating a new commit
452
- return {
453
- status: RebaseStatus.OK,
454
- newHead: ontoCommit,
455
- };
1012
+ // git's skip_unnecessary_picks (allow_ff): the first picks whose parent is where the
1013
+ // rebase starts are done already, HEAD starts at the last of them; the noops and drops
1014
+ // among and before them go to `done` with them
1015
+ let start = onto;
1016
+ let skippedPicks = 0;
1017
+ if (!forced) {
1018
+ for (; skippedPicks < todo.length; skippedPicks++) {
1019
+ const item = todo[skippedPicks] as TodoItem;
1020
+ if (isNoop(item)) continue;
1021
+ if (item.action !== RebaseAction.PICK) break;
1022
+ const parents = (await this.loadCommit(item.id))?.parents ?? [];
1023
+ if (parents.length !== 1 || parents[0] !== start) break;
1024
+ start = item.id;
1025
+ }
456
1026
  }
457
-
458
- // Get parent commit for diff base
459
- const parentId = commit.parents[0];
460
- if (!parentId) {
461
- // Root commit - just use its tree
462
- const newCommitId = await this.createRebasedCommit(commit, ontoCommit, commit.tree);
1027
+ await state.write(`${DIR}/done`, formatTodo(todo.slice(0, skippedPicks)));
1028
+ todo = todo.slice(skippedPicks);
1029
+ // a fixup after the picks skipped: the base waits in rewritten-pending
1030
+ if (skippedPicks > 0 && isFixup(peekCommand(todo, 0))) {
1031
+ await state.append(`${DIR}/rewritten-pending`, `${start}\n`);
1032
+ }
1033
+ await state.write(`${DIR}/git-rebase-todo`, formatTodo(todo, { abbreviate }));
1034
+ const startTreeId = start === onto ? ontoTreeId : await this.commits.getTree(start);
1035
+ const startTree = start === onto ? ontoTree : await flatTree(this.trees, startTreeId);
1036
+ // detach HEAD at upstream, the worktree switched to it (as git's checkout of onto)
1037
+ const refused = await switchTrees(this.context(worktree), headTree, startTree, {
1038
+ action: "checkout",
1039
+ operation: "rebase",
1040
+ targetTree: startTreeId,
1041
+ });
1042
+ if (refused) {
1043
+ await state.remove(DIR);
1044
+ await unstash();
463
1045
  return {
464
- status: RebaseStatus.OK,
465
- newHead: newCommitId,
1046
+ status: RebaseStatus.FAILED,
1047
+ message: `${refused.message}\nerror: could not detach HEAD`,
1048
+ output,
466
1049
  };
467
1050
  }
468
-
469
- // Three-way merge: parent -> commit changes applied to onto
470
- const parentCommit = await this.commits.load(parentId);
471
- const ontoCommitObj = await this.commits.load(ontoCommit);
472
- if (!parentCommit || !ontoCommitObj) {
473
- throw new CommitNotFoundError(parentId);
474
- }
475
-
476
- // Replay this commit's changes onto `onto`: base is the commit's own
477
- // parent, so base->commit is exactly the change being replayed. The merge
478
- // is path-level; a file both sides edited conflicts even if the edits are
479
- // to different regions.
480
- const mergeResult = await mergeTreesThreeWay(
481
- this.trees,
482
- parentCommit.tree,
483
- commit.tree,
484
- ontoCommitObj.tree,
1051
+ const commands = countTodoCommands(parsed.items);
1052
+ await state.write(`${DIR}/end`, `${commands}\n`);
1053
+ await state.write(`${DIR}/msgnum`, "0\n");
1054
+ // checkout_onto's reset_head: ORIG_HEAD expecting its old value, then HEAD detached
1055
+ // expecting the commit it left (as the reference-transaction hook sees both); an
1056
+ // ORIG_HEAD it cannot write is reported (as reset reports it) and HEAD moves all the same
1057
+ output.push(
1058
+ ...(await moveHeadAsReset(
1059
+ this.refsStore,
1060
+ state,
1061
+ headId,
1062
+ start,
1063
+ this.startLog(),
1064
+ "rebase: updating ORIG_HEAD",
1065
+ { detach: true },
1066
+ )),
485
1067
  );
1068
+ // checkout_onto's post-checkout hook: the HEAD left, the commit the picks start from
1069
+ await runPostCheckoutHook(this.hooks, headId, start, true);
1070
+ // pick_commits runs the list as expanded (full command names), not as written
1071
+ return this.processTodo(state, worktree, output, todo);
1072
+ }
486
1073
 
487
- if (mergeResult.conflicts && mergeResult.conflicts.length > 0) {
1074
+ /** Picks what is left in `git-rebase-todo`, then finishes the rebase (git's pick_commits). */
1075
+ private async processTodo(
1076
+ state: OperationState,
1077
+ worktree: Worktree | undefined,
1078
+ output: string[] = [],
1079
+ /** The list in memory (complete_action's), else read from `git-rebase-todo` */
1080
+ items?: TodoItem[],
1081
+ ): Promise<RebaseResult> {
1082
+ // git's read_populate_todo: a todo that cannot be read is an error, not an empty list
1083
+ if (state.supported && (await state.read(`${DIR}/git-rebase-todo`)) === undefined) {
1084
+ throw new RebaseTodoMissingError(`${DIR}/git-rebase-todo`);
1085
+ }
1086
+ const loaded = items ? { items, errors: [] } : await this.loadTodo(state);
1087
+ if (loaded.errors.length > 0) {
488
1088
  return {
489
- status: RebaseStatus.STOPPED,
490
- currentCommit: commitId,
491
- conflicts: mergeResult.conflicts,
1089
+ status: RebaseStatus.FAILED,
1090
+ message: [...loaded.errors, "error: please fix this using 'git rebase --edit-todo'."].join(
1091
+ "\n",
1092
+ ),
1093
+ output,
492
1094
  };
493
1095
  }
1096
+ let todo = loaded.items;
1097
+ // pick_commits: what a stop left
1098
+ await state.remove(`${DIR}/message`, `${DIR}/stopped-sha`, `${DIR}/amend`, `${DIR}/patch`);
1099
+ // the commands done so far (`end`, the total, was written as the list was read)
1100
+ let doneCount = countCommands((await state.read(`${DIR}/done`)) ?? "");
1101
+ while (todo.length > 0) {
1102
+ const item = todo[0] as TodoItem;
1103
+ const rest = todo.slice(1);
1104
+ const line = formatTodo([item], { verbatim: true });
1105
+ // git's save_todo: the rest written to `git-rebase-todo` first (a lock file renamed
1106
+ // into place), then the command appended to `done` (O_APPEND); a crash between the
1107
+ // two loses the `done` line, never the todo
1108
+ const restText = formatTodo(rest, { verbatim: true });
1109
+ await state.write(`${DIR}/git-rebase-todo`, restText);
1110
+ await state.append(`${DIR}/done`, line);
1111
+ if (item.action !== RebaseAction.COMMENT || item.invalid) {
1112
+ doneCount++;
1113
+ await state.write(`${DIR}/msgnum`, `${doneCount}\n`);
1114
+ }
1115
+ // what the previous command left (pick_commits unlinks it before each one)
1116
+ await state.remove(`${DIR}/message`, `${DIR}/stopped-sha`);
1117
+ await state.remove(`${DIR}/author-script`, "MERGE_HEAD");
1118
+ // deleted whether they exist or not (git 2.5x's reference-transaction hook hears both)
1119
+ await state.deleteRef("AUTO_MERGE", "REBASE_HEAD");
1120
+ if (item.action === RebaseAction.BREAK) {
1121
+ // stopped_at_head
1122
+ return { status: RebaseStatus.STOPPED, message: await this.stoppedAtHead(), output };
1123
+ }
1124
+ this.nextCommand = peekCommand(rest, 0);
1125
+ const outcome = await this.runTodoCommand(state, worktree, todo, output);
1126
+ if (outcome?.reschedule) {
1127
+ // git's "It has been rescheduled": the command goes back to the todo's head (it
1128
+ // stays in `done`), so `--continue` runs it again
1129
+ await state.write(`${DIR}/git-rebase-todo`, formatTodo(todo, { verbatim: true }));
1130
+ if (item.id && takesCommit(item)) await state.setRef("REBASE_HEAD", item.id);
1131
+ const { reschedule: _, checkTodo: __, ...result } = outcome;
1132
+ return {
1133
+ ...result,
1134
+ status: result.status ?? RebaseStatus.FAILED,
1135
+ message: `${result.message ?? ""}\n${rescheduledAdvice(line.replace(/\n$/, ""))}`,
1136
+ output,
1137
+ };
1138
+ }
1139
+ if (outcome && outcome.status !== undefined) {
1140
+ const { reschedule: _, checkTodo: __, ...result } = outcome;
1141
+ return { ...result, status: outcome.status, output };
1142
+ }
1143
+ todo = rest;
1144
+ // reread_todo_if_changed: an exec (or an edited message) may have rewritten the list
1145
+ if (outcome?.checkTodo) {
1146
+ const now = (await state.read(`${DIR}/git-rebase-todo`)) ?? "";
1147
+ if (now !== restText) {
1148
+ const reread = await this.loadTodo(state);
1149
+ if (reread.errors.length > 0) {
1150
+ return {
1151
+ status: RebaseStatus.FAILED,
1152
+ message: [
1153
+ ...reread.errors,
1154
+ "error: please fix this using 'git rebase --edit-todo'.",
1155
+ ].join("\n"),
1156
+ output,
1157
+ };
1158
+ }
1159
+ todo = reread.items;
1160
+ await this.writeTotal(state, todo);
1161
+ }
1162
+ }
1163
+ }
1164
+ // done: the branch takes the new commits, HEAD attached to it again
1165
+ const headName = (await state.read(`${DIR}/head-name`))?.trim() ?? "detached HEAD";
1166
+ const newHead = await this.resolveHead();
1167
+ const onto = (await state.read(`${DIR}/onto`))?.trim() ?? newHead;
1168
+ const origHead = (await state.read(`${DIR}/orig-head`))?.trim();
1169
+ await this.finishBranch(headName, newHead, onto, false, origHead || undefined);
1170
+ await this.flushRewrittenPending(state);
1171
+ // `git notes copy --for-rewrite=rebase` fed rewritten-list
1172
+ const rewritten = await state.read(`${DIR}/rewritten-list`);
1173
+ if (rewritten) {
1174
+ await copyNotesForRebase(this.notesContext(), rewritten);
1175
+ // the post-rewrite hook told "rebase", rewritten-list on its stdin
1176
+ await this.hooks.run("post-rewrite", { args: ["rebase"], stdin: rewritten });
1177
+ }
1178
+ const autostash = (await state.read(`${DIR}/autostash`))?.trim();
1179
+ if (autostash) output.push(...(await applyAutostash(this.context(worktree), autostash)));
1180
+ await this.doUpdateRefs(state, output);
1181
+ await this.deleteRewrittenRefs(state);
1182
+ await state.remove(DIR);
1183
+ return { status: RebaseStatus.OK, newHead, output };
1184
+ }
494
1185
 
495
- // Create new commit with merged tree
496
- const newCommitId = await this.createRebasedCommit(commit, ontoCommit, mergeResult.tree);
1186
+ /** git's commit_tree of the empty tree with no parent and no message (squash_onto). */
1187
+ private async createSquashOnto(): Promise<ObjectId> {
1188
+ this.resetClock();
1189
+ const tree = await this.trees.storeTree([]);
1190
+ return this.commits.store({
1191
+ tree,
1192
+ parents: [],
1193
+ author: this.resolveAuthor(),
1194
+ committer: this.committer ?? this.resolveCommitter(),
1195
+ message: "",
1196
+ });
1197
+ }
497
1198
 
498
- return {
499
- status: RebaseStatus.OK,
500
- newHead: newCommitId,
501
- };
1199
+ /** stopped_at_head: `Stopped at <abbrev> (<subject>)` (a `break`; get_message's label). */
1200
+ private async stoppedAtHead(): Promise<string> {
1201
+ const head = await this.resolveHead().catch(() => undefined);
1202
+ const commit = head ? await this.commits.load(head).catch(() => undefined) : undefined;
1203
+ if (!head || !commit) return "Stopped at HEAD";
1204
+ return `Stopped at ${await this.abbreviateObjectId(head)} (${subjectOf(commit.message)})`;
502
1205
  }
503
1206
 
504
1207
  /**
505
- * Create a new commit preserving the original author info.
1208
+ * git's record_in_rewritten: the commit waits in `rewritten-pending` while a fixup or
1209
+ * squash follows; otherwise the pending commits map to HEAD (`rewritten-list`).
506
1210
  */
507
- private async createRebasedCommit(
508
- original: {
509
- author: PersonIdent;
510
- message: string;
511
- },
512
- parentId: ObjectId,
513
- treeId: ObjectId,
514
- ): Promise<ObjectId> {
515
- const committer = await this.getCommitter();
1211
+ private async recordInRewritten(
1212
+ state: OperationState,
1213
+ id: ObjectId,
1214
+ next: RebaseAction | undefined,
1215
+ ): Promise<void> {
1216
+ await state.append(`${DIR}/rewritten-pending`, `${id}\n`);
1217
+ if (!isFixup(next)) await this.flushRewrittenPending(state);
1218
+ }
516
1219
 
517
- return this.commits.store({
518
- tree: treeId,
519
- parents: [parentId],
520
- author: original.author,
521
- committer,
522
- message: original.message,
523
- });
1220
+ /** git's flush_rewritten_pending: each pending commit mapped to HEAD. */
1221
+ private async flushRewrittenPending(state: OperationState): Promise<void> {
1222
+ const pending = await state.read(`${DIR}/rewritten-pending`);
1223
+ if (!pending) return;
1224
+ const head = await this.resolveHead();
1225
+ let out = "";
1226
+ for (const line of pending.split("\n")) {
1227
+ if (line !== "") out += `${line} ${head}\n`;
1228
+ }
1229
+ await state.append(`${DIR}/rewritten-list`, out);
1230
+ await state.remove(`${DIR}/rewritten-pending`);
524
1231
  }
525
1232
 
526
1233
  /**
527
- * Get default committer identity.
1234
+ * pick_one_commit: a pick-like command run (do_pick_commit) and what follows from its
1235
+ * outcome: `edit` stops, the commit recorded as rewritten, a conflict stops.
528
1236
  */
529
- private async getCommitter(): Promise<PersonIdent> {
1237
+ private async pickOne(
1238
+ state: OperationState,
1239
+ worktree: Worktree | undefined,
1240
+ todo: TodoItem[],
1241
+ output: string[],
1242
+ ): Promise<StepOutcome> {
1243
+ const item = todo[0] as TodoItem;
1244
+ const finalFixup = isFinalFixup(todo);
1245
+ const outcome = await this.pick(state, worktree, item, output, finalFixup);
1246
+ if (outcome.kind === "reschedule") return outcome.result;
1247
+ const rest = item.rest ?? (await this.instructionText(item.id));
1248
+ if (item.action === RebaseAction.EDIT) {
1249
+ const conflicts = outcome.kind === "conflicts";
1250
+ const lines: string[] = conflicts ? [...outcome.lines] : [];
1251
+ if (!conflicts) {
1252
+ lines.push(`Stopped at ${await this.abbreviateObjectId(item.id)}... ${rest}`);
1253
+ }
1254
+ lines.push(
1255
+ ...(await this.errorWithPatch(state, item.id, rest, {
1256
+ exitCode: conflicts ? 1 : 0,
1257
+ toAmend: outcome.kind === "ok",
1258
+ ...(conflicts ? { message: outcome.message } : {}),
1259
+ // the picked message (do_pick_commit's, --signoff's trailer appended)
1260
+ signoff: !conflicts && (await state.exists(`${DIR}/signoff`)),
1261
+ })),
1262
+ );
1263
+ return {
1264
+ status: conflicts ? RebaseStatus.STOPPED : RebaseStatus.EDIT,
1265
+ newHead: await this.resolveHead(),
1266
+ currentCommit: item.id,
1267
+ ...(conflicts ? { conflicts: outcome.conflicts } : {}),
1268
+ message: lines.join("\n"),
1269
+ };
1270
+ }
1271
+ if (outcome.kind === "ok") {
1272
+ await this.recordInRewritten(state, item.id, this.nextCommand);
1273
+ return undefined;
1274
+ }
1275
+ if (outcome.kind === "dropped") {
1276
+ if (finalFixup) await this.flushRewrittenPending(state);
1277
+ return undefined;
1278
+ }
1279
+ if (isFixup(item.action)) {
1280
+ // error_failed_squash: the chain's message for --continue, the commit to amend
1281
+ const squash = (await state.read(`${DIR}/message-squash`)) ?? "";
1282
+ await state.write(`${DIR}/message`, squash);
1283
+ await state.write("MERGE_MSG", squash);
1284
+ return {
1285
+ status: RebaseStatus.STOPPED,
1286
+ currentCommit: item.id,
1287
+ conflicts: outcome.conflicts,
1288
+ message: [
1289
+ ...outcome.lines,
1290
+ ...(await this.errorWithPatch(state, item.id, rest, { exitCode: 1, toAmend: true })),
1291
+ ].join("\n"),
1292
+ };
1293
+ }
1294
+ // a reword already fast-forwarded, or about to make a root commit (HEAD on git's
1295
+ // squash_onto), amends
1296
+ const head = await this.resolveHead();
1297
+ const squashOnto = (await state.read(`${DIR}/squash-onto`))?.trim();
1298
+ const toAmend =
1299
+ item.action === RebaseAction.REWORD &&
1300
+ (head === item.id || (squashOnto !== undefined && head === squashOnto));
530
1301
  return {
531
- name: "Unknown",
532
- email: "unknown@example.com",
533
- timestamp: Math.floor(Date.now() / 1000),
534
- tzOffset: getTimezoneOffset(),
1302
+ status: RebaseStatus.STOPPED,
1303
+ currentCommit: item.id,
1304
+ conflicts: outcome.conflicts,
1305
+ message: [
1306
+ ...outcome.lines,
1307
+ ...(await this.errorWithPatch(state, item.id, rest, {
1308
+ exitCode: 1,
1309
+ toAmend,
1310
+ ...(outcome.message !== undefined ? { message: outcome.message } : {}),
1311
+ })),
1312
+ ].join("\n"),
535
1313
  };
536
1314
  }
537
1315
 
538
1316
  /**
539
- * Abort the rebase and restore original HEAD.
1317
+ * git's error_with_patch: the message for `--continue`, make_patch's `stopped-sha`,
1318
+ * `REBASE_HEAD` and `patch`, and either the commit to amend (`amend`, "You can amend the
1319
+ * commit now") or `Could not apply <abbrev>... <rest>`; the lines printed.
540
1320
  */
541
- private async abort(): Promise<RebaseResult> {
542
- const state = RebaseCommand.rebaseStates.get(this._workingCopy);
543
- if (!state) {
1321
+ private async errorWithPatch(
1322
+ state: OperationState,
1323
+ id: ObjectId,
1324
+ rest: string,
1325
+ options: { exitCode: number; toAmend: boolean; message?: string; signoff?: boolean },
1326
+ ): Promise<string[]> {
1327
+ if (options.message !== undefined && !(await state.exists(`${DIR}/message`))) {
1328
+ await state.write(`${DIR}/message`, options.message);
1329
+ }
1330
+ // make_patch
1331
+ await state.write(`${DIR}/stopped-sha`, `${id}\n`);
1332
+ await state.setRef("REBASE_HEAD", id);
1333
+ await state.write(`${DIR}/patch`, "");
1334
+ if (!(await state.exists(`${DIR}/message`))) {
1335
+ const commit = await this.commits.load(id);
1336
+ const body = messageBody(commit?.message ?? "");
1337
+ await state.write(
1338
+ `${DIR}/message`,
1339
+ options.signoff
1340
+ ? appendSignoff(body, this.signoffLine(), trailerConfigOf(this.workingCopy))
1341
+ : `${body}\n`,
1342
+ );
1343
+ }
1344
+ if (options.toAmend) {
1345
+ await state.write(`${DIR}/amend`, `${await this.resolveHead()}\n`);
1346
+ return [
1347
+ "You can amend the commit now, with",
1348
+ "",
1349
+ " git commit --amend ",
1350
+ "",
1351
+ "Once you are satisfied with your changes, run",
1352
+ "",
1353
+ " git rebase --continue",
1354
+ ];
1355
+ }
1356
+ if (options.exitCode)
1357
+ return [`Could not apply ${await this.abbreviateObjectId(id)}... ${rest}`];
1358
+ return [];
1359
+ }
1360
+
1361
+ /**
1362
+ * do_pick_commit: one commit picked onto HEAD (fast-forwarded where its parent is HEAD),
1363
+ * a fixup or squash melded into HEAD, a reword amended; what came of it.
1364
+ */
1365
+ private async pick(
1366
+ state: OperationState,
1367
+ worktree: Worktree | undefined,
1368
+ item: TodoItem,
1369
+ output: string[],
1370
+ finalFixup: boolean,
1371
+ ): Promise<PickOutcome> {
1372
+ const commit = await this.commits.load(item.id);
1373
+ if (!commit) throw new CommitNotFoundError(item.id);
1374
+ const headId = await this.resolveHead();
1375
+ const signoff = await state.exists(`${DIR}/signoff`);
1376
+ const fixup = isFixup(item.action);
1377
+ // on git's squash_onto (--root, `reset [new root]`) the pick makes a root commit
1378
+ const squashOnto = (await state.read(`${DIR}/squash-onto`))?.trim();
1379
+ const unborn = squashOnto !== undefined && headId === squashOnto;
1380
+ if (unborn && fixup) {
544
1381
  return {
545
- status: RebaseStatus.ABORTED,
1382
+ kind: "reschedule",
1383
+ result: {
1384
+ status: RebaseStatus.FAILED,
1385
+ message: "error: cannot fixup root commit",
1386
+ reschedule: true,
1387
+ },
546
1388
  };
547
1389
  }
1390
+ // git's allow_ff (no --force-rebase): a commit whose parent is HEAD is kept as it is
1391
+ if (
1392
+ !fixup &&
1393
+ (commit.parents.length === 0 ? unborn : commit.parents[0] === headId) &&
1394
+ !signoff &&
1395
+ (await this.allowFastForward(state))
1396
+ ) {
1397
+ await this.writeAuthorScript(state, commit.author);
1398
+ const refused = await this.fastForward(state, worktree, headId, item.id);
1399
+ if (refused) return { kind: "reschedule", result: refused };
1400
+ if (item.action === RebaseAction.REWORD) {
1401
+ try {
1402
+ await this.rewordHead(state);
1403
+ } catch (error) {
1404
+ // fast_forward_edit's git commit failed: a stop with HEAD to amend
1405
+ return editorFailure(error);
1406
+ }
1407
+ }
1408
+ return { kind: "ok" };
1409
+ }
1410
+ // the trees read once: a pick's result is the next one's HEAD, a commit the next one's
1411
+ // parent; what is written and staged is only what the pick changes
1412
+ this.flatTrees ??= new FlatTreeCache(this.trees);
1413
+ const flats = this.flatTrees;
1414
+ const headTreeId = await this.commits.getTree(headId);
1415
+ const parentId = commit.parents[0];
1416
+ const parentTreeId = parentId ? await this.commits.getTree(parentId) : undefined;
1417
+ const subject = subjectOf(commit.message);
1418
+ // do_pick_commit: the message from its subject on; --signoff appends the committer's
1419
+ // sign-off (not for a fixup or squash), before the merge (MERGE_MSG has it)
1420
+ const body = messageBody(commit.message);
1421
+ const pickedMessage =
1422
+ signoff && !fixup
1423
+ ? appendSignoff(body, this.signoffLine(), trailerConfigOf(this.workingCopy))
1424
+ : body;
1425
+ let messageFile: "squash" | "fixup" | "edit" | undefined;
1426
+ if (fixup) {
1427
+ await this.updateSquashMessages(state, item, commit.message);
1428
+ if (!finalFixup) messageFile = "squash";
1429
+ else if (await state.exists(`${DIR}/message-fixup`)) messageFile = "fixup";
1430
+ else {
1431
+ await state.write("SQUASH_MSG", (await state.read(`${DIR}/message-squash`)) ?? "");
1432
+ await state.remove("MERGE_MSG");
1433
+ messageFile = "edit";
1434
+ }
1435
+ }
1436
+ await this.writeAuthorScript(state, commit.author);
1437
+ // short_commit_name: repo_find_unique_abbrev with DEFAULT_ABBREV
1438
+ const short = await this.abbreviateObjectId(item.id);
1439
+ const label = `${short} (${subject})`;
1440
+ const baseLabel = parentId ? `parent of ${label}` : "(empty tree)";
1441
+ // the trees as merge-ort reads them: what all three hold alike is never read
1442
+ const merge = await mergeStoredTrees(
1443
+ this.context(worktree),
1444
+ storedBase(parentTreeId, baseLabel, () => flats.get(parentTreeId)),
1445
+ headTreeId,
1446
+ commit.tree,
1447
+ {
1448
+ oursLabel: "HEAD",
1449
+ theirsLabel: label,
1450
+ baseLabel,
1451
+ style: conflictStyleOf(this.workingCopy),
1452
+ favor: favorOf(this.contentStrategy),
1453
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
1454
+ ...ortConfigOptions(this.workingCopy, worktree),
1455
+ },
1456
+ (id) => flats.get(id),
1457
+ );
1458
+ const target = await ortResultEntries(this.blobs, merge);
1459
+ // only the directories the pick changes are stored again
1460
+ const treeId = await storeFlatTreeOver(this.trees, headTreeId, merge.ours, target);
1461
+ const conflicts = [...merge.conflicts.values()];
1462
+ // only the paths HEAD and the result differ on are switched
1463
+ const delta = await treeDelta(this.trees, headTreeId, treeId);
1464
+ const refused = await switchTrees(this.context(worktree), delta.from, delta.to, {
1465
+ action: "merge",
1466
+ operation: "rebase",
1467
+ conflicts,
1468
+ targetTree: treeId,
1469
+ });
1470
+ if (refused) {
1471
+ // nothing written: the pick is rescheduled (git keeps the author and REBASE_HEAD)
1472
+ await state.setRef("REBASE_HEAD", item.id);
1473
+ return {
1474
+ kind: "reschedule",
1475
+ result: {
1476
+ status: RebaseStatus.FAILED,
1477
+ currentCommit: item.id,
1478
+ message: refused.message,
1479
+ reschedule: true,
1480
+ },
1481
+ };
1482
+ }
1483
+ // the sequencer shows merge-ort's messages of a rebase only when the pick conflicts
1484
+ if (conflicts.length > 0 || !merge.clean) output.push(...merge.messages);
1485
+ await state.setRef("AUTO_MERGE", treeId);
1486
+ const merged = pickedMessage.endsWith("\n") ? pickedMessage : `${pickedMessage}\n`;
1487
+ if (conflicts.length > 0 || !merge.clean) {
1488
+ const paths = [...new Set(conflicts.map((c) => c.stagePath))].sort(compareGitPaths);
1489
+ await state.write("MERGE_MSG", `${merged}${conflictsComment(paths, true)}`);
1490
+ if (!fixup) {
1491
+ // do_pick_commit writes CHERRY_PICK_HEAD after a conflicted merge too; the rebase
1492
+ // stopping there deletes it again (REBASE_HEAD names the commit instead)
1493
+ await state.writeAndDeleteRef("CHERRY_PICK_HEAD", item.id);
1494
+ }
1495
+ return {
1496
+ kind: "conflicts",
1497
+ conflicts: [...new Set(merge.conflicts.keys())].sort(),
1498
+ // git 2.43 writes the message and a blank line (2.5x the conflict list after it)
1499
+ message: `${merged}\n`,
1500
+ lines: [
1501
+ `error: could not apply ${short}... ${subject}`,
1502
+ "hint: Resolve all conflicts manually, mark them as resolved with",
1503
+ 'hint: "git add/rm <conflicted_files>", then run "git rebase --continue".',
1504
+ 'hint: You can instead skip this commit: run "git rebase --skip".',
1505
+ 'hint: To abort and get back to the state before "git rebase", run "git rebase --abort".',
1506
+ ],
1507
+ };
1508
+ }
1509
+ await state.write("MERGE_MSG", pickedMessage);
1510
+ // allow_empty: a commit that was empty from the start is kept; one that became empty is
1511
+ // dropped (drop_redundant_commits), kept (keep_redundant_commits) or stops the rebase
1512
+ let allowEmpty = false;
1513
+ if (treeId === headTreeId) {
1514
+ if (commit.tree === (parentTreeId ?? EMPTY_TREE_ID)) allowEmpty = true;
1515
+ else if (await state.exists(`${DIR}/keep_redundant_commits`)) allowEmpty = true;
1516
+ else if (await state.exists(`${DIR}/drop_redundant_commits`)) {
1517
+ await state.removeRef("AUTO_MERGE");
1518
+ await state.remove("MERGE_MSG");
1519
+ output.push(`dropping ${item.id} ${subject} -- patch contents already upstream`);
1520
+ // do_pick_commit: a dropped final fixup still ends the chain (its files removed)
1521
+ if (finalFixup) await this.endFixupChain(state);
1522
+ return { kind: "dropped" };
1523
+ }
1524
+ }
1525
+ if (fixup) {
1526
+ // try_to_commit with AMEND_MSG: HEAD's parents and author, the chain's message
1527
+ // verbatim; the last of a chain with a squash is edited (git commit -e)
1528
+ const head = await this.commits.load(headId);
1529
+ if (!head) throw new NoHeadError("HEAD cannot be resolved");
1530
+ // without ALLOW_EMPTY an amend whose tree is that of HEAD's first parent (the empty
1531
+ // tree for a root) is left to git commit, which refuses it: the chain stops
1532
+ // (error_failed_squash), HEAD to amend
1533
+ if (!allowEmpty && head.parents.length <= 1) {
1534
+ const parentTree = head.parents[0]
1535
+ ? await this.commits.getTree(head.parents[0])
1536
+ : EMPTY_TREE_ID;
1537
+ if (parentTree === treeId) {
1538
+ // do_commit: REBASE_HEAD written before git commit runs
1539
+ await state.setRef("REBASE_HEAD", item.id);
1540
+ return {
1541
+ kind: "conflicts",
1542
+ conflicts: [],
1543
+ lines: [
1544
+ "You asked to amend the most recent commit, but doing so would make",
1545
+ "it empty. You can repeat your command with --allow-empty, or you can",
1546
+ 'remove the commit entirely with "git reset HEAD^".',
1547
+ ],
1548
+ };
1549
+ }
1550
+ }
1551
+ let message: string;
1552
+ if (messageFile === "edit") {
1553
+ // do_commit hands it to git commit: REBASE_HEAD first, git commit drops AUTO_MERGE
1554
+ // once it has committed (an editor that fails stops the chain as a conflict does)
1555
+ await state.setRef("REBASE_HEAD", item.id);
1556
+ try {
1557
+ message = this.editMessage((await state.read("SQUASH_MSG")) ?? "");
1558
+ } catch (error) {
1559
+ return editorFailure(error);
1560
+ }
1561
+ await state.removeRef("AUTO_MERGE");
1562
+ } else {
1563
+ message =
1564
+ (await state.read(
1565
+ messageFile === "fixup" ? `${DIR}/message-fixup` : `${DIR}/message-squash`,
1566
+ )) ?? "";
1567
+ if (signoff) message = stripspace(message);
1568
+ }
1569
+ await this.amendHead(state, treeId, message, item.action, messageFile === "edit");
1570
+ // try_to_commit removes MERGE_MSG; git commit (the edited end of a chain) SQUASH_MSG too
1571
+ await state.remove("MERGE_MSG");
1572
+ if (messageFile === "edit") await state.remove("SQUASH_MSG");
1573
+ } else {
1574
+ if (treeId === headTreeId && !allowEmpty) {
1575
+ // try_to_commit refuses the empty commit; git commit says why
1576
+ await state.setRef("CHERRY_PICK_HEAD", item.id);
1577
+ return {
1578
+ kind: "conflicts",
1579
+ conflicts: [],
1580
+ message: pickedMessage,
1581
+ lines: [
1582
+ "The previous cherry-pick is now empty, possibly due to conflict resolution.",
1583
+ "If you wish to commit it anyway, use:",
1584
+ "",
1585
+ " git commit --allow-empty",
1586
+ "",
1587
+ "Otherwise, please use 'git rebase --skip'",
1588
+ ],
1589
+ };
1590
+ }
1591
+ // try_to_commit: a signed-off message is cleaned up as whitespace (else verbatim)
1592
+ const message = signoff ? stripspace(pickedMessage) : pickedMessage;
1593
+ // do_pick_commit writes CHERRY_PICK_HEAD for the commit to come; do_commit deletes it
1594
+ // once try_to_commit made it
1595
+ await state.withRefDuring("CHERRY_PICK_HEAD", item.id, () =>
1596
+ this.commitOnto(state, unborn ? [] : [headId], treeId, commit.author, message, item.action),
1597
+ );
1598
+ // do_commit: the commit made, MERGE_MSG removed
1599
+ await state.remove("MERGE_MSG");
1600
+ if (item.action === RebaseAction.REWORD) {
1601
+ try {
1602
+ await this.rewordHead(state);
1603
+ } catch (error) {
1604
+ // git commit --amend -e failed (the editor): the pick stays, the rebase stops
1605
+ return { ...editorFailure(error), message: pickedMessage };
1606
+ }
1607
+ }
1608
+ }
1609
+ if (finalFixup) await this.endFixupChain(state);
1610
+ return { kind: "ok" };
1611
+ }
1612
+
1613
+ /** do_pick_commit after a final fixup: the chain's files removed. */
1614
+ private async endFixupChain(state: OperationState): Promise<void> {
1615
+ await state.remove(`${DIR}/message-fixup`, `${DIR}/message-squash`, `${DIR}/current-fixups`);
1616
+ }
1617
+
1618
+ /** The commit message editor: the interactive handler, else the text as it is. */
1619
+ private editMessage(text: string): string {
1620
+ const edited = this.interactiveHandler?.modifyCommitMessage
1621
+ ? this.interactiveHandler.modifyCommitMessage(text)
1622
+ : text;
1623
+ // git commit -e: the comments stripped (commit.cleanup aside)
1624
+ return cleanupMessage(edited, commentPrefixOf(this.workingCopy));
1625
+ }
548
1626
 
549
- // Restore HEAD to original
550
- await this.updateHead(state.headName, state.originalHead);
1627
+ /**
1628
+ * A reword (git commit --amend -e after the pick): HEAD committed again with its message
1629
+ * edited, logged `rebase (reword): <subject>`.
1630
+ */
1631
+ private async rewordHead(state: OperationState): Promise<void> {
1632
+ const head = await this.commits.load(await this.resolveHead());
1633
+ if (!head) return;
1634
+ if (this.hooks.enabled) {
1635
+ // run_git_commit(EDIT_MSG | VERIFY_MSG | AMEND_MSG): git commit --amend -e, its hooks
1636
+ await state.removeRef("AUTO_MERGE");
1637
+ await this.amendHead(state, head.tree, head.message, RebaseAction.REWORD, true, {
1638
+ verify: true,
1639
+ editor: true,
1640
+ hookArgs: ["commit", "HEAD"],
1641
+ env: { GIT_REFLOG_ACTION: this.stepAction(RebaseAction.REWORD) },
1642
+ });
1643
+ await state.remove("SQUASH_MSG");
1644
+ return;
1645
+ }
1646
+ const message = this.editMessage(head.message);
1647
+ // git commit --amend: the merge state it removes
1648
+ await state.removeRef("AUTO_MERGE");
1649
+ await this.amendHead(state, head.tree, message, RebaseAction.REWORD, true);
1650
+ await state.remove("SQUASH_MSG");
1651
+ }
551
1652
 
552
- // Clean up state
553
- RebaseCommand.rebaseStates.delete(this._workingCopy);
1653
+ /** The reflog action of a rebase step (`rebase (reword)`), git's GIT_REFLOG_ACTION for it. */
1654
+ private stepAction(step: string): string {
1655
+ return reflogMessages.rebaseStep(this.reflogAction("rebase"), step);
1656
+ }
1657
+
1658
+ /** The editor of a `git commit -e` run (the interactive handler; comments kept). */
1659
+ private modifyMessage(text: string): string {
1660
+ return this.interactiveHandler?.modifyCommitMessage
1661
+ ? this.interactiveHandler.modifyCommitMessage(text)
1662
+ : text;
1663
+ }
1664
+
1665
+ /**
1666
+ * HEAD replaced by a commit of `tree` with HEAD's parents and author (an amend), its notes
1667
+ * carried over (`notes.rewriteRef`). `byGitCommit`: git runs `git commit --amend` for it,
1668
+ * whose notes commit takes the amended author (git exports it), not the environment's.
1669
+ */
1670
+ private async amendHead(
1671
+ state: OperationState,
1672
+ tree: ObjectId,
1673
+ message: string,
1674
+ step: string,
1675
+ byGitCommit = false,
1676
+ /** `git commit` run with hooks: `message` is its template, edited and checked by them */
1677
+ gitCommit?: GitCommitHookRun,
1678
+ ): Promise<ObjectId> {
1679
+ const headId = await this.resolveHead();
1680
+ const head = await this.commits.load(headId);
1681
+ if (!head) throw new NoHeadError("HEAD cannot be resolved");
1682
+ const id = await this.commitOnto(
1683
+ state,
1684
+ head.parents,
1685
+ tree,
1686
+ head.author,
1687
+ message,
1688
+ step,
1689
+ gitCommit,
1690
+ );
1691
+ // commit_post_rewrite of the amend (git commit --amend, try_to_commit's AMEND_MSG)
1692
+ await copyNotesForAmend(this.notesContext(), headId, id, byGitCommit ? head.author : undefined);
1693
+ // ... and git commit's post-rewrite hook, told "amend"
1694
+ if (gitCommit) await gitCommitAfterHooks(this.hooks, gitCommit, { from: headId, to: id });
1695
+ return id;
1696
+ }
1697
+
1698
+ /**
1699
+ * sequencer.c's update_squash_messages: the chain's message in `message-squash` (`# This
1700
+ * is a combination of N commits.`, each message after its header, a fixup's commented
1701
+ * out), `message-fixup` for a chain of fixups only (the first commit's message, or a
1702
+ * `fixup -C` commit's), the chain in `current-fixups`.
1703
+ */
1704
+ private async updateSquashMessages(
1705
+ state: OperationState,
1706
+ item: TodoItem,
1707
+ message: string,
1708
+ ): Promise<void> {
1709
+ const comment = commentPrefixOf(this.workingCopy);
1710
+ const currentFixups = (await state.read(`${DIR}/current-fixups`)) ?? "";
1711
+ let count = currentFixups === "" ? 0 : currentFixups.split("\n").length;
1712
+ const seenSquash = currentFixups.startsWith("squash") || currentFixups.includes("\nsquash");
1713
+ const fixupFlag =
1714
+ item.action === RebaseAction.FIXUP &&
1715
+ (item.replaceMessage === true || item.editMessage === true);
1716
+ let buf: string;
1717
+ if (count > 0) {
1718
+ const squash = await state.read(`${DIR}/message-squash`);
1719
+ if (!squash)
1720
+ throw new InvalidArgumentError("todo", item.id, `could not read '${DIR}/message-squash'`);
1721
+ const eol = !squash.startsWith(comment)
1722
+ ? 0
1723
+ : squash.indexOf("\n") < 0
1724
+ ? squash.length
1725
+ : squash.indexOf("\n");
1726
+ buf = `${comment} ${combinedMessage(count + 2)}${squash.slice(eol)}`;
1727
+ if (fixupFlag && !seenSquash) buf = squashMessageForFixup(buf, comment);
1728
+ } else {
1729
+ const head = await this.commits.load(await this.resolveHead());
1730
+ const headBody = messageBody(head?.message ?? "");
1731
+ if (item.action === RebaseAction.FIXUP && !fixupFlag) {
1732
+ await state.write(`${DIR}/message-fixup`, headBody);
1733
+ }
1734
+ buf = `${comment} ${combinedMessage(2)}\n${comment} ${fixupFlag ? squashTexts.skipFirstMessage : squashTexts.firstMessage}\n\n`;
1735
+ buf = fixupFlag ? commentLines(buf, headBody, comment) : buf + headBody;
1736
+ }
1737
+ const body = messageBody(message);
1738
+ if (item.action === RebaseAction.SQUASH || fixupFlag) {
1739
+ // append_squash_message
1740
+ let commented = 0;
1741
+ if (
1742
+ body.startsWith("amend!") ||
1743
+ ((item.action === RebaseAction.SQUASH || seenSquash) &&
1744
+ (body.startsWith("squash!") || body.startsWith("fixup!")))
1745
+ ) {
1746
+ commented = subjectLength(body);
1747
+ }
1748
+ buf += `\n${comment} ${squashTexts.nthMessage(++count + 1)}\n\n`;
1749
+ buf = commentLines(buf, body.slice(0, commented), comment);
1750
+ const fixupOff = buf.length;
1751
+ buf += body.slice(commented);
1752
+ if (fixupFlag && !seenSquash) {
1753
+ // the message replaced: --signoff's trailer appended (append_squash_message)
1754
+ if (await state.exists(`${DIR}/signoff`)) {
1755
+ buf = appendSignoff(buf, this.signoffLine(), trailerConfigOf(this.workingCopy));
1756
+ }
1757
+ if (
1758
+ item.replaceMessage &&
1759
+ ((await state.exists(`${DIR}/message-fixup`)) ||
1760
+ !(await state.exists(`${DIR}/message-squash`)))
1761
+ ) {
1762
+ await state.write(
1763
+ `${DIR}/message-fixup`,
1764
+ buf.slice(fixupOff).replace(/^([ \t\r]*\n)+/, ""),
1765
+ );
1766
+ } else await state.remove(`${DIR}/message-fixup`);
1767
+ } else await state.remove(`${DIR}/message-fixup`);
1768
+ } else {
1769
+ buf += `\n${comment} ${squashTexts.skipNthMessage(++count + 1)}\n\n`;
1770
+ buf = commentLines(buf, body, comment);
1771
+ }
1772
+ await state.write(`${DIR}/message-squash`, buf);
1773
+ const flag = fixupFlag && item.editMessage ? " -c" : "";
1774
+ await state.write(
1775
+ `${DIR}/current-fixups`,
1776
+ `${currentFixups}${currentFixups ? "\n" : ""}${item.action}${flag} ${item.id}`,
1777
+ );
1778
+ }
1779
+
1780
+ /** One todo command run: a pick, or a `label`, `reset`, `merge`; a result when it stops. */
1781
+ private async runTodoCommand(
1782
+ state: OperationState,
1783
+ worktree: Worktree | undefined,
1784
+ todo: TodoItem[],
1785
+ output: string[],
1786
+ ): Promise<StepOutcome> {
1787
+ const item = todo[0] as TodoItem;
1788
+ if (isNoop(item)) return undefined;
1789
+ switch (item.action) {
1790
+ case RebaseAction.LABEL:
1791
+ return this.label(state, item.rest ?? "");
1792
+ case RebaseAction.RESET:
1793
+ return this.reset(state, worktree, item.rest ?? "");
1794
+ case RebaseAction.MERGE: {
1795
+ const outcome = await this.merge(state, worktree, item, output);
1796
+ if (outcome?.reschedule) return outcome;
1797
+ // record_in_rewritten after do_merge (conflicted or not)
1798
+ if (item.id) await this.recordInRewritten(state, item.id, this.nextCommand);
1799
+ return outcome;
1800
+ }
1801
+ case RebaseAction.EXEC:
1802
+ return this.exec(state, worktree, item.rest ?? "", output);
1803
+ case RebaseAction.UPDATE_REF:
1804
+ await this.updateRefRecord(state, item.rest ?? "");
1805
+ return undefined;
1806
+ default:
1807
+ return this.pickOne(state, worktree, todo, output);
1808
+ }
1809
+ }
1810
+
1811
+ /**
1812
+ * git's do_exec: `Executing: <command>`, the command run by the exec handler, the index
1813
+ * read again; a failure, or changes left in the index or worktree, stop the rebase (with
1814
+ * `--reschedule-failed-exec` the exec goes back to the todo list).
1815
+ */
1816
+ private async exec(
1817
+ state: OperationState,
1818
+ worktree: Worktree | undefined,
1819
+ command: string,
1820
+ output: string[],
1821
+ ): Promise<StepOutcome> {
1822
+ output.push(`Executing: ${command}`);
1823
+ let status: number;
1824
+ if (this.execHandler) {
1825
+ const result = await this.execHandler(command);
1826
+ status = result.exitCode;
1827
+ output.push(...(result.output ?? []));
1828
+ } else {
1829
+ output.push(`${command}: no exec handler to run it`);
1830
+ status = 127;
1831
+ }
1832
+ // force re-reading of the index
1833
+ await this.staging.read?.();
1834
+ const head = await this.resolveHead();
1835
+ const dirty = await this.uncleanWorktree(head, worktree, "rebase", false);
1836
+ const lines: string[] = dirty ? (dirty.message ?? "").split("\n") : [];
1837
+ if (status !== 0) {
1838
+ lines.push(
1839
+ `warning: execution failed: ${command}`,
1840
+ ...(dirty ? ["and made changes to the index and/or the working tree."] : []),
1841
+ "You can fix the problem, and then run",
1842
+ "",
1843
+ " git rebase --continue",
1844
+ "",
1845
+ );
1846
+ } else if (dirty) {
1847
+ lines.push(
1848
+ `warning: execution succeeded: ${command}`,
1849
+ "but left changes to the index and/or the working tree.",
1850
+ "Commit or stash your changes, and then run",
1851
+ "",
1852
+ " git rebase --continue",
1853
+ "",
1854
+ );
1855
+ status = 1;
1856
+ }
1857
+ if (status === 0) return { checkTodo: true };
1858
+ return {
1859
+ status: RebaseStatus.STOPPED,
1860
+ message: lines.join("\n"),
1861
+ ...((await state.exists(`${DIR}/reschedule-failed-exec`)) ? { reschedule: true } : {}),
1862
+ };
1863
+ }
1864
+
1865
+ /** git's do_label: `refs/rewritten/<name>` at HEAD, listed in `refs-to-delete`. */
1866
+ private async label(
1867
+ state: OperationState,
1868
+ name: string,
1869
+ ): Promise<(RebaseResult & { reschedule?: boolean }) | undefined> {
1870
+ if (name === "#") {
1871
+ return {
1872
+ status: RebaseStatus.FAILED,
1873
+ message: `error: illegal label name: '${name}'`,
1874
+ reschedule: true,
1875
+ };
1876
+ }
1877
+ const head = await this.resolveHead();
1878
+ await this.refsStore.set(`refs/rewritten/${name}`, head);
1879
+ await state.append(`${DIR}/refs-to-delete`, `refs/rewritten/${name}\n`);
1880
+ return undefined;
1881
+ }
1882
+
1883
+ /**
1884
+ * sequencer.c's lookup_label: `refs/rewritten/<label>`, else the label as a commit-ish;
1885
+ * the name the merge's conflict markers show (the ref, or the name as written).
1886
+ */
1887
+ private async lookupLabel(
1888
+ state: OperationState,
1889
+ label: string,
1890
+ ): Promise<{ id: ObjectId; name: string } | undefined> {
1891
+ const rewritten = `refs/rewritten/${label}`;
1892
+ const ref = await this.refsStore.resolve(rewritten).catch(() => undefined);
1893
+ if (ref?.objectId) return { id: ref.objectId, name: rewritten };
1894
+ const named = await this.refsStore.resolve(label).catch(() => undefined);
1895
+ if (named?.objectId) return { id: await this.peelToCommit(named.objectId), name: label };
1896
+ for (const prefix of ["refs/tags/", "refs/heads/", "refs/remotes/"]) {
1897
+ const r = await this.refsStore.resolve(`${prefix}${label}`).catch(() => undefined);
1898
+ if (r?.objectId) return { id: await this.peelToCommit(r.objectId), name: label };
1899
+ }
1900
+ if (/^[0-9a-f]{4,64}$/i.test(label)) {
1901
+ try {
1902
+ const id = await expandCommitId(
1903
+ { commits: this.commits, refs: this.refsStore, state },
1904
+ label.toLowerCase(),
1905
+ );
1906
+ if (id) return { id, name: label };
1907
+ } catch {
1908
+ // not an abbreviation of one commit
1909
+ }
1910
+ }
1911
+ return undefined;
1912
+ }
1913
+
1914
+ /** An annotated tag peeled to what it tags. */
1915
+ private async peelToCommit(id: ObjectId): Promise<ObjectId> {
1916
+ let current = id;
1917
+ for (
1918
+ let depth = 0;
1919
+ depth < 32 && this.tagsStore && (await this.tagsStore.has(current));
1920
+ depth++
1921
+ ) {
1922
+ const tag = await this.tagsStore.load(current);
1923
+ if (!tag) break;
1924
+ current = tag.object;
1925
+ }
1926
+ return current;
1927
+ }
1928
+
1929
+ /** git's do_reset: HEAD, the index and the worktree moved to a label's commit. */
1930
+ private async reset(
1931
+ state: OperationState,
1932
+ worktree: Worktree | undefined,
1933
+ arg: string,
1934
+ ): Promise<(RebaseResult & { reschedule?: boolean }) | undefined> {
1935
+ // the label ends at the first blank (a `reset <label> # <oneline>` line); `[new root]`
1936
+ // is git's squash_onto (made when the rebase has none yet)
1937
+ const newRoot = arg.startsWith("[new root]");
1938
+ const end = arg.search(/[ \t\n\r]/);
1939
+ const name = newRoot ? "[new root]" : end < 0 ? arg : arg.slice(0, end);
1940
+ let found: { id: ObjectId; name: string } | undefined;
1941
+ if (newRoot) {
1942
+ let id = (await state.read(`${DIR}/squash-onto`))?.trim();
1943
+ if (!id) {
1944
+ id = await this.createSquashOnto();
1945
+ await state.write(`${DIR}/squash-onto`, id);
1946
+ }
1947
+ found = { id, name };
1948
+ } else found = await this.lookupLabel(state, name);
1949
+ if (!found) {
1950
+ return {
1951
+ status: RebaseStatus.FAILED,
1952
+ message: `error: could not resolve '${name}'`,
1953
+ reschedule: true,
1954
+ };
1955
+ }
1956
+ const headId = await this.resolveHead();
1957
+ const headTree = await this.commits.getTree(headId);
1958
+ const targetTree = await this.commits.getTree(found.id);
1959
+ const delta = await treeDelta(this.trees, headTree, targetTree);
1960
+ const refused = await switchTrees(this.context(worktree), delta.from, delta.to, {
1961
+ action: "checkout",
1962
+ operation: "reset",
1963
+ targetTree,
1964
+ });
1965
+ if (refused) {
1966
+ return { status: RebaseStatus.FAILED, message: refused.message, reschedule: true };
1967
+ }
1968
+ await this.refsStore.set(
1969
+ "HEAD",
1970
+ found.id,
1971
+ this.reflogLine(
1972
+ `${reflogMessages.rebaseStep(this.reflogAction("rebase"), "reset")}: '${name}'`,
1973
+ this.committer,
1974
+ ),
1975
+ );
1976
+ return undefined;
1977
+ }
1978
+
1979
+ /**
1980
+ * git's do_merge for one merge head: the original merge (`-C <commit>`) recreated on HEAD
1981
+ * with its message and author, merge-ort merging the label's commit; a fast-forward to the
1982
+ * original when HEAD and the heads are its parents; nothing when the head is already in
1983
+ * HEAD. A conflict stops as a pick does (`Could not apply <abbrev>... <label> # <oneline>`).
1984
+ */
1985
+ private async merge(
1986
+ state: OperationState,
1987
+ worktree: Worktree | undefined,
1988
+ item: TodoItem,
1989
+ output: string[],
1990
+ ): Promise<(RebaseResult & { reschedule?: boolean }) | undefined> {
1991
+ const arg = item.rest ?? "";
1992
+ // the merge heads, up to a `#` that starts the oneline
1993
+ const heads: { id: ObjectId; name: string }[] = [];
1994
+ let mergeArgEnd = arg.length;
1995
+ let oneline: string | undefined;
1996
+ let p = 0;
1997
+ for (;;) {
1998
+ while (p < arg.length && /[ \t\n]/.test(arg[p] as string)) p++;
1999
+ if (p >= arg.length) break;
2000
+ if (arg[p] === "#" && (p + 1 >= arg.length || /[ \t\n\r]/.test(arg[p + 1] as string))) {
2001
+ p++;
2002
+ while (p < arg.length && /[ \t\n]/.test(arg[p] as string)) p++;
2003
+ oneline = arg.slice(p);
2004
+ break;
2005
+ }
2006
+ let k = p;
2007
+ while (k < arg.length && !/[ \t\n]/.test(arg[k] as string)) k++;
2008
+ const label = arg.slice(p, k);
2009
+ const found = await this.lookupLabel(state, label);
2010
+ if (!found) {
2011
+ return {
2012
+ status: RebaseStatus.FAILED,
2013
+ message: `error: could not resolve '${label}'\nerror: unable to parse '${label}'`,
2014
+ reschedule: true,
2015
+ };
2016
+ }
2017
+ heads.push(found);
2018
+ p = k;
2019
+ mergeArgEnd = k;
2020
+ }
2021
+ if (heads.length === 0) {
2022
+ return { status: RebaseStatus.FAILED, message: `error: nothing to merge: '${arg}'` };
2023
+ }
2024
+ const original = item.id ? await this.commits.load(item.id) : undefined;
2025
+ const headId = await this.resolveHead();
2026
+ // a merge onto a `[new root]`: a fast-forward to the merge head
2027
+ const squashOnto = (await state.read(`${DIR}/squash-onto`))?.trim();
2028
+ if (squashOnto && headId === squashOnto) {
2029
+ if (heads.length > 1) {
2030
+ return {
2031
+ status: RebaseStatus.FAILED,
2032
+ message: "error: octopus merge cannot be executed on top of a [new root]",
2033
+ reschedule: true,
2034
+ };
2035
+ }
2036
+ return this.fastForward(state, worktree, headId, (heads[0] as { id: ObjectId }).id);
2037
+ }
2038
+ const forced = !(await this.allowFastForward(state));
2039
+ // HEAD the original's first parent, the heads its other parents: the original is kept
2040
+ if (
2041
+ !forced &&
2042
+ original &&
2043
+ original.parents[0] === headId &&
2044
+ original.parents.length === heads.length + 1 &&
2045
+ heads.every((h, k) => original.parents[k + 1] === h.id)
2046
+ ) {
2047
+ const refused = await this.fastForward(state, worktree, headId, item.id);
2048
+ if (refused) return refused;
2049
+ if (item.editMessage) await this.amendMergeMessage(state, item.id);
2050
+ return undefined;
2051
+ }
2052
+ let message: string;
2053
+ let author: PersonIdent;
2054
+ if (original) {
2055
+ // find_commit_subject: the message from its first non-blank line
2056
+ message = original.message.replace(/^([ \t\r]*\n)+/, "");
2057
+ author = original.author;
2058
+ } else {
2059
+ author = this.resolveAuthor();
2060
+ message =
2061
+ oneline !== undefined
2062
+ ? oneline
2063
+ : `Merge ${heads.length > 1 ? "branches" : "branch"} '${arg.slice(0, mergeArgEnd).replace(/^[ \t\n]+/, "")}'`;
2064
+ }
2065
+ await this.writeAuthorScript(state, author);
2066
+ await state.write("MERGE_MSG", message);
2067
+ if (heads.length > 1) {
2068
+ return this.octopus(state, item, heads, author, message, output);
2069
+ }
2070
+ const head = heads[0] as { id: ObjectId; name: string };
2071
+ const bases = await revisionMergeBases(this.commits, headId, head.id);
2072
+ if (bases[0] === head.id) {
2073
+ // the head is already in HEAD: nothing to merge
2074
+ return undefined;
2075
+ }
2076
+ await state.write("MERGE_HEAD", head.id);
2077
+ await state.write("MERGE_MODE", "no-ff");
2078
+ const headCommitTree = await this.commits.getTree(headId);
2079
+ const headTree = await this.commits.getTree(head.id);
2080
+ const common = {
2081
+ style: conflictStyleOf(this.workingCopy),
2082
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
2083
+ ...ortConfigOptions(this.workingCopy, worktree),
2084
+ };
2085
+ const base = await mergeBaseTree(
2086
+ {
2087
+ commits: this.commits,
2088
+ trees: this.trees,
2089
+ blobs: this.blobs,
2090
+ abbreviate: (id) => this.abbreviateObjectId(id),
2091
+ },
2092
+ headId,
2093
+ head.id,
2094
+ bases,
2095
+ common,
2096
+ );
2097
+ const merge = await mergeStoredTrees(
2098
+ { trees: this.trees, blobs: this.blobs },
2099
+ base,
2100
+ headCommitTree,
2101
+ headTree,
2102
+ {
2103
+ ...common,
2104
+ oursLabel: "HEAD",
2105
+ theirsLabel: head.name,
2106
+ baseLabel: base.label,
2107
+ favor: favorOf(this.contentStrategy),
2108
+ },
2109
+ );
2110
+ const target = await ortResultEntries(this.blobs, merge);
2111
+ const treeId = await storeFlatTreeOver(this.trees, headCommitTree, merge.ours, target);
2112
+ const conflicts = [...merge.conflicts.values()];
2113
+ const delta = await treeDelta(this.trees, headCommitTree, treeId);
2114
+ const refused = await switchTrees(this.context(worktree), delta.from, delta.to, {
2115
+ action: "merge",
2116
+ operation: "merge",
2117
+ conflicts,
2118
+ targetTree: treeId,
2119
+ });
2120
+ if (refused) {
2121
+ // could not even attempt to merge: rescheduled
2122
+ await state.remove("MERGE_MSG", "MERGE_HEAD", "MERGE_MODE");
2123
+ if (item.id) await state.setRef("REBASE_HEAD", item.id);
2124
+ return {
2125
+ status: RebaseStatus.FAILED,
2126
+ currentCommit: item.id || undefined,
2127
+ message: `${refused.message}\nerror: could not even attempt to merge '${arg.slice(0, mergeArgEnd)}'`,
2128
+ reschedule: true,
2129
+ };
2130
+ }
2131
+ if (conflicts.length > 0 || !merge.clean) {
2132
+ output.push(...merge.messages);
2133
+ await state.setRef("AUTO_MERGE", treeId);
2134
+ // the message as it is (do_merge appends no conflict list), also for --continue
2135
+ await state.write(`${DIR}/message`, message);
2136
+ // record_in_rewritten (pick_commits) runs before the stop: the merge maps to HEAD
2137
+ if (item.id) {
2138
+ await state.write(`${DIR}/stopped-sha`, `${item.id}\n`);
2139
+ await state.setRef("REBASE_HEAD", item.id);
2140
+ await state.write(`${DIR}/patch`, "");
2141
+ }
2142
+ const short = item.id ? await this.abbreviateObjectId(item.id) : "";
2143
+ return {
2144
+ status: RebaseStatus.STOPPED,
2145
+ ...(item.id ? { currentCommit: item.id } : {}),
2146
+ conflicts: [...new Set(merge.conflicts.keys())].sort(),
2147
+ message: item.id ? `Could not apply ${short}... ${arg}` : `Could not merge ${arg}`,
2148
+ };
2149
+ }
2150
+ // git commit -n -F MERGE_MSG --cleanup=verbatim (whitespace with --signoff, which the
2151
+ // merge does not get): the merge committed, its state removed
2152
+ const committed = (await state.exists(`${DIR}/signoff`)) ? stripspace(message) : message;
2153
+ const newId = await this.commitOnto(
2154
+ state,
2155
+ [headId, head.id],
2156
+ treeId,
2157
+ author,
2158
+ committed,
2159
+ "merge",
2160
+ );
2161
+ // (git commit removes SQUASH_MSG too; the octopus' git merge leaves it)
2162
+ await state.remove("MERGE_MSG", "MERGE_HEAD", "MERGE_MODE", "SQUASH_MSG");
2163
+ await state.removeRef("AUTO_MERGE");
2164
+ if (item.editMessage) await this.amendMergeMessage(state, newId);
2165
+ return undefined;
2166
+ }
554
2167
 
2168
+ /**
2169
+ * do_merge of several heads: git runs `git merge -s octopus --no-ff --no-edit -F MERGE_MSG
2170
+ * <heads>` with the author of `author-script`; our merge runs it (git-merge-octopus, its
2171
+ * messages, ORIG_HEAD, the reflog line `merge <heads>: Merge made by the 'octopus'
2172
+ * strategy.`). Merged, the merge maps to its commit; already up to date, to HEAD; with
2173
+ * conflicts left (the last head's) or given up ("Should not be doing an octopus."), the
2174
+ * rebase stops there as at a conflicting merge (never rescheduled), the merge mapped to
2175
+ * HEAD.
2176
+ */
2177
+ private async octopus(
2178
+ state: OperationState,
2179
+ item: TodoItem,
2180
+ heads: { id: ObjectId; name: string }[],
2181
+ picked: PersonIdent,
2182
+ message: string,
2183
+ output: string[],
2184
+ ): Promise<(RebaseResult & { reschedule?: boolean }) | undefined> {
2185
+ // the dates as the sequencer passes them to the merge (GIT_AUTHOR_DATE=, and
2186
+ // GIT_COMMITTER_DATE= the author's date or the clock)
2187
+ this.resetClock();
2188
+ let author = picked;
2189
+ let committer = this.committer ?? this.resolveCommitter();
2190
+ if (await state.exists(`${DIR}/ignore_date`)) {
2191
+ const now = this.clock();
2192
+ author = { ...author, timestamp: now, tzOffset: localTimezoneOffset(now) };
2193
+ }
2194
+ if (await state.exists(`${DIR}/cdate_is_adate`)) {
2195
+ committer = { ...committer, timestamp: author.timestamp, tzOffset: author.tzOffset };
2196
+ }
2197
+ const command = new MergeCommand(this._workingCopy)
2198
+ .setInProcess(true)
2199
+ .setFastForwardMode(FastForwardMode.NO_FF)
2200
+ .setMessage(message)
2201
+ .setAuthor(author)
2202
+ .setCommitter(committer);
2203
+ // `merge -c`: --edit, the message cleaned up as an edited one
2204
+ if (item.editMessage) command.setCleanupMode(CleanupMode.STRIP);
2205
+ // the merge inherits pull's GIT_REFLOG_ACTION, not the rebase's own action
2206
+ if (this.hasReflogAction()) command.setReflogAction(this.reflogAction("rebase"));
2207
+ for (const head of heads) command.include(head.id);
2208
+ let result: MergeResult;
2209
+ try {
2210
+ result = await command.call();
2211
+ } catch (error) {
2212
+ result = {
2213
+ status: MergeStatus.FAILED,
2214
+ mergedCommits: [],
2215
+ message: error instanceof Error ? error.message : String(error),
2216
+ };
2217
+ }
2218
+ output.push(...(result.output ?? []));
2219
+ if (result.status === MergeStatus.MERGED || result.status === MergeStatus.ALREADY_UP_TO_DATE) {
2220
+ // remove_merge_branch_state
2221
+ await state.remove("MERGE_MSG", "MERGE_HEAD", "MERGE_MODE");
2222
+ await state.removeRef("AUTO_MERGE");
2223
+ return undefined;
2224
+ }
2225
+ // error_with_patch, after record_in_rewritten
2226
+ await state.write(`${DIR}/message`, message);
2227
+ if (item.id) {
2228
+ await state.write(`${DIR}/stopped-sha`, `${item.id}\n`);
2229
+ await state.setRef("REBASE_HEAD", item.id);
2230
+ await state.write(`${DIR}/patch`, "");
2231
+ }
2232
+ const arg = item.rest ?? "";
2233
+ const stop = item.id
2234
+ ? `Could not apply ${await this.abbreviateObjectId(item.id)}... ${arg}`
2235
+ : `Could not merge ${arg}`;
555
2236
  return {
556
- status: RebaseStatus.ABORTED,
557
- newHead: state.originalHead,
2237
+ status: RebaseStatus.STOPPED,
2238
+ ...(item.id ? { currentCommit: item.id } : {}),
2239
+ conflicts: result.conflicts ?? [],
2240
+ message: result.message ? `${result.message}\n${stop}` : stop,
558
2241
  };
559
2242
  }
560
2243
 
561
2244
  /**
562
- * Continue rebase after conflict resolution.
2245
+ * `merge -c` without an editor to run (git's `commit --amend -e` with a no-op editor): the
2246
+ * merge committed again with its message cleaned up as an edited one (`strip`).
563
2247
  */
564
- private async continueRebase(): Promise<RebaseResult> {
565
- const state = RebaseCommand.rebaseStates.get(this._workingCopy);
566
- if (!state || !state.inProgress) {
567
- throw new NoRebaseInProgressError();
2248
+ private async amendMergeMessage(state: OperationState, id: ObjectId): Promise<void> {
2249
+ const commit = await this.commits.load(id);
2250
+ if (!commit) return;
2251
+ const message = cleanupMessage(commit.message, commentPrefixOf(this.workingCopy));
2252
+ this.resetClock();
2253
+ let committer = this.committer ?? this.resolveCommitter();
2254
+ if (await state.exists(`${DIR}/cdate_is_adate`)) {
2255
+ committer = {
2256
+ ...committer,
2257
+ timestamp: commit.author.timestamp,
2258
+ tzOffset: commit.author.tzOffset,
2259
+ };
568
2260
  }
2261
+ const newId = await this.commits.store({
2262
+ tree: commit.tree,
2263
+ parents: commit.parents,
2264
+ author: commit.author,
2265
+ committer,
2266
+ message,
2267
+ });
2268
+ const action = reflogMessages.rebaseStep(this.reflogAction("rebase"), "merge");
2269
+ await this.refsStore.set(
2270
+ "HEAD",
2271
+ newId,
2272
+ this.reflogLine(reflogMessages.pick(action, message), this.committer),
2273
+ );
2274
+ // git commit --amend: SQUASH_MSG removed with the merge state, the notes carried over
2275
+ await state.remove("SQUASH_MSG");
2276
+ await copyNotesForAmend(this.notesContext(), id, newId, commit.author);
2277
+ }
569
2278
 
570
- // Get current HEAD
571
- const headRef = await this.refsStore.resolve("HEAD");
572
- if (!headRef?.objectId) {
573
- throw new NoHeadError("HEAD cannot be resolved");
2279
+ /**
2280
+ * git's fast_forward_to: the worktree switched to `to` (refused as a merge would be) and
2281
+ * HEAD moved there, logged `rebase: fast-forward`; the refusal reschedules the command.
2282
+ */
2283
+ private async fastForward(
2284
+ state: OperationState,
2285
+ worktree: Worktree | undefined,
2286
+ from: ObjectId,
2287
+ to: ObjectId,
2288
+ ): Promise<(RebaseResult & { reschedule?: boolean }) | undefined> {
2289
+ const delta = await treeDelta(
2290
+ this.trees,
2291
+ await this.commits.getTree(from),
2292
+ await this.commits.getTree(to),
2293
+ );
2294
+ const refused = await switchTrees(this.context(worktree), delta.from, delta.to, {
2295
+ action: "merge",
2296
+ operation: "rebase",
2297
+ targetTree: await this.commits.getTree(to),
2298
+ });
2299
+ if (refused) {
2300
+ await state.setRef("REBASE_HEAD", to);
2301
+ return {
2302
+ status: RebaseStatus.FAILED,
2303
+ currentCommit: to,
2304
+ message: refused.message,
2305
+ reschedule: true,
2306
+ };
574
2307
  }
2308
+ await this.refsStore.set(
2309
+ "HEAD",
2310
+ to,
2311
+ this.reflogLine(`${this.reflogAction("rebase")}: fast-forward`, this.committer),
2312
+ );
2313
+ return undefined;
2314
+ }
575
2315
 
576
- // Calculate remaining commits to process
577
- const remaining: ObjectId[] = [];
578
- for (const step of state.todoSteps) {
579
- if (step.action === RebaseAction.COMMENT) continue;
580
- // Find full commit ID from original commits
581
- const commitId = state.originalHead; // Simplified - would need proper tracking
582
- remaining.push(commitId);
2316
+ /**
2317
+ * git's allow_ff as read_populate_opts leaves it: off with --force-rebase, which the date
2318
+ * options and --signoff imply (`cdate_is_adate`, `ignore_date`, `signoff` in the state).
2319
+ */
2320
+ private async allowFastForward(state: OperationState): Promise<boolean> {
2321
+ for (const name of ["cdate_is_adate", "ignore_date", "signoff"]) {
2322
+ if (await state.exists(`${DIR}/${name}`)) return false;
583
2323
  }
2324
+ return true;
2325
+ }
584
2326
 
585
- return this.processSteps(state, remaining);
2327
+ /** append_signoff's `Signed-off-by: <committer name> <email>` line. */
2328
+ private signoffLine(): string {
2329
+ const committer = this.committer ?? this.resolveCommitter();
2330
+ return `Signed-off-by: ${committer.name} <${committer.email}>\n`;
2331
+ }
2332
+
2333
+ /** The labels' refs (`refs-to-delete`) removed, as git's sequencer_remove_state does. */
2334
+ private async deleteRewrittenRefs(state: OperationState): Promise<void> {
2335
+ const text = (await state.read(`${DIR}/refs-to-delete`)) ?? "";
2336
+ for (const name of text.split("\n")) {
2337
+ if (!name.startsWith("refs/rewritten/")) continue;
2338
+ if (await this.refsStore.has(name).catch(() => false)) await this.refsStore.delete(name);
2339
+ }
586
2340
  }
587
2341
 
588
2342
  /**
589
- * Skip current commit and continue.
2343
+ * git's make_script_with_merges: the todo list of `--rebase-merges` for `range` (the
2344
+ * commits to rebase, oldest first): each side branch picked from where it forked
2345
+ * (`reset`), its tip labeled, each merge recreated (`merge -C`), branch points labeled,
2346
+ * the branches in the order their merges name them, HEAD's last.
590
2347
  */
591
- private async skip(): Promise<RebaseResult> {
592
- const state = RebaseCommand.rebaseStates.get(this._workingCopy);
593
- if (!state || !state.inProgress) {
594
- throw new NoRebaseInProgressError();
2348
+ private async makeScriptWithMerges(
2349
+ headId: ObjectId,
2350
+ upstream: ObjectId,
2351
+ range: ObjectId[],
2352
+ skipped: Set<ObjectId>,
2353
+ rebaseCousins: boolean,
2354
+ keepEmpty = true,
2355
+ ): Promise<string> {
2356
+ const comment = commentPrefixOf(this.workingCopy);
2357
+ const maxLength =
2358
+ Number.parseInt(configValue(this.workingCopy, "rebase.maxLabelLength") ?? "", 10) ||
2359
+ MAX_LABEL_LENGTH;
2360
+ const commit2label = new Map<ObjectId, string>();
2361
+ const labels = new Set<string>();
2362
+ // the first merge base is the bottom of `upstream...HEAD`: labeled "onto"
2363
+ const bases = await revisionMergeBases(this.commits, upstream, headId);
2364
+ if (bases[0]) {
2365
+ commit2label.set(bases[0], "onto");
2366
+ labels.add("onto");
2367
+ }
2368
+ const encoder = new TextEncoder();
2369
+ const labelOid = async (oid: ObjectId, wanted?: string): Promise<string> => {
2370
+ const known = commit2label.get(oid);
2371
+ if (known !== undefined) return known;
2372
+ let label: string;
2373
+ if (wanted === undefined) {
2374
+ label = await this.abbreviateObjectId(oid);
2375
+ if (labels.has(label)) {
2376
+ // lengthened until no label has it, else the whole id
2377
+ const start = label.length + 1;
2378
+ label = oid;
2379
+ for (let i = start; i < oid.length; i++) {
2380
+ if (!labels.has(oid.slice(0, i))) {
2381
+ label = oid.slice(0, i);
2382
+ break;
2383
+ }
2384
+ }
2385
+ }
2386
+ } else {
2387
+ // alphanumerics and other characters than ASCII kept, the rest a single dash
2388
+ let buf = "";
2389
+ let bytes = 0;
2390
+ for (const ch of wanted) {
2391
+ if (bytes + 1 >= maxLength) break;
2392
+ if (/^[A-Za-z0-9]$/.test(ch)) {
2393
+ buf += ch;
2394
+ bytes++;
2395
+ } else if ((ch.codePointAt(0) as number) >= 0x80) {
2396
+ const n = encoder.encode(ch).length;
2397
+ if (bytes + n > maxLength) break;
2398
+ buf += ch;
2399
+ bytes += n;
2400
+ } else if (buf.length > 0 && !buf.endsWith("-")) {
2401
+ buf += "-";
2402
+ bytes++;
2403
+ }
2404
+ }
2405
+ if (buf === "") buf = `rev-${await this.abbreviateObjectId(oid)}`;
2406
+ if (
2407
+ (buf.length === 40 && /^[0-9a-fA-F]{40}$/.test(buf)) ||
2408
+ buf === "#" ||
2409
+ labels.has(buf)
2410
+ ) {
2411
+ let i = 2;
2412
+ while (labels.has(`${buf}-${i}`)) i++;
2413
+ buf = `${buf}-${i}`;
2414
+ }
2415
+ label = buf;
2416
+ }
2417
+ labels.add(label);
2418
+ commit2label.set(oid, label);
2419
+ return label;
2420
+ };
2421
+ // the branch each commit is decorated by (load_branch_decorations: refs/heads/ only,
2422
+ // the last name in order is the one get_name_decoration gives)
2423
+ const branchOf = new Map<ObjectId, string>();
2424
+ const heads: { name: string; objectId?: ObjectId; target?: string }[] = [];
2425
+ for await (const ref of this.refsStore.list("refs/heads/")) {
2426
+ if (ref.name.startsWith("refs/heads/")) heads.push(ref);
2427
+ }
2428
+ heads.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
2429
+ for (const ref of heads) {
2430
+ const value =
2431
+ ref.objectId && ref.target === undefined
2432
+ ? ref.objectId
2433
+ : (await this.refsStore.resolve(ref.name).catch(() => undefined))?.objectId;
2434
+ if (value) branchOf.set(await this.peelToCommit(value), ref.name.slice("refs/heads/".length));
595
2435
  }
596
2436
 
597
- // Skip first step
598
- if (state.todoSteps.length > 0) {
599
- const skipped = state.todoSteps.shift();
600
- if (skipped) {
601
- state.doneSteps.push(skipped);
2437
+ const interesting = new Set(range);
2438
+ const commit2todo = new Map<ObjectId, string>();
2439
+ const tips: ObjectId[] = [];
2440
+ // first phase: the onelines, the tips of merged branches labeled
2441
+ for (const id of range) {
2442
+ const commit = await this.loadCommit(id);
2443
+ if (!commit) throw new CommitNotFoundError(id);
2444
+ const parentTree = commit.parents[0]
2445
+ ? (await this.loadCommit(commit.parents[0]))?.tree
2446
+ : EMPTY_TREE_ID;
2447
+ const empty = commit.tree === parentTree;
2448
+ if (!empty && skipped.has(id)) continue;
2449
+ if (empty && !keepEmpty) continue;
2450
+ const oneline = await this.instructionText(id);
2451
+ const toMerge = commit.parents.slice(1);
2452
+ if (toMerge.length === 0) {
2453
+ commit2todo.set(id, `pick ${id} ${oneline}${empty ? ` ${comment} empty` : ""}`);
2454
+ continue;
602
2455
  }
2456
+ // a label from the message: `Merge branch 'x'`, `Merge pull request #1 from x`
2457
+ let fromMessage = oneline;
2458
+ const quoted = /^# Merge [^']*'([^']*)'/.exec(oneline);
2459
+ if (quoted) fromMessage = quoted[1] as string;
2460
+ else if (oneline.startsWith("# Merge pull request ")) {
2461
+ const at = oneline.indexOf(" from ", "# Merge pull request ".length);
2462
+ if (at >= 0) fromMessage = oneline.slice(at + " from ".length);
2463
+ }
2464
+ let line = `merge -C ${id}`;
2465
+ for (const parent of toMerge) {
2466
+ const label = branchOf.get(parent) ?? fromMessage;
2467
+ if (!interesting.has(parent)) {
2468
+ line += ` ${await labelOid(parent)}`;
2469
+ continue;
2470
+ }
2471
+ tips.push(parent);
2472
+ line += ` ${await labelOid(parent, label)}`;
2473
+ }
2474
+ commit2todo.set(id, `${line} ${oneline}`);
2475
+ }
2476
+ // second phase: branch points (commits with several children) labeled, HEAD a tip
2477
+ const childSeen = new Set<ObjectId>();
2478
+ for (const [k, id] of range.entries()) {
2479
+ for (const parent of (await this.loadCommit(id))?.parents ?? []) {
2480
+ if (!interesting.has(parent)) continue;
2481
+ if (childSeen.has(parent)) await labelOid(parent, "branch-point");
2482
+ else childSeen.add(parent);
2483
+ }
2484
+ if (k === range.length - 1) tips.push(id);
603
2485
  }
2486
+ // third phase: each tip's branch, walking first parents down to what is shown
2487
+ let out = "label onto\n";
2488
+ const shown = new Set<ObjectId>();
2489
+ for (const tip of tips) {
2490
+ if (shown.has(tip)) continue;
2491
+ const tipLabel = commit2label.get(tip);
2492
+ out += tipLabel !== undefined ? `\n${comment} Branch ${tipLabel}\n` : "\n";
2493
+ const list: ObjectId[] = [];
2494
+ let commit: ObjectId | undefined = tip;
2495
+ while (commit !== undefined && interesting.has(commit) && !shown.has(commit)) {
2496
+ list.unshift(commit);
2497
+ const parents: ObjectId[] = (await this.loadCommit(commit))?.parents ?? [];
2498
+ commit = parents[0];
2499
+ }
2500
+ if (commit === undefined) out += `reset ${rebaseCousins ? "onto" : "[new root]"}\n`;
2501
+ else {
2502
+ let to = commit2label.get(commit);
2503
+ if (to === undefined && !rebaseCousins) to = await labelOid(commit);
2504
+ if (to === undefined || to === "onto") out += "reset onto\n";
2505
+ else out += `reset ${to} ${await this.instructionText(commit)}\n`;
2506
+ }
2507
+ for (const id of list) {
2508
+ const todo = commit2todo.get(id);
2509
+ if (todo !== undefined) out += `${todo}\n`;
2510
+ const label = commit2label.get(id);
2511
+ if (label !== undefined) out += `label ${label}\n`;
2512
+ shown.add(id);
2513
+ }
2514
+ }
2515
+ return out;
2516
+ }
2517
+
2518
+ /** git's `author-script` of the commit being picked. */
2519
+ private async writeAuthorScript(state: OperationState, author: PersonIdent): Promise<void> {
2520
+ await state.write(
2521
+ `${DIR}/author-script`,
2522
+ `GIT_AUTHOR_NAME=${sq(author.name)}\nGIT_AUTHOR_EMAIL=${sq(author.email)}\nGIT_AUTHOR_DATE=${sq(`@${author.timestamp} ${author.tzOffset}`)}\n`,
2523
+ );
2524
+ }
2525
+
2526
+ /** read_populate_todo's todo_list_write_total_nr: `end`, the commands done and to do. */
2527
+ private async writeTotal(state: OperationState, todo: TodoItem[]): Promise<void> {
2528
+ const done = countCommands((await state.read(`${DIR}/done`)) ?? "");
2529
+ await state.write(`${DIR}/end`, `${done + countTodoCommands(todo)}\n`);
2530
+ }
2531
+
2532
+ /** `git rebase --continue`: what is staged committed (commit_staged_changes), the rest picked. */
2533
+ private async continueRebase(
2534
+ state: OperationState,
2535
+ worktree: Worktree | undefined,
2536
+ ): Promise<RebaseResult> {
2537
+ if (!(await this.inProgress(state))) throw new NoRebaseInProgressError();
2538
+ const { unmerged } = await readIndex(this.staging);
2539
+ if (unmerged.length > 0) {
2540
+ // builtin/rebase.c: refresh_index's `<path>: needs merge`, then has_unstaged_changes
2541
+ return {
2542
+ status: RebaseStatus.STOPPED,
2543
+ conflicts: unmerged,
2544
+ message: [
2545
+ ...[...new Set(unmerged)].map((path) => `${path}: needs merge`),
2546
+ "You must edit all merge conflicts and then",
2547
+ "mark them as resolved using git add",
2548
+ ].join("\n"),
2549
+ };
2550
+ }
2551
+ // builtin/rebase.c: unstaged changes refused before the sequencer reads anything
2552
+ if (worktree) {
2553
+ const unclean = await this.uncleanWorktree(
2554
+ await this.resolveHead(),
2555
+ worktree,
2556
+ "rebase",
2557
+ false,
2558
+ true,
2559
+ );
2560
+ if (unclean) {
2561
+ return {
2562
+ status: RebaseStatus.FAILED,
2563
+ message:
2564
+ "You must edit all merge conflicts and then\nmark them as resolved using git add",
2565
+ };
2566
+ }
2567
+ }
2568
+ return this.resume(state, worktree);
2569
+ }
2570
+
2571
+ /** sequencer_continue for `--continue` and `--skip`: the stop settled, the rest picked. */
2572
+ private async resume(
2573
+ state: OperationState,
2574
+ worktree: Worktree | undefined,
2575
+ output: string[] = [],
2576
+ ): Promise<RebaseResult> {
2577
+ const loaded = await this.loadTodo(state);
2578
+ if (loaded.errors.length > 0) {
2579
+ return {
2580
+ status: RebaseStatus.FAILED,
2581
+ message: [...loaded.errors, "error: please fix this using 'git rebase --edit-todo'."].join(
2582
+ "\n",
2583
+ ),
2584
+ };
2585
+ }
2586
+ // read_populate_todo writes the total before anything may refuse to go on
2587
+ await this.writeTotal(state, loaded.items);
2588
+ if (await state.exists(`${DIR}/dropped`)) {
2589
+ // todo_list_check_against_backup: commits still dropped by mistake
2590
+ const backup = await this.resolveTodo(
2591
+ parseTodo(
2592
+ (await state.read(`${DIR}/git-rebase-todo.backup`)) ?? "",
2593
+ commentPrefixOf(this.workingCopy),
2594
+ ).items,
2595
+ );
2596
+ const level = this.missingCommitsCheckLevel(output);
2597
+ const missing = await this.missingCommits(backup.items, loaded.items, level);
2598
+ if (missing.length > 0 && level === "error") {
2599
+ return { status: RebaseStatus.FAILED, message: missing.join("\n"), output };
2600
+ }
2601
+ output.push(...missing);
2602
+ await state.remove(`${DIR}/dropped`);
2603
+ }
2604
+ const refusal = await this.commitStagedChanges(state, loaded.items);
2605
+ if (refusal) return { ...refusal, output };
2606
+ // sequencer_continue: the stopped commit maps to HEAD, committed or not
2607
+ const stopped = (await state.read(`${DIR}/stopped-sha`))?.trim();
2608
+ if (stopped && /^[0-9a-f]{40,64}$/.test(stopped)) {
2609
+ await this.recordInRewritten(state, stopped, peekCommand(loaded.items, 0));
2610
+ }
2611
+ return this.processTodo(state, worktree, output);
2612
+ }
2613
+
2614
+ /**
2615
+ * sequencer.c's commit_staged_changes: unstaged changes refuse; staged ones are committed
2616
+ * with `rebase-merge/message` (a new commit, or HEAD amended where the stop asked for it:
2617
+ * `amend`), after a failed fixup or squash the chain's bookkeeping put right.
2618
+ */
2619
+ private async commitStagedChanges(
2620
+ state: OperationState,
2621
+ todo: TodoItem[],
2622
+ ): Promise<RebaseResult | undefined> {
2623
+ // (its has_unstaged_changes refusal cannot happen: `--continue` refused them before the
2624
+ // list was read, `--skip` reset them)
2625
+ const headId = await this.resolveHead();
2626
+ const headCommit = await this.commits.load(headId);
2627
+ const treeId = await this.staging.writeTree(this.trees);
2628
+ const isClean = headCommit?.tree === treeId;
2629
+ if (!isClean && !(await state.exists(`${DIR}/message`))) {
2630
+ return { status: RebaseStatus.FAILED, message: STAGED_CHANGES_ADVICE };
2631
+ }
2632
+ let amend = false;
2633
+ let finalFixup = false;
2634
+ let edit = true;
2635
+ let currentFixups = (await state.read(`${DIR}/current-fixups`)) ?? "";
2636
+ let fixupCount = currentFixups === "" ? 0 : currentFixups.split("\n").length;
2637
+ const amendFile = (await state.read(`${DIR}/amend`))?.trim();
2638
+ if (amendFile !== undefined) {
2639
+ if (!/^[0-9a-f]{40,64}$/.test(amendFile)) {
2640
+ return { status: RebaseStatus.FAILED, message: `error: invalid contents: '${DIR}/amend'` };
2641
+ }
2642
+ if (!isClean && headId !== amendFile) {
2643
+ return {
2644
+ status: RebaseStatus.FAILED,
2645
+ message:
2646
+ "error: \nYou have uncommitted changes in your working tree. Please, commit them\nfirst and then run 'git rebase --continue' again.",
2647
+ };
2648
+ }
2649
+ const next = peekCommand(todo, 0);
2650
+ if (!isClean || fixupCount === 0) {
2651
+ // not the final fixup
2652
+ } else if (headId !== amendFile || !(await state.exists(`${DIR}/stopped-sha`))) {
2653
+ // a final fixup or squash done by hand
2654
+ if (!isFixup(next)) {
2655
+ await state.remove(
2656
+ `${DIR}/message-fixup`,
2657
+ `${DIR}/message-squash`,
2658
+ `${DIR}/current-fixups`,
2659
+ );
2660
+ currentFixups = "";
2661
+ fixupCount = 0;
2662
+ }
2663
+ } else {
2664
+ // a fixup/squash of a chain skipped: it is taken off the chain
2665
+ fixupCount--;
2666
+ const cut = currentFixups.lastIndexOf("\n");
2667
+ currentFixups = cut < 0 ? "" : currentFixups.slice(0, cut);
2668
+ await state.write(`${DIR}/current-fixups`, currentFixups);
2669
+ const seenSquash = currentFixups.startsWith("squash") || currentFixups.includes("\nsquash");
2670
+ const seenEdit =
2671
+ currentFixups.startsWith("fixup -c") || currentFixups.includes("\nfixup -c");
2672
+ if (fixupCount > 0 && !isFixup(next)) {
2673
+ finalFixup = true;
2674
+ // only fixups: the message cleaned up, no editor
2675
+ if (!seenSquash && !seenEdit) edit = false;
2676
+ } else if (isFixup(next)) {
2677
+ await state.write(`${DIR}/message-squash`, messageBody(headCommit?.message ?? ""));
2678
+ }
2679
+ }
2680
+ amend = true;
2681
+ }
2682
+ if (isClean) {
2683
+ await state.removeRef("CHERRY_PICK_HEAD");
2684
+ await state.remove("MERGE_MSG");
2685
+ if (!finalFixup) return undefined;
2686
+ }
2687
+ // run_git_commit: `rebase-merge/message` (HEAD's own message for a final fixup), edited
2688
+ // (git commit -e: comments stripped) or cleaned up (--cleanup=strip)
2689
+ const comment = commentPrefixOf(this.workingCopy);
2690
+ let message: string;
2691
+ // with hooks: git commit -n (-F rebase-merge/message) -e, the template edited between
2692
+ // its hooks (commit_staged_changes: EDIT_MSG without VERIFY_MSG)
2693
+ let gitCommit: GitCommitHookRun | undefined;
2694
+ try {
2695
+ if (this.hooks.enabled) {
2696
+ gitCommit = {
2697
+ verify: false,
2698
+ editor: !finalFixup || edit,
2699
+ hookArgs: finalFixup ? (amend ? ["commit", "HEAD"] : []) : ["message"],
2700
+ env: { GIT_REFLOG_ACTION: this.stepAction("continue") },
2701
+ };
2702
+ message = finalFixup
2703
+ ? (headCommit?.message ?? "")
2704
+ : ((await state.read(`${DIR}/message`)) ?? (await state.read("MERGE_MSG")) ?? "");
2705
+ } else if (finalFixup) {
2706
+ const own = headCommit?.message ?? "";
2707
+ message = edit ? this.editMessage(own) : cleanupMessage(own, comment);
2708
+ } else {
2709
+ message = this.editMessage(
2710
+ (await state.read(`${DIR}/message`)) ?? (await state.read("MERGE_MSG")) ?? "",
2711
+ );
2712
+ }
2713
+ if (gitCommit) {
2714
+ const run = gitCommit;
2715
+ if (amend) await this.amendHead(state, treeId, message, "continue", true, run);
2716
+ else {
2717
+ const mergeHeads = ((await state.read("MERGE_HEAD")) ?? "")
2718
+ .split("\n")
2719
+ .map((line) => line.trim())
2720
+ .filter((line) => /^[0-9a-f]{40,64}$/.test(line));
2721
+ const author =
2722
+ parseAuthorScript((await state.read(`${DIR}/author-script`)) ?? "") ??
2723
+ this.resolveAuthor();
2724
+ // git commit, a child with GIT_REFLOG_ACTION: its HEAD update and its cleanup
2725
+ // (sequencer_post_commit_cleanup: CHERRY_PICK_HEAD when there, AUTO_MERGE)
2726
+ await this.withRefTransactionEnv(run.env ?? {}, async () => {
2727
+ await this.commitOnto(
2728
+ state,
2729
+ [headId, ...mergeHeads],
2730
+ treeId,
2731
+ author,
2732
+ message,
2733
+ "continue",
2734
+ run,
2735
+ );
2736
+ await state.removeRef("CHERRY_PICK_HEAD", "REVERT_HEAD");
2737
+ await state.deleteRef("AUTO_MERGE");
2738
+ });
2739
+ await gitCommitAfterHooks(this.hooks, run);
2740
+ }
2741
+ }
2742
+ } catch (error) {
2743
+ // git commit failed on its editor: nothing committed, the stop stays as it is
2744
+ return {
2745
+ status: RebaseStatus.FAILED,
2746
+ message: [...editorFailure(error).lines, "error: could not commit staged changes."].join(
2747
+ "\n",
2748
+ ),
2749
+ };
2750
+ }
2751
+ if (gitCommit) {
2752
+ // committed above, with git commit's hooks
2753
+ } else if (amend) await this.amendHead(state, treeId, message, "continue", true);
2754
+ else {
2755
+ // a stopped merge: its other parents (git commit reads MERGE_HEAD, one per line: an
2756
+ // octopus has several)
2757
+ const mergeHeads = ((await state.read("MERGE_HEAD")) ?? "")
2758
+ .split("\n")
2759
+ .map((line) => line.trim())
2760
+ .filter((line) => /^[0-9a-f]{40,64}$/.test(line));
2761
+ const author =
2762
+ parseAuthorScript((await state.read(`${DIR}/author-script`)) ?? "") ?? this.resolveAuthor();
2763
+ await this.commitOnto(state, [headId, ...mergeHeads], treeId, author, message, "continue");
2764
+ }
2765
+ // git commit's cleanup (SQUASH_MSG of a final squash too), then commit_staged_changes'
2766
+ await state.remove(`${DIR}/amend`, "MERGE_HEAD", "MERGE_MODE", "MERGE_MSG", "SQUASH_MSG");
2767
+ await state.removeRef("CHERRY_PICK_HEAD");
2768
+ // commit_staged_changes deletes AUTO_MERGE once git commit is done, whether it exists
2769
+ await state.deleteRef("AUTO_MERGE");
2770
+ if (finalFixup) await state.remove(`${DIR}/message-fixup`, `${DIR}/message-squash`);
2771
+ if (fixupCount > 0) await state.remove(`${DIR}/current-fixups`);
2772
+ return undefined;
2773
+ }
604
2774
 
605
- state.currentCommit = undefined;
2775
+ /** `git rebase --skip`: the stopped pick dropped (`reset --hard`), then as `--continue`. */
2776
+ private async skip(state: OperationState, worktree: Worktree | undefined): Promise<RebaseResult> {
2777
+ if (!(await this.inProgress(state))) throw new NoRebaseInProgressError();
2778
+ const headId = await this.resolveHead();
2779
+ const refused = await resetMerge(this.context(worktree), headId, "HEAD", { hard: true });
2780
+ if (refused) {
2781
+ return {
2782
+ status: RebaseStatus.FAILED,
2783
+ message: `${refused.message.replace(/\nfatal: .*$/, "")}\nfatal: could not discard worktree changes`,
2784
+ };
2785
+ }
2786
+ // remove_branch_state (REBASE_HEAD stays: the next command removes it, so a skip of the
2787
+ // last one leaves it, as git does); AUTO_MERGE deleted twice, as git's hook hears it
2788
+ await removeBranchState(this.context(worktree), state);
2789
+ return this.resume(state, worktree);
2790
+ }
606
2791
 
607
- // Calculate remaining commits
608
- const remaining: ObjectId[] = [];
609
- return this.processSteps(state, remaining);
2792
+ /** `git rebase --abort`: back to the original branch and commit (`reset --hard`). */
2793
+ private async abort(
2794
+ state: OperationState,
2795
+ worktree: Worktree | undefined,
2796
+ ): Promise<RebaseResult> {
2797
+ if (!(await this.inProgress(state))) return { status: RebaseStatus.ABORTED };
2798
+ const origHead = (await state.read(`${DIR}/orig-head`))?.trim();
2799
+ const headName = (await state.read(`${DIR}/head-name`))?.trim() ?? "detached HEAD";
2800
+ if (!origHead)
2801
+ return { status: RebaseStatus.FAILED, message: "fatal: could not read orig-head" };
2802
+ const refused = await resetMerge(this.context(worktree), origHead, origHead, { hard: true });
2803
+ if (refused) {
2804
+ return {
2805
+ status: RebaseStatus.FAILED,
2806
+ message: `${refused.message.replace(/\nfatal: .*$/, "")}\nfatal: could not move back to ${origHead}`,
2807
+ };
2808
+ }
2809
+ await this.finishBranch(headName, origHead, undefined, true);
2810
+ const autostash = (await state.read(`${DIR}/autostash`))?.trim();
2811
+ // remove_branch_state, then finish_rebase's unconditional deletions of REBASE_HEAD and
2812
+ // AUTO_MERGE (git 2.5x's reference-transaction hook hears each)
2813
+ await removeBranchState(this.context(worktree), state);
2814
+ await state.deleteRef("REBASE_HEAD", "AUTO_MERGE");
2815
+ await this.deleteRewrittenRefs(state);
2816
+ await state.remove("MERGE_HEAD", "MERGE_MODE", "MERGE_MSG", "SQUASH_MSG", DIR);
2817
+ const output = autostash ? await applyAutostash(this.context(worktree), autostash) : [];
2818
+ return { status: RebaseStatus.ABORTED, newHead: origHead, output };
610
2819
  }
611
2820
 
612
2821
  /**
613
- * Calculate which commits need to be rebased.
2822
+ * git's `require_clean_work_tree(<action>)` on this command's working copy, without
2823
+ * rebasing: the refusal (`cannot <action>: You have unstaged changes.` ...), or undefined
2824
+ * when the tree is clean or HEAD is unborn. `git pull --rebase` checks it before fetching,
2825
+ * as `pull with rebase`.
614
2826
  */
615
- private async calculateCommitsToRebase(head: ObjectId, upstream: ObjectId): Promise<ObjectId[]> {
616
- const commits: ObjectId[] = [];
2827
+ async checkCleanWorkTree(action = "rebase"): Promise<RebaseResult | undefined> {
2828
+ const headId = (await this.refsStore.resolve("HEAD").catch(() => undefined))?.objectId;
2829
+ if (!headId) return undefined;
2830
+ return this.uncleanWorktree(headId, this.worktreeAccess, action);
2831
+ }
2832
+
2833
+ /** Refuses as git's require_clean_work_tree: unstaged, then staged changes. */
2834
+ private async uncleanWorktree(
2835
+ headId: ObjectId,
2836
+ worktree: Worktree | undefined,
2837
+ action = "rebase",
2838
+ /** "Please commit or stash them." after the refusal */
2839
+ hint = true,
2840
+ /** git's has_unstaged_changes: staged changes do not count */
2841
+ unstagedOnly = false,
2842
+ ): Promise<RebaseResult | undefined> {
2843
+ const { index, unmerged } = await readIndex(this.staging);
2844
+ const headTree = await flatTree(this.trees, await this.commits.getTree(headId));
2845
+ // has_uncommitted_changes: an unborn index (no index file) has none
2846
+ const staged = (await isIndexUnborn(this.staging)) ? [] : indexChanges(index, headTree);
2847
+ const unstaged: string[] = [...unmerged];
2848
+ if (worktree) {
2849
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
2850
+ const indexTime = this.staging.getUpdateTime();
2851
+ // every tracked file is checked (git's refresh_index); several at a time, as git's
2852
+ // preload-index stats in parallel, the results kept in index order
2853
+ // diff-files passes over a skip-worktree entry, and an assume-unchanged one matches
2854
+ // whatever its file holds (ie_match_stat honours CE_VALID)
2855
+ const entries = [...index].filter(([, e]) => {
2856
+ const flags = e as { assumeValid?: boolean; skipWorktree?: boolean };
2857
+ return !flags.assumeValid && !flags.skipWorktree;
2858
+ });
2859
+ for (let k = 0; k < entries.length; k += WORKTREE_CHECK_BATCH) {
2860
+ const batch = entries.slice(k, k + WORKTREE_CHECK_BATCH);
2861
+ const modified = await Promise.all(
2862
+ batch.map(([path, entry]) => worktreeModified(worktree, path, entry, trust, indexTime)),
2863
+ );
2864
+ // a deleted file is an unstaged change too
2865
+ batch.forEach(([path], j) => {
2866
+ if (modified[j]) unstaged.push(path);
2867
+ });
2868
+ }
2869
+ }
2870
+ if (unstagedOnly && unstaged.length === 0) return undefined;
2871
+ if (staged.length === 0 && unstaged.length === 0) return undefined;
2872
+ const lines = [`error: cannot ${action}: You have unstaged changes.`];
2873
+ if (unstaged.length === 0)
2874
+ lines[0] = `error: cannot ${action}: Your index contains uncommitted changes.`;
2875
+ else if (staged.length > 0)
2876
+ lines.push("error: additionally, your index contains uncommitted changes.");
2877
+ if (hint) lines.push("error: Please commit or stash them.");
2878
+ return {
2879
+ status: RebaseStatus.UNCOMMITTED_CHANGES,
2880
+ uncommittedChanges: [...new Set([...unstaged, ...staged])].sort(),
2881
+ message: lines.join("\n"),
2882
+ };
2883
+ }
2884
+
2885
+ /** A commit made on the detached HEAD, logged `rebase (<step>): <subject>`. */
2886
+ private async commitOnto(
2887
+ state: OperationState,
2888
+ parents: ObjectId[],
2889
+ tree: ObjectId,
2890
+ picked: PersonIdent,
2891
+ message: string,
2892
+ step: string,
2893
+ /**
2894
+ * A `git commit` run (sequencer.c `run_git_commit`) with its hooks, `message` its
2895
+ * template: post-commit is left to the caller (post-rewrite follows it for an amend)
2896
+ */
2897
+ gitCommit?: GitCommitHookRun,
2898
+ ): Promise<ObjectId> {
2899
+ // git's try_to_commit: reset_ident_date() first, so each pick is committed (and its
2900
+ // reflog line written) at its own time
2901
+ this.resetClock();
2902
+ // the pick keeps its author; the committer is resolved as git's git_committer_info
2903
+ let author = picked;
2904
+ let committer = this.committer ?? this.resolveCommitter();
2905
+ // git's try_to_commit: --ignore-date dates the author now (the clock, local offset),
2906
+ // --committer-date-is-author-date gives the committer the author's date
2907
+ if (await state.exists(`${DIR}/ignore_date`)) {
2908
+ const now = this.clock();
2909
+ author = { ...author, timestamp: now, tzOffset: localTimezoneOffset(now) };
2910
+ }
2911
+ if (await state.exists(`${DIR}/cdate_is_adate`)) {
2912
+ committer = { ...committer, timestamp: author.timestamp, tzOffset: author.tzOffset };
2913
+ }
2914
+ const hooked = gitCommit
2915
+ ? cleanupMessage(
2916
+ await gitCommitMessageHooks(this.hooks, state, message, gitCommit, (text) =>
2917
+ gitCommit.editor ? this.modifyMessage(text) : text,
2918
+ ),
2919
+ commentPrefixOf(this.workingCopy),
2920
+ )
2921
+ : await sequencerPrepareMessage(this.hooks, state, message);
2922
+ const id = await this.commits.store({
2923
+ tree,
2924
+ parents,
2925
+ author,
2926
+ committer,
2927
+ message: hooked,
2928
+ });
2929
+ const action = reflogMessages.rebaseStep(this.reflogAction("rebase"), step);
2930
+ const log = this.reflogLine(reflogMessages.pick(action, hooked), this.committer);
2931
+ const refs = this.refsStore;
2932
+ if (refsWatched(refs)) {
2933
+ // update_head_with_reflog: HEAD expecting the commit it is at (detached while
2934
+ // rebasing), as the reference-transaction hook hears it
2935
+ const current = (await refs.resolve("HEAD").catch(() => undefined))?.objectId;
2936
+ await updateHeadExpecting(refs, id, current, log);
2937
+ } else {
2938
+ // no hook to hear an old value: one batch through HEAD to its branch, unchecked
2939
+ await updateHeadExpecting(refs, id, undefined, log);
2940
+ }
2941
+ if (!gitCommit) await sequencerPostCommit(this.hooks);
2942
+ return id;
2943
+ }
2944
+
2945
+ /**
2946
+ * `name` set to `id` as git's `refs_update_ref(..., name, id, old, REF_NO_DEREF)`: one
2947
+ * transaction expecting `old` (unchecked when undefined), as the reference-transaction hook
2948
+ * sees it; a store that cannot batch the ref sets it plainly.
2949
+ */
2950
+ private async setRefExpecting(
2951
+ name: string,
2952
+ id: ObjectId,
2953
+ old: ObjectId | undefined,
2954
+ log: RefLogOptions | undefined,
2955
+ ): Promise<void> {
2956
+ if (old === undefined) {
2957
+ await this.refsStore.set(name, id, log);
2958
+ return;
2959
+ }
2960
+ const result = await this.refsStore.batch([{ name, old, new: id, noDeref: true }], log);
2961
+ if (result.ok) return;
2962
+ if (result.rejected.every((r) => r.reason === "unsupported" || r.reason === "invalid-name")) {
2963
+ await this.refsStore.set(name, id, log);
2964
+ return;
2965
+ }
2966
+ throw new Error(
2967
+ `cannot lock ref '${name}': ${result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ")}`,
2968
+ );
2969
+ }
2970
+
2971
+ /** HEAD detached at upstream: `rebase (start): checkout <upstream as given>`. */
2972
+ private startLog(): RefLogOptions {
2973
+ const onto = this.upstreamCommitName ?? this.upstreamCommit ?? "";
2974
+ return this.reflogLine(
2975
+ reflogMessages.rebaseStart(this.reflogAction("rebase"), onto),
2976
+ this.committer,
2977
+ );
2978
+ }
2979
+
2980
+ /**
2981
+ * The branch rebased moves to `id` and HEAD is attached to it again, logged as git's
2982
+ * move_to_original_branch: `rebase (finish): <branch> onto <onto>` for the branch,
2983
+ * `rebase (finish): returning to <branch>` for HEAD; an abort logs both
2984
+ * `rebase (abort): returning to <branch>`. A detached rebase leaves HEAD where it is.
2985
+ */
2986
+ private async finishBranch(
2987
+ headName: string,
2988
+ id: ObjectId,
2989
+ onto: ObjectId | undefined,
2990
+ abort = false,
2991
+ /** The value the branch is expected at (pick_commits' `orig-head`), shown to the hook */
2992
+ old?: ObjectId,
2993
+ ): Promise<void> {
2994
+ const action = this.reflogAction("rebase");
2995
+ if (headName.startsWith("refs/")) {
2996
+ const headLog = this.reflogLine(
2997
+ abort
2998
+ ? reflogMessages.rebaseAbort(action, headName)
2999
+ : reflogMessages.rebaseFinishHead(action, headName),
3000
+ this.committer,
3001
+ );
3002
+ const branchLog = abort
3003
+ ? headLog
3004
+ : this.reflogLine(
3005
+ reflogMessages.rebaseFinishBranch(action, headName, onto ?? id),
3006
+ this.committer,
3007
+ );
3008
+ await this.setRefExpecting(headName, id, old, branchLog);
3009
+ await this.refsStore.setSymbolic("HEAD", headName, headLog);
3010
+ } else {
3011
+ // git's abort of a detached rebase: HEAD back at orig-head ("rebase (abort): returning
3012
+ // to <id>"); a finished one stays where the picks left it
3013
+ const log = abort
3014
+ ? this.reflogLine(reflogMessages.rebaseAbort(action, id), this.committer)
3015
+ : undefined;
3016
+ await this.refsStore.set("HEAD", id, log);
3017
+ }
3018
+ }
3019
+
3020
+ /** `git-rebase-todo` read and its names resolved (read_populate_todo). */
3021
+ private async loadTodo(state: OperationState): Promise<{ items: TodoItem[]; errors: string[] }> {
3022
+ const fixupOkay = await state.exists(`${DIR}/done`);
3023
+ const parsed = parseTodo(
3024
+ (await state.read(`${DIR}/git-rebase-todo`)) ?? "",
3025
+ commentPrefixOf(this.workingCopy),
3026
+ fixupOkay,
3027
+ );
3028
+ return this.resolveTodo(parsed.items, { fixupOkay });
3029
+ }
3030
+
3031
+ /**
3032
+ * The commit names of parsed todo items resolved (git's repo_get_oid in parse_insn_line),
3033
+ * the lines git refuses made invalid: names that resolve to no commit, merges where a pick
3034
+ * cannot take one; then todo_list_parse_insn_buffer's check of a fixup with no commit
3035
+ * before it (a line that failed is none). The errors in line order.
3036
+ */
3037
+ private async resolveTodo(
3038
+ items: TodoItem[],
3039
+ options: {
3040
+ /**
3041
+ * The abbreviations of the commits the list was made of (as written for the editor): a
3042
+ * name that starts with one of them is that commit, without a look at the store
3043
+ */
3044
+ known?: Map<ObjectId, string>;
3045
+ /** `rebase-merge/done` exists: a fixup or squash may start the list */
3046
+ fixupOkay?: boolean;
3047
+ } = {},
3048
+ ): Promise<{ items: TodoItem[]; errors: string[]; warnings: string[] }> {
3049
+ const errors: string[] = [];
3050
+ const { objects: resolved, warnings } = await this.resolveObjectNames(
3051
+ items.filter(takesCommit).map((item) => item.id),
3052
+ options.known,
3053
+ );
3054
+ let fixupOkay = options.fixupOkay ?? false;
3055
+ for (const [k, item] of items.entries()) {
3056
+ // parseTodo's check of a fixup made again below, once the names are resolved
3057
+ if (!item.invalid) delete item.errors;
3058
+ if (takesCommit(item)) {
3059
+ const name = item.id;
3060
+ const named = resolved.get(name);
3061
+ const fail = (lines: string[]) => {
3062
+ item.errors = [...lines, `error: invalid line ${k + 1}: ${item.line ?? ""}`];
3063
+ item.invalid = true;
3064
+ item.rest = item.line ?? "";
3065
+ item.action = RebaseAction.COMMENT;
3066
+ item.id = "";
3067
+ };
3068
+ // lookup_commit_reference: tags peeled; another object refused with git's line
3069
+ const peeled = named?.commit
3070
+ ? { id: named.id, type: "commit" }
3071
+ : named
3072
+ ? await this.revisionResolver().peelTags(named.id)
3073
+ : undefined;
3074
+ const id = peeled?.type === "commit" ? peeled.id : undefined;
3075
+ if (!named) fail([`error: could not parse '${name}'`]);
3076
+ else if (!id) {
3077
+ fail(peeled?.type ? [`error: object ${named.id} is a ${peeled.type}, not a commit`] : []);
3078
+ } else {
3079
+ item.id = id;
3080
+ const parents = (await this.loadCommit(id))?.parents ?? [];
3081
+ if (parents.length > 1 && isPickLike(item.action)) fail(mergeCommitErrors(item.action));
3082
+ }
3083
+ }
3084
+ if (fixupOkay) {
3085
+ // nothing to check
3086
+ } else if (isFixup(item.action) && !item.invalid) {
3087
+ item.errors = [`error: cannot '${item.action}' without a previous commit`];
3088
+ } else if (!isNoop(item)) fixupOkay = true;
3089
+ if (item.errors) errors.push(...item.errors);
3090
+ }
3091
+ return { items, errors, warnings };
3092
+ }
3093
+
3094
+ /** Commit names resolved at once (see {@link resolveObjectNames}), tags peeled. */
3095
+ private async resolveCommitNames(
3096
+ names: string[],
3097
+ known?: Map<ObjectId, string>,
3098
+ ): Promise<Map<string, ObjectId | undefined>> {
3099
+ const { objects } = await this.resolveObjectNames(names, known);
3100
+ const out = new Map<string, ObjectId | undefined>();
3101
+ for (const [name, named] of objects) {
3102
+ out.set(name, !named ? undefined : named.commit ? named.id : await this.commitOf(named.id));
3103
+ }
3104
+ return out;
3105
+ }
3106
+
3107
+ /**
3108
+ * The objects todo names stand for, resolved at once as git's repo_get_oid (get_oid_1)
3109
+ * resolves each: a full id the store holds is that object; a ref by git's rules
3110
+ * (get_oid_basic) before an abbreviation, with git's `warning: refname '<name>' is
3111
+ * ambiguous.` when the abbreviation names one object as well (the refs listed once, a
3112
+ * ref looked up only for a name some ref could have); an abbreviation as long as one of
3113
+ * `known` that starts the same is that commit (unique in the store, as it was written);
3114
+ * the other abbreviations looked up in the store together (one listing of its ids where
3115
+ * it cannot list by prefix), a prefix of several objects refused as git's get_short_oid
3116
+ * refuses it (unless core.disambiguate tells them apart). `commit` marks the ids known to
3117
+ * be commits.
3118
+ */
3119
+ private async resolveObjectNames(
3120
+ names: string[],
3121
+ known?: Map<ObjectId, string>,
3122
+ ): Promise<{
3123
+ objects: Map<string, { id: ObjectId; commit?: boolean } | undefined>;
3124
+ warnings: string[];
3125
+ }> {
3126
+ const objects = new Map<string, { id: ObjectId; commit?: boolean } | undefined>();
3127
+ const warnings: string[] = [];
3128
+ const pending: string[] = [];
3129
+ const viaRef: string[] = [];
3130
+ let refNames: Set<string> | undefined | null = null;
3131
+ for (const name of new Set(names)) {
3132
+ if (!/^[0-9a-f]{4,39}$/i.test(name)) {
3133
+ objects.set(name, await this.objectNamed(name));
3134
+ continue;
3135
+ }
3136
+ if (refNames === null) refNames = await this.refShortNames();
3137
+ if (!refNames || refNames.has(name)) {
3138
+ const ids = await this.refsNamed(name, false);
3139
+ if (ids[0]) {
3140
+ objects.set(name, { id: ids[0] });
3141
+ if (ids.length > 1) warnings.push(`warning: refname '${name}' is ambiguous.`);
3142
+ else viaRef.push(name);
3143
+ continue;
3144
+ }
3145
+ }
3146
+ const fast = known ? knownPrefix(name.toLowerCase(), known) : undefined;
3147
+ if (fast) objects.set(name, { id: fast, commit: true });
3148
+ else pending.push(name);
3149
+ }
3150
+ if (pending.length === 0 && viaRef.length === 0) return { objects, warnings };
3151
+ const candidates = await this.objectsWithPrefixes(
3152
+ [...pending, ...viaRef].map((name) => name.toLowerCase()),
3153
+ );
3154
+ // get_oid_basic: a ref that an abbreviation of one object (get_short_oid, quietly, no
3155
+ // hint) shares
3156
+ for (const name of viaRef) {
3157
+ if (candidates?.get(name.toLowerCase())?.length === 1) {
3158
+ warnings.push(`warning: refname '${name}' is ambiguous.`);
3159
+ }
3160
+ }
3161
+ for (const name of pending) {
3162
+ const found = candidates?.get(name.toLowerCase());
3163
+ if (!found) {
3164
+ const id = await this.commitNamed(name);
3165
+ objects.set(name, id ? { id, commit: true } : undefined);
3166
+ } else if (found.length === 0) objects.set(name, undefined);
3167
+ else if (found.length === 1) objects.set(name, { id: found[0] as ObjectId });
3168
+ else {
3169
+ // ambiguous: only core.disambiguate can pick one (the revision resolver applies it)
3170
+ const id = await this.resolveRevision(name).catch(() => undefined);
3171
+ objects.set(name, id ? { id } : undefined);
3172
+ }
3173
+ }
3174
+ return { objects, warnings };
3175
+ }
3176
+
3177
+ /**
3178
+ * A name that is no abbreviation, as get_oid_basic resolves it: a full id the store holds
3179
+ * (of any object), else a ref by git's rules; undefined if neither.
3180
+ */
3181
+ private async objectNamed(name: string): Promise<{ id: ObjectId; commit?: boolean } | undefined> {
3182
+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(name)) {
3183
+ const id = name.toLowerCase();
3184
+ if (await this.commits.has(id).catch(() => false)) return { id, commit: true };
3185
+ if (await this.revisionResolver().objectType(id)) return { id };
3186
+ }
3187
+ const ids = await this.refsNamed(name, true);
3188
+ return ids[0] ? { id: ids[0] } : undefined;
3189
+ }
3190
+
3191
+ /**
3192
+ * The objects of the refs a name stands for by git's ref_rev_parse_rules (as written,
3193
+ * under refs/, a tag, a branch, a remote, a remote's HEAD), in that order; the name as
3194
+ * written only with `asWritten` (a lowercase abbreviation is no root ref).
3195
+ */
3196
+ private async refsNamed(name: string, asWritten: boolean): Promise<ObjectId[]> {
3197
+ const out: ObjectId[] = [];
3198
+ const candidates = [
3199
+ ...(asWritten ? [name] : []),
3200
+ `refs/${name}`,
3201
+ `refs/tags/${name}`,
3202
+ `refs/heads/${name}`,
3203
+ `refs/remotes/${name}`,
3204
+ `refs/remotes/${name}/HEAD`,
3205
+ ];
3206
+ for (const candidate of candidates) {
3207
+ const ref = await this.refsStore.resolve(candidate).catch(() => undefined);
3208
+ if (ref?.objectId) out.push(ref.objectId);
3209
+ }
3210
+ return out;
3211
+ }
3212
+
3213
+ /**
3214
+ * The names refs/ refs answer to under git's rules (each without `refs/`, `refs/tags/`,
3215
+ * `refs/heads/`, `refs/remotes/`, and a remote's `HEAD`), from one listing; undefined
3216
+ * where the refs cannot be listed.
3217
+ */
3218
+ private async refShortNames(): Promise<Set<string> | undefined> {
3219
+ const names = new Set<string>();
3220
+ try {
3221
+ for await (const entry of this.refsStore.list("refs/")) {
3222
+ const full = entry.name;
3223
+ names.add(full.slice("refs/".length));
3224
+ for (const prefix of ["refs/tags/", "refs/heads/", "refs/remotes/"]) {
3225
+ if (full.startsWith(prefix)) names.add(full.slice(prefix.length));
3226
+ }
3227
+ if (full.startsWith("refs/remotes/") && full.endsWith("/HEAD")) {
3228
+ names.add(full.slice("refs/remotes/".length, -"/HEAD".length));
3229
+ }
3230
+ }
3231
+ } catch {
3232
+ return undefined;
3233
+ }
3234
+ return names;
3235
+ }
3236
+
3237
+ /** The commit an object is (a tag peeled, as lookup_commit_reference), else undefined. */
3238
+ private async commitOf(id: ObjectId): Promise<ObjectId | undefined> {
3239
+ const peeled = await this.peelToCommit(id);
3240
+ return (await this.commits.has(peeled).catch(() => false)) ? peeled : undefined;
3241
+ }
3242
+
3243
+ /**
3244
+ * The stored ids starting with each lowercase prefix: by prefix where the store can list
3245
+ * so, else one listing of every id for all of them; undefined without an object store.
3246
+ */
3247
+ private async objectsWithPrefixes(
3248
+ prefixes: string[],
3249
+ ): Promise<Map<string, ObjectId[]> | undefined> {
3250
+ const objects = this.workingCopy.history?.objects;
3251
+ if (!objects) return undefined;
3252
+ const found = new Map(prefixes.map((prefix) => [prefix, new Set<ObjectId>()]));
3253
+ try {
3254
+ if (objects.listPrefix) {
3255
+ for (const [prefix, ids] of found) {
3256
+ for await (const id of listObjectsWithPrefix(objects, prefix)) ids.add(id);
3257
+ }
3258
+ } else {
3259
+ const lengths = [...new Set(prefixes.map((prefix) => prefix.length))];
3260
+ for await (const id of objects.list()) {
3261
+ for (const length of lengths) found.get(id.slice(0, length))?.add(id);
3262
+ }
3263
+ }
3264
+ } catch {
3265
+ return undefined;
3266
+ }
3267
+ return new Map([...found].map(([prefix, ids]) => [prefix, [...ids]]));
3268
+ }
3269
+
3270
+ /** A commit by name: an id (abbreviated), a ref, a branch, a tag; undefined if none. */
3271
+ private async commitNamed(name: string): Promise<ObjectId | undefined> {
3272
+ if (/^[0-9a-f]{4,64}$/i.test(name)) {
3273
+ try {
3274
+ return await expandCommitId(
3275
+ {
3276
+ commits: this.commits,
3277
+ refs: this.refsStore,
3278
+ state: new OperationState(this.workingCopy.checkout, this.refsStore),
3279
+ },
3280
+ name.toLowerCase(),
3281
+ );
3282
+ } catch {
3283
+ // not an abbreviation of one commit: maybe a ref
3284
+ }
3285
+ }
3286
+ return this.refNamed(name);
3287
+ }
3288
+
3289
+ /** A commit by ref name (as given, under refs/, a tag, a branch); undefined if none. */
3290
+ private async refNamed(name: string): Promise<ObjectId | undefined> {
3291
+ for (const candidate of [name, `refs/${name}`, `refs/tags/${name}`, `refs/heads/${name}`]) {
3292
+ const ref = await this.refsStore.resolve(candidate).catch(() => undefined);
3293
+ if (ref?.objectId) {
3294
+ const id = await this.peelToCommit(ref.objectId);
3295
+ if (await this.commits.has(id).catch(() => false)) return id;
3296
+ }
3297
+ }
3298
+ return undefined;
3299
+ }
3300
+
3301
+ /**
3302
+ * An `--autosquash` target that is one word (todo_list_rearrange_squash's
3303
+ * lookup_commit_reference_by_name, whose commit counts only when it is in the list): the
3304
+ * list's own commits matched by id first; a hex word no commit of the list starts with can
3305
+ * only name one of them as a ref.
3306
+ */
3307
+ private async autosquashTarget(
3308
+ name: string,
3309
+ known: Map<ObjectId, string>,
3310
+ ): Promise<ObjectId | undefined> {
3311
+ if (!/^[0-9a-f]{4,64}$/i.test(name)) return this.commitNamed(name);
3312
+ const lower = name.toLowerCase();
3313
+ if (lower.length >= 40) return known.has(lower) ? lower : this.refNamed(name);
3314
+ const fast = knownPrefix(lower, known);
3315
+ if (fast) return fast;
3316
+ for (const id of known.keys()) {
3317
+ // lookup_commit_reference_by_name: an abbreviation read as a committish
3318
+ if (id.startsWith(lower)) return this.commitNamed(name);
3319
+ }
3320
+ return this.refNamed(name);
3321
+ }
3322
+
3323
+ /** is_original_commit_empty: the commit changes nothing against its parent (or none). */
3324
+ private async originallyEmpty(id: ObjectId): Promise<boolean> {
3325
+ const commit = await this.loadCommit(id);
3326
+ if (!commit) return false;
3327
+ const parentTree = commit.parents[0]
3328
+ ? (await this.loadCommit(commit.parents[0]))?.tree
3329
+ : EMPTY_TREE_ID;
3330
+ return commit.tree === parentTree;
3331
+ }
3332
+
3333
+ /** rebase.missingCommitsCheck (ignore, warn, error; anything else warned about). */
3334
+ private missingCommitsCheckLevel(output: string[]): "ignore" | "warn" | "error" {
3335
+ const value = configValue(this.workingCopy, "rebase.missingCommitsCheck");
3336
+ if (value === undefined || value.toLowerCase() === "ignore") return "ignore";
3337
+ if (value.toLowerCase() === "warn") return "warn";
3338
+ if (value.toLowerCase() === "error") return "error";
3339
+ output.push(
3340
+ `warning: unrecognized setting ${value} for option rebase.missingCommitsCheck. Ignoring.`,
3341
+ );
3342
+ return "ignore";
3343
+ }
3344
+
3345
+ /**
3346
+ * rebase-interactive.c's todo_list_check: the commits of the list before editing that the
3347
+ * edited one dropped (newer to older), with git's warning; nothing when none or ignored.
3348
+ */
3349
+ private async missingCommits(
3350
+ before: TodoItem[],
3351
+ after: TodoItem[],
3352
+ level: "ignore" | "warn" | "error",
3353
+ ): Promise<string[]> {
3354
+ if (level === "ignore") return [];
617
3355
  const seen = new Set<ObjectId>();
3356
+ for (const item of after) if (takesCommit(item)) seen.add(item.id);
3357
+ const missing: string[] = [];
3358
+ for (let i = before.length - 1; i >= 0; i--) {
3359
+ const item = before[i] as TodoItem;
3360
+ if (!takesCommit(item) || seen.has(item.id)) continue;
3361
+ missing.push(` - ${await this.abbreviateObjectId(item.id)} ${item.rest ?? ""}`);
3362
+ seen.add(item.id);
3363
+ }
3364
+ if (missing.length === 0) return [];
3365
+ return [
3366
+ "Warning: some commits may have been dropped accidentally.",
3367
+ "Dropped commits (newer to older):",
3368
+ ...missing,
3369
+ 'To avoid this message, use "drop" to explicitly remove a commit.',
3370
+ "",
3371
+ "Use 'git config rebase.missingCommitsCheck' to change the level of warnings.",
3372
+ "The possible behaviours are: ignore, warn, error.",
3373
+ "",
3374
+ ...EDIT_TODO_ADVICE,
3375
+ ];
3376
+ }
618
3377
 
619
- // Get all commits reachable from upstream
620
- const upstreamCommits = new Set<ObjectId>();
621
- for await (const commitId of this.commits.walkAncestry([upstream])) {
622
- upstreamCommits.add(commitId);
3378
+ /** The abbreviated ids of the list's commits (TODO_LIST_SHORTEN_IDS), in one batch. */
3379
+ private async shortIds(items: TodoItem[]): Promise<Map<ObjectId, string>> {
3380
+ const ids = [...new Set(items.filter(takesCommit).map((item) => item.id))];
3381
+ const lengths = await this.idAbbreviator().lengths(ids);
3382
+ return new Map(ids.map((id) => [id, id.slice(0, lengths.get(id) ?? 7)]));
3383
+ }
3384
+
3385
+ /**
3386
+ * launch_sequence_editor: the interactive handler edits the list (editTodo, then the
3387
+ * steps of prepareSteps); without one the list is kept.
3388
+ */
3389
+ private async runSequenceEditor(
3390
+ text: string,
3391
+ /** The abbreviations the list was written with (see {@link resolveCommitNames}) */
3392
+ known?: Map<ObjectId, string>,
3393
+ ): Promise<string> {
3394
+ const handler = this.interactiveHandler;
3395
+ let out = text;
3396
+ if (handler?.editTodo) out = await handler.editTodo(out);
3397
+ if (handler?.prepareSteps) {
3398
+ const comment = commentPrefixOf(this.workingCopy);
3399
+ const items = parseTodo(stripspace(out, comment), comment).items.filter(
3400
+ (item) => item.action !== RebaseAction.COMMENT,
3401
+ );
3402
+ const ids = await this.resolveCommitNames(
3403
+ items.filter(takesCommit).map((item) => item.id),
3404
+ known,
3405
+ );
3406
+ const steps: RebaseTodoLine[] = [];
3407
+ for (const item of items) {
3408
+ if (takesCommit(item)) {
3409
+ const id = ids.get(item.id);
3410
+ steps.push({
3411
+ action: item.action,
3412
+ commit: item.id,
3413
+ shortMessage: subjectOf((id ? await this.loadCommit(id) : undefined)?.message ?? ""),
3414
+ ...(item.replaceMessage ? { fixupFlag: "C" as const } : {}),
3415
+ ...(item.editMessage && item.action === RebaseAction.FIXUP
3416
+ ? { fixupFlag: "c" as const }
3417
+ : {}),
3418
+ });
3419
+ } else
3420
+ steps.push({
3421
+ action: item.action,
3422
+ commit: "",
3423
+ shortMessage: "",
3424
+ argument: item.rest ?? "",
3425
+ });
3426
+ }
3427
+ try {
3428
+ handler.prepareSteps(steps);
3429
+ } catch (error) {
3430
+ throw new HandlerFailure("prepareSteps", error);
3431
+ }
3432
+ out = "";
3433
+ for (const step of steps) {
3434
+ if (step.action === RebaseAction.COMMENT) continue;
3435
+ if (!step.commit) {
3436
+ out += `${step.action}${step.argument ? ` ${step.argument}` : ""}\n`;
3437
+ continue;
3438
+ }
3439
+ const original = items.find(
3440
+ (item) =>
3441
+ takesCommit(item) &&
3442
+ (item.id.startsWith(step.commit) || step.commit.startsWith(item.id)),
3443
+ );
3444
+ const flag = step.fixupFlag ? ` -${step.fixupFlag}` : "";
3445
+ const rest = original?.rest ?? (step.shortMessage ? `# ${step.shortMessage}` : "");
3446
+ out += `${step.action}${flag} ${step.commit}${rest ? ` ${rest}` : ""}\n`;
3447
+ }
623
3448
  }
3449
+ return out;
3450
+ }
624
3451
 
625
- // Walk from head and collect commits not in upstream
626
- for await (const commitId of this.commits.walkAncestry([head])) {
627
- if (upstreamCommits.has(commitId)) {
3452
+ /**
3453
+ * `git rebase --edit-todo` (edit_todo_file): the rest of the list edited by the
3454
+ * interactive handler (git's help for an ongoing rebase after it), checked as git checks
3455
+ * it, written back with the full ids.
3456
+ */
3457
+ private async editTodo(state: OperationState): Promise<RebaseResult> {
3458
+ if (!(await this.inProgress(state))) throw new NoRebaseInProgressError();
3459
+ const comment = commentPrefixOf(this.workingCopy);
3460
+ const abbreviate = configBool(this.workingCopy, "rebase.abbreviateCommands", false);
3461
+ const output: string[] = [];
3462
+ const current = stripspace((await state.read(`${DIR}/git-rebase-todo`)) ?? "", comment);
3463
+ const fixupOkay = await state.exists(`${DIR}/done`);
3464
+ const old = await this.resolveTodo(parseTodo(current, comment, fixupOkay).items, {
3465
+ fixupOkay,
3466
+ });
3467
+ const incorrect = old.errors.length > 0 || (await state.exists(`${DIR}/dropped`));
3468
+ const level = this.missingCommitsCheckLevel(output);
3469
+ const help = todoHelp(countTodoCommands(old.items), comment, undefined, level === "error");
3470
+ const shorts = await this.shortIds(old.items);
3471
+ const text = `${formatTodo(old.items, { abbreviate, idOf: (id) => shorts.get(id) ?? id })}${help}`;
3472
+ await state.write(`${DIR}/git-rebase-todo`, text);
3473
+ if (!incorrect) {
3474
+ await state.write(
3475
+ `${DIR}/git-rebase-todo.backup`,
3476
+ `${formatTodo(old.items, { abbreviate })}${help}`,
3477
+ );
3478
+ }
3479
+ let edited: string;
3480
+ try {
3481
+ edited = await this.runSequenceEditor(text, shorts);
3482
+ } catch (error) {
3483
+ // edit_todo_list's -2: the list stays as written for the editor
3484
+ return { status: RebaseStatus.FAILED, message: sequenceEditorFailure(error), output };
3485
+ }
3486
+ await state.write(`${DIR}/git-rebase-todo`, edited);
3487
+ // the names read back against the list as it was before the edit
3488
+ const parsed = await this.resolveTodo(
3489
+ parseTodo(stripspace(edited, comment), comment, fixupOkay).items,
3490
+ { known: shorts, fixupOkay },
3491
+ );
3492
+ output.push(...parsed.warnings);
3493
+ if (parsed.errors.length > 0) {
3494
+ return {
3495
+ status: RebaseStatus.FAILED,
3496
+ message: [...parsed.errors, ...EDIT_TODO_ADVICE].join("\n"),
3497
+ output,
3498
+ };
3499
+ }
3500
+ let reference = old.items;
3501
+ if (incorrect) {
3502
+ reference = (
3503
+ await this.resolveTodo(
3504
+ parseTodo((await state.read(`${DIR}/git-rebase-todo.backup`)) ?? "", comment).items,
3505
+ )
3506
+ ).items;
3507
+ }
3508
+ const missing = await this.missingCommits(reference, parsed.items, level);
3509
+ if (missing.length > 0 && level === "error") {
3510
+ await state.write(`${DIR}/dropped`, "");
3511
+ return { status: RebaseStatus.FAILED, message: missing.join("\n"), output };
3512
+ }
3513
+ output.push(...missing);
3514
+ // edit_todo_list unlinks it only when `incorrect` is positive: the list read before the
3515
+ // edit parsed (todo_list_parse_insn_buffer's -1 or'ed with the file's 1 stays negative)
3516
+ if (incorrect && old.errors.length === 0) await state.remove(`${DIR}/dropped`);
3517
+ await this.filterUpdateRefs(state, parsed.items);
3518
+ await state.write(
3519
+ `${DIR}/git-rebase-todo`,
3520
+ formatTodo(
3521
+ parsed.items.map(({ line: _, ...item }) => item as TodoItem),
3522
+ { abbreviate },
3523
+ ),
3524
+ );
3525
+ return { status: RebaseStatus.OK, output };
3526
+ }
3527
+
3528
+ /** `rebase-merge/update-refs`: ref, its value at the start, the value to give it. */
3529
+ private async readUpdateRefs(state: OperationState): Promise<UpdateRefRecord[]> {
3530
+ const lines = ((await state.read(`${DIR}/update-refs`)) ?? "").split("\n");
3531
+ const out: UpdateRefRecord[] = [];
3532
+ for (let k = 0; k + 2 < lines.length; k += 3) {
3533
+ out.push({
3534
+ ref: lines[k] as string,
3535
+ before: lines[k + 1] as string,
3536
+ after: lines[k + 2] as string,
3537
+ });
3538
+ }
3539
+ return out;
3540
+ }
3541
+
3542
+ /** write_update_refs_state: the records sorted by ref; no file when there are none. */
3543
+ private async writeUpdateRefs(state: OperationState, records: UpdateRefRecord[]): Promise<void> {
3544
+ if (records.length === 0) {
3545
+ await state.remove(`${DIR}/update-refs`);
3546
+ return;
3547
+ }
3548
+ const sorted = [...records].sort((a, b) => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
3549
+ await state.write(
3550
+ `${DIR}/update-refs`,
3551
+ sorted.map((r) => `${r.ref}\n${r.before}\n${r.after}\n`).join(""),
3552
+ );
3553
+ }
3554
+
3555
+ /**
3556
+ * todo_list_add_update_ref_commands (`--update-refs`): after each command with a commit,
3557
+ * an `update-ref <branch>` for each other branch at that commit (the last in name order
3558
+ * first, as git's decorations list them); a branch checked out in another worktree gets a
3559
+ * comment instead. The records written to `rebase-merge/update-refs`.
3560
+ */
3561
+ private async addUpdateRefCommands(
3562
+ state: OperationState,
3563
+ items: TodoItem[],
3564
+ comment: string,
3565
+ ): Promise<TodoItem[]> {
3566
+ const headRef = await this.refsStore.get("HEAD");
3567
+ const current = headRef && isSymbolicRef(headRef) ? headRef.target : undefined;
3568
+ const branches = new Map<ObjectId, string[]>();
3569
+ const names: string[] = [];
3570
+ for await (const ref of this.refsStore.list("refs/heads/")) {
3571
+ if (ref.name.startsWith("refs/heads/")) names.push(ref.name);
3572
+ }
3573
+ names.sort();
3574
+ const values = new Map<string, ObjectId>();
3575
+ for (const name of names) {
3576
+ const value = (await this.refsStore.resolve(name).catch(() => undefined))?.objectId;
3577
+ if (!value) continue;
3578
+ values.set(name, value);
3579
+ const id = await this.peelToCommit(value);
3580
+ branches.set(id, [name, ...(branches.get(id) ?? [])]);
3581
+ }
3582
+ const checkedOut = new Map<string, string>();
3583
+ const worktrees = this.workingCopy.worktrees;
3584
+ if (worktrees) {
3585
+ for (const wt of await worktrees.list().catch(() => [])) {
3586
+ for (const name of names) {
3587
+ if (!checkedOut.has(name) && usesBranch(wt, name)) checkedOut.set(name, wt.path);
3588
+ }
3589
+ }
3590
+ }
3591
+ const records: UpdateRefRecord[] = [];
3592
+ const out: TodoItem[] = [];
3593
+ for (const item of items) {
3594
+ out.push(item);
3595
+ if (!item.id || item.action === RebaseAction.COMMENT) continue;
3596
+ for (const name of branches.get(item.id) ?? []) {
3597
+ if (name === current) continue;
3598
+ const path = checkedOut.get(name);
3599
+ if (path !== undefined) {
3600
+ out.push({
3601
+ action: RebaseAction.COMMENT,
3602
+ id: "",
3603
+ rest: `${comment} Ref ${name} checked out at '${path}'`,
3604
+ blankAfter: true,
3605
+ });
3606
+ } else {
3607
+ out.push({ action: RebaseAction.UPDATE_REF, id: "", rest: name, blankAfter: true });
3608
+ if (!records.some((r) => r.ref === name)) {
3609
+ records.push({ ref: name, before: values.get(name) ?? ZERO_ID, after: ZERO_ID });
3610
+ }
3611
+ }
3612
+ }
3613
+ }
3614
+ await this.writeUpdateRefs(state, records);
3615
+ return out;
3616
+ }
3617
+
3618
+ /**
3619
+ * todo_list_filter_update_refs: the records of refs the edited list no longer updates (and
3620
+ * not updated yet) dropped, the refs it newly names added.
3621
+ */
3622
+ private async filterUpdateRefs(state: OperationState, items: TodoItem[]): Promise<void> {
3623
+ const records = await this.readUpdateRefs(state);
3624
+ const named = items
3625
+ .filter((item) => item.action === RebaseAction.UPDATE_REF && !item.invalid)
3626
+ .map((item) => item.rest ?? "");
3627
+ let updated = false;
3628
+ const kept = records.filter((r) => {
3629
+ const keep = r.after !== ZERO_ID || named.includes(r.ref);
3630
+ if (!keep) updated = true;
3631
+ return keep;
3632
+ });
3633
+ for (const ref of named) {
3634
+ if (!kept.some((r) => r.ref === ref)) {
3635
+ const value = (await this.refsStore.resolve(ref).catch(() => undefined))?.objectId;
3636
+ kept.push({ ref, before: value ?? ZERO_ID, after: ZERO_ID });
3637
+ updated = true;
3638
+ }
3639
+ }
3640
+ if (updated) await this.writeUpdateRefs(state, kept);
3641
+ }
3642
+
3643
+ /** do_update_ref: the ref's record takes HEAD. */
3644
+ private async updateRefRecord(state: OperationState, ref: string): Promise<void> {
3645
+ const records = await this.readUpdateRefs(state);
3646
+ const head = await this.resolveHead();
3647
+ for (const record of records) {
3648
+ if (record.ref === ref) {
3649
+ record.after = head;
628
3650
  break;
629
3651
  }
630
- if (!seen.has(commitId)) {
631
- seen.add(commitId);
632
- commits.push(commitId);
3652
+ }
3653
+ await this.writeUpdateRefs(state, records);
3654
+ }
3655
+
3656
+ /**
3657
+ * do_update_refs: each recorded ref moved to its new value if it still has its old one
3658
+ * (`rewritten during rebase`), with git's `Updated the following refs with --update-refs:`.
3659
+ */
3660
+ private async doUpdateRefs(state: OperationState, output: string[]): Promise<void> {
3661
+ const records = await this.readUpdateRefs(state);
3662
+ const updated: string[] = [];
3663
+ const failed: string[] = [];
3664
+ for (const record of records) {
3665
+ const value = (await this.refsStore.resolve(record.ref).catch(() => undefined))?.objectId;
3666
+ if ((value ?? ZERO_ID) !== record.before || record.after === ZERO_ID) {
3667
+ failed.push(record.ref);
3668
+ continue;
3669
+ }
3670
+ await this.refsStore.set(
3671
+ record.ref,
3672
+ record.after,
3673
+ this.reflogLine("rewritten during rebase", this.committer),
3674
+ );
3675
+ updated.push(record.ref);
3676
+ }
3677
+ if (updated.length + failed.length === 0) return;
3678
+ output.push("Updated the following refs with --update-refs:", ...updated.map((r) => `\t${r}`));
3679
+ if (failed.length > 0) {
3680
+ output.push(
3681
+ "Failed to update the following refs with --update-refs:",
3682
+ ...failed.map((r) => `\t${r}`),
3683
+ );
3684
+ }
3685
+ }
3686
+
3687
+ /**
3688
+ * The text after a pick's id, as git 2.5x's sequencer_make_script writes it: the commit
3689
+ * through `rebase.instructionFormat` (default `# %s`; a format that does not start with
3690
+ * `#` gets `# ` before it), `%h` unabbreviated (its pretty context has abbrev 0), trailing
3691
+ * blanks dropped.
3692
+ */
3693
+ private async instructionText(id: ObjectId): Promise<string> {
3694
+ let format = configValue(this.workingCopy, "rebase.instructionFormat") ?? "";
3695
+ if (format === "") format = "# %s";
3696
+ if (!format.startsWith("#")) format = `# ${format}`;
3697
+ if (format === "# %s") {
3698
+ let subject = this.subjects.get(id);
3699
+ if (subject === undefined) {
3700
+ subject = subjectOf((await this.commits.load(id))?.message ?? "");
3701
+ this.subjects.set(id, subject);
633
3702
  }
3703
+ return `# ${subject}`;
634
3704
  }
3705
+ const commit = await this.commits.load(id);
3706
+ if (!commit) return format;
3707
+ // %d and friends: the refs decorate the commits (load_ref_decorations, no filter)
3708
+ if (this.decorations === undefined && /%[-+ ]?(?:[dD]|\(decorate)/.test(format)) {
3709
+ this.decorations = await this.refDecorations();
3710
+ }
3711
+ // the list goes through the todo editing's stripspace: no trailing blanks
3712
+ const text = await formatCommitPretty(format, commit, id, {
3713
+ now: this.clock(),
3714
+ ...(this.decorations ? { decorations: this.decorations } : {}),
3715
+ ...(format.includes("%(trailers") ? { trailers: trailerConfigOf(this.workingCopy) } : {}),
3716
+ ...(format.includes("%(describe") ? { describe: this.describer() } : {}),
3717
+ });
3718
+ return text.replace(/[ \t]+$/, "");
3719
+ }
635
3720
 
636
- // Reverse to get oldest first
637
- return commits.reverse();
3721
+ /** `%(describe)` of rebase.instructionFormat: git describe over this repository's tags. */
3722
+ private describer(): (id: ObjectId, options: DescribeOptions) => Promise<string> {
3723
+ const abbreviator = createIdAbbreviator(this._workingCopy);
3724
+ const tags = this.tagsStore;
3725
+ return createDescriber({
3726
+ refs: this.refsStore,
3727
+ ...(tags ? { tags } : {}),
3728
+ commits: this.commits,
3729
+ abbreviate: async (id, length) => {
3730
+ if (length === 0) return id;
3731
+ const lengths = await abbreviator.lengths([id], length);
3732
+ return id.slice(0, lengths.get(id) ?? 7);
3733
+ },
3734
+ });
638
3735
  }
639
3736
 
640
3737
  /**
641
- * Check if commit A is an ancestor of commit B.
3738
+ * The decorations git's sequencer shows for `%d` (load_ref_decorations without a filter):
3739
+ * every ref, HEAD, the grafted and shallow commits, the objects replace refs replace.
642
3740
  */
643
- private async isAncestor(a: ObjectId, b: ObjectId): Promise<boolean> {
644
- if (a === b) return true;
3741
+ private async refDecorations(): Promise<RefDecorations> {
3742
+ const replacements = await this.objectReplacements();
3743
+ const shallow = (await this.refsStore.getShallow?.().catch(() => undefined)) ?? [];
3744
+ const environment = hostEnvironmentOf(this._workingCopy);
3745
+ const objects = this._workingCopy.history?.objects;
3746
+ const tags = this.tagsStore;
3747
+ return loadRefDecorations({
3748
+ refs: this.refsStore,
3749
+ ...(tags ? { tags } : {}),
3750
+ ...(environment?.replaceRefBase !== undefined
3751
+ ? { replaceRefBase: environment.replaceRefBase }
3752
+ : {}),
3753
+ useReplaceRefs: this.useReplaceRefs(),
3754
+ grafted: new Set([...(replacements?.grafts.keys() ?? []), ...shallow]),
3755
+ ...(objects ? { hasObject: (id: ObjectId) => objects.has(id) } : {}),
3756
+ onWarning: (message) => this.decorationWarnings.push(message),
3757
+ });
3758
+ }
3759
+
3760
+ /**
3761
+ * The commits of `head` not in `upstream`, merges dropped, oldest first: git's
3762
+ * `rev-list --reverse --topo-order --no-merges upstream..head` as its todo list is made
3763
+ * (`sort_in_topological_order` in graph order: a commit once all its children are out,
3764
+ * the last parent's line first, then reversed).
3765
+ */
3766
+ private async commitsToRebase(
3767
+ head: ObjectId,
3768
+ upstream: ObjectId,
3769
+ keepMerges = false,
3770
+ ): Promise<ObjectId[]> {
3771
+ const upstreamCommits = new Set<ObjectId>();
3772
+ const walk = [upstream];
3773
+ while (walk.length > 0) {
3774
+ const id = walk.pop() as ObjectId;
3775
+ if (upstreamCommits.has(id)) continue;
3776
+ upstreamCommits.add(id);
3777
+ walk.push(...((await this.loadCommit(id))?.parents ?? []));
3778
+ }
3779
+ const parents = new Map<ObjectId, ObjectId[]>();
3780
+ const stack = [head];
3781
+ while (stack.length > 0) {
3782
+ const id = stack.pop() as ObjectId;
3783
+ if (parents.has(id) || upstreamCommits.has(id)) continue;
3784
+ const commit = await this.loadCommit(id);
3785
+ if (!commit) continue;
3786
+ parents.set(id, commit.parents);
3787
+ stack.push(...commit.parents);
3788
+ }
3789
+ // the indegree within the range (1 + the children there), as git counts it
3790
+ const indegree = new Map<ObjectId, number>();
3791
+ for (const id of parents.keys()) indegree.set(id, 1);
3792
+ for (const list of parents.values()) {
3793
+ for (const p of list) {
3794
+ const d = indegree.get(p);
3795
+ if (d) indegree.set(p, d + 1);
3796
+ }
3797
+ }
3798
+ const order: ObjectId[] = [];
3799
+ const queue: ObjectId[] = [...parents.keys()].filter((id) => indegree.get(id) === 1);
3800
+ // graph order: the queue is a stack, the tips taken in the walk's order
3801
+ queue.reverse();
3802
+ while (queue.length > 0) {
3803
+ const id = queue.pop() as ObjectId;
3804
+ for (const p of parents.get(id) ?? []) {
3805
+ const d = indegree.get(p);
3806
+ if (!d) continue;
3807
+ indegree.set(p, d - 1);
3808
+ if (d - 1 === 1) queue.push(p);
3809
+ }
3810
+ indegree.set(id, 0);
3811
+ order.push(id);
3812
+ }
3813
+ order.reverse();
3814
+ return keepMerges ? order : order.filter((id) => (parents.get(id)?.length ?? 0) <= 1);
3815
+ }
645
3816
 
646
- for await (const commitId of this.commits.walkAncestry([b])) {
647
- if (commitId === a) {
648
- return true;
3817
+ /**
3818
+ * The commits of `range` (HEAD's side of `upstream...head`) whose patch-id one of
3819
+ * upstream's side has: git's `--cherry-mark` of the todo list (merges and commits that
3820
+ * change nothing never match). As git's cherry_pick_list and patch-ids.c: upstream's side
3821
+ * ends at the merge bases (not HEAD's whole history), every commit gets the cheap id of
3822
+ * its diff's headers, and the full patch-id is computed only where those collide.
3823
+ */
3824
+ private async appliedUpstream(
3825
+ head: ObjectId,
3826
+ upstream: ObjectId,
3827
+ range: ObjectId[],
3828
+ ): Promise<Set<ObjectId>> {
3829
+ const skipped = new Set<ObjectId>();
3830
+ const left = await this.onlyReachableFrom(upstream, head);
3831
+ if (left.length === 0 || range.length === 0) return skipped;
3832
+ // each tree read once: a commit's tree is its child's parent tree
3833
+ const treeEntries = new Map<ObjectId, TreeEntry[]>();
3834
+ const trees: PatchIdTrees = {
3835
+ loadTree: async function* (this: void, id: ObjectId) {
3836
+ let entries = treeEntries.get(id);
3837
+ if (!entries) {
3838
+ entries = [];
3839
+ for await (const e of loadTree(id)) entries.push(e);
3840
+ treeEntries.set(id, entries);
3841
+ }
3842
+ yield* entries;
3843
+ },
3844
+ };
3845
+ const loadTree = (id: ObjectId) => this.trees.loadTree(id);
3846
+ const patchIdOf = async (id: ObjectId, headerOnly: boolean) => {
3847
+ const commit = await this.loadCommit(id);
3848
+ if (!commit || commit.parents.length > 1) return undefined;
3849
+ const parentTree = commit.parents[0]
3850
+ ? (await this.loadCommit(commit.parents[0]))?.tree
3851
+ : undefined;
3852
+ return patchId(trees, this.blobs, parentTree, commit.tree, { headerOnly });
3853
+ };
3854
+ const full = new Map<ObjectId, string | undefined>();
3855
+ const fullOf = async (id: ObjectId) => {
3856
+ if (!full.has(id)) full.set(id, await patchIdOf(id, false));
3857
+ return full.get(id);
3858
+ };
3859
+ // HEAD's side by header id
3860
+ const byHeader = new Map<string, ObjectId[]>();
3861
+ for (const id of range) {
3862
+ const header = await patchIdOf(id, true);
3863
+ if (!header) continue;
3864
+ const list = byHeader.get(header) ?? [];
3865
+ list.push(id);
3866
+ byHeader.set(header, list);
3867
+ }
3868
+ if (byHeader.size === 0) return skipped;
3869
+ for (const id of left) {
3870
+ const header = await patchIdOf(id, true);
3871
+ const candidates = header ? byHeader.get(header) : undefined;
3872
+ if (!candidates) continue;
3873
+ const mine = await fullOf(id);
3874
+ if (!mine) continue;
3875
+ for (const c of candidates) {
3876
+ if (!skipped.has(c) && (await fullOf(c)) === mine) skipped.add(c);
649
3877
  }
650
3878
  }
651
- return false;
3879
+ return skipped;
652
3880
  }
653
3881
 
654
3882
  /**
655
- * Update HEAD and optionally the branch it points to.
3883
+ * The commits reachable from `tip` and not from `other` (`other..tip`), merges left out,
3884
+ * without walking `other`'s whole history: revision.c's limit_list, newest commit first,
3885
+ * what `other` reaches painted uninteresting, done once every commit still queued is
3886
+ * uninteresting (and a few more, git's slop against clock skew).
656
3887
  */
657
- private async updateHead(headName: string, commitId: ObjectId): Promise<void> {
658
- if (headName.startsWith("refs/")) {
659
- // Update the branch ref
660
- await this.refsStore.set(headName, commitId);
3888
+ private async onlyReachableFrom(tip: ObjectId, other: ObjectId): Promise<ObjectId[]> {
3889
+ interface Node {
3890
+ id: ObjectId;
3891
+ time: number;
3892
+ parents?: ObjectId[];
3893
+ uninteresting: boolean;
3894
+ queued: boolean;
661
3895
  }
662
- // HEAD is symbolic, so it should follow
663
- await this.refsStore.set("HEAD", commitId);
3896
+ const nodes = new Map<ObjectId, Node>();
3897
+ const queue: Node[] = [];
3898
+ /** The interesting commits still queued */
3899
+ let interesting = 0;
3900
+ const push = async (id: ObjectId, uninteresting: boolean) => {
3901
+ const known = nodes.get(id);
3902
+ if (known) {
3903
+ if (uninteresting) markUninteresting(known);
3904
+ return;
3905
+ }
3906
+ const commit = await this.loadCommit(id);
3907
+ if (!commit) return;
3908
+ const node: Node = { id, time: commit.committer.timestamp, uninteresting, queued: true };
3909
+ nodes.set(id, node);
3910
+ if (!uninteresting) interesting++;
3911
+ // newest first, ties in the order queued (commit_list_insert_by_date)
3912
+ let k = queue.length;
3913
+ while (k > 0 && queue[k - 1].time < node.time) k--;
3914
+ queue.splice(k, 0, node);
3915
+ };
3916
+ // mark_parents_uninteresting: through the commits already walked
3917
+ const markUninteresting = (start: Node) => {
3918
+ const stack = [start];
3919
+ while (stack.length > 0) {
3920
+ const n = stack.pop() as Node;
3921
+ if (n.uninteresting && n !== start) continue;
3922
+ if (!n.uninteresting && n.queued) interesting--;
3923
+ n.uninteresting = true;
3924
+ for (const p of n.parents ?? []) {
3925
+ const pn = nodes.get(p);
3926
+ if (pn && !pn.uninteresting) stack.push(pn);
3927
+ }
3928
+ }
3929
+ };
3930
+ await push(other, true);
3931
+ await push(tip, false);
3932
+ const out: Node[] = [];
3933
+ let slop = 5;
3934
+ while (queue.length > 0) {
3935
+ const node = queue.shift() as Node;
3936
+ node.queued = false;
3937
+ if (!node.uninteresting) interesting--;
3938
+ node.parents = (await this.loadCommit(node.id))?.parents ?? [];
3939
+ if (node.uninteresting) markUninteresting(node);
3940
+ else out.push(node);
3941
+ for (const p of node.parents) await push(p, node.uninteresting);
3942
+ if (interesting === 0) {
3943
+ if (--slop <= 0) break;
3944
+ } else slop = 5;
3945
+ }
3946
+ return out.filter((n) => !n.uninteresting && (n.parents?.length ?? 0) <= 1).map((n) => n.id);
3947
+ }
3948
+
3949
+ /** A commit, read once for the walks that pick the todo list. */
3950
+ private async loadCommit(id: ObjectId): Promise<Commit | undefined> {
3951
+ let commit = this.loadedCommits.get(id);
3952
+ if (!commit) {
3953
+ commit = await this.commits.load(id);
3954
+ if (commit) this.loadedCommits.set(id, commit);
3955
+ }
3956
+ return commit;
3957
+ }
3958
+
3959
+ /**
3960
+ * builtin/rebase.c's can_fast_forward for `git rebase <upstream>` (onto the upstream, no
3961
+ * fork point, no --keep-base): HEAD and upstream have one merge base, upstream itself, and
3962
+ * the first-parent line from HEAD down to it has no merge (is_linear_history). Upstream
3963
+ * in HEAD's history is that one merge base.
3964
+ */
3965
+ private async canFastForward(onto: ObjectId, head: ObjectId): Promise<boolean> {
3966
+ if (!(await this.isAncestor(onto, head))) return false;
3967
+ let id: ObjectId | undefined = head;
3968
+ while (id !== undefined && id !== onto) {
3969
+ const parents: ObjectId[] = (await this.loadCommit(id))?.parents ?? [];
3970
+ if (parents.length > 1) return false;
3971
+ id = parents[0];
3972
+ }
3973
+ return true;
3974
+ }
3975
+
3976
+ private async isAncestor(a: ObjectId, b: ObjectId): Promise<boolean> {
3977
+ // the store's walk: commit-graph generations cut it short
3978
+ return this.commits.isAncestor(a, b);
3979
+ }
3980
+ }
3981
+
3982
+ /** The commands in a todo or done list (comments and blank lines not counted). */
3983
+ function countCommands(text: string): number {
3984
+ return text.split("\n").filter((l) => l.trim() !== "" && !l.trim().startsWith("#")).length;
3985
+ }
3986
+
3987
+ /** git's advice where a todo command could not run and was put back (`rescheduled_advice`). */
3988
+ function rescheduledAdvice(line: string): string {
3989
+ return [
3990
+ "hint: Could not execute the todo command",
3991
+ "hint:",
3992
+ `hint: ${line}`,
3993
+ "hint:",
3994
+ "hint: It has been rescheduled; To edit the command before continuing, please",
3995
+ "hint: edit the todo list first:",
3996
+ "hint:",
3997
+ "hint: git rebase --edit-todo",
3998
+ "hint: git rebase --continue",
3999
+ ].join("\n");
4000
+ }
4001
+
4002
+ /** The author of git's `author-script` (`GIT_AUTHOR_NAME='...'`, ...). */
4003
+ function parseAuthorScript(text: string): PersonIdent | undefined {
4004
+ const values: Record<string, string> = {};
4005
+ for (const line of text.split("\n")) {
4006
+ const match = /^(GIT_AUTHOR_\w+)='(.*)'$/.exec(line);
4007
+ if (match) values[match[1]] = match[2].replaceAll("'\\''", "'");
4008
+ }
4009
+ const date = /^@?(\d+)\s+([+-]\d{4})$/.exec(values.GIT_AUTHOR_DATE ?? "");
4010
+ if (!values.GIT_AUTHOR_NAME || !date) return undefined;
4011
+ return {
4012
+ name: values.GIT_AUTHOR_NAME,
4013
+ email: values.GIT_AUTHOR_EMAIL ?? "",
4014
+ timestamp: Number(date[1]),
4015
+ tzOffset: date[2],
4016
+ };
4017
+ }
4018
+
4019
+ /** check_merge_commit_insn: a merge where a pick-like command cannot take one. */
4020
+ function mergeCommitErrors(action: RebaseAction): string[] {
4021
+ switch (action) {
4022
+ case RebaseAction.PICK:
4023
+ return [
4024
+ "error: 'pick' does not accept merge commits",
4025
+ "hint: 'pick' does not take a merge commit. If you wanted to",
4026
+ "hint: replay the merge, use 'merge -C' on the commit.",
4027
+ 'hint: Disable this message with "git config set advice.rebaseTodoError false"',
4028
+ ];
4029
+ case RebaseAction.REWORD:
4030
+ return [
4031
+ "error: 'reword' does not accept merge commits",
4032
+ "hint: 'reword' does not take a merge commit. If you wanted to",
4033
+ "hint: replay the merge and reword the commit message, use",
4034
+ "hint: 'merge -c' on the commit",
4035
+ 'hint: Disable this message with "git config set advice.rebaseTodoError false"',
4036
+ ];
4037
+ case RebaseAction.EDIT:
4038
+ return [
4039
+ "error: 'edit' does not accept merge commits",
4040
+ "hint: 'edit' does not take a merge commit. If you wanted to",
4041
+ "hint: replay the merge, use 'merge -C' on the commit, and then",
4042
+ "hint: 'break' to give the control back to you so that you can",
4043
+ "hint: do 'git commit --amend && git rebase --continue'.",
4044
+ 'hint: Disable this message with "git config set advice.rebaseTodoError false"',
4045
+ ];
4046
+ default:
4047
+ return ["error: cannot squash merge commit into another commit"];
4048
+ }
4049
+ }
4050
+
4051
+ /**
4052
+ * A message editor (the interactive handler's modifyCommitMessage) that threw, as git commit
4053
+ * failing on its editor: the pick counts as conflicted (do_pick_commit's `res = !!res`).
4054
+ */
4055
+ function editorFailure(error: unknown): Extract<PickOutcome, { kind: "conflicts" }> {
4056
+ return {
4057
+ kind: "conflicts",
4058
+ conflicts: [],
4059
+ // git commit's line after the editor's
4060
+ lines: [
4061
+ editorProblem("modifyCommitMessage", error),
4062
+ "Please supply the message using either -m or -F option.",
4063
+ ],
4064
+ };
4065
+ }
4066
+
4067
+ /** launch_sequence_editor failing (the interactive handler's editTodo or prepareSteps threw). */
4068
+ function sequenceEditorFailure(error: unknown): string {
4069
+ return error instanceof HandlerFailure
4070
+ ? editorProblem(error.editor, error.reason)
4071
+ : editorProblem("editTodo", error);
4072
+ }
4073
+
4074
+ /**
4075
+ * editor.c's `there was a problem with the editor '<editor>'`: the editor named by the
4076
+ * interactive handler's method that threw, its reason after.
4077
+ */
4078
+ function editorProblem(editor: string, error: unknown): string {
4079
+ const reason = error instanceof Error ? error.message : String(error);
4080
+ return `error: there was a problem with the editor '${editor}': ${reason}`;
4081
+ }
4082
+
4083
+ /** An interactive handler's method that threw, named. */
4084
+ class HandlerFailure extends Error {
4085
+ constructor(
4086
+ readonly editor: string,
4087
+ readonly reason: unknown,
4088
+ ) {
4089
+ super(reason instanceof Error ? reason.message : String(reason));
4090
+ }
4091
+ }
4092
+
4093
+ /**
4094
+ * The commit of `known` whose abbreviation `prefix` extends (at least as long as it, so no
4095
+ * other stored object starts with it), else undefined.
4096
+ */
4097
+ function knownPrefix(prefix: string, known: Map<ObjectId, string>): ObjectId | undefined {
4098
+ for (const [id, short] of known) {
4099
+ if (prefix.length >= short.length && id.startsWith(prefix)) return id;
664
4100
  }
4101
+ return undefined;
665
4102
  }