@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
@@ -33,18 +33,98 @@
33
33
  * ```
34
34
  */
35
35
 
36
- import { FileMode, isValidBranchName, type ObjectId, type Ref } from "@statewalker/vcs-core";
37
- import { UpdateStagingEntry } from "@statewalker/vcs-working-tree";
38
-
39
36
  import {
37
+ FileMode,
38
+ isSymbolicRef,
39
+ isValidBranchName,
40
+ type ObjectId,
41
+ type Ref,
42
+ } from "@statewalker/vcs-core";
43
+ import { type ConflictStyle, parseGitBool } from "@statewalker/vcs-utils";
44
+ import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
45
+ import {
46
+ attributesIndexOf,
47
+ cacheTreeOfTree,
48
+ entryStatOf,
49
+ isIndexUnborn,
50
+ type StagingEntry,
51
+ type Worktree,
52
+ } from "@statewalker/vcs-working-tree";
53
+ import {
54
+ IncompatibleOptionsError,
55
+ InvalidArgumentError,
40
56
  InvalidRefNameError,
41
57
  MissingArgumentError,
42
- NotADirectoryError,
43
- PathNotFoundInTreeError,
44
- PathNotInIndexError,
58
+ NoHeadError,
59
+ NotACommitError,
60
+ RefAlreadyExistsError,
45
61
  RefNotFoundError,
62
+ SwitchRefusedError,
46
63
  } from "../errors/index.js";
47
64
  import { GitCommand } from "../git-command.js";
65
+ import { RemoteConfigStore } from "../remote-config/index.js";
66
+ import { StashApplyStatus } from "../results/index.js";
67
+ import {
68
+ type PatchCompatibility,
69
+ type PatchOptions,
70
+ type PatchResult,
71
+ type PatchSelector,
72
+ patchRevisionOf,
73
+ pathPatchMode,
74
+ runPatchSelection,
75
+ } from "./add-patch/index.js";
76
+ import {
77
+ guessRemoteBranch,
78
+ installTracking,
79
+ planTracking,
80
+ type TrackingPlan,
81
+ TrackMode,
82
+ trackableStart,
83
+ } from "./branch-tracking.js";
84
+ import { type CheckoutPathsOutcome, runPathCheckout } from "./checkout-paths.js";
85
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
86
+ import { runPostCheckoutHook } from "./git-hooks.js";
87
+ import { hostEnvironmentOf } from "./git-ident.js";
88
+ import { OperationState, updateIndexCacheTree } from "./merge-support.js";
89
+ import { globalPathspecMagic, parsePathspecFile } from "./pathspec.js";
90
+ import { markIndexUpdate } from "./post-index-change.js";
91
+ import { reflogMessages } from "./reflog-messages.js";
92
+ import { checkFlaggedEntries, recordWrittenStat, restoreWorktreeHard } from "./reset-command.js";
93
+ import { removeBranchState } from "./sequencer-support.js";
94
+ import { pushSparseWarnings, SparseUnpack } from "./sparse-checkout-support.js";
95
+ import { StashApplyCommand } from "./stash-apply-command.js";
96
+ import { StashCreateCommand } from "./stash-create-command.js";
97
+ import { STASH_REF } from "./stash-list-command.js";
98
+ import { planTreeRestore, restoreCaseOptions, writeTreeRestorePlan } from "./tree-restore.js";
99
+ import {
100
+ entryNotUptodate,
101
+ findInTheWay,
102
+ flaggedEntryDiffers,
103
+ overwriteMessage,
104
+ pruneEmptyParents,
105
+ } from "./worktree-overwrite-checks.js";
106
+ import { refuseIfCheckedOut, shortBranchName } from "./worktree-support.js";
107
+
108
+ /** git's `apply_save_autostash_oid` advice when the autostash conflicts. */
109
+ const AUTOSTASH_CONFLICT_ADVICE = [
110
+ "Your local changes are stashed, however applying them",
111
+ "resulted in conflicts. You can either resolve the conflicts",
112
+ 'and then discard the stash with "git stash drop", or, if you',
113
+ 'do not want to resolve them now, run "git reset --hard" and',
114
+ 'apply the local changes later by running "git stash pop".',
115
+ ].join("\n");
116
+
117
+ /**
118
+ * The name git's `switch_branches` gives the target (`new_branch_info->name`), which
119
+ * labels the autostash: the branch, the name as given for a detached HEAD, the start point
120
+ * of a branch being created.
121
+ */
122
+ function autostashLabel(plan: SwitchPlan): string {
123
+ return plan.kind === "create" ? plan.startName : plan.logName;
124
+ }
125
+
126
+ /** Names a branch checkout in failure messages. */
127
+ const CHECKOUT = "checkout";
48
128
 
49
129
  /**
50
130
  * Stage to check out for conflicting files.
@@ -92,8 +172,80 @@ export interface CheckoutResult {
92
172
 
93
173
  /** The ref that was checked out (null for path checkout) */
94
174
  readonly ref: Ref | null;
175
+
176
+ /**
177
+ * Why a checkout was refused, in git's words (`status` CONFLICTS): local changes or
178
+ * untracked files the switch would overwrite, or an index with unmerged entries.
179
+ */
180
+ readonly message?: string;
181
+
182
+ /**
183
+ * What a branch switch printed on stderr while applying the sparse checkout's patterns,
184
+ * line by line (the patterns' warnings, git's "The following paths are not up to date and
185
+ * were left despite sparse patterns:" block), and git's "Autostash exists; creating a new
186
+ * stash entry." lines when a stopped merge's autostash is kept on `refs/stash`; absent when
187
+ * there was nothing to say.
188
+ */
189
+ readonly warnings?: string[];
190
+
191
+ /**
192
+ * git's exit status where `status` alone does not give it (OK: 0, CONFLICTS: 1): a path
193
+ * checkout that could not write an entry exits 255
194
+ */
195
+ readonly exitCode?: number;
196
+
197
+ /** With `setPatch`: what the hunk selection printed and applied */
198
+ readonly patch?: PatchResult;
199
+ }
200
+
201
+ /** A tree or index entry, as the two-way merge compares them (index entries with stat). */
202
+ interface Side {
203
+ objectId: ObjectId;
204
+ mode: number;
205
+ size?: number;
206
+ mtime?: number;
207
+ ctime?: number;
208
+ }
209
+
210
+ const sameSide = (a: Side | undefined, b: Side | undefined) =>
211
+ a === undefined || b === undefined ? a === b : a.objectId === b.objectId && a.mode === b.mode;
212
+
213
+ /**
214
+ * How a new branch tracks its start point, decided before anything is written; the
215
+ * refusals are thrown where git dies (`create_branch`): a start point `--track` cannot
216
+ * track before the branch is created, ambiguous remotes after.
217
+ */
218
+ interface CreateTracking {
219
+ readonly plan?: TrackingPlan;
220
+ readonly notABranch?: unknown;
221
+ readonly ambiguous?: unknown;
95
222
  }
96
223
 
224
+ /**
225
+ * What a branch checkout switches to; `logName` names it in HEAD's reflog line. A
226
+ * `stay` plan (`checkout HEAD`) checks the worktree out but leaves HEAD as it is.
227
+ */
228
+ type SwitchPlan =
229
+ | { kind: "branch"; branch: string; targetId: ObjectId; logName: string }
230
+ | {
231
+ kind: "create";
232
+ branch: string;
233
+ startName: string;
234
+ targetId: ObjectId;
235
+ logName: string;
236
+ tracking: CreateTracking;
237
+ }
238
+ | {
239
+ kind: "orphan";
240
+ branch: string;
241
+ targetId?: undefined;
242
+ logName: string;
243
+ /** `checkout --orphan <new> <start-point>`: the commit whose tree the switch merges to */
244
+ startId?: ObjectId;
245
+ }
246
+ | { kind: "detach"; targetId: ObjectId; logName: string }
247
+ | { kind: "stay"; targetId: ObjectId; logName: string };
248
+
97
249
  /**
98
250
  * Command to checkout branches, commits, or paths.
99
251
  *
@@ -103,6 +255,11 @@ export interface CheckoutResult {
103
255
  export class CheckoutCommand extends GitCommand<CheckoutResult> {
104
256
  private name: string | undefined;
105
257
  private createBranch = false;
258
+ private patch = false;
259
+ private patchSelector?: PatchSelector;
260
+ private patchOptions: PatchOptions = {};
261
+ private patchCompatibility: PatchCompatibility = "2.56";
262
+ private forceCreateBranch = false;
106
263
  private orphan = false;
107
264
  private force = false;
108
265
  // biome-ignore lint/correctness/noUnusedPrivateClassMembers: JGit compatibility - will be used for branch reset
@@ -111,6 +268,24 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
111
268
  private paths: string[] = [];
112
269
  private allPaths = false;
113
270
  private stage: CheckoutStage | undefined;
271
+ private ignoreOtherWorktrees = false;
272
+ private detach = false;
273
+ private orphanFromEmptyTree = false;
274
+ private onlyMergeOnSwitchingBranches = false;
275
+ private track = TrackMode.DEFAULT;
276
+ private guess?: boolean;
277
+ private protectUntracked = false;
278
+ private merge = false;
279
+ private overlay?: boolean;
280
+ private ignoreSkipWorktreeBits = false;
281
+ private conflictStyle?: ConflictStyle;
282
+ private quiet = false;
283
+ private countCheckoutPaths = false;
284
+ private pathspecFromFile: string[] = [];
285
+ /** Whether `--pathspec-from-file` was given (an empty file included) */
286
+ private pathspecFileGiven = false;
287
+ /** Set by a `merge` checkout the two-way merge refused: what the autostash needs */
288
+ private autostashSwitch?: { label: string; base: string };
114
289
 
115
290
  /**
116
291
  * Set the name of the branch or commit to check out.
@@ -133,7 +308,9 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
133
308
  * If true, a new branch with setName() will be created at setStartPoint()
134
309
  * (or HEAD if not specified) and checked out.
135
310
  *
136
- * Equivalent to `git checkout -b <name>`.
311
+ * Equivalent to `git checkout -b <name>`: refused when the branch exists
312
+ * (`RefAlreadyExistsError`, "fatal: a branch named 'x' already exists"); use
313
+ * {@link setForceCreateBranch} (`-B`) to reset an existing branch instead.
137
314
  *
138
315
  * @param createBranch Whether to create a new branch
139
316
  * @returns this for chaining
@@ -141,6 +318,22 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
141
318
  setCreateBranch(createBranch: boolean): this {
142
319
  this.checkCallable();
143
320
  this.createBranch = createBranch;
321
+ if (!createBranch) this.forceCreateBranch = false;
322
+ return this;
323
+ }
324
+
325
+ /**
326
+ * Create the branch named by setName(), or reset it to the start point when it exists,
327
+ * and check it out (git's `checkout -B <name> [<start-point>]`; "branch: Reset to
328
+ * <start>" in its reflog). Implies {@link setCreateBranch}.
329
+ *
330
+ * @param force Whether to create or reset the branch
331
+ * @returns this for chaining
332
+ */
333
+ setForceCreateBranch(force: boolean): this {
334
+ this.checkCallable();
335
+ this.forceCreateBranch = force;
336
+ if (force) this.createBranch = true;
144
337
  return this;
145
338
  }
146
339
 
@@ -178,6 +371,147 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
178
371
  return this;
179
372
  }
180
373
 
374
+ /**
375
+ * Check out a branch even when another worktree has it checked out (git's
376
+ * `--ignore-other-worktrees`). Without it such a checkout, and resetting such a branch
377
+ * with `setForceCreateBranch` (`checkout -B`, as git 2.44 and later refuse it), is refused with
378
+ * `BranchUsedByWorktreeError` ("'x' is already used by worktree at '<path>'"), where the
379
+ * backend keeps linked worktrees (`WorkingCopy.worktrees`).
380
+ *
381
+ * @param ignore Whether to ignore other worktrees
382
+ * @returns this for chaining
383
+ */
384
+ setIgnoreOtherWorktrees(ignore: boolean): this {
385
+ this.checkCallable();
386
+ this.ignoreOtherWorktrees = ignore;
387
+ return this;
388
+ }
389
+
390
+ /**
391
+ * Detach HEAD at the commit named by {@link setName} (`HEAD` when no name is set), even
392
+ * when it names a branch (git's `checkout --detach [<commit>]`): HEAD's reflog reads
393
+ * `checkout: moving from main to HEAD` (or the name as given).
394
+ *
395
+ * @param detach Whether to detach HEAD
396
+ * @returns this for chaining
397
+ */
398
+ setDetach(detach: boolean): this {
399
+ this.checkCallable();
400
+ this.detach = detach;
401
+ return this;
402
+ }
403
+
404
+ /**
405
+ * How a branch created by the checkout tracks its start point (git's `--track`,
406
+ * `--track=inherit`, `--no-track`); by default as `branch.autoSetupMerge` says, which
407
+ * tracks a remote-tracking start point (`branch.<name>.remote`, `branch.<name>.merge`).
408
+ *
409
+ * @param mode Tracking mode
410
+ * @returns this for chaining
411
+ */
412
+ setTrack(mode: TrackMode): this {
413
+ this.checkCallable();
414
+ this.track = mode;
415
+ return this;
416
+ }
417
+
418
+ /**
419
+ * Whether a name no ref has is taken for the one remote-tracking branch of that name
420
+ * (git's `--guess`/`--no-guess`, default `checkout.guess`, true): `checkout dev` with
421
+ * only `origin/dev` creates `dev` from it, tracking it. With several remotes having it,
422
+ * `checkout.defaultRemote` picks one, else the checkout is refused (`'dev' matched
423
+ * multiple (2) remote tracking branches`).
424
+ *
425
+ * @param guess Whether to guess
426
+ * @returns this for chaining
427
+ */
428
+ setGuess(guess: boolean): this {
429
+ this.checkCallable();
430
+ this.guess = guess;
431
+ return this;
432
+ }
433
+
434
+ /**
435
+ * git's `only_merge_on_switching_branches` (`git switch`, and `git checkout -b <new>`
436
+ * given exactly so): a switch that names no target (a new branch without a start point,
437
+ * `--detach` without a commit) only moves HEAD, leaving the index and the worktree as
438
+ * they are (no index write, no check of unmerged entries, an unborn index left unborn).
439
+ * By default, as `git checkout` with any other arguments, such a switch still runs the
440
+ * two-way merge from HEAD to HEAD (an unborn index is then checked out).
441
+ *
442
+ * @param only Whether only a switch to a named target merges
443
+ * @returns this for chaining
444
+ */
445
+ setOnlyMergeOnSwitchingBranches(only: boolean): this {
446
+ this.checkCallable();
447
+ this.onlyMergeOnSwitchingBranches = only;
448
+ return this;
449
+ }
450
+
451
+ /** Whether this switch skips merge_working_tree (see {@link setOnlyMergeOnSwitchingBranches}). */
452
+ private skipsMergeWorkingTree(): boolean {
453
+ if (!this.onlyMergeOnSwitchingBranches || this.orphan) return false;
454
+ if (this.createBranch || this.forceCreateBranch) return this.startPoint === undefined;
455
+ return this.detach && this.name === undefined;
456
+ }
457
+
458
+ /**
459
+ * With {@link setOrphan}: the new branch starts from an empty index and worktree, the
460
+ * tracked files removed as by a switch to an empty tree (git's `switch --orphan`; local
461
+ * changes to tracked files refuse it, untracked files stay).
462
+ *
463
+ * @param empty Whether the orphan starts empty
464
+ * @returns this for chaining
465
+ */
466
+ setOrphanFromEmptyTree(empty: boolean): this {
467
+ this.checkCallable();
468
+ this.orphanFromEmptyTree = empty;
469
+ return this;
470
+ }
471
+
472
+ /**
473
+ * With {@link setForced}: local changes are thrown away but untracked files in the way
474
+ * still refuse the switch (git's `switch --discard-changes` without `-f`, a reset that
475
+ * protects untracked files): `error: Untracked working tree file '<path>' would be
476
+ * overwritten by merge.`
477
+ *
478
+ * @param protect Whether untracked files are kept
479
+ * @returns this for chaining
480
+ */
481
+ setProtectUntracked(protect: boolean): this {
482
+ this.checkCallable();
483
+ this.protectUntracked = protect;
484
+ return this;
485
+ }
486
+
487
+ /**
488
+ * `-m` / `--merge` (git 2.55+): when local changes stand in the way of the switch, they
489
+ * are carried over as git does it, through an autostash. The changes are stashed, the
490
+ * switch made from a clean index and worktree, and the stash applied on top with the
491
+ * conflict labels `<target>` (the new branch's side) and `local` (the changes). Clean,
492
+ * the result is `OK` with message `Applied autostash.` (staged changes come back
493
+ * unstaged, new files staged, as `git stash apply` leaves them). With conflicts the
494
+ * switch is still made: status `CONFLICTS` with `ref` set (HEAD's new value), the
495
+ * conflicted paths at stages 1-3 with conflict markers, the changes kept as `stash@{0}`
496
+ * ("autostash while switching to '<target>'"), and git's advice as the message.
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * const result = await git.checkout().setName("feature").setMerge(true).call();
501
+ * if (result.status === CheckoutStatus.CONFLICTS && result.ref) {
502
+ * // switched; resolve result.conflicts, then `git stash drop`
503
+ * }
504
+ * ```
505
+ *
506
+ * @param merge Whether to merge local changes into the switch
507
+ * @returns this for chaining
508
+ */
509
+ setMerge(merge: boolean): this {
510
+ this.checkCallable();
511
+ this.merge = merge;
512
+ return this;
513
+ }
514
+
181
515
  /**
182
516
  * Set whether to force ref update.
183
517
  *
@@ -252,356 +586,997 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
252
586
  return this;
253
587
  }
254
588
 
589
+ /**
590
+ * `--overlay` / `--no-overlay` for a path checkout: in overlay mode (the default) entries
591
+ * the tree-ish lacks are kept; without it, the paths the pathspec names that the
592
+ * tree-ish lacks are removed from the index and the worktree.
593
+ */
594
+ setOverlay(overlay: boolean): this {
595
+ this.checkCallable();
596
+ this.overlay = overlay;
597
+ return this;
598
+ }
599
+
600
+ /**
601
+ * `--ignore-skip-worktree-bits`: a path checkout also checks out skip-worktree entries
602
+ * (by default it passes over them, so an element naming only such entries matches
603
+ * nothing).
604
+ */
605
+ setIgnoreSkipWorktreeBits(ignore: boolean): this {
606
+ this.checkCallable();
607
+ this.ignoreSkipWorktreeBits = ignore;
608
+ return this;
609
+ }
610
+
611
+ /**
612
+ * `--conflict=<style>` (`merge`, `diff3`, `zdiff3`): for a path checkout, implies
613
+ * {@link setMerge}, the unmerged paths re-created with this conflict style.
614
+ */
615
+ setConflictStyle(style: ConflictStyle): this {
616
+ this.checkCallable();
617
+ this.conflictStyle = style;
618
+ return this;
619
+ }
620
+
621
+ /** `-q`: a path checkout reports no counts and no "path is unmerged" warnings. */
622
+ setQuiet(quiet: boolean): this {
623
+ this.checkCallable();
624
+ this.quiet = quiet;
625
+ return this;
626
+ }
627
+
628
+ /**
629
+ * Whether a path checkout reports what it did ("Updated 2 paths from the index",
630
+ * "Recreated 1 merge conflict") in `warnings`, as `git checkout` does when its paths
631
+ * follow no `--` (`count_checkout_paths`).
632
+ */
633
+ setCountCheckoutPaths(count: boolean): this {
634
+ this.checkCallable();
635
+ this.countCheckoutPaths = count;
636
+ return this;
637
+ }
638
+
639
+ /**
640
+ * `--pathspec-from-file`: the pathspec elements of `content`, one per line (C-quoted
641
+ * lines unquoted), or NUL-separated with `nul` (`--pathspec-file-nul`).
642
+ */
643
+ setPathspecFromFile(content: string | Uint8Array, nul = false): this {
644
+ this.checkCallable();
645
+ this.pathspecFileGiven = true;
646
+ try {
647
+ this.pathspecFromFile = parsePathspecFile(content, nul);
648
+ } catch (error) {
649
+ throw new InvalidArgumentError(
650
+ "pathspecFromFile",
651
+ content,
652
+ `fatal: ${(error as Error).message}`,
653
+ );
654
+ }
655
+ return this;
656
+ }
657
+
255
658
  /**
256
659
  * Execute the checkout command.
257
660
  *
258
661
  * @returns Result with status and affected files
259
662
  * @throws RefNotFoundError if target cannot be resolved
260
663
  */
261
- async call(): Promise<CheckoutResult> {
664
+ /**
665
+ * `git checkout -p [<tree-ish>] [-- <paths>]`: the differences between the index (or the
666
+ * tree-ish) and the worktree are offered hunk by hunk, as git's add-patch.c does; the
667
+ * selected hunks are discarded from the worktree (from the index too with a tree-ish:
668
+ * "Discard this hunk from index and worktree", or "Apply this hunk to index and worktree"
669
+ * for another commit than HEAD). The prompts are answered by {@link setPatchSelector};
670
+ * the result's `patch` carries git's transcript. No post-checkout hook runs.
671
+ *
672
+ * @example
673
+ * ```typescript
674
+ * const answers = ["y", "n"];
675
+ * const { patch } = await git.checkout().setPatch(true).setStartPoint("HEAD")
676
+ * .setPatchSelector(() => answers.shift()).call();
677
+ * ```
678
+ */
679
+ setPatch(patch: boolean): this {
262
680
  this.checkCallable();
263
- this.setCallable(false);
681
+ this.patch = patch;
682
+ return this;
683
+ }
264
684
 
265
- // Path checkout mode
266
- if (this.allPaths || this.paths.length > 0) {
267
- return this.checkoutPaths();
268
- }
685
+ /** Answers the prompts of {@link setPatch}. */
686
+ setPatchSelector(selector: PatchSelector): this {
687
+ this.checkCallable();
688
+ this.patchSelector = selector;
689
+ return this;
690
+ }
269
691
 
270
- // Branch checkout mode
271
- return this.checkoutBranch();
692
+ /** `-U<n>`, `--inter-hunk-context=<n>` and `--no-auto-advance` of {@link setPatch}. */
693
+ setPatchOptions(options: PatchOptions): this {
694
+ this.checkCallable();
695
+ this.patchOptions = { ...options };
696
+ return this;
272
697
  }
273
698
 
274
699
  /**
275
- * Checkout paths from index or commit.
700
+ * The git version this checkout reproduces where they differ (default 2.56): the prompts
701
+ * of {@link setPatch}, and {@link setMerge}'s refusal. Under 2.43 a `-m` switch the
702
+ * two-way merge refuses dies with `fatal: cannot continue with staged changes in the
703
+ * following files:` when the index differs from HEAD (an unborn index always does, with
704
+ * HEAD's files as staged deletions), exit 128; 2.43's in-place merge of unstaged changes
705
+ * is not reproduced (the switch then takes 2.56's autostash).
276
706
  */
277
- private async checkoutPaths(): Promise<CheckoutResult> {
278
- const updated: string[] = [];
279
- const conflicts: string[] = [];
280
-
281
- // Determine source tree
282
- let sourceTreeId: ObjectId | undefined;
283
- if (this.startPoint) {
284
- sourceTreeId = await this.resolveTreeId(this.startPoint);
285
- if (!sourceTreeId) {
286
- throw new RefNotFoundError(this.startPoint);
287
- }
288
- }
289
-
290
- // Get paths to checkout
291
- const pathsToCheckout = this.allPaths ? await this.getAllPaths(sourceTreeId) : this.paths;
707
+ setCompatibility(version: PatchCompatibility): this {
708
+ this.checkCallable();
709
+ this.patchCompatibility = version;
710
+ return this;
711
+ }
292
712
 
293
- // Checkout each path
294
- for (const path of pathsToCheckout) {
295
- try {
296
- if (sourceTreeId) {
297
- // Checkout from commit tree
298
- await this.checkoutPathFromTree(path, sourceTreeId);
299
- } else {
300
- // Checkout from index
301
- await this.checkoutPathFromIndex(path);
302
- }
303
- updated.push(path);
304
- } catch {
305
- conflicts.push(path);
306
- }
713
+ /** checkout_main's checks of `--pathspec-from-file` with `-p`. */
714
+ private refusePathspecFileWithPatch(): void {
715
+ if (!this.pathspecFileGiven) return;
716
+ if (this.paths.length > 0) {
717
+ throw new InvalidArgumentError(
718
+ "pathspecFromFile",
719
+ this.pathspecFromFile,
720
+ "fatal: '--pathspec-from-file' and pathspec arguments cannot be used together",
721
+ );
307
722
  }
723
+ throw new IncompatibleOptionsError(
724
+ ["--pathspec-from-file", "--patch"],
725
+ "fatal: options '--pathspec-from-file' and '--patch' cannot be used together",
726
+ );
727
+ }
308
728
 
729
+ /** `git checkout -p`: run_add_p(ADD_P_CHECKOUT, rev). */
730
+ private async callPatch(): Promise<CheckoutResult> {
731
+ if (this.overlay === true) {
732
+ throw new InvalidArgumentError(
733
+ "overlay",
734
+ true,
735
+ "fatal: options '-p' and '--overlay' cannot be used together",
736
+ );
737
+ }
738
+ this.refusePathspecFileWithPatch();
739
+ const { revision, diffRevision } = await patchRevisionOf(this.startPoint ?? this.name, {
740
+ headId: async () => (await this.refsStore.resolve("HEAD"))?.objectId,
741
+ resolve: (name) => this.resolveRevision(name),
742
+ peelCommit: (id) => this.revisionResolver().peelToType(id, "commit"),
743
+ });
744
+ const patch = await runPatchSelection(this.workingCopy, {
745
+ hookSource: this,
746
+ ...this.patchOptions,
747
+ mode: pathPatchMode(true, true, revision),
748
+ selector: this.patchSelector,
749
+ ...(diffRevision !== undefined ? { diffRevision } : {}),
750
+ paths: [...this.pathspecFromFile, ...this.paths],
751
+ compatibility: this.patchCompatibility,
752
+ });
309
753
  return {
310
- status: conflicts.length > 0 ? CheckoutStatus.CONFLICTS : CheckoutStatus.OK,
311
- updated,
754
+ status: CheckoutStatus.OK,
755
+ updated: patch.applied,
312
756
  removed: [],
313
- conflicts,
757
+ conflicts: [],
314
758
  ref: null,
759
+ patch,
315
760
  };
316
761
  }
317
762
 
763
+ async call(): Promise<CheckoutResult> {
764
+ this.checkCallable();
765
+ this.setCallable(false);
766
+ // the index as it is now, before the worktree or a ref is touched: one another writer
767
+ // replaced is read again (git reads the index at its start), unless this instance holds
768
+ // unwritten edits (refused)
769
+ await this.readCurrentIndex();
770
+ if (this.patch) return this.callPatch();
771
+
772
+ // path checkout, or branch checkout; one worktree batch, so the checks and the writes
773
+ // share one reading of the ignore rules
774
+ const pathCheckout = this.allPaths || this.paths.length > 0 || this.pathspecFromFile.length > 0;
775
+ const oldHead = this.hooks.enabled
776
+ ? (await this.refsStore.resolve("HEAD"))?.objectId
777
+ : undefined;
778
+ const run = () => (pathCheckout ? this.checkoutPaths() : this.checkoutBranch());
779
+ const worktree = this.worktreeAccess;
780
+ let result = await (worktree?.batch ? worktree.batch(run) : run());
781
+ const autostash = this.autostashSwitch;
782
+ if (autostash) {
783
+ const done = await this.switchWithAutostash(autostash.label, autostash.base);
784
+ if (done) result = done;
785
+ }
786
+ return this.withPostCheckoutHook(result, oldHead, pathCheckout);
787
+ }
788
+
318
789
  /**
319
- * Detect conflicts between staged changes and checkout target.
320
- *
321
- * Returns list of paths that have uncommitted staged changes.
322
- * Git prevents checkout when staged changes differ from HEAD,
323
- * as they would be lost during checkout.
324
- *
325
- * @param _targetTreeId Target tree to checkout (unused for now, checks HEAD vs staging)
326
- * @returns Array of conflicting paths
790
+ * The post-checkout hook after a switch (`<old> <new> 1`) or a path checkout (`<HEAD>
791
+ * <HEAD> 0`) that went through; a non-zero exit becomes the result's `exitCode`, as git's
792
+ * exit status.
327
793
  */
328
- private async detectCheckoutConflicts(_targetTreeId?: ObjectId): Promise<string[]> {
329
- const conflicts: string[] = [];
794
+ private async withPostCheckoutHook(
795
+ result: CheckoutResult,
796
+ oldHead: ObjectId | undefined,
797
+ pathCheckout: boolean,
798
+ ): Promise<CheckoutResult> {
799
+ if (!this.hooks.enabled || this.noPostCheckout) return result;
800
+ if (result.status !== CheckoutStatus.OK && result.exitCode === undefined) return result;
801
+ const newHead = (await this.refsStore.resolve("HEAD"))?.objectId;
802
+ const code = await runPostCheckoutHook(
803
+ this.hooks,
804
+ pathCheckout ? newHead : oldHead,
805
+ newHead,
806
+ !pathCheckout,
807
+ );
808
+ // a switch exits 1 for a failing hook (`ret || writeout_error`), a path checkout with
809
+ // the hook's code (`errs |= ...`)
810
+ const exitCode = pathCheckout ? code : 1;
811
+ return code !== 0 && result.exitCode === undefined ? { ...result, exitCode } : result;
812
+ }
330
813
 
331
- // Get current HEAD tree for comparison
332
- const headId = await this.resolveCommitId("HEAD");
333
- if (!headId) {
334
- // No HEAD commit yet (empty repository) - no conflicts possible
335
- return conflicts;
814
+ /**
815
+ * git 2.55+'s `checkout -m` / `switch -m` (`switch_branches` with `merge`): the local
816
+ * changes are stashed (`git stash create "autostash while switching to '<target>'"`),
817
+ * index and worktree reset to HEAD, the switch made, then the stash applied with the
818
+ * labels git gives it (`<target>` for the new branch's side, `local` for the changes,
819
+ * the branch left, or its abbreviated commit, for the base). A conflicting apply leaves
820
+ * the conflicts in the index and worktree and keeps the changes as a stash entry
821
+ * (`stash@{0}`, "autostash while switching to '<target>'"). Undefined when there was
822
+ * nothing to stash (the refusal stands).
823
+ */
824
+ private async switchWithAutostash(
825
+ label: string,
826
+ base: string,
827
+ ): Promise<CheckoutResult | undefined> {
828
+ // create_autostash: nothing to stash in an unborn index (no unstaged changes without
829
+ // entries, has_uncommitted_changes 0 by is_index_unborn), so the refusal stands
830
+ if (await isIndexUnborn(this.staging)) return undefined;
831
+ const message = `autostash while switching to '${label}'`;
832
+ const stashId = await new StashCreateCommand(this._workingCopy)
833
+ .setRef(null)
834
+ .setMessage(message)
835
+ .call();
836
+ if (stashId === undefined) return undefined;
837
+ // from here on the changes live only in the stash: whatever happens to the switch, the
838
+ // stash is applied or stored (git applies it after merge_working_tree, failed or not)
839
+ let switched: CheckoutResult | undefined;
840
+ let failure: { error: unknown } | undefined;
841
+ try {
842
+ // create_autostash's reset_working_tree(HARD): index and worktree back to HEAD
843
+ await this.resetHardToHead();
844
+ // the switch again, now from a clean index and worktree
845
+ switched = await this.copy().call();
846
+ } catch (error) {
847
+ failure = { error };
336
848
  }
337
-
338
- const headTreeId = await this.commits.getTree(headId);
339
- if (!headTreeId) {
340
- return conflicts;
849
+ const applied = await this.applySaveAutostash(stashId, message, label, base);
850
+ if (failure) {
851
+ // git returns the switch's failure once the stash is applied or stored
852
+ const { error } = failure;
853
+ if (error instanceof Error) error.message = `${error.message}\n${applied.message}`;
854
+ throw error;
341
855
  }
342
-
343
- // Collect HEAD tree entries
344
- const headEntries = new Map<string, { objectId: ObjectId; mode: number }>();
345
- await this.collectTreeEntries(headTreeId, "", headEntries);
346
-
347
- // Compare staging with HEAD
348
- for await (const entry of this.staging.entries()) {
349
- // Skip conflict stages (1-3) - only check stage 0
350
- if (entry.stage !== 0) continue;
351
-
352
- const headEntry = headEntries.get(entry.path);
353
-
354
- // Check if staged content differs from HEAD
355
- if (!headEntry || headEntry.objectId !== entry.objectId) {
356
- // Staged change differs from HEAD - this is an uncommitted change
357
- conflicts.push(entry.path);
358
- }
856
+ if (!switched) throw new Error("unreachable: checkout without a result");
857
+ if (switched.status !== CheckoutStatus.OK) {
858
+ // the switch refused (untracked files in the way): HEAD stays, the changes are back
859
+ return {
860
+ ...switched,
861
+ conflicts: [...switched.conflicts, ...applied.conflicts],
862
+ message: [switched.message ?? "", applied.message].join("\n"),
863
+ };
359
864
  }
360
-
361
- return conflicts;
865
+ if (applied.conflicts.length > 0 || applied.conflicted) {
866
+ return {
867
+ status: CheckoutStatus.CONFLICTS,
868
+ updated: switched.updated,
869
+ removed: switched.removed,
870
+ conflicts: applied.conflicts,
871
+ ref: switched.ref,
872
+ message: applied.message,
873
+ };
874
+ }
875
+ return { ...switched, message: applied.message };
362
876
  }
363
877
 
364
878
  /**
365
- * Checkout a branch or commit.
879
+ * git's `apply_save_autostash_oid`: the stash applied (`Applied autostash.`), else
880
+ * stored as `stash@{0}` with `message`, with git's advice for a conflicting apply or
881
+ * `error: could not apply autostash; your changes are safe in the stash`.
366
882
  */
367
- private async checkoutBranch(): Promise<CheckoutResult> {
368
- if (!this.name) {
369
- throw new MissingArgumentError("name", "Branch name is required for checkout");
370
- }
371
-
372
- // Create branch if requested
373
- if (this.createBranch) {
374
- if (!isValidBranchName(this.name)) {
375
- throw new InvalidRefNameError(this.name);
376
- }
377
- const startPointId = this.startPoint
378
- ? await this.resolveCommitId(this.startPoint)
379
- : await this.resolveCommitId("HEAD");
380
-
381
- if (!startPointId) {
382
- throw new RefNotFoundError(this.startPoint ?? "HEAD");
383
- }
384
-
385
- await this.refsStore.set(`refs/heads/${this.name}`, startPointId);
883
+ private async applySaveAutostash(
884
+ stashId: ObjectId,
885
+ message: string,
886
+ ours: string,
887
+ base: string,
888
+ ): Promise<{ message: string; conflicts: string[]; conflicted: boolean }> {
889
+ let status: StashApplyStatus = StashApplyStatus.FAILED;
890
+ let conflicts: string[] = [];
891
+ try {
892
+ const apply = await new StashApplyCommand(this._workingCopy)
893
+ .setStashRef(stashId)
894
+ .setLabels({ ours, theirs: "local", base })
895
+ .call();
896
+ status = apply.status;
897
+ conflicts = [...(apply.conflicts ?? [])].sort();
898
+ } catch {
899
+ // git's do_stash_apply: any other exit status is STASH_APPLY_ERROR
900
+ status = StashApplyStatus.FAILED;
386
901
  }
387
-
388
- // Resolve target
389
- const targetId = await this.resolveCommitId(this.name);
390
- if (!targetId && !this.orphan) {
391
- throw new RefNotFoundError(this.name);
902
+ if (status === StashApplyStatus.OK) {
903
+ return { message: "Applied autostash.", conflicts: [], conflicted: false };
392
904
  }
393
-
394
- // Get target tree for conflict detection and checkout
395
- const targetTreeId = targetId ? await this.commits.getTree(targetId) : undefined;
396
-
397
- // Detect conflicts with staged changes before checkout
398
- if (!this.force && !this.orphan) {
399
- const conflicts = await this.detectCheckoutConflicts(targetTreeId);
400
- if (conflicts.length > 0) {
401
- return {
402
- status: CheckoutStatus.CONFLICTS,
403
- updated: [],
404
- removed: [],
405
- conflicts,
406
- ref: null,
407
- };
408
- }
905
+ // git stash store -m <message> -q <stash>
906
+ await this.refsStore.batch([{ name: STASH_REF, new: stashId }], {
907
+ ...this.reflogLine(message),
908
+ createReflog: true,
909
+ });
910
+ if (status === StashApplyStatus.CONFLICTS) {
911
+ return { message: AUTOSTASH_CONFLICT_ADVICE, conflicts, conflicted: true };
409
912
  }
913
+ return {
914
+ message: "error: could not apply autostash; your changes are safe in the stash",
915
+ conflicts: [],
916
+ conflicted: false,
917
+ };
918
+ }
410
919
 
411
- // Determine if we should use symbolic ref (branch) or detached HEAD (commit/tag)
412
- // Check if it's a local branch
413
- const isLocalBranch = await this.refsStore.has(`refs/heads/${this.name}`);
414
-
415
- // Decide whether to create symbolic ref or detached HEAD
416
- if (this.orphan) {
417
- // Orphan branch: symbolic ref to a branch that doesn't exist yet
418
- await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
419
- } else if (isLocalBranch) {
420
- // Local branch exists: use symbolic ref to the branch
421
- await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
422
- } else if (targetId) {
423
- // Not a local branch but resolves to a commit: detached HEAD
424
- // This handles: commit IDs, tags, remote branches, etc.
425
- await this.refsStore.set("HEAD", targetId);
920
+ /**
921
+ * `reset --hard` to HEAD without touching a ref (git's `reset_working_tree` with
922
+ * `RESET_WORKING_TREE_HARD`, the oid HEAD's own): the index read from HEAD's tree, the
923
+ * worktree rewritten from it, tracked files HEAD lacks deleted.
924
+ */
925
+ private async resetHardToHead(): Promise<void> {
926
+ const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
927
+ if (!headId) throw new NoHeadError("could not determine HEAD revision");
928
+ const treeId = await this.commits.getTree(headId);
929
+ if (!treeId) throw new RefNotFoundError(headId, `unable to read tree (${headId})`);
930
+ const trackedBefore = new Set<string>();
931
+ for await (const entry of this.staging.entries()) trackedBefore.add(entry.path);
932
+ const worktree = this.worktreeAccess;
933
+ // in a sparse checkout, unpack-trees with its patterns
934
+ const sparse = await SparseUnpack.start({
935
+ workingCopy: this.workingCopy,
936
+ worktree,
937
+ staging: this.staging,
938
+ });
939
+ // unpack-trees' one-way merge: unchanged entries keep their flags, a skip-worktree file
940
+ // the tree keeps is left alone
941
+ const { keptOut } = await checkFlaggedEntries(
942
+ {
943
+ trees: this.trees,
944
+ staging: this.staging,
945
+ workingCopy: this.workingCopy,
946
+ worktree,
947
+ },
948
+ treeId,
949
+ sparse,
950
+ );
951
+ await this.staging.readTree(this.trees, treeId, { keepMatching: "flags" });
952
+ // reset_head's prime_cache_tree: the index is HEAD's tree
953
+ this.staging.setCacheTree?.(await cacheTreeOfTree(this.trees, treeId));
954
+ markIndexUpdate(this.staging, { workdir: true });
955
+ await this.staging.write();
956
+ if (worktree) {
957
+ const written = await restoreWorktreeHard(
958
+ { trees: this.trees, blobs: this.blobs, workingCopy: this.workingCopy, worktree },
959
+ treeId,
960
+ trackedBefore,
961
+ keptOut,
962
+ sparse,
963
+ );
964
+ // check_updates: the entries written carry the stat of their new files
965
+ await recordWrittenStat(this.staging, worktree, written);
966
+ await this.staging.write();
967
+ await sparse?.finish(
968
+ { workingCopy: this.workingCopy, worktree, staging: this.staging, blobs: this.blobs },
969
+ { written },
970
+ );
426
971
  }
972
+ }
427
973
 
428
- // Sync staging to match target tree AFTER updating HEAD
429
- const updated: string[] = [];
430
- const removed: string[] = [];
974
+ /**
975
+ * The index a switch leaves, written as git's `merge_working_tree` writes it: with the
976
+ * cache-tree updated (`cache_tree_update` with `WRITE_TREE_REPAIR`, as unpack-trees and
977
+ * checkout do before the write).
978
+ */
979
+ private async writeSwitchedIndex(): Promise<void> {
980
+ await updateIndexCacheTree(this.staging, this.trees);
981
+ markIndexUpdate(this.staging, { workdir: true });
982
+ await this.staging.write();
983
+ }
431
984
 
432
- if (targetTreeId) {
433
- // Use this.trees which is CommandTrees (has loadTree method for TreeStore compatibility)
434
- await this.staging.readTree(this.trees as any, targetTreeId);
985
+ /** The switch an autostash switch makes again: its caller runs post-checkout once. */
986
+ private noPostCheckout = false;
987
+ private withoutPostCheckout(): this {
988
+ this.noPostCheckout = true;
989
+ return this;
990
+ }
435
991
 
436
- // Persist staging to .git/index so native git sees the correct state
437
- await this.staging.write();
992
+ /** This checkout's settings on a new command (without `merge`). */
993
+ private copy(): CheckoutCommand {
994
+ const copy = new CheckoutCommand(this._workingCopy)
995
+ .shareHooksOf(this)
996
+ .withoutPostCheckout()
997
+ .setCreateBranch(this.createBranch)
998
+ .setForceCreateBranch(this.forceCreateBranch)
999
+ .setOrphan(this.orphan)
1000
+ .setIgnoreOtherWorktrees(this.ignoreOtherWorktrees)
1001
+ .setDetach(this.detach)
1002
+ .setTrack(this.track)
1003
+ .setOrphanFromEmptyTree(this.orphanFromEmptyTree)
1004
+ .setOnlyMergeOnSwitchingBranches(this.onlyMergeOnSwitchingBranches)
1005
+ .setProtectUntracked(this.protectUntracked);
1006
+ if (this.createBranch) copy.setCreateBranch(true);
1007
+ if (this.name !== undefined) copy.setName(this.name);
1008
+ if (this.startPoint !== undefined) copy.setStartPoint(this.startPoint);
1009
+ if (this.guess !== undefined) copy.setGuess(this.guess);
1010
+ if (this.hasReflogAction()) copy.setReflogAction(this.reflogAction("checkout"));
1011
+ return copy;
1012
+ }
438
1013
 
439
- // Write files to working directory if not a bare repository
440
- if (this.hasFileWriteSupport()) {
441
- await this.writeTreeToWorkdir(targetTreeId, "");
442
- }
1014
+ /**
1015
+ * git's `checkout [<tree-ish>] [--] <pathspec>...` (`checkout_paths`): see
1016
+ * {@link runPathCheckout}. An error git reports (an element that matched nothing, an
1017
+ * unmerged path) leaves the index and the worktree as they were: status `CONFLICTS`, the
1018
+ * elements or paths in `conflicts`, git's lines in `message`.
1019
+ */
1020
+ private async checkoutPaths(): Promise<CheckoutResult> {
1021
+ if (this.createBranch || this.forceCreateBranch || this.orphan) {
1022
+ throw new SwitchRefusedError(
1023
+ `fatal: Cannot update paths and switch to branch '${this.name ?? ""}' at the same time.`,
1024
+ );
443
1025
  }
1026
+ if (this.detach) {
1027
+ throw new SwitchRefusedError(
1028
+ `fatal: git checkout: --detach does not take a path argument '${this.paths[0] ?? ""}'`,
1029
+ );
1030
+ }
1031
+ if (this.track !== TrackMode.DEFAULT) {
1032
+ throw new SwitchRefusedError("fatal: '--track' cannot be used with updating paths");
1033
+ }
1034
+ if (this.paths.length > 0 && this.pathspecFromFile.length > 0) {
1035
+ throw new InvalidArgumentError(
1036
+ "pathspecFromFile",
1037
+ this.pathspecFromFile,
1038
+ "fatal: '--pathspec-from-file' and pathspec arguments cannot be used together",
1039
+ );
1040
+ }
1041
+ const source = this.startPoint ?? this.name;
1042
+ const outcome = await runPathCheckout(this.pathCheckoutContext(), {
1043
+ command: "checkout",
1044
+ paths: [...this.pathspecFromFile, ...this.paths],
1045
+ allPaths: this.allPaths,
1046
+ ...(source !== undefined ? { source } : {}),
1047
+ ...(this.overlay !== undefined ? { overlay: this.overlay } : {}),
1048
+ ignoreSkipWorktree: this.ignoreSkipWorktreeBits,
1049
+ ...(this.stage !== undefined ? { stage: this.stage } : {}),
1050
+ merge: this.merge,
1051
+ ...(this.conflictStyle ? { conflictStyle: this.conflictStyle } : {}),
1052
+ force: this.force,
1053
+ quiet: this.quiet,
1054
+ countCheckoutPaths: this.countCheckoutPaths,
1055
+ globalMagic: this.globalPathspecMagic(),
1056
+ });
1057
+ return pathCheckoutResult(outcome);
1058
+ }
444
1059
 
445
- // Get the ref we checked out
446
- const ref = await this.refsStore.resolve("HEAD");
447
-
1060
+ /** What a path checkout reads and writes. */
1061
+ private pathCheckoutContext() {
448
1062
  return {
449
- status: CheckoutStatus.OK,
450
- updated,
451
- removed,
452
- conflicts: [],
453
- ref: ref ?? null,
1063
+ workingCopy: this.workingCopy,
1064
+ staging: this.staging,
1065
+ trees: this.trees,
1066
+ blobs: this.blobs,
1067
+ worktree: this.worktreeAccess,
1068
+ abbreviate: (id: ObjectId) => this.abbreviateObjectId(id),
1069
+ resolveTree: (rev: string) => this.resolveSourceTree(rev),
454
1070
  };
455
1071
  }
456
1072
 
1073
+ /** git's `get_global_magic` from the host environment (`GIT_LITERAL_PATHSPECS`, ...). */
1074
+ private globalPathspecMagic() {
1075
+ try {
1076
+ return globalPathspecMagic(hostEnvironmentOf(this.workingCopy)?.pathspecs);
1077
+ } catch (error) {
1078
+ throw new InvalidArgumentError("path", this.paths, `fatal: ${(error as Error).message}`);
1079
+ }
1080
+ }
1081
+
457
1082
  /**
458
- * Check if the store supports file writes (not a bare repository).
459
- *
460
- * A repository is considered "bare" if it doesn't have a worktree interface.
1083
+ * HEAD as git's checkout names the side it leaves: the branch (short name, also an unborn
1084
+ * one), else the full id of the detached HEAD, else `(invalid)`.
461
1085
  */
462
- private hasFileWriteSupport(): boolean {
463
- return !!this.worktreeAccess;
1086
+ private async describeHeadForReflog(): Promise<string> {
1087
+ const head = await this.refsStore.get("HEAD");
1088
+ if (head && isSymbolicRef(head)) return shortBranchName(head.target);
1089
+ return head?.objectId ?? "(invalid)";
1090
+ }
1091
+
1092
+ /** Whether an untracked (not ignored) file or link is at `path`. */
1093
+ private async untrackedFileAt(worktree: Worktree, path: string): Promise<boolean> {
1094
+ const entry = await worktree.getEntry(path);
1095
+ return !!entry && !entry.isDirectory && !(await worktree.isIgnored(path));
464
1096
  }
465
1097
 
466
1098
  /**
467
- * Write all files from a tree to the working directory.
468
- *
469
- * @param treeId The tree ID to checkout
470
- * @param basePath The base path prefix for entries in this tree
1099
+ * Checkout a branch or commit.
471
1100
  */
472
- private async writeTreeToWorkdir(treeId: ObjectId, basePath: string): Promise<void> {
473
- const worktree = this.worktreeAccess;
474
- if (!worktree) {
475
- throw new Error("Worktree not available for file writes");
1101
+ private async checkoutBranch(): Promise<CheckoutResult> {
1102
+ // parse_branchname_arg and validate_new_branchname first, then checkout_branch's
1103
+ // option checks, then switch_branches' refusal of a non-commit
1104
+ let plan: SwitchPlan | SwitchRefusedError;
1105
+ try {
1106
+ plan = await this.planSwitch();
1107
+ } catch (error) {
1108
+ if (!(error instanceof SwitchRefusedError && NON_COMMIT_SWITCH.test(error.message))) {
1109
+ throw error;
1110
+ }
1111
+ plan = error;
1112
+ }
1113
+ if (this.merge && this.force) {
1114
+ throw new SwitchRefusedError("fatal: '-f' cannot be used with '-m'");
1115
+ }
1116
+ if (plan instanceof SwitchRefusedError) throw plan;
1117
+ const switchTo = plan;
1118
+ const { targetId } = switchTo;
1119
+ const branchName =
1120
+ switchTo.kind === "detach" || switchTo.kind === "stay" ? undefined : switchTo.branch;
1121
+
1122
+ // git's die_if_checked_out: a branch another worktree has checked out is not switched to
1123
+ const worktrees = this.workingCopy.worktrees;
1124
+ if (worktrees && !this.ignoreOtherWorktrees && branchName !== undefined) {
1125
+ const ref = `refs/heads/${branchName}`;
1126
+ // (`checkout -B`: an existing branch is reset, so not one another worktree uses, git
1127
+ // 2.44+ die_if_switching_to_a_branch_in_use for new_branch_force)
1128
+ if (switchTo.kind === "create" || switchTo.kind === "branch") {
1129
+ await refuseIfCheckedOut(worktrees, ref, true);
1130
+ }
476
1131
  }
477
1132
 
478
- for await (const entry of this.trees.loadTree(treeId)) {
479
- const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;
480
- const isDirectory = entry.mode === FileMode.TREE;
1133
+ // git's switch_branches without a target name (`switch -c <new>` or `switch --detach`
1134
+ // without a start point, the bare `checkout -b <new>`: only_merge_on_switching_branches)
1135
+ // does not run merge_working_tree: index and worktree stay as they are, an unborn index
1136
+ // is not checked out
1137
+ if (this.skipsMergeWorkingTree()) return this.updateRefsForSwitch(switchTo, [], [], []);
481
1138
 
482
- if (isDirectory) {
483
- // Recursively process subdirectories
484
- await this.writeTreeToWorkdir(entry.id, relativePath);
485
- } else {
486
- // Ensure parent directory exists
487
- const lastSlash = relativePath.lastIndexOf("/");
488
- if (lastSlash > 0) {
489
- const parentDir = relativePath.substring(0, lastSlash);
490
- await worktree.mkdir(parentDir);
491
- }
1139
+ // Get target tree for conflict detection and checkout
1140
+ const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
1141
+ const headTreeId = headId ? await this.commits.getTree(headId) : undefined;
1142
+ // git's initial checkout (`topts.initial_checkout = is_index_unborn(...)`): with no index
1143
+ // file and no entries, twoway_merge takes every path of the target as new
1144
+ // (merged_entry: written, untracked files in the way refused) instead of reading HEAD's
1145
+ // files as staged deletions. `checkout --orphan` merges HEAD into HEAD (the new branch
1146
+ // keeps its tree), which then checks HEAD's files out too.
1147
+ // `checkout --orphan <new> <start-point>` merges to the start point's tree as a switch to
1148
+ // that commit would.
1149
+ const unborn = !this.force && (await isIndexUnborn(this.staging));
1150
+ const orphanStart = switchTo.kind === "orphan" ? switchTo.startId : undefined;
1151
+ const orphanCheckout = unborn && this.orphan && !this.orphanFromEmptyTree;
1152
+ const targetTreeId = orphanStart
1153
+ ? await this.commits.getTree(orphanStart)
1154
+ : orphanCheckout
1155
+ ? headTreeId
1156
+ : targetId
1157
+ ? await this.commits.getTree(targetId)
1158
+ : undefined;
1159
+ // in a sparse checkout, unpack-trees with its patterns: a path that stays outside is
1160
+ // neither checked nor touched in the worktree (its index entry still switches)
1161
+ const sparse = await SparseUnpack.start({
1162
+ workingCopy: this.workingCopy,
1163
+ worktree: this.worktreeAccess,
1164
+ staging: this.staging,
1165
+ });
1166
+ const quiet = (path: string) => sparse?.leavesAlone(path) === true;
1167
+ const writes = (path: string) => !sparse || sparse.writes(path);
1168
+
1169
+ // git's two-way merge (unpack-trees `twoway_merge`, checkout without -f): a path HEAD
1170
+ // and the target agree on keeps its index entry and worktree file as they are (local
1171
+ // edits survive the switch); a path they differ on is switched only when the index and
1172
+ // the worktree still hold HEAD's version, else the checkout is refused, as are
1173
+ // untracked files in the way and an index with unmerged entries. With `setForce`, as
1174
+ // `git checkout -f`, the target's tree replaces index and worktree whatever they hold.
1175
+ const worktree = this.worktreeAccess;
1176
+ const head = new Map<string, Side>();
1177
+ const target = new Map<string, Side>();
1178
+ if (headTreeId) await this.collectTreeEntries(headTreeId, "", head);
1179
+ if (targetTreeId) await this.collectTreeEntries(targetTreeId, "", target);
1180
+ const index = new Map<string, Side>();
1181
+ const unmerged = new Set<string>();
1182
+ for await (const entry of this.staging.entries()) {
1183
+ if (entry.stage === 0) index.set(entry.path, entry);
1184
+ else unmerged.add(entry.path);
1185
+ }
492
1186
 
493
- // Stream the blob into the file (an empty file when the blob is missing)
494
- const blobContent = await this.blobs.load(entry.id);
495
- await worktree.writeContent(relativePath, blobContent ?? []);
496
- }
1187
+ // (an orphan branch keeps index and worktree as they are, as git's checkout --orphan;
1188
+ // switch --orphan switches to the empty tree)
1189
+ const keepAll =
1190
+ this.orphan && !this.orphanFromEmptyTree && !orphanCheckout && orphanStart === undefined;
1191
+ if (!this.force && !keepAll && unmerged.size > 0) {
1192
+ return {
1193
+ status: CheckoutStatus.CONFLICTS,
1194
+ updated: [],
1195
+ removed: [],
1196
+ conflicts: [...unmerged].sort(),
1197
+ ref: null,
1198
+ message: "error: you need to resolve your current index first",
1199
+ };
497
1200
  }
498
- }
499
1201
 
500
- /**
501
- * Checkout a path from the staging index.
502
- */
503
- private async checkoutPathFromIndex(path: string): Promise<void> {
504
- // Find the entry in staging
505
- let found = false;
506
- for await (const entry of this.staging.entries()) {
507
- if (entry.path !== path) continue;
508
-
509
- // Handle conflict stages
510
- if (entry.stage !== 0) {
511
- if (this.stage && entry.stage === this.stage) {
512
- // Replace with specified stage
513
- const editor = this.staging.createEditor();
514
- editor.add(
515
- new UpdateStagingEntry(path, entry.objectId, entry.mode, {
516
- size: entry.size,
517
- mtime: Date.now(),
518
- }),
519
- );
520
- await editor.finish();
521
- found = true;
522
- break;
1202
+ // the paths the switch changes, and those it must refuse to touch
1203
+ const switched: string[] = [];
1204
+ const local: string[] = [];
1205
+ const untracked: string[] = [];
1206
+ const untrackedRemoved: string[] = [];
1207
+ const lostDirs: string[] = [];
1208
+ /** Case variants of index paths in directories files replace (see findInTheWay) */
1209
+ const caseVariants: string[] = [];
1210
+ const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : undefined;
1211
+ const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
1212
+ const initial = unborn && !keepAll;
1213
+ const paths = [...new Set([...head.keys(), ...target.keys()])].sort();
1214
+ for (const path of keepAll ? [] : paths) {
1215
+ const h = head.get(path);
1216
+ const t = target.get(path);
1217
+ if (initial && t) {
1218
+ switched.push(path);
1219
+ continue;
1220
+ }
1221
+ if (!this.force && sameSide(h, t)) continue;
1222
+ const i = index.get(path);
1223
+ if (this.force) {
1224
+ // oneway_merge leaves a skip-worktree entry the target keeps (and its file) alone, as
1225
+ // the sparse checkout does whatever stays outside it
1226
+ if ((i as { skipWorktree?: boolean } | undefined)?.skipWorktree && sameSide(i, t)) {
1227
+ continue;
523
1228
  }
1229
+ if (quiet(path)) continue;
1230
+ if (!sameSide(i, t) || t) switched.push(path);
524
1231
  continue;
525
1232
  }
526
-
527
- found = true;
528
- break;
1233
+ if (sameSide(i, t)) {
1234
+ // kept; but a staged deletion the target also makes leaves the file untracked in
1235
+ // the worktree, and the switch would remove it (git refuses)
1236
+ if (h && !i && !t && worktree && (await this.untrackedFileAt(worktree, path))) {
1237
+ untrackedRemoved.push(path);
1238
+ }
1239
+ continue;
1240
+ }
1241
+ if (!sameSide(i, h)) {
1242
+ // staged changes (or a staged deletion) the switch would lose
1243
+ if (i !== undefined || t !== undefined) local.push(path);
1244
+ continue;
1245
+ }
1246
+ if (
1247
+ i !== undefined &&
1248
+ worktree &&
1249
+ !quiet(path) &&
1250
+ (await entryNotUptodate(worktree, path, i, trust, this.staging.getUpdateTime()))
1251
+ ) {
1252
+ local.push(path);
1253
+ continue;
1254
+ }
1255
+ switched.push(path);
529
1256
  }
530
1257
 
531
- if (!found) {
532
- throw new PathNotInIndexError(path);
1258
+ // what stands where the switch writes (git's verify_absent, check_leading_path and
1259
+ // verify_clean_subdirectory): untracked files or links on the path or a leading
1260
+ // component, untracked files in a directory a file replaces
1261
+ if (worktree && !this.force) {
1262
+ const found = await findInTheWay(worktree, {
1263
+ writes: switched.filter((p) => target.has(p) && writes(p)),
1264
+ removes: new Set(switched.filter((p) => !target.has(p))),
1265
+ index,
1266
+ ...(await restoreCaseOptions(worktree, ignoreCase)),
1267
+ caseVariantsExpendable: true,
1268
+ });
1269
+ untracked.push(...found.untracked);
1270
+ lostDirs.push(...found.lostDirs);
1271
+ caseVariants.push(...(found.caseVariants ?? []));
533
1272
  }
534
- }
535
-
536
- /**
537
- * Checkout a path from a tree.
538
- */
539
- private async checkoutPathFromTree(path: string, treeId: ObjectId): Promise<void> {
540
- // Navigate tree to find the entry
541
- const parts = path.split("/");
542
- let currentTreeId = treeId;
543
-
544
- for (let i = 0; i < parts.length; i++) {
545
- const name = parts[i];
546
- const entry = await this.trees.getEntry(currentTreeId, name);
547
-
548
- if (!entry) {
549
- throw new PathNotFoundInTreeError(path);
1273
+ // a reset that protects untracked files (switch --discard-changes): unpack-trees'
1274
+ // own messages, one line per path
1275
+ if (worktree && this.force && this.protectUntracked) {
1276
+ const found = await findInTheWay(worktree, {
1277
+ writes: switched.filter((p) => target.has(p) && writes(p)),
1278
+ removes: new Set(switched.filter((p) => !target.has(p))),
1279
+ index,
1280
+ ...(await restoreCaseOptions(worktree, ignoreCase)),
1281
+ caseVariantsExpendable: true,
1282
+ });
1283
+ caseVariants.push(...(found.caseVariants ?? []));
1284
+ const lines = [
1285
+ ...found.untracked.map((p) => ({
1286
+ p,
1287
+ line: `error: Untracked working tree file '${p}' would be overwritten by merge.`,
1288
+ })),
1289
+ ...found.lostDirs.map((p) => ({
1290
+ p,
1291
+ line: `error: Updating '${p}' would lose untracked files in it`,
1292
+ })),
1293
+ ].sort((a, b) => (a.p < b.p ? -1 : a.p > b.p ? 1 : 0));
1294
+ if (lines.length > 0) {
1295
+ return {
1296
+ status: CheckoutStatus.CONFLICTS,
1297
+ updated: [],
1298
+ removed: [],
1299
+ conflicts: lines.map((l) => l.p),
1300
+ ref: null,
1301
+ message: lines.map((l) => l.line).join("\n"),
1302
+ };
550
1303
  }
551
-
552
- if (i < parts.length - 1) {
553
- if (entry.mode !== FileMode.TREE) {
554
- throw new NotADirectoryError(parts.slice(0, i + 1).join("/"));
1304
+ }
1305
+ // a forced checkout is a one-way reset, but an entry whose flags cheat (assume-unchanged,
1306
+ // skip-worktree) is still checked: one the target changes or deletes over a changed file
1307
+ // is refused (verify_uptodate_1), as git's "Entry '<path>' not uptodate. Cannot merge."
1308
+ if (this.force && !keepAll && worktree) {
1309
+ const indexTime = this.staging.getUpdateTime();
1310
+ for (const [path, i] of index) {
1311
+ const e = i as StagingEntry;
1312
+ if (!e.assumeValid && !e.skipWorktree) continue;
1313
+ if (sameSide(i, target.get(path)) || quiet(path)) continue;
1314
+ if (await flaggedEntryDiffers(worktree, path, e, trust, indexTime)) {
1315
+ return {
1316
+ status: CheckoutStatus.CONFLICTS,
1317
+ updated: [],
1318
+ removed: [],
1319
+ conflicts: [path],
1320
+ ref: null,
1321
+ message: `error: Entry '${path}' not uptodate. Cannot merge.`,
1322
+ };
555
1323
  }
556
- currentTreeId = entry.id;
557
- } else {
558
- // Found the file - update staging
559
- const editor = this.staging.createEditor();
560
- editor.add(
561
- new UpdateStagingEntry(path, entry.id, entry.mode, {
562
- size: 0,
563
- mtime: Date.now(),
564
- }),
1324
+ }
1325
+ }
1326
+ // git 2.55+ `checkout -m`: a two-way merge that fails (local changes, untracked files
1327
+ // in the way) falls back to an autostash, run by call() outside this worktree batch;
1328
+ // with nothing to stash the refusal stands
1329
+ const refused = local.length + untracked.length + untrackedRemoved.length + lostDirs.length;
1330
+ if (this.merge && headId && refused > 0 && this.patchCompatibility === "2.43") {
1331
+ // git 2.43's merge_working_tree: a failed two-way merge under `-m` dies when the index
1332
+ // holds changes against HEAD (repo_index_has_changes), an unborn index's missing
1333
+ // entries included (staged deletions of every HEAD file)
1334
+ const staged = [...new Set([...index.keys(), ...head.keys()])]
1335
+ .filter((p) => !sameSide(index.get(p), head.get(p)))
1336
+ .sort(compareGitPaths);
1337
+ if (staged.length > 0) {
1338
+ throw new SwitchRefusedError(
1339
+ `fatal: cannot continue with staged changes in the following files:\n${staged.join(" ")}`,
565
1340
  );
566
- await editor.finish();
567
1341
  }
568
1342
  }
569
- }
1343
+ if (this.merge && headId && refused > 0) {
1344
+ const left = await this.getCurrentBranch();
1345
+ // the base's label: the branch left, else its commit uniquely abbreviated
1346
+ // (strbuf_add_unique_abbrev, DEFAULT_ABBREV)
1347
+ this.autostashSwitch = {
1348
+ label: autostashLabel(switchTo),
1349
+ base: left?.startsWith("refs/heads/")
1350
+ ? shortBranchName(left)
1351
+ : await this.abbreviateObjectId(headId),
1352
+ };
1353
+ }
1354
+ if (local.length + untracked.length + untrackedRemoved.length + lostDirs.length > 0) {
1355
+ const message = overwriteMessage("checkout", {
1356
+ local,
1357
+ lostDirs,
1358
+ untracked,
1359
+ untrackedRemoved,
1360
+ });
1361
+ return {
1362
+ status: CheckoutStatus.CONFLICTS,
1363
+ updated: [],
1364
+ removed: [],
1365
+ conflicts: [...local, ...lostDirs, ...untracked, ...untrackedRemoved],
1366
+ ref: null,
1367
+ message,
1368
+ };
1369
+ }
570
1370
 
571
- /**
572
- * Get all paths from staging or tree.
573
- */
574
- private async getAllPaths(sourceTreeId?: ObjectId): Promise<string[]> {
575
- const paths: string[] = [];
1371
+ // The worktree first, as git: the target tree is planned (paths verified, entries
1372
+ // checked not to collide) before anything is written; the switched paths the target
1373
+ // drops are removed, then its switched files, links and submodule directories written.
1374
+ const updated: string[] = [];
1375
+ const removed: string[] = [];
1376
+ const switching = new Set(switched);
1377
+ /** The paths whose files the switch wrote */
1378
+ const written = new Set<string>();
1379
+ if (worktree && (targetTreeId || switched.length > 0 || this.force)) {
1380
+ const plan = targetTreeId
1381
+ ? await planTreeRestore(this.trees, this.blobs, targetTreeId, CHECKOUT, {
1382
+ symlinks: true,
1383
+ ...(await restoreCaseOptions(worktree, ignoreCase)),
1384
+ windows: worktree.capabilities?.windowsPaths === true,
1385
+ reservedNames: worktree.capabilities?.reservedNames,
1386
+ })
1387
+ : undefined;
1388
+ if (sparse && !keepAll) {
1389
+ // apply_sparse_checkout before check_updates: the files leaving the checkout
1390
+ const unlink = await sparse.leaving(
1391
+ worktree,
1392
+ (p) => (this.force || switching.has(p) ? target.get(p) : index.get(p)),
1393
+ { reset: this.force, trust },
1394
+ );
1395
+ await sparse.unlink(worktree, unlink);
1396
+ }
1397
+ for (const path of switched) {
1398
+ if (target.has(path) || quiet(path)) continue;
1399
+ await worktree.remove(path);
1400
+ await pruneEmptyParents(worktree, path);
1401
+ removed.push(path);
1402
+ }
1403
+ // core.ignorecase: what verify_clean_subdirectory took as tracked in a directory a
1404
+ // file replaces goes with the directory, as git's checkout_entry removes the subtree
1405
+ for (const path of caseVariants) {
1406
+ await worktree.remove(path);
1407
+ await pruneEmptyParents(worktree, path);
1408
+ }
1409
+ // a forced checkout also drops tracked files no tree holds any more
1410
+ if (this.force) {
1411
+ for (const path of index.keys()) {
1412
+ if (!target.has(path) && !switching.has(path) && !quiet(path)) {
1413
+ await worktree.remove(path);
1414
+ removed.push(path);
1415
+ }
1416
+ }
1417
+ }
1418
+ // in a sparse checkout, only the paths in its patterns are written
1419
+ const only = plan && {
1420
+ ...plan,
1421
+ entries: plan.entries.filter((e) => switching.has(e.path) && writes(e.path)),
1422
+ gitlinks: plan.gitlinks.filter((e) => switching.has(e.path) && writes(e.path)),
1423
+ };
1424
+ // the attributes of the index the switch leaves (git's o->result): the target's
1425
+ // entries for the switched paths, the index's own for every other
1426
+ const result = new Map<string, ObjectId>();
1427
+ if (!this.force) for (const [path, entry] of index) result.set(path, entry.objectId);
1428
+ for (const path of this.force ? target.keys() : switched) {
1429
+ const t = target.get(path);
1430
+ if (t) result.set(path, t.objectId);
1431
+ else result.delete(path);
1432
+ }
1433
+ // everything in the way was checked above (or the checkout is forced): a file or link
1434
+ // where a directory goes, a clean directory where a file goes, are replaced
1435
+ if (only) {
1436
+ await writeTreeRestorePlan(worktree, this.blobs, only, CHECKOUT, {
1437
+ symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
1438
+ gitlinks: true,
1439
+ replaceInTheWay: true,
1440
+ // a forced checkout overwrites untracked files, as git's checkout -f
1441
+ ...(this.force && !this.protectUntracked ? { discardUntracked: true } : {}),
1442
+ attributes: { direction: "checkout", index: attributesIndexOf(result) },
1443
+ });
1444
+ updated.push(...only.entries.map((e) => e.path));
1445
+ for (const e of [...only.entries, ...only.gitlinks]) written.add(e.path);
1446
+ }
1447
+ }
576
1448
 
577
- if (sourceTreeId) {
578
- // Get all paths from tree
579
- await this.collectTreePaths(sourceTreeId, "", paths);
580
- } else {
581
- // Get all paths from staging
582
- for await (const entry of this.staging.entries()) {
583
- if (entry.stage === 0 && !paths.includes(entry.path)) {
584
- paths.push(entry.path);
1449
+ // The index (written with the worktree, as git's merge_working_tree, before any ref
1450
+ // moves): forced, the target's tree; else the switched paths take the target's
1451
+ // entries (with the stat of the files just written), every other path keeps its own.
1452
+ // git's switch writes a new index (unpack-trees): no resolve-undo records survive it
1453
+ this.staging.clearResolveUndo?.();
1454
+ if (targetTreeId && this.force) {
1455
+ // oneway_merge: an unchanged entry keeps its flags and stat, a changed one its
1456
+ // skip-worktree bit
1457
+ await this.staging.readTree(this.trees as any, targetTreeId, { keepMatching: "flags" });
1458
+ // check_updates: the entries written carry the stat of their new files
1459
+ if (worktree) await recordWrittenStat(this.staging, worktree, written);
1460
+ await this.writeSwitchedIndex();
1461
+ } else if (this.force && !keepAll) {
1462
+ // forced onto the empty tree (switch --orphan --discard-changes): an empty index
1463
+ const editor = this.staging.createEditor();
1464
+ for (const path of index.keys()) editor.remove(path);
1465
+ await editor.finish();
1466
+ await this.writeSwitchedIndex();
1467
+ } else if (switched.length > 0) {
1468
+ const editor = this.staging.createEditor();
1469
+ for (const path of switched) {
1470
+ const t = target.get(path);
1471
+ if (!t) {
1472
+ editor.remove(path);
1473
+ continue;
585
1474
  }
1475
+ // the stat of a file written (an entry left outside the checkout has none)
1476
+ const stats = worktree && written.has(path) ? await worktree.getEntry(path) : undefined;
1477
+ // merged_entry: the replaced entry's skip-worktree bit migrates over
1478
+ const old = index.get(path) as { skipWorktree?: boolean } | undefined;
1479
+ editor.upsert({
1480
+ path,
1481
+ objectId: t.objectId,
1482
+ mode: t.mode,
1483
+ ...entryStatOf(stats ?? {}),
1484
+ ...(old?.skipWorktree ? { skipWorktree: true } : {}),
1485
+ });
586
1486
  }
1487
+ await editor.finish();
1488
+ await this.writeSwitchedIndex();
1489
+ } else {
1490
+ await this.writeSwitchedIndex();
1491
+ }
1492
+
1493
+ // the flags, and the entries coming back into the patterns (verify_absent_sparse; a
1494
+ // forced checkout overwrites what stands there, UNPACK_RESET_OVERWRITE_UNTRACKED)
1495
+ const sparseWarnings: string[] = [];
1496
+ if (sparse && !keepAll) {
1497
+ const outcome = await sparse.finish(
1498
+ {
1499
+ workingCopy: this.workingCopy,
1500
+ worktree: this.worktreeAccess,
1501
+ staging: this.staging,
1502
+ blobs: this.blobs,
1503
+ },
1504
+ { written, overwrite: this.force && !this.protectUntracked },
1505
+ );
1506
+ pushSparseWarnings(sparseWarnings, sparse, outcome, true);
587
1507
  }
588
1508
 
589
- return paths;
1509
+ return this.updateRefsForSwitch(switchTo, updated, removed, sparseWarnings);
590
1510
  }
591
1511
 
592
1512
  /**
593
- * Collect all paths from a tree recursively.
1513
+ * git's update_refs_for_switch after the index and worktree are switched (or left alone):
1514
+ * the new branch, HEAD and its reflog, remove_branch_state.
594
1515
  */
595
- private async collectTreePaths(treeId: ObjectId, prefix: string, paths: string[]): Promise<void> {
596
- for await (const entry of this.trees.loadTree(treeId)) {
597
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
1516
+ private async updateRefsForSwitch(
1517
+ switchTo: SwitchPlan,
1518
+ updated: string[],
1519
+ removed: string[],
1520
+ sparseWarnings: string[],
1521
+ ): Promise<CheckoutResult> {
1522
+ // HEAD's reflog line (git's update_refs_for_switch): "checkout: moving from <branch
1523
+ // left, or the detached HEAD's full id> to <the name as interpreted: `-` and @{-N}
1524
+ // expanded, the new branch's name>", read before anything moves
1525
+ const log = this.reflogLine(
1526
+ this.hasReflogAction()
1527
+ ? this.reflogAction("checkout")
1528
+ : reflogMessages.checkout(await this.describeHeadForReflog(), switchTo.logName),
1529
+ );
1530
+
1531
+ if (switchTo.kind === "create") {
1532
+ // git's create_branch (after the worktree and the index, as update_refs_for_switch
1533
+ // does it): a start point --track cannot track dies before the branch is made;
1534
+ // "branch: Created from <start>", or "Reset to" an existing one; then its upstream
1535
+ // (ambiguous remotes die once the branch exists)
1536
+ const { tracking } = switchTo;
1537
+ if (tracking.notABranch !== undefined) throw tracking.notABranch;
1538
+ const branchRef = `refs/heads/${switchTo.branch}`;
1539
+ const message = (await this.refsStore.has(branchRef))
1540
+ ? reflogMessages.branchReset(switchTo.startName)
1541
+ : reflogMessages.branchCreated(switchTo.startName);
1542
+ await this.refsStore.set(branchRef, switchTo.targetId, this.reflogLine(message));
1543
+ if (tracking.ambiguous !== undefined) throw tracking.ambiguous;
1544
+ if (tracking.plan) await installTracking(this.workingCopy, switchTo.branch, tracking.plan);
1545
+ }
598
1546
 
599
- if (entry.mode === FileMode.TREE) {
600
- await this.collectTreePaths(entry.id, path, paths);
601
- } else {
602
- paths.push(path);
603
- }
1547
+ if (switchTo.kind === "stay") {
1548
+ // `checkout HEAD`: git's update_refs_for_switch has nothing to do
1549
+ } else if (switchTo.kind === "detach") {
1550
+ // a commit, tag, remote-tracking branch or --detach: HEAD holds the commit itself
1551
+ await this.refsStore.set("HEAD", switchTo.targetId, log);
1552
+ } else {
1553
+ // a branch (an orphan's is unborn: git logs nothing for an unborn target)
1554
+ await this.refsStore.setSymbolic("HEAD", `refs/heads/${switchTo.branch}`, log);
604
1555
  }
1556
+ // git's remove_branch_state: a merge, cherry-pick or revert stopped here is forgotten
1557
+ // (a merge's autostash kept on refs/stash, git's lines printed)
1558
+ sparseWarnings.push(
1559
+ ...(await removeBranchState(
1560
+ { commits: this.commits, refs: this.refsStore },
1561
+ new OperationState(this.workingCopy.checkout, this.refsStore),
1562
+ )),
1563
+ );
1564
+
1565
+ // conditional includes on the branch (includeIf.onbranch:) follow the new HEAD
1566
+ const config = this._workingCopy.config as { refresh?: () => Promise<unknown> } | undefined;
1567
+ if (typeof config?.refresh === "function") await config.refresh();
1568
+
1569
+ // Get the ref we checked out
1570
+ const ref = await this.refsStore.resolve("HEAD");
1571
+
1572
+ return {
1573
+ status: CheckoutStatus.OK,
1574
+ updated,
1575
+ removed,
1576
+ conflicts: [],
1577
+ ref: ref ?? null,
1578
+ ...(sparseWarnings.length > 0 ? { warnings: sparseWarnings } : {}),
1579
+ };
605
1580
  }
606
1581
 
607
1582
  /**
@@ -624,36 +1599,159 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
624
1599
  }
625
1600
 
626
1601
  /**
627
- * Resolve a ref to a tree ID.
1602
+ * The object a revision names (`HEAD~1`, a branch, a tag, `@{-1}`, `-`) and its tree, as
1603
+ * git's `parse_tree_indirect` peels it: the tree undefined for an object that is no
1604
+ * tree-ish.
1605
+ *
1606
+ * @throws RefNotFoundError when it names nothing
628
1607
  */
629
- private async resolveTreeId(refName: string): Promise<ObjectId | undefined> {
630
- const commitId = await this.resolveCommitId(refName);
631
- if (!commitId) return undefined;
632
- return this.commits.getTree(commitId);
1608
+ private async resolveSourceTree(
1609
+ refName: string,
1610
+ ): Promise<{ id: ObjectId; tree: ObjectId | undefined }> {
1611
+ const id = await this.resolveRevision(refName === "-" ? "@{-1}" : refName);
1612
+ return { id, tree: await this.revisionResolver().peelToType(id, "tree") };
633
1613
  }
634
1614
 
635
1615
  /**
636
- * Resolve a ref to a commit ID.
1616
+ * Resolve a revision to a commit, as git's rev parsing does (`resolveRef`), or undefined
1617
+ * when it names nothing. One that names a tree, a blob or a missing object is refused as
1618
+ * git's checkout refuses it (see {@link nonCommitSwitchError}), named `given`.
637
1619
  */
638
- private async resolveCommitId(refName: string): Promise<ObjectId | undefined> {
639
- // Try as branch
640
- let ref = await this.refsStore.resolve(`refs/heads/${refName}`);
641
- if (ref?.objectId) return ref.objectId;
642
-
643
- // Try as tag
644
- ref = await this.refsStore.resolve(`refs/tags/${refName}`);
645
- if (ref?.objectId) return ref.objectId;
646
-
647
- // Try as direct ref (HEAD, etc.)
648
- ref = await this.refsStore.resolve(refName);
649
- if (ref?.objectId) return ref.objectId;
1620
+ private async resolveCommitId(
1621
+ refName: string,
1622
+ given: string = refName,
1623
+ ): Promise<ObjectId | undefined> {
1624
+ try {
1625
+ return await this.resolveRef(refName);
1626
+ } catch (error) {
1627
+ if (error instanceof RefNotFoundError) return undefined;
1628
+ if (error instanceof NotACommitError) throw nonCommitSwitchError(given, error);
1629
+ throw error;
1630
+ }
1631
+ }
650
1632
 
651
- // Try as commit ID
652
- if (await this.commits.has(refName)) {
653
- return refName;
1633
+ /**
1634
+ * What a branch checkout switches to (git's `parse_branchname_arg`): a new branch
1635
+ * (`-b`/`-B`, or a name guessed into a remote-tracking branch's local twin), an orphan,
1636
+ * an existing local branch, or a commit HEAD is detached at. `-` is `@{-1}`, and `@{-N}`
1637
+ * is the branch or commit it stands for, which also names the switch in the reflog.
1638
+ */
1639
+ private async planSwitch(): Promise<SwitchPlan> {
1640
+ const given = this.name ?? (this.detach ? "HEAD" : undefined);
1641
+ if (given === undefined) {
1642
+ throw new MissingArgumentError("name", "Branch name is required for checkout");
654
1643
  }
1644
+ if (this.orphan || this.createBranch) {
1645
+ if (!isValidBranchName(given)) throw new InvalidRefNameError(given);
1646
+ if (this.orphan && this.startPoint === undefined) {
1647
+ // validate_new_branchname
1648
+ if (await this.refsStore.has(`refs/heads/${given}`)) {
1649
+ throw new RefAlreadyExistsError(
1650
+ `refs/heads/${given}`,
1651
+ `fatal: a branch named '${given}' already exists`,
1652
+ );
1653
+ }
1654
+ return { kind: "orphan", branch: given, logName: given };
1655
+ }
1656
+ // the start point as git's setup_branch_path names it: `-` and @{-N} expanded (the
1657
+ // reflog's "Created from feat", the branch tracked). git's parse_branchname_arg reads
1658
+ // it before validate_new_branchname looks at the branch: a start point that names
1659
+ // nothing dies first, one that names a tree after the branch check
1660
+ const startArg = this.startPoint === "-" ? "@{-1}" : (this.startPoint ?? "HEAD");
1661
+ const startName = await this.expandPriorCheckout(startArg);
1662
+ let targetId: ObjectId | undefined;
1663
+ let nonCommit: unknown;
1664
+ try {
1665
+ targetId = await this.resolveCommitId(startName, this.startPoint ?? startName);
1666
+ } catch (error) {
1667
+ if (!(error instanceof SwitchRefusedError)) throw error;
1668
+ nonCommit = error;
1669
+ }
1670
+ if (!targetId && nonCommit === undefined) {
1671
+ if (this.startPoint === undefined) throw new RefNotFoundError(startName);
1672
+ throw new RefNotFoundError(
1673
+ this.startPoint,
1674
+ `fatal: '${this.startPoint}' is not a commit and a branch '${given}' cannot be created from it`,
1675
+ );
1676
+ }
1677
+ // validate_new_branchname: `-b` refuses an existing branch, `-B` resets it
1678
+ if (
1679
+ (this.orphan || !this.forceCreateBranch) &&
1680
+ (await this.refsStore.has(`refs/heads/${given}`))
1681
+ ) {
1682
+ throw new RefAlreadyExistsError(
1683
+ `refs/heads/${given}`,
1684
+ `fatal: a branch named '${given}' already exists`,
1685
+ );
1686
+ }
1687
+ if (!targetId) throw nonCommit;
1688
+ // `checkout --orphan <new> <start-point>`: the index and worktree merge to the start
1689
+ // point's tree (switch_branches with the start point's commit), the new branch unborn
1690
+ if (this.orphan) return { kind: "orphan", branch: given, logName: given, startId: targetId };
1691
+ return {
1692
+ kind: "create",
1693
+ branch: given,
1694
+ startName,
1695
+ targetId,
1696
+ logName: given,
1697
+ tracking: await this.planCreateTracking(given, startName),
1698
+ };
1699
+ }
1700
+ // git's parse_branchname_arg: `-` is @{-1}; the name a remote-tracking branch is guessed
1701
+ // from is the argument itself, so `-` or @{-N} naming a deleted branch guesses nothing
1702
+ const arg = given === "-" ? "@{-1}" : given;
1703
+ const name = await this.interpretLocalBranch(await this.expandPriorCheckout(arg));
1704
+ if (!this.detach && (name === "HEAD" || name === "@")) {
1705
+ // `checkout HEAD`: the worktree is checked out, HEAD left as it is
1706
+ const headId = await this.resolveCommitId("HEAD");
1707
+ if (headId) return { kind: "stay", targetId: headId, logName: "HEAD" };
1708
+ }
1709
+ if (!this.detach && isValidBranchName(name)) {
1710
+ const branch = await this.refsStore.resolve(`refs/heads/${name}`);
1711
+ if (branch?.objectId) {
1712
+ return { kind: "branch", branch: name, targetId: branch.objectId, logName: name };
1713
+ }
1714
+ }
1715
+ const targetId = await this.resolveCommitId(name, given);
1716
+ if (targetId) return { kind: "detach", targetId, logName: name };
1717
+ // git's dwim of a name no ref has into the remote-tracking branch of that name
1718
+ const config = RemoteConfigStore.from(this.workingCopy);
1719
+ const guess = this.guess ?? parseGitBool(config.value("checkout.guess")) ?? true;
1720
+ if (!this.detach && guess && isValidBranchName(arg)) {
1721
+ const remote = await guessRemoteBranch(this.workingCopy, this.refsStore, arg);
1722
+ const remoteId = remote ? await this.resolveCommitId(remote) : undefined;
1723
+ if (remote && remoteId) {
1724
+ return {
1725
+ kind: "create",
1726
+ branch: arg,
1727
+ startName: remote,
1728
+ targetId: remoteId,
1729
+ logName: arg,
1730
+ tracking: await this.planCreateTracking(arg, remote),
1731
+ };
1732
+ }
1733
+ }
1734
+ throw new RefNotFoundError(given);
1735
+ }
655
1736
 
656
- return undefined;
1737
+ /**
1738
+ * How the new branch `branch` tracks `startName` (git's dwim_branch_start and
1739
+ * setup_tracking), decided before the switch writes anything; the refusals are kept for
1740
+ * the point git dies at.
1741
+ */
1742
+ private async planCreateTracking(branch: string, startName: string): Promise<CreateTracking> {
1743
+ let startRef: string | undefined;
1744
+ try {
1745
+ startRef = await trackableStart(this.workingCopy, this.refsStore, startName, this.track);
1746
+ } catch (error) {
1747
+ return { notABranch: error };
1748
+ }
1749
+ if (startRef === undefined) return {};
1750
+ try {
1751
+ return { plan: planTracking(this.workingCopy, branch, startRef, this.track) };
1752
+ } catch (error) {
1753
+ return { ambiguous: error };
1754
+ }
657
1755
  }
658
1756
 
659
1757
  /**
@@ -675,3 +1773,34 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
675
1773
  }
676
1774
  }
677
1775
  }
1776
+
1777
+ /** A path checkout's outcome as a {@link CheckoutResult}. */
1778
+ export function pathCheckoutResult(outcome: CheckoutPathsOutcome): CheckoutResult {
1779
+ return {
1780
+ status: outcome.ok ? CheckoutStatus.OK : CheckoutStatus.CONFLICTS,
1781
+ updated: outcome.updated,
1782
+ removed: outcome.removed,
1783
+ conflicts: outcome.conflicts,
1784
+ ref: null,
1785
+ ...(outcome.errors.length > 0 ? { message: outcome.errors.join("\n") } : {}),
1786
+ ...(outcome.warnings.length > 0 ? { warnings: outcome.warnings } : {}),
1787
+ ...(outcome.exitCode !== undefined ? { exitCode: outcome.exitCode } : {}),
1788
+ };
1789
+ }
1790
+
1791
+ /** The refusals of {@link nonCommitSwitchError}. */
1792
+ const NON_COMMIT_SWITCH = /^fatal: (Cannot switch branch to a non-commit|unable to read tree) /;
1793
+
1794
+ /**
1795
+ * git's checkout of a revision that names no commit (`switch_branches`, 2.56): a tree is
1796
+ * `fatal: Cannot switch branch to a non-commit '<given>'`, a blob or a missing object
1797
+ * `fatal: unable to read tree (<id>)` (git 2.43 said `fatal: reference is not a tree:
1798
+ * <given>` there).
1799
+ */
1800
+ export function nonCommitSwitchError(given: string, error: NotACommitError): SwitchRefusedError {
1801
+ return new SwitchRefusedError(
1802
+ error.objectType === "tree"
1803
+ ? `fatal: Cannot switch branch to a non-commit '${given}'`
1804
+ : `fatal: unable to read tree (${error.objectId})`,
1805
+ );
1806
+ }