@statewalker/vcs-commands 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (561) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +300 -18
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +49 -16
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +134 -0
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/comment-char-config.d.ts +35 -0
  71. package/dist/commands/comment-char-config.d.ts.map +1 -0
  72. package/dist/commands/commit-command.d.ts +311 -17
  73. package/dist/commands/commit-command.d.ts.map +1 -1
  74. package/dist/commands/core-config.d.ts +78 -1
  75. package/dist/commands/core-config.d.ts.map +1 -1
  76. package/dist/commands/date-format.d.ts +58 -0
  77. package/dist/commands/date-format.d.ts.map +1 -0
  78. package/dist/commands/default-branch.d.ts +70 -0
  79. package/dist/commands/default-branch.d.ts.map +1 -0
  80. package/dist/commands/describe-command.d.ts.map +1 -1
  81. package/dist/commands/diff-command.d.ts +377 -30
  82. package/dist/commands/diff-command.d.ts.map +1 -1
  83. package/dist/commands/diff-textconv.d.ts +40 -0
  84. package/dist/commands/diff-textconv.d.ts.map +1 -0
  85. package/dist/commands/fetch-command.d.ts +149 -10
  86. package/dist/commands/fetch-command.d.ts.map +1 -1
  87. package/dist/commands/format-patch-command.d.ts +164 -0
  88. package/dist/commands/format-patch-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  90. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-command.d.ts +227 -0
  92. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-loose.d.ts +71 -0
  94. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  96. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-object-checks.d.ts +159 -0
  98. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  99. package/dist/commands/fsck/fsck-object-table.d.ts +140 -0
  100. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  101. package/dist/commands/fsck/fsck-pack.d.ts +122 -0
  102. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  103. package/dist/commands/fsck/index.d.ts +6 -0
  104. package/dist/commands/fsck/index.d.ts.map +1 -0
  105. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  106. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  107. package/dist/commands/gc-command.d.ts +106 -39
  108. package/dist/commands/gc-command.d.ts.map +1 -1
  109. package/dist/commands/git-date.d.ts +2 -0
  110. package/dist/commands/git-date.d.ts.map +1 -0
  111. package/dist/commands/git-describe.d.ts +67 -0
  112. package/dist/commands/git-describe.d.ts.map +1 -0
  113. package/dist/commands/git-hooks.d.ts +424 -0
  114. package/dist/commands/git-hooks.d.ts.map +1 -0
  115. package/dist/commands/git-ident.d.ts +128 -0
  116. package/dist/commands/git-ident.d.ts.map +1 -0
  117. package/dist/commands/hook-command.d.ts +96 -0
  118. package/dist/commands/hook-command.d.ts.map +1 -0
  119. package/dist/commands/index-adder.d.ts +233 -0
  120. package/dist/commands/index-adder.d.ts.map +1 -0
  121. package/dist/commands/index-host.d.ts +86 -0
  122. package/dist/commands/index-host.d.ts.map +1 -0
  123. package/dist/commands/index.d.ts +56 -0
  124. package/dist/commands/index.d.ts.map +1 -1
  125. package/dist/commands/index.js +3 -2
  126. package/dist/commands/init-command.d.ts +62 -4
  127. package/dist/commands/init-command.d.ts.map +1 -1
  128. package/dist/commands/legacy-remotes.d.ts +55 -0
  129. package/dist/commands/legacy-remotes.d.ts.map +1 -0
  130. package/dist/commands/local-clone.d.ts +60 -0
  131. package/dist/commands/local-clone.d.ts.map +1 -0
  132. package/dist/commands/local-transport.d.ts +117 -0
  133. package/dist/commands/local-transport.d.ts.map +1 -0
  134. package/dist/commands/log-command.d.ts +216 -24
  135. package/dist/commands/log-command.d.ts.map +1 -1
  136. package/dist/commands/log-graph.d.ts +120 -0
  137. package/dist/commands/log-graph.d.ts.map +1 -0
  138. package/dist/commands/log-output.d.ts +323 -0
  139. package/dist/commands/log-output.d.ts.map +1 -0
  140. package/dist/commands/ls-remote-command.d.ts +23 -7
  141. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  142. package/dist/commands/mailmap.d.ts +31 -0
  143. package/dist/commands/mailmap.d.ts.map +1 -0
  144. package/dist/commands/merge-bases.d.ts +85 -0
  145. package/dist/commands/merge-bases.d.ts.map +1 -0
  146. package/dist/commands/merge-command.d.ts +221 -74
  147. package/dist/commands/merge-command.d.ts.map +1 -1
  148. package/dist/commands/merge-config.d.ts +13 -0
  149. package/dist/commands/merge-config.d.ts.map +1 -0
  150. package/dist/commands/merge-drivers.d.ts +130 -0
  151. package/dist/commands/merge-drivers.d.ts.map +1 -0
  152. package/dist/commands/merge-support.d.ts +260 -0
  153. package/dist/commands/merge-support.d.ts.map +1 -0
  154. package/dist/commands/message-cleanup.d.ts +86 -0
  155. package/dist/commands/message-cleanup.d.ts.map +1 -0
  156. package/dist/commands/mv-command.d.ts +94 -0
  157. package/dist/commands/mv-command.d.ts.map +1 -0
  158. package/dist/commands/notes-command.d.ts +256 -0
  159. package/dist/commands/notes-command.d.ts.map +1 -0
  160. package/dist/commands/notes-commands.d.ts +41 -0
  161. package/dist/commands/notes-commands.d.ts.map +1 -0
  162. package/dist/commands/notes-merge-command.d.ts +105 -0
  163. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  164. package/dist/commands/notes-support.d.ts +125 -0
  165. package/dist/commands/notes-support.d.ts.map +1 -0
  166. package/dist/commands/notes-tree.d.ts +116 -0
  167. package/dist/commands/notes-tree.d.ts.map +1 -0
  168. package/dist/commands/object-id-input.d.ts +20 -0
  169. package/dist/commands/object-id-input.d.ts.map +1 -0
  170. package/dist/commands/octopus-merge.d.ts +59 -0
  171. package/dist/commands/octopus-merge.d.ts.map +1 -0
  172. package/dist/commands/ort-merge.d.ts +126 -0
  173. package/dist/commands/ort-merge.d.ts.map +1 -0
  174. package/dist/commands/ort-recursive.d.ts +53 -0
  175. package/dist/commands/ort-recursive.d.ts.map +1 -0
  176. package/dist/commands/pack-refs-command.d.ts +20 -0
  177. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  178. package/dist/commands/patch-id.d.ts +44 -0
  179. package/dist/commands/patch-id.d.ts.map +1 -0
  180. package/dist/commands/pathspec-attributes.d.ts +64 -0
  181. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  182. package/dist/commands/pathspec.d.ts +324 -0
  183. package/dist/commands/pathspec.d.ts.map +1 -0
  184. package/dist/commands/post-index-change.d.ts +33 -0
  185. package/dist/commands/post-index-change.d.ts.map +1 -0
  186. package/dist/commands/pretty-format.d.ts +222 -0
  187. package/dist/commands/pretty-format.d.ts.map +1 -0
  188. package/dist/commands/promisor-remote.d.ts +80 -0
  189. package/dist/commands/promisor-remote.d.ts.map +1 -0
  190. package/dist/commands/pull-command.d.ts +59 -8
  191. package/dist/commands/pull-command.d.ts.map +1 -1
  192. package/dist/commands/push-command.d.ts +24 -8
  193. package/dist/commands/push-command.d.ts.map +1 -1
  194. package/dist/commands/read-tree-command.d.ts +112 -0
  195. package/dist/commands/read-tree-command.d.ts.map +1 -0
  196. package/dist/commands/rebase-command.d.ts +507 -75
  197. package/dist/commands/rebase-command.d.ts.map +1 -1
  198. package/dist/commands/rebase-todo.d.ts +130 -0
  199. package/dist/commands/rebase-todo.d.ts.map +1 -0
  200. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  201. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  202. package/dist/commands/reflog-messages.d.ts +98 -0
  203. package/dist/commands/reflog-messages.d.ts.map +1 -0
  204. package/dist/commands/remote-command.d.ts +31 -0
  205. package/dist/commands/remote-command.d.ts.map +1 -1
  206. package/dist/commands/remote-transport.d.ts +120 -0
  207. package/dist/commands/remote-transport.d.ts.map +1 -0
  208. package/dist/commands/reset-command.d.ts +161 -7
  209. package/dist/commands/reset-command.d.ts.map +1 -1
  210. package/dist/commands/restore-command.d.ts +103 -0
  211. package/dist/commands/restore-command.d.ts.map +1 -0
  212. package/dist/commands/rev-list-command.d.ts +78 -0
  213. package/dist/commands/rev-list-command.d.ts.map +1 -0
  214. package/dist/commands/rev-parse-command.d.ts +89 -0
  215. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  216. package/dist/commands/revert-command.d.ts +46 -38
  217. package/dist/commands/revert-command.d.ts.map +1 -1
  218. package/dist/commands/revision-filenames.d.ts +95 -0
  219. package/dist/commands/revision-filenames.d.ts.map +1 -0
  220. package/dist/commands/revision-range.d.ts +67 -0
  221. package/dist/commands/revision-range.d.ts.map +1 -0
  222. package/dist/commands/revision-resolver.d.ts +325 -0
  223. package/dist/commands/revision-resolver.d.ts.map +1 -0
  224. package/dist/commands/rm-command.d.ts +69 -7
  225. package/dist/commands/rm-command.d.ts.map +1 -1
  226. package/dist/commands/sequencer-pick.d.ts +191 -0
  227. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  228. package/dist/commands/sequencer-support.d.ts +125 -0
  229. package/dist/commands/sequencer-support.d.ts.map +1 -0
  230. package/dist/commands/serve-repository.d.ts +52 -0
  231. package/dist/commands/serve-repository.d.ts.map +1 -0
  232. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  233. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  234. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  235. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  236. package/dist/commands/stash-apply-command.d.ts +42 -8
  237. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  238. package/dist/commands/stash-create-command.d.ts +156 -2
  239. package/dist/commands/stash-create-command.d.ts.map +1 -1
  240. package/dist/commands/stash-drop-command.d.ts +2 -0
  241. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  242. package/dist/commands/stash-working-tree.d.ts +23 -0
  243. package/dist/commands/stash-working-tree.d.ts.map +1 -1
  244. package/dist/commands/status-command.d.ts +300 -15
  245. package/dist/commands/status-command.d.ts.map +1 -1
  246. package/dist/commands/status-format.d.ts +155 -0
  247. package/dist/commands/status-format.d.ts.map +1 -0
  248. package/dist/commands/status-header.d.ts +64 -0
  249. package/dist/commands/status-header.d.ts.map +1 -0
  250. package/dist/commands/strerror.d.ts +7 -0
  251. package/dist/commands/strerror.d.ts.map +1 -0
  252. package/dist/commands/submodule-config.d.ts +38 -0
  253. package/dist/commands/submodule-config.d.ts.map +1 -0
  254. package/dist/commands/submodule-summary-command.d.ts +80 -0
  255. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  256. package/dist/commands/submodule-summary.d.ts +150 -0
  257. package/dist/commands/submodule-summary.d.ts.map +1 -0
  258. package/dist/commands/switch-command.d.ts +132 -0
  259. package/dist/commands/switch-command.d.ts.map +1 -0
  260. package/dist/commands/tag-command.d.ts +23 -2
  261. package/dist/commands/tag-command.d.ts.map +1 -1
  262. package/dist/commands/tracking-info.d.ts +64 -0
  263. package/dist/commands/tracking-info.d.ts.map +1 -0
  264. package/dist/commands/trailers.d.ts +73 -0
  265. package/dist/commands/trailers.d.ts.map +1 -0
  266. package/dist/commands/tree-restore.d.ts +85 -1
  267. package/dist/commands/tree-restore.d.ts.map +1 -1
  268. package/dist/commands/untracked-cache-support.d.ts +54 -0
  269. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  270. package/dist/commands/worktree-add-command.d.ts +108 -0
  271. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-list-command.d.ts +69 -0
  273. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  274. package/dist/commands/worktree-lock-command.d.ts +44 -0
  275. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-overwrite-checks.d.ts +146 -6
  277. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  278. package/dist/commands/worktree-prune-command.d.ts +48 -0
  279. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-remove-command.d.ts +59 -0
  281. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  282. package/dist/commands/worktree-repair-command.d.ts +35 -0
  283. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  284. package/dist/commands/worktree-support.d.ts +64 -0
  285. package/dist/commands/worktree-support.d.ts.map +1 -0
  286. package/dist/commands-DIJ91NnD.js +62225 -0
  287. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  288. package/dist/errors/add-errors.d.ts +55 -0
  289. package/dist/errors/add-errors.d.ts.map +1 -1
  290. package/dist/errors/checkout-errors.d.ts +16 -0
  291. package/dist/errors/checkout-errors.d.ts.map +1 -1
  292. package/dist/errors/command-errors.d.ts +77 -0
  293. package/dist/errors/command-errors.d.ts.map +1 -1
  294. package/dist/errors/commit-errors.d.ts +9 -0
  295. package/dist/errors/commit-errors.d.ts.map +1 -1
  296. package/dist/errors/git-api-error.d.ts +59 -2
  297. package/dist/errors/git-api-error.d.ts.map +1 -1
  298. package/dist/errors/index.d.ts +1 -0
  299. package/dist/errors/index.d.ts.map +1 -1
  300. package/dist/errors/index.js +354 -19
  301. package/dist/errors/rebase-errors.d.ts +9 -0
  302. package/dist/errors/rebase-errors.d.ts.map +1 -1
  303. package/dist/errors/ref-errors.d.ts +32 -0
  304. package/dist/errors/ref-errors.d.ts.map +1 -1
  305. package/dist/errors/transport-errors.d.ts +12 -2
  306. package/dist/errors/transport-errors.d.ts.map +1 -1
  307. package/dist/errors/worktree-errors.d.ts +35 -0
  308. package/dist/errors/worktree-errors.d.ts.map +1 -0
  309. package/dist/git-command-BGiOJ8Zk.js +7246 -0
  310. package/dist/git-command.d.ts +428 -32
  311. package/dist/git-command.d.ts.map +1 -1
  312. package/dist/git.d.ts +315 -5
  313. package/dist/git.d.ts.map +1 -1
  314. package/dist/index.d.ts +1 -1
  315. package/dist/index.d.ts.map +1 -1
  316. package/dist/index.js +5 -5
  317. package/dist/remote-config/index.d.ts +1 -1
  318. package/dist/remote-config/index.d.ts.map +1 -1
  319. package/dist/remote-config/remote-config-store.d.ts +167 -6
  320. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  321. package/dist/remote-config/remote-refs.d.ts +7 -3
  322. package/dist/remote-config/remote-refs.d.ts.map +1 -1
  323. package/dist/rename/detect-renames.d.ts +148 -0
  324. package/dist/rename/detect-renames.d.ts.map +1 -0
  325. package/dist/rename/git-similarity.d.ts +44 -0
  326. package/dist/rename/git-similarity.d.ts.map +1 -0
  327. package/dist/rename/index.d.ts +2 -0
  328. package/dist/rename/index.d.ts.map +1 -1
  329. package/dist/results/binary-patch.d.ts +11 -0
  330. package/dist/results/binary-patch.d.ts.map +1 -0
  331. package/dist/results/blame-format.d.ts +55 -0
  332. package/dist/results/blame-format.d.ts.map +1 -0
  333. package/dist/results/cherry-pick-result.d.ts +10 -0
  334. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  335. package/dist/results/clone-result.d.ts +18 -0
  336. package/dist/results/clone-result.d.ts.map +1 -1
  337. package/dist/results/combined-diff.d.ts +77 -0
  338. package/dist/results/combined-diff.d.ts.map +1 -0
  339. package/dist/results/diff-entry.d.ts +32 -0
  340. package/dist/results/diff-entry.d.ts.map +1 -1
  341. package/dist/results/diff-formatter.d.ts +34 -60
  342. package/dist/results/diff-formatter.d.ts.map +1 -1
  343. package/dist/results/diff-order.d.ts +25 -0
  344. package/dist/results/diff-order.d.ts.map +1 -0
  345. package/dist/results/diff-output.d.ts +249 -0
  346. package/dist/results/diff-output.d.ts.map +1 -0
  347. package/dist/results/fetch-result.d.ts +15 -0
  348. package/dist/results/fetch-result.d.ts.map +1 -1
  349. package/dist/results/index.d.ts +5 -0
  350. package/dist/results/index.d.ts.map +1 -1
  351. package/dist/results/index.js +2 -252
  352. package/dist/results/init-result.d.ts +7 -0
  353. package/dist/results/init-result.d.ts.map +1 -1
  354. package/dist/results/merge-result.d.ts +15 -1
  355. package/dist/results/merge-result.d.ts.map +1 -1
  356. package/dist/results/pull-result.d.ts +17 -3
  357. package/dist/results/pull-result.d.ts.map +1 -1
  358. package/dist/results/push-result.d.ts +47 -0
  359. package/dist/results/push-result.d.ts.map +1 -1
  360. package/dist/results/quote-path.d.ts +27 -0
  361. package/dist/results/quote-path.d.ts.map +1 -0
  362. package/dist/results/rebase-result.d.ts +28 -1
  363. package/dist/results/rebase-result.d.ts.map +1 -1
  364. package/dist/results/revert-result.d.ts +10 -0
  365. package/dist/results/revert-result.d.ts.map +1 -1
  366. package/dist/results/stash-result.d.ts +5 -0
  367. package/dist/results/stash-result.d.ts.map +1 -1
  368. package/dist/results/status-result.d.ts +60 -6
  369. package/dist/results/status-result.d.ts.map +1 -1
  370. package/dist/results-WVlBhVb1.js +2935 -0
  371. package/dist/transport-command.d.ts +44 -1
  372. package/dist/transport-command.d.ts.map +1 -1
  373. package/package.json +15 -11
  374. package/src/commands/add-command.ts +1291 -226
  375. package/src/commands/add-patch/add-interactive.ts +941 -0
  376. package/src/commands/add-patch/add-patch.ts +1169 -0
  377. package/src/commands/add-patch/index.ts +5 -0
  378. package/src/commands/add-patch/patch-backend.ts +239 -0
  379. package/src/commands/add-patch/patch-modes.ts +249 -0
  380. package/src/commands/add-patch/patch-session.ts +159 -0
  381. package/src/commands/am/am-command.ts +1111 -0
  382. package/src/commands/am/index.ts +2 -0
  383. package/src/commands/am/mailinfo.ts +1015 -0
  384. package/src/commands/am/patch-format.ts +121 -0
  385. package/src/commands/apply/apply-command.ts +842 -0
  386. package/src/commands/apply/apply-engine.ts +1602 -0
  387. package/src/commands/apply/apply-parse.ts +1210 -0
  388. package/src/commands/apply/apply-types.ts +112 -0
  389. package/src/commands/apply/index.ts +5 -0
  390. package/src/commands/apply/latin1.ts +171 -0
  391. package/src/commands/apply/whitespace.ts +260 -0
  392. package/src/commands/attributes-source.ts +96 -0
  393. package/src/commands/backfill-command.ts +694 -0
  394. package/src/commands/bisect/bisect-checkout.ts +217 -0
  395. package/src/commands/bisect/bisect-command.ts +788 -0
  396. package/src/commands/bisect/bisect-engine.ts +1080 -0
  397. package/src/commands/bisect/bisect-graph.ts +595 -0
  398. package/src/commands/bisect/bisect-quote.ts +92 -0
  399. package/src/commands/bisect/index.ts +4 -0
  400. package/src/commands/blame-command.ts +711 -986
  401. package/src/commands/branch-command.ts +354 -32
  402. package/src/commands/branch-tracking.ts +331 -0
  403. package/src/commands/checkout-command.ts +1290 -243
  404. package/src/commands/checkout-paths.ts +784 -0
  405. package/src/commands/cherry-pick-command.ts +156 -396
  406. package/src/commands/clean-command.ts +504 -156
  407. package/src/commands/clone-command.ts +748 -69
  408. package/src/commands/comment-char-config.ts +160 -0
  409. package/src/commands/commit-command.ts +1782 -166
  410. package/src/commands/core-config.ts +166 -6
  411. package/src/commands/date-format.ts +668 -0
  412. package/src/commands/default-branch.ts +196 -0
  413. package/src/commands/describe-command.ts +2 -0
  414. package/src/commands/diff-command.ts +1916 -110
  415. package/src/commands/diff-textconv.ts +50 -0
  416. package/src/commands/fetch-command.ts +622 -68
  417. package/src/commands/format-patch-command.ts +974 -0
  418. package/src/commands/fsck/fetch-fsck.ts +229 -0
  419. package/src/commands/fsck/fsck-command.ts +3464 -0
  420. package/src/commands/fsck/fsck-loose.ts +297 -0
  421. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  422. package/src/commands/fsck/fsck-object-checks.ts +1085 -0
  423. package/src/commands/fsck/fsck-object-table.ts +373 -0
  424. package/src/commands/fsck/fsck-pack.ts +634 -0
  425. package/src/commands/fsck/index.ts +5 -0
  426. package/src/commands/fsck/verify-pack-command.ts +252 -0
  427. package/src/commands/gc-command.ts +324 -77
  428. package/src/commands/git-date.ts +9 -0
  429. package/src/commands/git-describe.ts +316 -0
  430. package/src/commands/git-hooks.ts +1483 -0
  431. package/src/commands/git-ident.ts +344 -0
  432. package/src/commands/hook-command.ts +247 -0
  433. package/src/commands/index-adder.ts +711 -0
  434. package/src/commands/index-host.ts +291 -0
  435. package/src/commands/index.ts +84 -0
  436. package/src/commands/init-command.ts +194 -14
  437. package/src/commands/legacy-remotes.ts +224 -0
  438. package/src/commands/local-clone.ts +183 -0
  439. package/src/commands/local-transport.ts +762 -0
  440. package/src/commands/log-command.ts +1930 -170
  441. package/src/commands/log-graph.ts +671 -0
  442. package/src/commands/log-output.ts +1359 -0
  443. package/src/commands/ls-remote-command.ts +105 -58
  444. package/src/commands/mailmap.ts +129 -0
  445. package/src/commands/merge-bases.ts +296 -0
  446. package/src/commands/merge-command.ts +1416 -491
  447. package/src/commands/merge-config.ts +25 -0
  448. package/src/commands/merge-drivers.ts +306 -0
  449. package/src/commands/merge-support.ts +1219 -0
  450. package/src/commands/message-cleanup.ts +275 -0
  451. package/src/commands/mv-command.ts +976 -0
  452. package/src/commands/notes-command.ts +890 -0
  453. package/src/commands/notes-commands.ts +87 -0
  454. package/src/commands/notes-merge-command.ts +777 -0
  455. package/src/commands/notes-support.ts +402 -0
  456. package/src/commands/notes-tree.ts +617 -0
  457. package/src/commands/object-id-input.ts +27 -0
  458. package/src/commands/octopus-merge.ts +378 -0
  459. package/src/commands/ort-merge.ts +1660 -0
  460. package/src/commands/ort-recursive.ts +160 -0
  461. package/src/commands/pack-refs-command.ts +39 -22
  462. package/src/commands/patch-id.ts +204 -0
  463. package/src/commands/pathspec-attributes.ts +162 -0
  464. package/src/commands/pathspec.ts +1199 -0
  465. package/src/commands/post-index-change.ts +62 -0
  466. package/src/commands/pretty-format.ts +1432 -0
  467. package/src/commands/promisor-remote.ts +298 -0
  468. package/src/commands/pull-command.ts +326 -33
  469. package/src/commands/push-command.ts +257 -29
  470. package/src/commands/read-tree-command.ts +861 -0
  471. package/src/commands/rebase-command.ts +3820 -372
  472. package/src/commands/rebase-todo.ts +584 -0
  473. package/src/commands/ref-decoration-filter.ts +118 -0
  474. package/src/commands/reflog-messages.ts +177 -0
  475. package/src/commands/remote-command.ts +124 -23
  476. package/src/commands/remote-transport.ts +383 -0
  477. package/src/commands/reset-command.ts +821 -104
  478. package/src/commands/restore-command.ts +350 -0
  479. package/src/commands/rev-list-command.ts +167 -0
  480. package/src/commands/rev-parse-command.ts +299 -0
  481. package/src/commands/revert-command.ts +152 -399
  482. package/src/commands/revision-filenames.ts +254 -0
  483. package/src/commands/revision-range.ts +222 -0
  484. package/src/commands/revision-resolver.ts +1397 -0
  485. package/src/commands/rm-command.ts +613 -67
  486. package/src/commands/sequencer-pick.ts +874 -0
  487. package/src/commands/sequencer-support.ts +876 -0
  488. package/src/commands/serve-repository.ts +125 -0
  489. package/src/commands/sparse-checkout-command.ts +1389 -0
  490. package/src/commands/sparse-checkout-support.ts +793 -0
  491. package/src/commands/stash-apply-command.ts +376 -343
  492. package/src/commands/stash-create-command.ts +625 -42
  493. package/src/commands/stash-drop-command.ts +15 -2
  494. package/src/commands/stash-working-tree.ts +168 -24
  495. package/src/commands/status-command.ts +1326 -105
  496. package/src/commands/status-format.ts +775 -0
  497. package/src/commands/status-header.ts +332 -0
  498. package/src/commands/strerror.ts +29 -0
  499. package/src/commands/submodule-config.ts +94 -0
  500. package/src/commands/submodule-summary-command.ts +333 -0
  501. package/src/commands/submodule-summary.ts +446 -0
  502. package/src/commands/switch-command.ts +402 -0
  503. package/src/commands/tag-command.ts +129 -41
  504. package/src/commands/tracking-info.ts +201 -0
  505. package/src/commands/trailers.ts +417 -0
  506. package/src/commands/tree-restore.ts +204 -4
  507. package/src/commands/untracked-cache-support.ts +198 -0
  508. package/src/commands/worktree-add-command.ts +458 -0
  509. package/src/commands/worktree-list-command.ts +206 -0
  510. package/src/commands/worktree-lock-command.ts +96 -0
  511. package/src/commands/worktree-overwrite-checks.ts +452 -26
  512. package/src/commands/worktree-prune-command.ts +99 -0
  513. package/src/commands/worktree-remove-command.ts +186 -0
  514. package/src/commands/worktree-repair-command.ts +59 -0
  515. package/src/commands/worktree-support.ts +214 -0
  516. package/src/core-commands/add.command.impl.ts +8 -2
  517. package/src/errors/add-errors.ts +45 -0
  518. package/src/errors/checkout-errors.ts +26 -2
  519. package/src/errors/command-errors.ts +101 -1
  520. package/src/errors/commit-errors.ts +18 -2
  521. package/src/errors/git-api-error.ts +82 -2
  522. package/src/errors/index.ts +1 -0
  523. package/src/errors/merge-errors.ts +2 -2
  524. package/src/errors/rebase-errors.ts +12 -0
  525. package/src/errors/ref-errors.ts +56 -2
  526. package/src/errors/remote-errors.ts +2 -2
  527. package/src/errors/stash-errors.ts +1 -1
  528. package/src/errors/transport-errors.ts +20 -4
  529. package/src/errors/worktree-errors.ts +49 -0
  530. package/src/git-command.ts +1207 -118
  531. package/src/git.ts +538 -12
  532. package/src/index.ts +1 -1
  533. package/src/remote-config/index.ts +2 -0
  534. package/src/remote-config/remote-config-store.ts +378 -18
  535. package/src/remote-config/remote-refs.ts +22 -6
  536. package/src/rename/detect-renames.ts +715 -0
  537. package/src/rename/git-similarity.ts +116 -0
  538. package/src/rename/index.ts +2 -0
  539. package/src/results/binary-patch.ts +401 -0
  540. package/src/results/blame-format.ts +239 -0
  541. package/src/results/cherry-pick-result.ts +10 -0
  542. package/src/results/clone-result.ts +21 -0
  543. package/src/results/combined-diff.ts +585 -0
  544. package/src/results/diff-entry.ts +35 -0
  545. package/src/results/diff-formatter.ts +152 -288
  546. package/src/results/diff-order.ts +64 -0
  547. package/src/results/diff-output.ts +1053 -0
  548. package/src/results/fetch-result.ts +15 -0
  549. package/src/results/index.ts +5 -0
  550. package/src/results/init-result.ts +9 -0
  551. package/src/results/merge-result.ts +15 -1
  552. package/src/results/pull-result.ts +17 -3
  553. package/src/results/push-result.ts +48 -0
  554. package/src/results/quote-path.ts +103 -0
  555. package/src/results/rebase-result.ts +37 -0
  556. package/src/results/revert-result.ts +10 -0
  557. package/src/results/stash-result.ts +6 -0
  558. package/src/results/status-result.ts +127 -46
  559. package/src/transport-command.ts +121 -2
  560. package/dist/commands-CsLNyvZ1.js +0 -12587
  561. package/dist/status-result-BpyUK1Sg.js +0 -519
@@ -0,0 +1,1219 @@
1
+ /**
2
+ * What `merge`, `cherry-pick`, `revert` and `rebase` share: flat trees, the operation's
3
+ * state files (MERGE_HEAD, MERGE_MSG, sequencer/, rebase-merge/, ...), and writing a merge's
4
+ * result to the worktree and the index as git's merge-ort does (`merge_switch_to_result`: a
5
+ * two-way unpack-trees from HEAD to the result tree, refused before anything is written
6
+ * where it would overwrite local changes or untracked files, then the conflicts staged).
7
+ */
8
+
9
+ import {
10
+ type Blobs,
11
+ collectTreeBytes,
12
+ FileMode,
13
+ type ObjectId,
14
+ objectFormatOf,
15
+ type RefLogOptions,
16
+ type TreeEntry,
17
+ } from "@statewalker/vcs-core";
18
+ import { bytesToHex, createSha1, objectFormatByHexLength } from "@statewalker/vcs-utils";
19
+ import { compareGitPaths, decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
20
+ import type { ObjectFormat } from "@statewalker/vcs-utils/hash";
21
+ import {
22
+ attributesIndexOf,
23
+ type CacheTree,
24
+ type Checkout,
25
+ cacheTreeFullyValid,
26
+ entryStatOf,
27
+ type IndexEntryOptions,
28
+ invalidateCacheTreeAgainstIndex,
29
+ invalidateCacheTreeForIntentToAdd,
30
+ invalidateCacheTreePath,
31
+ type Staging,
32
+ updateCacheTree,
33
+ type WorkingCopy,
34
+ type Worktree,
35
+ } from "@statewalker/vcs-working-tree";
36
+ import type { CommandRefs, CommandTrees } from "../git-command.js";
37
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
38
+ import type { OrtConflict } from "./ort-merge.js";
39
+ import { markIndexUpdate } from "./post-index-change.js";
40
+ import { pushSparseWarnings, SparseUnpack } from "./sparse-checkout-support.js";
41
+ import {
42
+ planFlatRestore,
43
+ planTreeRestore,
44
+ restoreCaseOptions,
45
+ type TreeRestorePlan,
46
+ writeTreeRestorePlan,
47
+ } from "./tree-restore.js";
48
+ import {
49
+ type CheckedEntry,
50
+ entryNotUptodate,
51
+ findInTheWay,
52
+ overwriteMessage,
53
+ pruneEmptyParents,
54
+ removeCaseVariants,
55
+ } from "./worktree-overwrite-checks.js";
56
+
57
+ const sameEntry = (a: CheckedEntry | undefined, b: CheckedEntry | undefined) =>
58
+ a === undefined || b === undefined ? a === b : a.objectId === b.objectId && a.mode === b.mode;
59
+
60
+ /** The blobs, links and gitlinks of a tree, by path (none for no tree). */
61
+ export async function flatTree(
62
+ trees: CommandTrees,
63
+ treeId: ObjectId | undefined,
64
+ ): Promise<Map<string, CheckedEntry>> {
65
+ const out = new Map<string, CheckedEntry>();
66
+ if (!treeId) return out;
67
+ const walk = async (id: ObjectId, prefix: string): Promise<void> => {
68
+ for await (const entry of trees.loadTree(id)) {
69
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
70
+ if (entry.mode === FileMode.TREE) await walk(entry.id, path);
71
+ else out.set(path, { objectId: entry.id, mode: entry.mode });
72
+ }
73
+ };
74
+ await walk(treeId, "");
75
+ return out;
76
+ }
77
+
78
+ /**
79
+ * The trees `ids` as flat maps for a merge of them, as merge-ort reads them: a directory
80
+ * that every one of the trees holds with the same tree id is not read at all, it stands in
81
+ * each map as one entry of mode TREE carrying that id (merge-ort resolves such a directory
82
+ * at once, `side1_matches_mbase && side2_matches_mbase`). Every other directory is read.
83
+ * `dirs` gives, per tree, the id of each directory read or stood in for.
84
+ */
85
+ export async function prunedFlatTrees(
86
+ trees: CommandTrees,
87
+ ids: (ObjectId | undefined)[],
88
+ ): Promise<{ flats: Map<string, CheckedEntry>[]; dirs: Map<string, ObjectId>[] }> {
89
+ const flats = ids.map(() => new Map<string, CheckedEntry>());
90
+ const dirs = ids.map(() => new Map<string, ObjectId>());
91
+ const read = async (id: ObjectId | undefined) => {
92
+ const out: { name: string; mode: number; id: ObjectId }[] = [];
93
+ if (id) for await (const e of trees.loadTree(id)) out.push(e);
94
+ return out;
95
+ };
96
+ const walk = async (level: (ObjectId | undefined)[], prefix: string): Promise<void> => {
97
+ const listed = await Promise.all(level.map(read));
98
+ const byName = new Map<string, ({ mode: number; id: ObjectId } | undefined)[]>();
99
+ listed.forEach((entries, i) => {
100
+ for (const e of entries) {
101
+ let slot = byName.get(e.name);
102
+ if (!slot) {
103
+ slot = level.map(() => undefined);
104
+ byName.set(e.name, slot);
105
+ }
106
+ slot[i] = e;
107
+ }
108
+ });
109
+ for (const [name, slot] of byName) {
110
+ const path = prefix ? `${prefix}/${name}` : name;
111
+ const first = slot[0];
112
+ if (
113
+ first?.mode === FileMode.TREE &&
114
+ slot.every((e) => e !== undefined && e.mode === FileMode.TREE && e.id === first.id)
115
+ ) {
116
+ for (let i = 0; i < slot.length; i++) {
117
+ flats[i].set(path, { objectId: first.id, mode: FileMode.TREE });
118
+ dirs[i].set(path, first.id);
119
+ }
120
+ continue;
121
+ }
122
+ const sub: (ObjectId | undefined)[] = slot.map(() => undefined);
123
+ let nested = false;
124
+ slot.forEach((e, i) => {
125
+ if (!e) return;
126
+ if (e.mode === FileMode.TREE) {
127
+ sub[i] = e.id;
128
+ dirs[i].set(path, e.id);
129
+ nested = true;
130
+ } else flats[i].set(path, { objectId: e.id, mode: e.mode });
131
+ });
132
+ if (nested) await walk(sub, path);
133
+ }
134
+ };
135
+ await walk(ids, "");
136
+ return { flats, dirs };
137
+ }
138
+
139
+ /**
140
+ * The paths where the trees `from` and `to` differ, with their entries on each side (a
141
+ * path one side lacks is absent from its map): what comparing their flat maps finds, read
142
+ * without descending into a subtree both hold with the same id.
143
+ */
144
+ export async function treeDelta(
145
+ trees: CommandTrees,
146
+ from: ObjectId | undefined,
147
+ to: ObjectId | undefined,
148
+ ): Promise<{ from: Map<string, CheckedEntry>; to: Map<string, CheckedEntry> }> {
149
+ const out = { from: new Map<string, CheckedEntry>(), to: new Map<string, CheckedEntry>() };
150
+ const read = async (id: ObjectId | undefined) => {
151
+ const map = new Map<string, { mode: number; id: ObjectId }>();
152
+ if (id) for await (const e of trees.loadTree(id)) map.set(e.name, { mode: e.mode, id: e.id });
153
+ return map;
154
+ };
155
+ const addAll = async (side: Map<string, CheckedEntry>, id: ObjectId, prefix: string) => {
156
+ for await (const e of trees.loadTree(id)) {
157
+ const path = `${prefix}/${e.name}`;
158
+ if (e.mode === FileMode.TREE) await addAll(side, e.id, path);
159
+ else side.set(path, { objectId: e.id, mode: e.mode });
160
+ }
161
+ };
162
+ const walk = async (a: ObjectId | undefined, b: ObjectId | undefined, prefix: string) => {
163
+ if (a === b) return;
164
+ const [x, y] = await Promise.all([read(a), read(b)]);
165
+ for (const name of new Set([...x.keys(), ...y.keys()])) {
166
+ const ex = x.get(name);
167
+ const ey = y.get(name);
168
+ if (ex && ey && ex.mode === ey.mode && ex.id === ey.id) continue;
169
+ const path = prefix ? `${prefix}/${name}` : name;
170
+ const xTree = ex?.mode === FileMode.TREE;
171
+ const yTree = ey?.mode === FileMode.TREE;
172
+ if (xTree && yTree) {
173
+ await walk(ex.id, ey.id, path);
174
+ continue;
175
+ }
176
+ if (ex) {
177
+ if (xTree) await addAll(out.from, ex.id, path);
178
+ else out.from.set(path, { objectId: ex.id, mode: ex.mode });
179
+ }
180
+ if (ey) {
181
+ if (yTree) await addAll(out.to, ey.id, path);
182
+ else out.to.set(path, { objectId: ey.id, mode: ey.mode });
183
+ }
184
+ }
185
+ };
186
+ await walk(from, to, "");
187
+ return out;
188
+ }
189
+
190
+ /** The index's entries of one directory: its files, its subdirectories, its tree id. */
191
+ interface IndexDir {
192
+ files: Map<string, CheckedEntry>;
193
+ dirs: Map<string, IndexDir>;
194
+ id?: ObjectId;
195
+ }
196
+
197
+ /** The index's stage-0 entries as directories, each with the id its tree would have. */
198
+ async function indexDirs(index: Map<string, CheckedEntry>): Promise<IndexDir> {
199
+ const root: IndexDir = { files: new Map(), dirs: new Map() };
200
+ const first = index.values().next().value as CheckedEntry | undefined;
201
+ const newHasher =
202
+ objectFormatByHexLength(first?.objectId.length ?? 40)?.createHasher ?? createSha1;
203
+ for (const [path, entry] of index) {
204
+ let dir = root;
205
+ let from = 0;
206
+ for (let k = path.indexOf("/"); k >= 0; k = path.indexOf("/", from)) {
207
+ const name = path.slice(from, k);
208
+ let next = dir.dirs.get(name);
209
+ if (!next) {
210
+ next = { files: new Map(), dirs: new Map() };
211
+ dir.dirs.set(name, next);
212
+ }
213
+ dir = next;
214
+ from = k + 1;
215
+ }
216
+ dir.files.set(path.slice(from), entry);
217
+ }
218
+ const hash = async (dir: IndexDir): Promise<ObjectId> => {
219
+ const entries: TreeEntry[] = [];
220
+ for (const [name, sub] of dir.dirs)
221
+ entries.push({ name, mode: FileMode.TREE, id: await hash(sub) });
222
+ for (const [name, e] of dir.files) entries.push({ name, mode: e.mode, id: e.objectId });
223
+ let id: ObjectId;
224
+ try {
225
+ const bytes = await collectTreeBytes(entries);
226
+ // the index's own format: its ids are SHA-256 ones in a SHA-256 repository
227
+ const hasher = newHasher().update(new TextEncoder().encode(`tree ${bytes.length}\0`));
228
+ id = bytesToHex(hasher.update(bytes).digest());
229
+ } catch {
230
+ // a name no tree can hold: never the id of a stored tree
231
+ id = "";
232
+ }
233
+ dir.id = id;
234
+ return id;
235
+ };
236
+ await hash(root);
237
+ return root;
238
+ }
239
+
240
+ /**
241
+ * The paths where the index's stage-0 entries differ from the tree `treeId`, sorted (as
242
+ * {@link indexChanges} over the tree's flat map). As git's cache-tree, each directory of the
243
+ * index is given the id its tree would have: a subtree of `treeId` with that id holds what
244
+ * the index holds there and is not read.
245
+ */
246
+ export async function indexChangesFromTree(
247
+ index: Map<string, CheckedEntry>,
248
+ trees: CommandTrees,
249
+ treeId: ObjectId | undefined,
250
+ ): Promise<string[]> {
251
+ const out: string[] = [];
252
+ const all = (dir: IndexDir, prefix: string) => {
253
+ for (const name of dir.files.keys()) out.push(join(prefix, name));
254
+ for (const [name, sub] of dir.dirs) all(sub, join(prefix, name));
255
+ };
256
+ const allOfTree = async (id: ObjectId, prefix: string): Promise<void> => {
257
+ for await (const e of trees.loadTree(id)) {
258
+ const path = join(prefix, e.name);
259
+ if (e.mode === FileMode.TREE) await allOfTree(e.id, path);
260
+ else out.push(path);
261
+ }
262
+ };
263
+ const compare = async (
264
+ id: ObjectId | undefined,
265
+ dir: IndexDir | undefined,
266
+ prefix: string,
267
+ ): Promise<void> => {
268
+ if (!id) {
269
+ if (dir) all(dir, prefix);
270
+ return;
271
+ }
272
+ if (!dir) return allOfTree(id, prefix);
273
+ if (dir.id === id) return;
274
+ const files = new Map<string, { mode: number; id: ObjectId }>();
275
+ const subtrees = new Map<string, ObjectId>();
276
+ for await (const e of trees.loadTree(id)) {
277
+ if (e.mode === FileMode.TREE) subtrees.set(e.name, e.id);
278
+ else files.set(e.name, { mode: e.mode, id: e.id });
279
+ }
280
+ for (const name of new Set([...files.keys(), ...dir.files.keys()])) {
281
+ const t = files.get(name);
282
+ const i = dir.files.get(name);
283
+ if (!t || !i || t.id !== i.objectId || t.mode !== i.mode) out.push(join(prefix, name));
284
+ }
285
+ for (const name of new Set([...subtrees.keys(), ...dir.dirs.keys()])) {
286
+ await compare(subtrees.get(name), dir.dirs.get(name), join(prefix, name));
287
+ }
288
+ };
289
+ await compare(treeId, index.size > 0 ? await indexDirs(index) : undefined, "");
290
+ return out.sort();
291
+ }
292
+
293
+ const join = (prefix: string, name: string) => (prefix ? `${prefix}/${name}` : name);
294
+
295
+ /** Stores a flat path map as a tree. */
296
+ export async function storeFlatTree(
297
+ trees: CommandTrees,
298
+ entries: Map<string, CheckedEntry>,
299
+ ): Promise<ObjectId> {
300
+ type Node = Map<string, Node | CheckedEntry>;
301
+ const root: Node = new Map();
302
+ for (const [path, entry] of entries) {
303
+ const parts = path.split("/");
304
+ let node = root;
305
+ for (const part of parts.slice(0, -1)) {
306
+ let next = node.get(part);
307
+ if (!(next instanceof Map)) {
308
+ next = new Map();
309
+ node.set(part, next);
310
+ }
311
+ node = next;
312
+ }
313
+ node.set(parts[parts.length - 1], entry);
314
+ }
315
+ const store = async (node: Node): Promise<ObjectId> => {
316
+ const list: { name: string; mode: number; id: ObjectId }[] = [];
317
+ for (const [name, value] of node) {
318
+ if (value instanceof Map) list.push({ name, mode: FileMode.TREE, id: await store(value) });
319
+ else list.push({ name, mode: value.mode, id: value.objectId });
320
+ }
321
+ return trees.storeTree(list);
322
+ };
323
+ return store(root);
324
+ }
325
+
326
+ /**
327
+ * Stores `target` as a tree, given that `base` is the flat form of the stored tree
328
+ * `baseTree`: only the directories holding a changed path are stored again, every other
329
+ * subtree is taken from `baseTree` as it is (what a pick changes is a few paths of a large
330
+ * tree). Without a base tree the whole map is stored.
331
+ */
332
+ export async function storeFlatTreeOver(
333
+ trees: CommandTrees,
334
+ baseTree: ObjectId | undefined,
335
+ base: Map<string, CheckedEntry>,
336
+ target: Map<string, CheckedEntry>,
337
+ ): Promise<ObjectId> {
338
+ if (!baseTree) return storeFlatTree(trees, target);
339
+ const changes = new Map<string, CheckedEntry | null>();
340
+ for (const [path, entry] of target) {
341
+ if (!sameEntry(base.get(path), entry)) changes.set(path, entry);
342
+ }
343
+ for (const path of base.keys()) if (!target.has(path)) changes.set(path, null);
344
+ // a directory the target takes whole (one TREE entry): what the base held under it goes
345
+ const whole = [...changes].filter(([, e]) => e?.mode === FileMode.TREE).map(([p]) => `${p}/`);
346
+ if (whole.length > 0) {
347
+ for (const path of [...changes.keys()]) {
348
+ if (whole.some((dir) => path.startsWith(dir))) changes.delete(path);
349
+ }
350
+ }
351
+ if (changes.size === 0) return baseTree;
352
+ const rebuild = async (
353
+ treeId: ObjectId | undefined,
354
+ edits: Map<string, CheckedEntry | null>,
355
+ ): Promise<ObjectId | undefined> => {
356
+ const entries = new Map<string, { mode: number; id: ObjectId }>();
357
+ if (treeId) {
358
+ for await (const e of trees.loadTree(treeId)) entries.set(e.name, { mode: e.mode, id: e.id });
359
+ }
360
+ const direct = new Map<string, CheckedEntry | null>();
361
+ const nested = new Map<string, Map<string, CheckedEntry | null>>();
362
+ for (const [path, entry] of edits) {
363
+ const k = path.indexOf("/");
364
+ if (k < 0) direct.set(path, entry);
365
+ else {
366
+ const name = path.slice(0, k);
367
+ const sub = nested.get(name) ?? new Map<string, CheckedEntry | null>();
368
+ sub.set(path.slice(k + 1), entry);
369
+ nested.set(name, sub);
370
+ }
371
+ }
372
+ // removals first (a file `d` making way for `d/x`), then directories, then files
373
+ for (const [name, entry] of direct) if (!entry) entries.delete(name);
374
+ for (const [name, sub] of nested) {
375
+ const current = entries.get(name);
376
+ const childTree = current?.mode === FileMode.TREE ? current.id : undefined;
377
+ const id = await rebuild(childTree, sub);
378
+ if (id) entries.set(name, { mode: FileMode.TREE, id });
379
+ else if (childTree) entries.delete(name);
380
+ }
381
+ for (const [name, entry] of direct) {
382
+ if (entry) entries.set(name, { mode: entry.mode, id: entry.objectId });
383
+ }
384
+ if (entries.size === 0) return undefined;
385
+ return trees.storeTree([...entries].map(([name, e]) => ({ name, mode: e.mode, id: e.id })));
386
+ };
387
+ return (await rebuild(baseTree, changes)) ?? (await trees.storeTree([]));
388
+ }
389
+
390
+ /**
391
+ * Flat trees by tree id, for an operation that reads the same trees again and again (a
392
+ * rebase: each pick's result is the next pick's HEAD, each commit the next one's parent).
393
+ * Keeps the last few.
394
+ */
395
+ export class FlatTreeCache {
396
+ private readonly cache = new Map<ObjectId, Map<string, CheckedEntry>>();
397
+
398
+ constructor(
399
+ private readonly trees: CommandTrees,
400
+ private readonly size = 8,
401
+ ) {}
402
+
403
+ /** The flat tree (none for no tree); the map is shared, never to be changed. */
404
+ async get(treeId: ObjectId | undefined): Promise<Map<string, CheckedEntry>> {
405
+ if (!treeId) return new Map();
406
+ const hit = this.cache.get(treeId);
407
+ if (hit) {
408
+ this.cache.delete(treeId);
409
+ this.cache.set(treeId, hit);
410
+ return hit;
411
+ }
412
+ const flat = await flatTree(this.trees, treeId);
413
+ this.put(treeId, flat);
414
+ return flat;
415
+ }
416
+
417
+ /** Records the flat form of a tree just stored. */
418
+ put(treeId: ObjectId, flat: Map<string, CheckedEntry>): void {
419
+ this.cache.delete(treeId);
420
+ this.cache.set(treeId, flat);
421
+ while (this.cache.size > this.size) {
422
+ const oldest = this.cache.keys().next().value as ObjectId;
423
+ this.cache.delete(oldest);
424
+ }
425
+ }
426
+ }
427
+
428
+ /**
429
+ * The restore plan of the paths in `writing`, taken from the flat `target` (the tree
430
+ * `targetTree`): each path validated and its blob checked as {@link planTreeRestore} does,
431
+ * without walking the whole tree. With `core.ignorecase` on a worktree that folds case (or
432
+ * cannot tell) the whole tree is planned (case collisions are found across it).
433
+ */
434
+ export async function planPathsRestore(
435
+ ctx: MergeWriteContext,
436
+ target: Map<string, CheckedEntry>,
437
+ targetTree: ObjectId | undefined,
438
+ writing: Set<string>,
439
+ operation: string,
440
+ ): Promise<TreeRestorePlan> {
441
+ const worktree = ctx.worktree;
442
+ const options = {
443
+ symlinks: true,
444
+ windows: worktree?.capabilities?.windowsPaths === true,
445
+ reservedNames: worktree?.capabilities?.reservedNames,
446
+ };
447
+ const caseOptions = await restoreCaseOptions(
448
+ worktree,
449
+ coreBool(ctx.workingCopy, "ignorecase", false),
450
+ );
451
+ if (caseOptions.ignoreCase && caseOptions.foldsCase !== false) {
452
+ const tree = targetTree ?? (await storeFlatTree(ctx.trees, target));
453
+ const plan = await planTreeRestore(ctx.trees, ctx.blobs, tree, operation, {
454
+ ...options,
455
+ ...caseOptions,
456
+ writing,
457
+ });
458
+ return {
459
+ ...plan,
460
+ entries: plan.entries.filter((e) => writing.has(e.path)),
461
+ gitlinks: plan.gitlinks.filter((e) => writing.has(e.path)),
462
+ };
463
+ }
464
+ return planFlatRestore(ctx.blobs, target, writing, operation, options);
465
+ }
466
+
467
+ /** The index: its stage-0 entries by path, and the paths with unmerged entries. */
468
+ export async function readIndex(
469
+ staging: Staging,
470
+ ): Promise<{ index: Map<string, CheckedEntry>; unmerged: string[] }> {
471
+ const index = new Map<string, CheckedEntry>();
472
+ const unmerged = new Set<string>();
473
+ for (const entry of await indexEntryList(staging)) {
474
+ if (entry.stage === 0) index.set(entry.path, entry);
475
+ else unmerged.add(entry.path);
476
+ }
477
+ return { index, unmerged: [...unmerged].sort() };
478
+ }
479
+
480
+ /**
481
+ * The tree of the index, as git's `write_index_as_tree` (`cherry-pick -n`, `revert -n`):
482
+ * unless the index holds a fully valid cache-tree, the index file is written again with
483
+ * one. That write smudges racily clean entries and gives the index a new timestamp, which
484
+ * later overwrite checks compare entries with (an entry as new as it is read again).
485
+ */
486
+ export async function writeIndexAsTree(
487
+ staging: Staging,
488
+ trees: CommandTrees,
489
+ /** the repository's object format, the cache-tree's trees are hashed in */
490
+ format: ObjectFormat,
491
+ options: { write?: boolean } = {},
492
+ ): Promise<ObjectId> {
493
+ if (!staging.getCacheTree || !staging.setCacheTree) return staging.writeTree(trees);
494
+ const previous = staging.getCacheTree();
495
+ const treeId = await staging.writeTree(trees);
496
+ if (!previous || !cacheTreeFullyValid(previous)) {
497
+ // the valid directories kept, the others computed (cache_tree_update)
498
+ const cacheTree = await updateCacheTree(trees, treeId, previous, format);
499
+ for (const entry of await indexEntryList(staging)) {
500
+ if (entry.intentToAdd) {
501
+ invalidateCacheTreeForIntentToAdd(cacheTree, entry.path);
502
+ }
503
+ }
504
+ staging.setCacheTree(cacheTree);
505
+ // unless the caller writes the index itself (into the lock it holds)
506
+ if (options.write !== false) await staging.write();
507
+ }
508
+ return treeId;
509
+ }
510
+
511
+ /**
512
+ * git's `cache_tree_update(WRITE_TREE_SILENT | WRITE_TREE_REPAIR)` before an index write
513
+ * (`checkout` after its unpack-trees): unless the cache-tree is fully valid, the invalid
514
+ * directories are computed from the index (the valid ones kept, a stored tree included), the
515
+ * directories of intent-to-add entries left invalid; nothing where the index has conflicts.
516
+ * Sets the cache-tree the next `write` writes.
517
+ */
518
+ export async function updateIndexCacheTree(
519
+ staging: Staging,
520
+ trees: CommandTrees,
521
+ /** the repository's object format, the cache-tree's trees are hashed in */
522
+ format: ObjectFormat,
523
+ ): Promise<void> {
524
+ if (!staging.getCacheTree || !staging.setCacheTree) return;
525
+ if (await staging.hasConflicts()) return;
526
+ const previous = staging.getCacheTree();
527
+ if (previous && cacheTreeFullyValid(previous)) return;
528
+ const treeId = await staging.writeTree(trees);
529
+ const cacheTree = await updateCacheTree(trees, treeId, previous, format);
530
+ for (const entry of await indexEntryList(staging)) {
531
+ if (entry.intentToAdd) {
532
+ invalidateCacheTreeForIntentToAdd(cacheTree, entry.path);
533
+ }
534
+ }
535
+ staging.setCacheTree(cacheTree);
536
+ }
537
+
538
+ /** Every index entry in the index's order, at once where the staging can give them so. */
539
+ async function indexEntryList(staging: Staging): Promise<readonly IndexEntryInput[]> {
540
+ const list = staging.entryList?.();
541
+ if (list) return list;
542
+ const out: IndexEntryInput[] = [];
543
+ for await (const entry of staging.entries()) out.push(entry);
544
+ return out;
545
+ }
546
+
547
+ /** An index entry to write: path, blob, mode, stage and the file's stat. */
548
+ export type IndexEntryInput = IndexEntryOptions;
549
+
550
+ /**
551
+ * Rewrites the index: the entries of each path in `changes` replaced by the ones given
552
+ * (none: the path removed, every stage), every other entry kept as it is.
553
+ */
554
+ export async function rewriteIndex(
555
+ staging: Staging,
556
+ changes: Map<string, IndexEntryInput[]>,
557
+ options: {
558
+ updateCacheTreeWith?: { trees: CommandTrees; format: ObjectFormat };
559
+ cacheTree?: CacheTree;
560
+ /**
561
+ * Whether the kept entries count as up to date (default true: the merge family refreshes
562
+ * the whole index first). False for a write without a refresh (`git apply --cached`):
563
+ * the write then smudges the racily clean entries it keeps, as `write_locked_index`
564
+ */
565
+ upToDate?: boolean;
566
+ /** False: the index built in memory, left for the caller to write (through its lock) */
567
+ write?: boolean;
568
+ } = {},
569
+ ): Promise<void> {
570
+ // the kept entries are in the index's order already: only the changes are sorted, then
571
+ // both merged (git's order: the paths' bytes, then the stage)
572
+ const kept: IndexEntryInput[] = [];
573
+ for (const entry of await indexEntryList(staging)) {
574
+ if (!changes.has(entry.path)) kept.push(entry);
575
+ }
576
+ const keys = new Map<string, Uint8Array>();
577
+ const key = (path: string) => {
578
+ let k = keys.get(path);
579
+ if (!k) {
580
+ k = encodeGitPath(path);
581
+ keys.set(path, k);
582
+ }
583
+ return k;
584
+ };
585
+ const compareBytes = (a: string, b: string) => {
586
+ const x = key(a);
587
+ const y = key(b);
588
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
589
+ return x.length - y.length;
590
+ };
591
+ const compare = (a: IndexEntryInput, b: IndexEntryInput) => {
592
+ if (a.path === b.path) return (a.stage ?? 0) - (b.stage ?? 0);
593
+ // below the surrogates, UTF-16 code units order as the UTF-8 bytes do
594
+ const x = a.path;
595
+ const y = b.path;
596
+ const n = Math.min(x.length, y.length);
597
+ for (let i = 0; i < n; i++) {
598
+ const cx = x.charCodeAt(i);
599
+ const cy = y.charCodeAt(i);
600
+ if (cx === cy) continue;
601
+ return cx < 0xd800 && cy < 0xd800 ? cx - cy : compareBytes(x, y);
602
+ }
603
+ return x.length - y.length;
604
+ };
605
+ const added = [...changes.values()].flat().sort(compare);
606
+ const builder = staging.createBuilder();
607
+ let a = 0;
608
+ for (const entry of kept) {
609
+ while (a < added.length && compare(added[a], entry) < 0) builder.add(added[a++]);
610
+ builder.add(entry);
611
+ }
612
+ while (a < added.length) builder.add(added[a++]);
613
+ // the index is rewritten around the changed paths only: the kept entries count as up to
614
+ // date (as after the whole-index refresh git runs first), so the write checks no untouched
615
+ // racily clean file and the command reads only the paths it writes
616
+ await builder.finish({ upToDate: options.upToDate ?? true });
617
+ // a cache-tree computed for the entries just built
618
+ if (options.cacheTree) staging.setCacheTree?.(options.cacheTree);
619
+ // unpack-trees' cache_tree_update before its index write
620
+ if (options.updateCacheTreeWith) {
621
+ const { trees, format } = options.updateCacheTreeWith;
622
+ await updateIndexCacheTree(staging, trees, format);
623
+ }
624
+ if (options.write !== false) await staging.write();
625
+ }
626
+
627
+ /** Whether the index holds exactly `tree` (no staged change; git's index_differs_from). */
628
+ export function indexMatches(
629
+ index: Map<string, CheckedEntry>,
630
+ tree: Map<string, CheckedEntry>,
631
+ ): boolean {
632
+ return indexChanges(index, tree).length === 0;
633
+ }
634
+
635
+ /** The paths where the index differs from `tree`, sorted. */
636
+ export function indexChanges(
637
+ index: Map<string, CheckedEntry>,
638
+ tree: Map<string, CheckedEntry>,
639
+ ): string[] {
640
+ const out: string[] = [];
641
+ for (const path of new Set([...index.keys(), ...tree.keys()])) {
642
+ if (!sameEntry(index.get(path), tree.get(path))) out.push(path);
643
+ }
644
+ return out.sort();
645
+ }
646
+
647
+ /**
648
+ * The state files of an operation in progress, in git's directory: plain files through the
649
+ * checkout (`MERGE_MSG`, `sequencer/todo`, ...), pseudo refs through the ref store
650
+ * (`MERGE_HEAD`, `ORIG_HEAD`, `CHERRY_PICK_HEAD`, `REVERT_HEAD`, `AUTO_MERGE`).
651
+ */
652
+ export class OperationState {
653
+ constructor(
654
+ private readonly checkout: Checkout,
655
+ private readonly refs: CommandRefs,
656
+ ) {}
657
+
658
+ /** Whether the checkout can keep state files at all. */
659
+ get supported(): boolean {
660
+ return typeof this.checkout.writeStateFile === "function";
661
+ }
662
+
663
+ async read(name: string): Promise<string | undefined> {
664
+ const bytes = await this.checkout.readStateFile?.(name);
665
+ // a path in a state file (MERGE_MSG's conflicts) is its bytes, as git writes it
666
+ return bytes ? decodeGitPath(bytes) : undefined;
667
+ }
668
+
669
+ async write(name: string, content: string | Uint8Array): Promise<void> {
670
+ const bytes = typeof content === "string" ? encodeGitPath(content) : content;
671
+ await this.checkout.writeStateFile?.(name, bytes);
672
+ }
673
+
674
+ /** Appends to a state file (O_APPEND where the checkout can; else a rewrite). */
675
+ async append(name: string, content: string): Promise<void> {
676
+ if (this.checkout.appendStateFile) {
677
+ // the same bytes `write` would store (escaped bytes as themselves)
678
+ await this.checkout.appendStateFile(name, encodeGitPath(content));
679
+ return;
680
+ }
681
+ await this.write(name, `${(await this.read(name)) ?? ""}${content}`);
682
+ }
683
+
684
+ async remove(...names: string[]): Promise<void> {
685
+ for (const name of names) await this.checkout.removeStateFile?.(name);
686
+ }
687
+
688
+ /** The names in a state directory, sorted (empty: none, or a checkout that cannot list). */
689
+ async listDir(name: string): Promise<string[]> {
690
+ return (await this.checkout.listStateDir?.(name)) ?? [];
691
+ }
692
+
693
+ async exists(name: string): Promise<boolean> {
694
+ if ((await this.checkout.readStateFile?.(name)) !== undefined) return true;
695
+ return ((await this.checkout.listStateDir?.(name)) ?? []).length > 0;
696
+ }
697
+
698
+ async ref(name: string): Promise<ObjectId | undefined> {
699
+ const ref = await this.refs.get(name).catch(() => undefined);
700
+ return ref && "objectId" in ref && ref.objectId ? ref.objectId : undefined;
701
+ }
702
+
703
+ /**
704
+ * Writes a pseudo ref. With `old` (an id, or `null` for none), as git's refs_update_ref
705
+ * given the value it read: a ref store with a transaction hook shows it, and checks it under
706
+ * the lock (a store that cannot batch the ref writes it plainly).
707
+ */
708
+ async setRef(
709
+ name: string,
710
+ id: ObjectId,
711
+ options?: { old: ObjectId | null; log?: RefLogOptions },
712
+ ): Promise<void> {
713
+ if (options) {
714
+ const result = await this.refs.batch([{ name, old: options.old, new: id }], options.log);
715
+ if (result.ok) return;
716
+ if (
717
+ !result.rejected.every((r) => r.reason === "invalid-name" || r.reason === "unsupported")
718
+ ) {
719
+ throw Object.assign(
720
+ new Error(
721
+ `cannot update ${name}: ${result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ")}`,
722
+ ),
723
+ { rejected: result.rejected },
724
+ );
725
+ }
726
+ }
727
+ await this.refs.set(name, id);
728
+ }
729
+
730
+ async removeRef(...names: string[]): Promise<void> {
731
+ for (const name of names) {
732
+ if (await this.refs.has(name).catch(() => false)) await this.refs.delete(name);
733
+ }
734
+ }
735
+
736
+ /** Each name on its own, a failure ignored (git's unconditional `refs_delete_ref` calls). */
737
+ private async removeRefsIgnoringFailures(names: string[]): Promise<void> {
738
+ for (const name of names) await this.removeRef(name).catch(() => undefined);
739
+ }
740
+
741
+ /**
742
+ * Deletes pseudo refs whether they exist or not, as git's unconditional `refs_delete_ref`
743
+ * calls (AUTO_MERGE after a commit): a ref store with a transaction hook tells it of the
744
+ * deletion either way. Without one nothing can tell, and only the refs there are removed
745
+ * (a check is far cheaper than a deletion's transaction). A failure is ignored, as git
746
+ * ignores it there.
747
+ */
748
+ async deleteRef(...names: string[]): Promise<void> {
749
+ if (!refsWatched(this.refs)) {
750
+ await this.removeRefsIgnoringFailures(names);
751
+ return;
752
+ }
753
+ for (const name of names) await this.refs.delete(name).catch(() => false);
754
+ }
755
+
756
+ /**
757
+ * A pseudo ref git's sequencer writes and deletes again before anyone else could read it
758
+ * (CHERRY_PICK_HEAD of a rebase's pick that stops): written and deleted where a
759
+ * transaction hook hears both, else only deleted (a stale one goes either way).
760
+ */
761
+ async writeAndDeleteRef(name: string, id: ObjectId): Promise<void> {
762
+ if (refsWatched(this.refs)) await this.setRef(name, id);
763
+ await this.deleteRef(name);
764
+ }
765
+
766
+ /**
767
+ * Runs `body` with pseudo ref `name` at `id`, deleted once `body` succeeds (git's sequencer:
768
+ * CHERRY_PICK_HEAD written before the commit, deleted by do_commit after it). Only hooks
769
+ * can read it meanwhile, and they run only where a transaction hook is installed: without
770
+ * one it is written only when `body` fails, which leaves it, as git does.
771
+ */
772
+ async withRefDuring<T>(name: string, id: ObjectId, body: () => Promise<T>): Promise<T> {
773
+ const watched = refsWatched(this.refs);
774
+ if (watched) await this.setRef(name, id);
775
+ let result: T;
776
+ try {
777
+ result = await body();
778
+ } catch (error) {
779
+ if (!watched) await this.setRef(name, id).catch(() => undefined);
780
+ throw error;
781
+ }
782
+ await this.deleteRef(name);
783
+ return result;
784
+ }
785
+ }
786
+
787
+ /**
788
+ * Whether a reference-transaction hook is installed on `refs` (the files store while a
789
+ * command with a hook runner runs, or a receive-pack): writes it alone would see can be
790
+ * skipped without one.
791
+ */
792
+ export function refsWatched(refs: unknown): boolean {
793
+ return (refs as { getTransactionHook?(): unknown }).getTransactionHook?.() !== undefined;
794
+ }
795
+
796
+ /** The parts of a command a merge's write needs. */
797
+ export interface MergeWriteContext {
798
+ workingCopy: WorkingCopy;
799
+ worktree?: Worktree;
800
+ staging: Staging;
801
+ blobs: Blobs;
802
+ trees: CommandTrees;
803
+ /**
804
+ * Collects what the sparse checkout prints on stderr while the write applies its patterns
805
+ * (git's `warning:` lines for files left despite the patterns), one entry per line.
806
+ */
807
+ sparseWarnings?: string[];
808
+ }
809
+
810
+ /** Why a merge's write was refused: git's message, and the paths it lists. */
811
+ export interface MergeRefusal {
812
+ message: string;
813
+ paths: string[];
814
+ }
815
+
816
+ /** Whether an untracked, not ignored file or link stands at `path`. */
817
+ async function untrackedFileAt(worktree: Worktree, path: string): Promise<boolean> {
818
+ const entry = await worktree.getEntry(path);
819
+ if (!entry || entry.isDirectory) return false;
820
+ return !(await worktree.isIgnored(path));
821
+ }
822
+
823
+ /**
824
+ * git's two-way unpack-trees (`twoway_merge`, with update) from `head` to `target` on the
825
+ * current index and worktree, as merge-ort's checkout of its result and a fast-forward
826
+ * run it: a path the two trees agree on keeps its index entry and worktree file (local
827
+ * edits survive); a path they differ on is switched when the index and the worktree still
828
+ * hold `head`'s version, else everything is refused with git's messages. Then the
829
+ * conflicts are staged at stages 1-3 (`record_conflicted_index_entries`).
830
+ *
831
+ * @returns the refusal (nothing written), or undefined once written
832
+ */
833
+ export async function switchTrees(
834
+ ctx: MergeWriteContext,
835
+ head: Map<string, CheckedEntry>,
836
+ target: Map<string, CheckedEntry>,
837
+ options: SwitchTreesOptions,
838
+ ): Promise<MergeRefusal | undefined> {
839
+ // unpack-trees with a destination index: the index written next follows a worktree update
840
+ // (post-index-change's first flag)
841
+ markIndexUpdate(ctx.staging, { workdir: true });
842
+ // in a sparse checkout: unpack-trees with its patterns (a conflict's file is written
843
+ // whatever they say where its entry was outside the checkout, as
844
+ // record_conflicted_index_entries does; one leaving the checkout is unlinked)
845
+ const conflicts = [...(options.conflicts ?? [])];
846
+ // without update nothing in the worktree is touched (unpack-trees skips the sparse
847
+ // checkout: `skip_sparse_checkout` when `!o->update`)
848
+ const sparse =
849
+ options.update === false || options.skipSparseCheckout
850
+ ? undefined
851
+ : await SparseUnpack.start(ctx);
852
+ sparse?.conflict(conflicts.map((c) => c.stagePath));
853
+ const switched = await switchTreesWith(ctx, head, target, { ...options, conflicts }, sparse);
854
+ if (switched.refused) return switched.refused;
855
+ if (sparse) {
856
+ const outcome = await sparse.finish(ctx, { written: switched.written });
857
+ pushSparseWarnings(ctx.sparseWarnings, sparse, outcome, true);
858
+ }
859
+ return undefined;
860
+ }
861
+
862
+ /** Options of {@link switchTrees}. */
863
+ export interface SwitchTreesOptions {
864
+ /** Names the operation in git's refusal messages */
865
+ action: "merge" | "checkout";
866
+ /** Names the operation in restore failures */
867
+ operation: string;
868
+ /** The conflicts to stage */
869
+ conflicts?: Iterable<OrtConflict>;
870
+ /**
871
+ * The stored tree the switch leaves in the index (`target` whole, or the tree `target`
872
+ * changes HEAD to): planned from (saves storing it again), and written as the index's
873
+ * cache-tree, as unpack-trees does
874
+ */
875
+ targetTree?: ObjectId;
876
+ /**
877
+ * Whether the worktree is updated (default true: `-u`). False (`read-tree -m H M`
878
+ * without `-u`): the entries are still checked against their files (`verify_uptodate`),
879
+ * but nothing is written or removed and untracked files are not looked for.
880
+ */
881
+ update?: boolean;
882
+ /** `--no-sparse-checkout`: the sparse-checkout patterns are not applied */
883
+ skipSparseCheckout?: boolean;
884
+ /**
885
+ * unpack-trees without porcelain messages (`read-tree`): the refusal is the first path's
886
+ * one `error:` line ("Entry 'x' would be overwritten by merge. Cannot merge.", ...)
887
+ */
888
+ plainErrors?: boolean;
889
+ /**
890
+ * unpack-trees' `initial_checkout` (`read-tree -m H M` into an unborn index,
891
+ * `isIndexUnborn`): a path of `target` missing from the index is taken as new
892
+ * (written, untracked files in the way refused), never as a staged deletion
893
+ */
894
+ initialCheckout?: boolean;
895
+ }
896
+
897
+ /** git's default unpack-trees messages (`unpack_plumbing_errors`) for one refused path. */
898
+ export function plainUnpackError(
899
+ kind: "wouldOverwrite" | "notUptodate" | "lostDir" | "untracked" | "untrackedRemoved",
900
+ path: string,
901
+ ): string {
902
+ switch (kind) {
903
+ case "wouldOverwrite":
904
+ return `error: Entry '${path}' would be overwritten by merge. Cannot merge.`;
905
+ case "notUptodate":
906
+ return `error: Entry '${path}' not uptodate. Cannot merge.`;
907
+ case "lostDir":
908
+ return `error: Updating '${path}' would lose untracked files in it`;
909
+ case "untracked":
910
+ return `error: Untracked working tree file '${path}' would be overwritten by merge.`;
911
+ case "untrackedRemoved":
912
+ return `error: Untracked working tree file '${path}' would be removed by merge.`;
913
+ }
914
+ }
915
+
916
+ async function switchTreesWith(
917
+ ctx: MergeWriteContext,
918
+ head: Map<string, CheckedEntry>,
919
+ target: Map<string, CheckedEntry>,
920
+ options: SwitchTreesOptions,
921
+ sparse: SparseUnpack | undefined,
922
+ ): Promise<{ refused?: MergeRefusal; written: Set<string> }> {
923
+ const { index, unmerged } = await readIndex(ctx.staging);
924
+ // a path staying outside the sparse checkout: neither checked nor touched in the worktree
925
+ const quiet = (path: string) => sparse?.leavesAlone(path) === true;
926
+ const update = options.update !== false;
927
+ const checked = ctx.worktree;
928
+ const worktree = update ? checked : undefined;
929
+ const trust = checked ? worktreeModeTrust(ctx.workingCopy, checked) : undefined;
930
+ const indexTime = ctx.staging.getUpdateTime();
931
+ const ignoreCase = coreBool(ctx.workingCopy, "ignorecase", false);
932
+ const staged: string[] = [];
933
+ const local: string[] = [];
934
+ const untrackedRemoved: string[] = [];
935
+ const updates: string[] = [];
936
+ const removes: string[] = [];
937
+ const paths = [...new Set([...head.keys(), ...target.keys()])].sort();
938
+ for (const path of paths) {
939
+ const h = head.get(path);
940
+ const t = target.get(path);
941
+ const i = index.get(path);
942
+ if (sameEntry(h, t) && !(options.initialCheckout && t && !i)) continue;
943
+ if (i) {
944
+ if (t && sameEntry(i, t)) continue;
945
+ if (!sameEntry(i, h)) {
946
+ // a staged change the switch would lose (reject_merge)
947
+ staged.push(path);
948
+ continue;
949
+ }
950
+ if (checked && !quiet(path) && (await entryNotUptodate(checked, path, i, trust, indexTime))) {
951
+ local.push(path);
952
+ continue;
953
+ }
954
+ (t ? updates : removes).push(path);
955
+ continue;
956
+ }
957
+ if (t) {
958
+ // a staged deletion of a path the target changes (none in an initial checkout)
959
+ if (h && !options.initialCheckout) staged.push(path);
960
+ else updates.push(path);
961
+ continue;
962
+ }
963
+ // a deletion already staged: an untracked file there would be removed
964
+ if (worktree && (await untrackedFileAt(worktree, path))) untrackedRemoved.push(path);
965
+ }
966
+ // a dirty file the target deletes is reported as a local change only (git's
967
+ // verify_clean_subdirectory counts tracked files under a replaced directory as such)
968
+ const deleting = [...removes, ...local.filter((p) => !target.has(p))];
969
+ // the files written: in a sparse checkout, those of the paths in its patterns only
970
+ const writing = new Set(updates.filter((p) => !sparse || sparse.writes(p)));
971
+ const found = worktree
972
+ ? await findInTheWay(worktree, {
973
+ writes: [...writing],
974
+ removes: new Set(deleting),
975
+ index,
976
+ ...(await restoreCaseOptions(worktree, ignoreCase)),
977
+ // verify_clean_subdirectory's read_directory folds case: removed before the writes
978
+ caseVariantsExpendable: true,
979
+ })
980
+ : { untracked: [], lostDirs: [], caseVariants: [] };
981
+ const message = options.plainErrors
982
+ ? firstPlainError({
983
+ wouldOverwrite: staged,
984
+ notUptodate: local,
985
+ lostDir: found.lostDirs,
986
+ untracked: found.untracked,
987
+ untrackedRemoved,
988
+ })
989
+ : overwriteMessage(options.action, {
990
+ staged,
991
+ local,
992
+ lostDirs: found.lostDirs,
993
+ untracked: found.untracked,
994
+ untrackedRemoved,
995
+ });
996
+ if (message) {
997
+ return {
998
+ refused: {
999
+ message,
1000
+ paths: [...staged, ...local, ...found.lostDirs, ...found.untracked, ...untrackedRemoved],
1001
+ },
1002
+ written: new Set(),
1003
+ };
1004
+ }
1005
+
1006
+ // record_conflicted_index_entries checks out a conflict's stage-0 entry left skip-worktree
1007
+ // (the switch kept it: the trees agree on it, or the index holds the target's already):
1008
+ // its file is written whatever the patterns say, as checkout_entry with force writes it
1009
+ let planTarget = target;
1010
+ if (worktree && sparse) {
1011
+ for (const conflict of options.conflicts ?? []) {
1012
+ const path = conflict.stagePath;
1013
+ const i = index.get(path) as IndexEntryInput | undefined;
1014
+ if (!i?.skipWorktree || writing.has(path) || removes.includes(path)) continue;
1015
+ const t = target.get(path);
1016
+ if (t ? !sameEntry(i, t) : head.has(path)) continue;
1017
+ if (planTarget === target) planTarget = new Map(target);
1018
+ planTarget.set(path, i);
1019
+ writing.add(path);
1020
+ }
1021
+ }
1022
+
1023
+ // the worktree: deletions first (a deleted file `d` makes way for `d/x`), then the files
1024
+ if (worktree) {
1025
+ if (sparse) {
1026
+ // apply_sparse_checkout before check_updates: the files leaving the checkout
1027
+ const removing = new Set(removes);
1028
+ const updating = new Set(updates);
1029
+ const unlink = await sparse.leaving(
1030
+ worktree,
1031
+ (p) => (removing.has(p) ? undefined : updating.has(p) ? target.get(p) : index.get(p)),
1032
+ { trust },
1033
+ );
1034
+ await sparse.unlink(worktree, unlink);
1035
+ }
1036
+ for (const path of removes) {
1037
+ if (quiet(path)) continue;
1038
+ await worktree.remove(path);
1039
+ await pruneEmptyParents(worktree, path);
1040
+ }
1041
+ // core.ignorecase: what verify_clean_subdirectory took as tracked in a directory a file
1042
+ // replaces goes with the directory (checkout_entry removes the subtree)
1043
+ await removeCaseVariants(worktree, found.caseVariants ?? []);
1044
+ if (writing.size > 0) {
1045
+ // only the written paths are planned (each validated, its blob checked)
1046
+ const plan = await planPathsRestore(
1047
+ ctx,
1048
+ planTarget,
1049
+ planTarget === target ? options.targetTree : undefined,
1050
+ writing,
1051
+ options.operation,
1052
+ );
1053
+ // the attributes of the index the switch leaves (git's o->result): only its
1054
+ // attributes files are looked up
1055
+ const result = new Map<string, ObjectId>();
1056
+ for (const [path, entry] of index) {
1057
+ if (path.endsWith(".gitattributes")) result.set(path, entry.objectId);
1058
+ }
1059
+ for (const path of removes) result.delete(path);
1060
+ for (const path of updates) result.set(path, (target.get(path) as CheckedEntry).objectId);
1061
+ await writeTreeRestorePlan(
1062
+ worktree,
1063
+ ctx.blobs,
1064
+ {
1065
+ ...plan,
1066
+ entries: plan.entries.filter((e) => writing.has(e.path)),
1067
+ gitlinks: plan.gitlinks.filter((e) => writing.has(e.path)),
1068
+ },
1069
+ options.operation,
1070
+ {
1071
+ symlinks: trust?.symlinks ?? true,
1072
+ gitlinks: true,
1073
+ replaceInTheWay: true,
1074
+ attributes: { direction: "checkout", index: attributesIndexOf(result) },
1075
+ },
1076
+ );
1077
+ }
1078
+ }
1079
+
1080
+ // the index: the switched paths take the target's entries (with the stat of the files
1081
+ // just written), the conflicts their stages
1082
+ const changes = new Map<string, IndexEntryOptions[]>();
1083
+ for (const path of removes) changes.set(path, []);
1084
+ for (const path of updates) {
1085
+ const t = target.get(path) as CheckedEntry;
1086
+ // the stat of a file written (an entry left outside the checkout has none)
1087
+ const stats = worktree && writing.has(path) ? await worktree.getEntry(path) : undefined;
1088
+ // the skip-worktree bit of the entry replaced is kept (merged_entry: "Migrate old flags
1089
+ // over"); assume-unchanged is not
1090
+ const old = index.get(path) as IndexEntryInput | undefined;
1091
+ changes.set(path, [
1092
+ {
1093
+ path,
1094
+ objectId: t.objectId,
1095
+ mode: t.mode,
1096
+ ...entryStatOf(stats && !stats.isDirectory ? stats : {}),
1097
+ ...(old?.skipWorktree ? { skipWorktree: true } : {}),
1098
+ },
1099
+ ]);
1100
+ }
1101
+ const conflicts = [...(options.conflicts ?? [])];
1102
+ for (const conflict of conflicts) {
1103
+ const stages: [CheckedEntry | undefined, 1 | 2 | 3][] = [
1104
+ [conflict.base, 1],
1105
+ [conflict.ours, 2],
1106
+ [conflict.theirs, 3],
1107
+ ];
1108
+ const list: IndexEntryOptions[] = [];
1109
+ for (const [entry, stage] of stages) {
1110
+ if (!entry) continue;
1111
+ list.push({
1112
+ path: conflict.stagePath,
1113
+ objectId: entry.objectId,
1114
+ mode: entry.mode,
1115
+ stage,
1116
+ size: 0,
1117
+ mtime: 0,
1118
+ });
1119
+ }
1120
+ // a stage-0 entry the switch wrote here gives way to the conflict's stages
1121
+ changes.set(conflict.stagePath, [
1122
+ ...(changes.get(conflict.stagePath) ?? []).filter((e) => (e.stage ?? 0) > 0),
1123
+ ...list,
1124
+ ]);
1125
+ }
1126
+ // unpack-trees writes a new index: the resolve-undo records are gone (git keeps them only
1127
+ // through commands that edit the index in place)
1128
+ ctx.staging.clearResolveUndo?.();
1129
+ let switchedCacheTree: CacheTree | undefined;
1130
+ if (options.targetTree && ctx.staging.setCacheTree) {
1131
+ // the cache-tree of the target (unpack_trees: the index's cache-tree, each path changed
1132
+ // invalidated, then cache_tree_update: only invalid directories are read), the
1133
+ // directories of the intent-to-add entries kept and of the conflicts invalid
1134
+ // (record_conflicted_index_entries)
1135
+ const previous = ctx.staging.getCacheTree?.();
1136
+ if (previous) {
1137
+ for (const path of [...updates, ...removes]) invalidateCacheTreePath(previous, path);
1138
+ }
1139
+ const cacheTree = await updateCacheTree(
1140
+ ctx.trees,
1141
+ options.targetTree,
1142
+ previous,
1143
+ objectFormatOf(ctx.workingCopy.history),
1144
+ );
1145
+ // the index the switch leaves is the target only where it switched: an entry it kept
1146
+ // (a staged change the two trees agree on, carried over) differs from the target, and
1147
+ // its directories are invalid, as cache_tree_update computes them from the index
1148
+ const result = new Map<string, CheckedEntry>();
1149
+ for (const [path, entry] of index) {
1150
+ const e = entry as IndexEntryInput;
1151
+ if (changes.has(path) || e.intentToAdd) continue;
1152
+ result.set(path, { objectId: entry.objectId, mode: entry.mode });
1153
+ }
1154
+ for (const path of updates) {
1155
+ if (changes.get(path)?.some((e) => (e.stage ?? 0) === 0)) {
1156
+ result.set(path, target.get(path) as CheckedEntry);
1157
+ }
1158
+ }
1159
+ await invalidateCacheTreeAgainstIndex(
1160
+ ctx.trees,
1161
+ cacheTree,
1162
+ options.targetTree,
1163
+ result,
1164
+ previous,
1165
+ );
1166
+ for (const path of unmerged) invalidateCacheTreePath(cacheTree, path);
1167
+ for (const [path, entry] of index) {
1168
+ const e = entry as IndexEntryInput;
1169
+ if (e.intentToAdd && !changes.has(path)) {
1170
+ invalidateCacheTreeForIntentToAdd(cacheTree, path);
1171
+ }
1172
+ }
1173
+ for (const conflict of conflicts) {
1174
+ invalidateCacheTreePath(cacheTree, conflict.stagePath);
1175
+ }
1176
+ switchedCacheTree = cacheTree;
1177
+ }
1178
+ // set once the changes are in: it describes the index they leave
1179
+ await rewriteIndex(ctx.staging, changes, { cacheTree: switchedCacheTree });
1180
+ return { written: worktree ? writing : new Set() };
1181
+ }
1182
+
1183
+ /**
1184
+ * The refusal unpack-trees prints without porcelain messages: it stops at the first path
1185
+ * refused (in path order), with that path's one `error:` line.
1186
+ */
1187
+ export function firstPlainError(
1188
+ found: Partial<Record<Parameters<typeof plainUnpackError>[0], string[]>>,
1189
+ ): string | undefined {
1190
+ let best: { kind: Parameters<typeof plainUnpackError>[0]; path: string } | undefined;
1191
+ for (const [kind, paths] of Object.entries(found) as [
1192
+ Parameters<typeof plainUnpackError>[0],
1193
+ string[] | undefined,
1194
+ ][]) {
1195
+ for (const path of paths ?? []) {
1196
+ if (!best || compareGitPaths(path, best.path) < 0) best = { kind, path };
1197
+ }
1198
+ }
1199
+ return best ? plainUnpackError(best.kind, best.path) : undefined;
1200
+ }
1201
+
1202
+ /** git's `# Conflicts:` block appended to MERGE_MSG. */
1203
+ export function conflictsComment(paths: string[], unclean = paths.length > 0): string {
1204
+ if (!unclean) return "";
1205
+ return `\n# Conflicts:\n${paths.map((p) => `#\t${p}\n`).join("")}`;
1206
+ }
1207
+
1208
+ /** The commit's first line (git's subject, as in `<abbrev> (<subject>)`). */
1209
+ export function subjectOf(message: string): string {
1210
+ // git's format_subject after skip_blank_lines: the first paragraph's lines, each without
1211
+ // its trailing blanks (git's isspace: ASCII space, tab, LF, CR; never a no-break space),
1212
+ // joined with a space
1213
+ const lines = message.split("\n").map((l) => l.replace(/[ \t\r]+$/, ""));
1214
+ let i = 0;
1215
+ while (i < lines.length && lines[i] === "") i++;
1216
+ const subject: string[] = [];
1217
+ for (; i < lines.length && lines[i] !== ""; i++) subject.push(lines[i] as string);
1218
+ return subject.join(" ");
1219
+ }