@statewalker/vcs-commands 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (546) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +300 -18
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +49 -16
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +117 -0
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +78 -1
  73. package/dist/commands/core-config.d.ts.map +1 -1
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +149 -10
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +54 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +31 -0
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +42 -8
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +155 -1
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +2 -0
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-working-tree.d.ts +23 -0
  237. package/dist/commands/stash-working-tree.d.ts.map +1 -1
  238. package/dist/commands/status-command.d.ts +300 -15
  239. package/dist/commands/status-command.d.ts.map +1 -1
  240. package/dist/commands/status-format.d.ts +155 -0
  241. package/dist/commands/status-format.d.ts.map +1 -0
  242. package/dist/commands/status-header.d.ts +64 -0
  243. package/dist/commands/status-header.d.ts.map +1 -0
  244. package/dist/commands/strerror.d.ts +7 -0
  245. package/dist/commands/strerror.d.ts.map +1 -0
  246. package/dist/commands/submodule-config.d.ts +38 -0
  247. package/dist/commands/submodule-config.d.ts.map +1 -0
  248. package/dist/commands/submodule-summary-command.d.ts +80 -0
  249. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary.d.ts +150 -0
  251. package/dist/commands/submodule-summary.d.ts.map +1 -0
  252. package/dist/commands/switch-command.d.ts +132 -0
  253. package/dist/commands/switch-command.d.ts.map +1 -0
  254. package/dist/commands/tag-command.d.ts +23 -2
  255. package/dist/commands/tag-command.d.ts.map +1 -1
  256. package/dist/commands/tracking-info.d.ts +64 -0
  257. package/dist/commands/tracking-info.d.ts.map +1 -0
  258. package/dist/commands/trailers.d.ts +73 -0
  259. package/dist/commands/trailers.d.ts.map +1 -0
  260. package/dist/commands/tree-restore.d.ts +85 -1
  261. package/dist/commands/tree-restore.d.ts.map +1 -1
  262. package/dist/commands/untracked-cache-support.d.ts +53 -0
  263. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  264. package/dist/commands/worktree-add-command.d.ts +108 -0
  265. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  266. package/dist/commands/worktree-list-command.d.ts +69 -0
  267. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-lock-command.d.ts +44 -0
  269. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-overwrite-checks.d.ts +146 -6
  271. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  272. package/dist/commands/worktree-prune-command.d.ts +48 -0
  273. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  274. package/dist/commands/worktree-remove-command.d.ts +59 -0
  275. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-repair-command.d.ts +35 -0
  277. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-support.d.ts +64 -0
  279. package/dist/commands/worktree-support.d.ts.map +1 -0
  280. package/dist/commands-DnmlfwGV.js +61620 -0
  281. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  282. package/dist/errors/add-errors.d.ts +55 -0
  283. package/dist/errors/add-errors.d.ts.map +1 -1
  284. package/dist/errors/checkout-errors.d.ts +16 -0
  285. package/dist/errors/checkout-errors.d.ts.map +1 -1
  286. package/dist/errors/command-errors.d.ts +77 -0
  287. package/dist/errors/command-errors.d.ts.map +1 -1
  288. package/dist/errors/commit-errors.d.ts +9 -0
  289. package/dist/errors/commit-errors.d.ts.map +1 -1
  290. package/dist/errors/git-api-error.d.ts +59 -2
  291. package/dist/errors/git-api-error.d.ts.map +1 -1
  292. package/dist/errors/index.d.ts +1 -0
  293. package/dist/errors/index.d.ts.map +1 -1
  294. package/dist/errors/index.js +354 -19
  295. package/dist/errors/rebase-errors.d.ts +9 -0
  296. package/dist/errors/rebase-errors.d.ts.map +1 -1
  297. package/dist/errors/ref-errors.d.ts +32 -0
  298. package/dist/errors/ref-errors.d.ts.map +1 -1
  299. package/dist/errors/transport-errors.d.ts +12 -2
  300. package/dist/errors/transport-errors.d.ts.map +1 -1
  301. package/dist/errors/worktree-errors.d.ts +35 -0
  302. package/dist/errors/worktree-errors.d.ts.map +1 -0
  303. package/dist/git-command-DxvwPrPB.js +7612 -0
  304. package/dist/git-command.d.ts +413 -32
  305. package/dist/git-command.d.ts.map +1 -1
  306. package/dist/git.d.ts +306 -3
  307. package/dist/git.d.ts.map +1 -1
  308. package/dist/index.d.ts +1 -1
  309. package/dist/index.d.ts.map +1 -1
  310. package/dist/index.js +5 -5
  311. package/dist/remote-config/remote-config-store.d.ts +105 -3
  312. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  313. package/dist/remote-config/remote-refs.d.ts +7 -3
  314. package/dist/remote-config/remote-refs.d.ts.map +1 -1
  315. package/dist/rename/detect-renames.d.ts +148 -0
  316. package/dist/rename/detect-renames.d.ts.map +1 -0
  317. package/dist/rename/git-similarity.d.ts +44 -0
  318. package/dist/rename/git-similarity.d.ts.map +1 -0
  319. package/dist/rename/index.d.ts +2 -0
  320. package/dist/rename/index.d.ts.map +1 -1
  321. package/dist/results/binary-patch.d.ts +11 -0
  322. package/dist/results/binary-patch.d.ts.map +1 -0
  323. package/dist/results/blame-format.d.ts +55 -0
  324. package/dist/results/blame-format.d.ts.map +1 -0
  325. package/dist/results/cherry-pick-result.d.ts +10 -0
  326. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  327. package/dist/results/clone-result.d.ts +10 -0
  328. package/dist/results/clone-result.d.ts.map +1 -1
  329. package/dist/results/combined-diff.d.ts +77 -0
  330. package/dist/results/combined-diff.d.ts.map +1 -0
  331. package/dist/results/diff-entry.d.ts +32 -0
  332. package/dist/results/diff-entry.d.ts.map +1 -1
  333. package/dist/results/diff-formatter.d.ts +34 -60
  334. package/dist/results/diff-formatter.d.ts.map +1 -1
  335. package/dist/results/diff-order.d.ts +25 -0
  336. package/dist/results/diff-order.d.ts.map +1 -0
  337. package/dist/results/diff-output.d.ts +249 -0
  338. package/dist/results/diff-output.d.ts.map +1 -0
  339. package/dist/results/fetch-result.d.ts +15 -0
  340. package/dist/results/fetch-result.d.ts.map +1 -1
  341. package/dist/results/index.d.ts +5 -0
  342. package/dist/results/index.d.ts.map +1 -1
  343. package/dist/results/index.js +2 -252
  344. package/dist/results/merge-result.d.ts +15 -1
  345. package/dist/results/merge-result.d.ts.map +1 -1
  346. package/dist/results/pull-result.d.ts +12 -3
  347. package/dist/results/pull-result.d.ts.map +1 -1
  348. package/dist/results/push-result.d.ts +42 -0
  349. package/dist/results/push-result.d.ts.map +1 -1
  350. package/dist/results/quote-path.d.ts +27 -0
  351. package/dist/results/quote-path.d.ts.map +1 -0
  352. package/dist/results/rebase-result.d.ts +28 -1
  353. package/dist/results/rebase-result.d.ts.map +1 -1
  354. package/dist/results/revert-result.d.ts +10 -0
  355. package/dist/results/revert-result.d.ts.map +1 -1
  356. package/dist/results/stash-result.d.ts +5 -0
  357. package/dist/results/stash-result.d.ts.map +1 -1
  358. package/dist/results/status-result.d.ts +60 -6
  359. package/dist/results/status-result.d.ts.map +1 -1
  360. package/dist/results-BZGa2Z3I.js +2934 -0
  361. package/dist/transport-command.d.ts +44 -1
  362. package/dist/transport-command.d.ts.map +1 -1
  363. package/package.json +15 -11
  364. package/src/commands/add-command.ts +1291 -226
  365. package/src/commands/add-patch/add-interactive.ts +941 -0
  366. package/src/commands/add-patch/add-patch.ts +1169 -0
  367. package/src/commands/add-patch/index.ts +5 -0
  368. package/src/commands/add-patch/patch-backend.ts +239 -0
  369. package/src/commands/add-patch/patch-modes.ts +249 -0
  370. package/src/commands/add-patch/patch-session.ts +159 -0
  371. package/src/commands/am/am-command.ts +1111 -0
  372. package/src/commands/am/index.ts +2 -0
  373. package/src/commands/am/mailinfo.ts +1015 -0
  374. package/src/commands/am/patch-format.ts +121 -0
  375. package/src/commands/apply/apply-command.ts +832 -0
  376. package/src/commands/apply/apply-engine.ts +1603 -0
  377. package/src/commands/apply/apply-parse.ts +1209 -0
  378. package/src/commands/apply/apply-types.ts +112 -0
  379. package/src/commands/apply/index.ts +5 -0
  380. package/src/commands/apply/latin1.ts +171 -0
  381. package/src/commands/apply/whitespace.ts +260 -0
  382. package/src/commands/attributes-source.ts +96 -0
  383. package/src/commands/backfill-command.ts +694 -0
  384. package/src/commands/bisect/bisect-checkout.ts +217 -0
  385. package/src/commands/bisect/bisect-command.ts +788 -0
  386. package/src/commands/bisect/bisect-engine.ts +1079 -0
  387. package/src/commands/bisect/bisect-graph.ts +595 -0
  388. package/src/commands/bisect/bisect-quote.ts +92 -0
  389. package/src/commands/bisect/index.ts +4 -0
  390. package/src/commands/blame-command.ts +711 -986
  391. package/src/commands/branch-command.ts +354 -32
  392. package/src/commands/branch-tracking.ts +331 -0
  393. package/src/commands/checkout-command.ts +1290 -243
  394. package/src/commands/checkout-paths.ts +784 -0
  395. package/src/commands/cherry-pick-command.ts +156 -396
  396. package/src/commands/clean-command.ts +504 -156
  397. package/src/commands/clone-command.ts +634 -67
  398. package/src/commands/commit-command.ts +1781 -166
  399. package/src/commands/core-config.ts +161 -6
  400. package/src/commands/date-format.ts +668 -0
  401. package/src/commands/describe-command.ts +2 -0
  402. package/src/commands/diff-command.ts +1898 -110
  403. package/src/commands/diff-textconv.ts +50 -0
  404. package/src/commands/fetch-command.ts +606 -66
  405. package/src/commands/format-patch-command.ts +969 -0
  406. package/src/commands/fsck/fetch-fsck.ts +229 -0
  407. package/src/commands/fsck/fsck-command.ts +3347 -0
  408. package/src/commands/fsck/fsck-loose.ts +287 -0
  409. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  410. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  411. package/src/commands/fsck/fsck-object-table.ts +363 -0
  412. package/src/commands/fsck/fsck-pack.ts +604 -0
  413. package/src/commands/fsck/index.ts +5 -0
  414. package/src/commands/fsck/verify-pack-command.ts +249 -0
  415. package/src/commands/gc-command.ts +147 -1
  416. package/src/commands/git-date.ts +895 -0
  417. package/src/commands/git-describe.ts +316 -0
  418. package/src/commands/git-hooks.ts +1472 -0
  419. package/src/commands/git-ident.ts +344 -0
  420. package/src/commands/hook-command.ts +247 -0
  421. package/src/commands/index-adder.ts +706 -0
  422. package/src/commands/index-host.ts +291 -0
  423. package/src/commands/index.ts +82 -0
  424. package/src/commands/init-command.ts +28 -4
  425. package/src/commands/local-clone.ts +183 -0
  426. package/src/commands/local-transport.ts +762 -0
  427. package/src/commands/log-command.ts +1915 -170
  428. package/src/commands/log-graph.ts +671 -0
  429. package/src/commands/log-output.ts +1359 -0
  430. package/src/commands/ls-remote-command.ts +101 -58
  431. package/src/commands/mailmap.ts +129 -0
  432. package/src/commands/merge-bases.ts +296 -0
  433. package/src/commands/merge-command.ts +1386 -491
  434. package/src/commands/merge-config.ts +25 -0
  435. package/src/commands/merge-drivers.ts +306 -0
  436. package/src/commands/merge-support.ts +1198 -0
  437. package/src/commands/message-cleanup.ts +275 -0
  438. package/src/commands/mv-command.ts +976 -0
  439. package/src/commands/notes-command.ts +890 -0
  440. package/src/commands/notes-commands.ts +87 -0
  441. package/src/commands/notes-merge-command.ts +768 -0
  442. package/src/commands/notes-support.ts +402 -0
  443. package/src/commands/notes-tree.ts +602 -0
  444. package/src/commands/object-id-input.ts +27 -0
  445. package/src/commands/octopus-merge.ts +377 -0
  446. package/src/commands/ort-merge.ts +1660 -0
  447. package/src/commands/ort-recursive.ts +160 -0
  448. package/src/commands/pack-refs-command.ts +39 -22
  449. package/src/commands/patch-id.ts +196 -0
  450. package/src/commands/pathspec-attributes.ts +162 -0
  451. package/src/commands/pathspec.ts +1199 -0
  452. package/src/commands/post-index-change.ts +62 -0
  453. package/src/commands/pretty-format.ts +1431 -0
  454. package/src/commands/promisor-remote.ts +298 -0
  455. package/src/commands/pull-command.ts +207 -22
  456. package/src/commands/push-command.ts +236 -23
  457. package/src/commands/read-tree-command.ts +857 -0
  458. package/src/commands/rebase-command.ts +3808 -371
  459. package/src/commands/rebase-todo.ts +584 -0
  460. package/src/commands/ref-decoration-filter.ts +118 -0
  461. package/src/commands/reflog-messages.ts +177 -0
  462. package/src/commands/remote-command.ts +93 -22
  463. package/src/commands/remote-transport.ts +383 -0
  464. package/src/commands/reset-command.ts +827 -103
  465. package/src/commands/restore-command.ts +350 -0
  466. package/src/commands/rev-list-command.ts +167 -0
  467. package/src/commands/rev-parse-command.ts +277 -0
  468. package/src/commands/revert-command.ts +152 -399
  469. package/src/commands/revision-filenames.ts +254 -0
  470. package/src/commands/revision-range.ts +222 -0
  471. package/src/commands/revision-resolver.ts +1379 -0
  472. package/src/commands/rm-command.ts +613 -67
  473. package/src/commands/sequencer-pick.ts +869 -0
  474. package/src/commands/sequencer-support.ts +869 -0
  475. package/src/commands/serve-repository.ts +125 -0
  476. package/src/commands/sparse-checkout-command.ts +1389 -0
  477. package/src/commands/sparse-checkout-support.ts +793 -0
  478. package/src/commands/stash-apply-command.ts +376 -343
  479. package/src/commands/stash-create-command.ts +625 -42
  480. package/src/commands/stash-drop-command.ts +15 -2
  481. package/src/commands/stash-working-tree.ts +168 -24
  482. package/src/commands/status-command.ts +1328 -105
  483. package/src/commands/status-format.ts +775 -0
  484. package/src/commands/status-header.ts +330 -0
  485. package/src/commands/strerror.ts +29 -0
  486. package/src/commands/submodule-config.ts +94 -0
  487. package/src/commands/submodule-summary-command.ts +334 -0
  488. package/src/commands/submodule-summary.ts +446 -0
  489. package/src/commands/switch-command.ts +402 -0
  490. package/src/commands/tag-command.ts +129 -41
  491. package/src/commands/tracking-info.ts +201 -0
  492. package/src/commands/trailers.ts +417 -0
  493. package/src/commands/tree-restore.ts +204 -4
  494. package/src/commands/untracked-cache-support.ts +194 -0
  495. package/src/commands/worktree-add-command.ts +458 -0
  496. package/src/commands/worktree-list-command.ts +208 -0
  497. package/src/commands/worktree-lock-command.ts +96 -0
  498. package/src/commands/worktree-overwrite-checks.ts +452 -26
  499. package/src/commands/worktree-prune-command.ts +99 -0
  500. package/src/commands/worktree-remove-command.ts +186 -0
  501. package/src/commands/worktree-repair-command.ts +59 -0
  502. package/src/commands/worktree-support.ts +214 -0
  503. package/src/core-commands/add.command.impl.ts +7 -1
  504. package/src/errors/add-errors.ts +45 -0
  505. package/src/errors/checkout-errors.ts +26 -2
  506. package/src/errors/command-errors.ts +101 -1
  507. package/src/errors/commit-errors.ts +18 -2
  508. package/src/errors/git-api-error.ts +82 -2
  509. package/src/errors/index.ts +1 -0
  510. package/src/errors/merge-errors.ts +2 -2
  511. package/src/errors/rebase-errors.ts +12 -0
  512. package/src/errors/ref-errors.ts +56 -2
  513. package/src/errors/remote-errors.ts +2 -2
  514. package/src/errors/stash-errors.ts +1 -1
  515. package/src/errors/transport-errors.ts +20 -4
  516. package/src/errors/worktree-errors.ts +49 -0
  517. package/src/git-command.ts +1177 -118
  518. package/src/git.ts +523 -10
  519. package/src/index.ts +1 -1
  520. package/src/remote-config/remote-config-store.ts +242 -8
  521. package/src/remote-config/remote-refs.ts +22 -6
  522. package/src/rename/detect-renames.ts +711 -0
  523. package/src/rename/git-similarity.ts +116 -0
  524. package/src/rename/index.ts +2 -0
  525. package/src/results/binary-patch.ts +401 -0
  526. package/src/results/blame-format.ts +239 -0
  527. package/src/results/cherry-pick-result.ts +10 -0
  528. package/src/results/clone-result.ts +12 -0
  529. package/src/results/combined-diff.ts +585 -0
  530. package/src/results/diff-entry.ts +35 -0
  531. package/src/results/diff-formatter.ts +152 -288
  532. package/src/results/diff-order.ts +64 -0
  533. package/src/results/diff-output.ts +1051 -0
  534. package/src/results/fetch-result.ts +15 -0
  535. package/src/results/index.ts +5 -0
  536. package/src/results/merge-result.ts +15 -1
  537. package/src/results/pull-result.ts +12 -3
  538. package/src/results/push-result.ts +43 -0
  539. package/src/results/quote-path.ts +103 -0
  540. package/src/results/rebase-result.ts +37 -0
  541. package/src/results/revert-result.ts +10 -0
  542. package/src/results/stash-result.ts +6 -0
  543. package/src/results/status-result.ts +123 -45
  544. package/src/transport-command.ts +121 -2
  545. package/dist/commands-CsLNyvZ1.js +0 -12587
  546. package/dist/status-result-BpyUK1Sg.js +0 -519
@@ -33,26 +33,95 @@
33
33
  * ```
34
34
  */
35
35
 
36
- import { FileMode, isValidBranchName, type ObjectId, type Ref } from "@statewalker/vcs-core";
37
- import { entryStatOf, UpdateStagingEntry, type Worktree } 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";
48
85
  import { coreBool, worktreeModeTrust } from "./core-config.js";
49
- import { planTreeRestore, writeTreeRestorePlan } from "./tree-restore.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";
50
99
  import {
100
+ entryNotUptodate,
51
101
  findInTheWay,
102
+ flaggedEntryDiffers,
52
103
  overwriteMessage,
53
104
  pruneEmptyParents,
54
- worktreeDiffers,
55
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
+ }
56
125
 
57
126
  /** Names a branch checkout in failure messages. */
58
127
  const CHECKOUT = "checkout";
@@ -109,6 +178,24 @@ export interface CheckoutResult {
109
178
  * untracked files the switch would overwrite, or an index with unmerged entries.
110
179
  */
111
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;
112
199
  }
113
200
 
114
201
  /** A tree or index entry, as the two-way merge compares them (index entries with stat). */
@@ -123,6 +210,42 @@ interface Side {
123
210
  const sameSide = (a: Side | undefined, b: Side | undefined) =>
124
211
  a === undefined || b === undefined ? a === b : a.objectId === b.objectId && a.mode === b.mode;
125
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;
222
+ }
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
+
126
249
  /**
127
250
  * Command to checkout branches, commits, or paths.
128
251
  *
@@ -132,6 +255,11 @@ const sameSide = (a: Side | undefined, b: Side | undefined) =>
132
255
  export class CheckoutCommand extends GitCommand<CheckoutResult> {
133
256
  private name: string | undefined;
134
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;
135
263
  private orphan = false;
136
264
  private force = false;
137
265
  // biome-ignore lint/correctness/noUnusedPrivateClassMembers: JGit compatibility - will be used for branch reset
@@ -140,6 +268,24 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
140
268
  private paths: string[] = [];
141
269
  private allPaths = false;
142
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 };
143
289
 
144
290
  /**
145
291
  * Set the name of the branch or commit to check out.
@@ -162,7 +308,9 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
162
308
  * If true, a new branch with setName() will be created at setStartPoint()
163
309
  * (or HEAD if not specified) and checked out.
164
310
  *
165
- * 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.
166
314
  *
167
315
  * @param createBranch Whether to create a new branch
168
316
  * @returns this for chaining
@@ -170,6 +318,22 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
170
318
  setCreateBranch(createBranch: boolean): this {
171
319
  this.checkCallable();
172
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;
173
337
  return this;
174
338
  }
175
339
 
@@ -207,6 +371,147 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
207
371
  return this;
208
372
  }
209
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
+
210
515
  /**
211
516
  * Set whether to force ref update.
212
517
  *
@@ -281,68 +586,509 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
281
586
  return this;
282
587
  }
283
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
+
284
658
  /**
285
659
  * Execute the checkout command.
286
660
  *
287
661
  * @returns Result with status and affected files
288
662
  * @throws RefNotFoundError if target cannot be resolved
289
663
  */
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 {
680
+ this.checkCallable();
681
+ this.patch = patch;
682
+ return this;
683
+ }
684
+
685
+ /** Answers the prompts of {@link setPatch}. */
686
+ setPatchSelector(selector: PatchSelector): this {
687
+ this.checkCallable();
688
+ this.patchSelector = selector;
689
+ return this;
690
+ }
691
+
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;
697
+ }
698
+
699
+ /**
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).
706
+ */
707
+ setCompatibility(version: PatchCompatibility): this {
708
+ this.checkCallable();
709
+ this.patchCompatibility = version;
710
+ return this;
711
+ }
712
+
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
+ );
722
+ }
723
+ throw new IncompatibleOptionsError(
724
+ ["--pathspec-from-file", "--patch"],
725
+ "fatal: options '--pathspec-from-file' and '--patch' cannot be used together",
726
+ );
727
+ }
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
+ });
753
+ return {
754
+ status: CheckoutStatus.OK,
755
+ updated: patch.applied,
756
+ removed: [],
757
+ conflicts: [],
758
+ ref: null,
759
+ patch,
760
+ };
761
+ }
762
+
290
763
  async call(): Promise<CheckoutResult> {
291
764
  this.checkCallable();
292
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();
293
771
 
294
772
  // path checkout, or branch checkout; one worktree batch, so the checks and the writes
295
773
  // share one reading of the ignore rules
296
- const run = () =>
297
- this.allPaths || this.paths.length > 0 ? this.checkoutPaths() : this.checkoutBranch();
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());
298
779
  const worktree = this.worktreeAccess;
299
- return worktree?.batch ? worktree.batch(run) : run();
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);
300
787
  }
301
788
 
302
789
  /**
303
- * Checkout paths from index or commit.
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.
304
793
  */
305
- private async checkoutPaths(): Promise<CheckoutResult> {
306
- const updated: string[] = [];
307
- const conflicts: string[] = [];
308
-
309
- // Determine source tree
310
- let sourceTreeId: ObjectId | undefined;
311
- if (this.startPoint) {
312
- sourceTreeId = await this.resolveTreeId(this.startPoint);
313
- if (!sourceTreeId) {
314
- throw new RefNotFoundError(this.startPoint);
315
- }
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
+ }
813
+
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 };
848
+ }
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;
855
+ }
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
+ };
864
+ }
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
+ };
316
874
  }
875
+ return { ...switched, message: applied.message };
876
+ }
317
877
 
318
- // Get paths to checkout
319
- const pathsToCheckout = this.allPaths ? await this.getAllPaths(sourceTreeId) : this.paths;
878
+ /**
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`.
882
+ */
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;
901
+ }
902
+ if (status === StashApplyStatus.OK) {
903
+ return { message: "Applied autostash.", conflicts: [], conflicted: false };
904
+ }
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 };
912
+ }
913
+ return {
914
+ message: "error: could not apply autostash; your changes are safe in the stash",
915
+ conflicts: [],
916
+ conflicted: false,
917
+ };
918
+ }
320
919
 
321
- // Checkout each path
322
- for (const path of pathsToCheckout) {
323
- try {
324
- if (sourceTreeId) {
325
- // Checkout from commit tree
326
- await this.checkoutPathFromTree(path, sourceTreeId);
327
- } else {
328
- // Checkout from index
329
- await this.checkoutPathFromIndex(path);
330
- }
331
- updated.push(path);
332
- } catch {
333
- conflicts.push(path);
334
- }
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
+ );
971
+ }
972
+ }
973
+
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
+ }
984
+
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
+ }
991
+
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
+ }
1013
+
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
+ );
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
+ );
335
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
+ }
336
1059
 
1060
+ /** What a path checkout reads and writes. */
1061
+ private pathCheckoutContext() {
337
1062
  return {
338
- status: conflicts.length > 0 ? CheckoutStatus.CONFLICTS : CheckoutStatus.OK,
339
- updated,
340
- removed: [],
341
- conflicts,
342
- 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),
343
1070
  };
344
1071
  }
345
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
+
1082
+ /**
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)`.
1085
+ */
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
+
346
1092
  /** Whether an untracked (not ignored) file or link is at `path`. */
347
1093
  private async untrackedFileAt(worktree: Worktree, path: string): Promise<boolean> {
348
1094
  const entry = await worktree.getEntry(path);
@@ -353,34 +1099,72 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
353
1099
  * Checkout a branch or commit.
354
1100
  */
355
1101
  private async checkoutBranch(): Promise<CheckoutResult> {
356
- if (!this.name) {
357
- throw new MissingArgumentError("name", "Branch name is required for checkout");
358
- }
359
-
360
- // Create branch if requested
361
- if (this.createBranch) {
362
- if (!isValidBranchName(this.name)) {
363
- throw new InvalidRefNameError(this.name);
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;
364
1110
  }
365
- const startPointId = this.startPoint
366
- ? await this.resolveCommitId(this.startPoint)
367
- : await this.resolveCommitId("HEAD");
368
-
369
- if (!startPointId) {
370
- throw new RefNotFoundError(this.startPoint ?? "HEAD");
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);
371
1130
  }
372
-
373
- await this.refsStore.set(`refs/heads/${this.name}`, startPointId);
374
1131
  }
375
1132
 
376
- // Resolve target
377
- const targetId = await this.resolveCommitId(this.name);
378
- if (!targetId && !this.orphan) {
379
- throw new RefNotFoundError(this.name);
380
- }
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, [], [], []);
381
1138
 
382
1139
  // Get target tree for conflict detection and checkout
383
- const targetTreeId = targetId ? await this.commits.getTree(targetId) : undefined;
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);
384
1168
 
385
1169
  // git's two-way merge (unpack-trees `twoway_merge`, checkout without -f): a path HEAD
386
1170
  // and the target agree on keeps its index entry and worktree file as they are (local
@@ -389,8 +1173,6 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
389
1173
  // untracked files in the way and an index with unmerged entries. With `setForce`, as
390
1174
  // `git checkout -f`, the target's tree replaces index and worktree whatever they hold.
391
1175
  const worktree = this.worktreeAccess;
392
- const headId = await this.resolveCommitId("HEAD");
393
- const headTreeId = headId ? await this.commits.getTree(headId) : undefined;
394
1176
  const head = new Map<string, Side>();
395
1177
  const target = new Map<string, Side>();
396
1178
  if (headTreeId) await this.collectTreeEntries(headTreeId, "", head);
@@ -402,7 +1184,11 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
402
1184
  else unmerged.add(entry.path);
403
1185
  }
404
1186
 
405
- if (!this.force && !this.orphan && unmerged.size > 0) {
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) {
406
1192
  return {
407
1193
  status: CheckoutStatus.CONFLICTS,
408
1194
  updated: [],
@@ -419,16 +1205,28 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
419
1205
  const untracked: string[] = [];
420
1206
  const untrackedRemoved: string[] = [];
421
1207
  const lostDirs: string[] = [];
1208
+ /** Case variants of index paths in directories files replace (see findInTheWay) */
1209
+ const caseVariants: string[] = [];
422
1210
  const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : undefined;
423
1211
  const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
1212
+ const initial = unborn && !keepAll;
424
1213
  const paths = [...new Set([...head.keys(), ...target.keys()])].sort();
425
- // (an orphan branch keeps index and worktree as they are, as git's --orphan)
426
- for (const path of this.orphan ? [] : paths) {
1214
+ for (const path of keepAll ? [] : paths) {
427
1215
  const h = head.get(path);
428
1216
  const t = target.get(path);
1217
+ if (initial && t) {
1218
+ switched.push(path);
1219
+ continue;
1220
+ }
429
1221
  if (!this.force && sameSide(h, t)) continue;
430
1222
  const i = index.get(path);
431
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;
1228
+ }
1229
+ if (quiet(path)) continue;
432
1230
  if (!sameSide(i, t) || t) switched.push(path);
433
1231
  continue;
434
1232
  }
@@ -445,7 +1243,12 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
445
1243
  if (i !== undefined || t !== undefined) local.push(path);
446
1244
  continue;
447
1245
  }
448
- if (i !== undefined && worktree && (await worktreeDiffers(worktree, path, i, trust))) {
1246
+ if (
1247
+ i !== undefined &&
1248
+ worktree &&
1249
+ !quiet(path) &&
1250
+ (await entryNotUptodate(worktree, path, i, trust, this.staging.getUpdateTime()))
1251
+ ) {
449
1252
  local.push(path);
450
1253
  continue;
451
1254
  }
@@ -457,13 +1260,96 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
457
1260
  // component, untracked files in a directory a file replaces
458
1261
  if (worktree && !this.force) {
459
1262
  const found = await findInTheWay(worktree, {
460
- writes: switched.filter((p) => target.has(p)),
1263
+ writes: switched.filter((p) => target.has(p) && writes(p)),
461
1264
  removes: new Set(switched.filter((p) => !target.has(p))),
462
1265
  index,
463
- ignoreCase,
1266
+ ...(await restoreCaseOptions(worktree, ignoreCase)),
1267
+ caseVariantsExpendable: true,
464
1268
  });
465
1269
  untracked.push(...found.untracked);
466
1270
  lostDirs.push(...found.lostDirs);
1271
+ caseVariants.push(...(found.caseVariants ?? []));
1272
+ }
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
+ };
1303
+ }
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
+ };
1323
+ }
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(" ")}`,
1340
+ );
1341
+ }
1342
+ }
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
+ };
467
1353
  }
468
1354
  if (local.length + untracked.length + untrackedRemoved.length + lostDirs.length > 0) {
469
1355
  const message = overwriteMessage("checkout", {
@@ -488,65 +1374,96 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
488
1374
  const updated: string[] = [];
489
1375
  const removed: string[] = [];
490
1376
  const switching = new Set(switched);
491
- if (targetTreeId && worktree) {
492
- const plan = await planTreeRestore(this.trees, this.blobs, targetTreeId, CHECKOUT, {
493
- symlinks: true,
494
- ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
495
- windows: worktree.capabilities?.windowsPaths === true,
496
- reservedNames: worktree.capabilities?.reservedNames,
497
- });
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
+ }
498
1397
  for (const path of switched) {
499
- if (target.has(path)) continue;
1398
+ if (target.has(path) || quiet(path)) continue;
500
1399
  await worktree.remove(path);
501
1400
  await pruneEmptyParents(worktree, path);
502
1401
  removed.push(path);
503
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
+ }
504
1409
  // a forced checkout also drops tracked files no tree holds any more
505
1410
  if (this.force) {
506
1411
  for (const path of index.keys()) {
507
- if (!target.has(path) && !switching.has(path)) {
1412
+ if (!target.has(path) && !switching.has(path) && !quiet(path)) {
508
1413
  await worktree.remove(path);
509
1414
  removed.push(path);
510
1415
  }
511
1416
  }
512
1417
  }
513
- const only = {
1418
+ // in a sparse checkout, only the paths in its patterns are written
1419
+ const only = plan && {
514
1420
  ...plan,
515
- entries: plan.entries.filter((e) => switching.has(e.path)),
516
- gitlinks: plan.gitlinks.filter((e) => switching.has(e.path)),
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)),
517
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
+ }
518
1433
  // everything in the way was checked above (or the checkout is forced): a file or link
519
1434
  // where a directory goes, a clean directory where a file goes, are replaced
520
- await writeTreeRestorePlan(worktree, this.blobs, only, CHECKOUT, {
521
- symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
522
- gitlinks: true,
523
- replaceInTheWay: true,
524
- });
525
- updated.push(...only.entries.map((e) => e.path));
526
- }
527
-
528
- // Determine if we should use symbolic ref (branch) or detached HEAD (commit/tag)
529
- // Check if it's a local branch
530
- const isLocalBranch = await this.refsStore.has(`refs/heads/${this.name}`);
531
-
532
- // Decide whether to create symbolic ref or detached HEAD
533
- if (this.orphan) {
534
- // Orphan branch: symbolic ref to a branch that doesn't exist yet
535
- await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
536
- } else if (isLocalBranch) {
537
- // Local branch exists: use symbolic ref to the branch
538
- await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
539
- } else if (targetId) {
540
- // Not a local branch but resolves to a commit: detached HEAD
541
- // This handles: commit IDs, tags, remote branches, etc.
542
- await this.refsStore.set("HEAD", targetId);
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
+ }
543
1447
  }
544
1448
 
545
- // The index: forced, the target's tree; else the switched paths take the target's
546
- // entries (with the stat of the files just written), every other path keeps its own
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?.();
547
1454
  if (targetTreeId && this.force) {
548
- await this.staging.readTree(this.trees as any, targetTreeId);
549
- await this.staging.write();
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();
550
1467
  } else if (switched.length > 0) {
551
1468
  const editor = this.staging.createEditor();
552
1469
  for (const path of switched) {
@@ -555,135 +1472,111 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
555
1472
  editor.remove(path);
556
1473
  continue;
557
1474
  }
558
- const stats = worktree ? await worktree.getEntry(path) : undefined;
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;
559
1479
  editor.upsert({
560
1480
  path,
561
1481
  objectId: t.objectId,
562
1482
  mode: t.mode,
563
1483
  ...entryStatOf(stats ?? {}),
1484
+ ...(old?.skipWorktree ? { skipWorktree: true } : {}),
564
1485
  });
565
1486
  }
566
1487
  await editor.finish();
567
- await this.staging.write();
1488
+ await this.writeSwitchedIndex();
1489
+ } else {
1490
+ await this.writeSwitchedIndex();
568
1491
  }
569
1492
 
570
- // Get the ref we checked out
571
- const ref = await this.refsStore.resolve("HEAD");
572
-
573
- return {
574
- status: CheckoutStatus.OK,
575
- updated,
576
- removed,
577
- conflicts: [],
578
- ref: ref ?? null,
579
- };
580
- }
581
-
582
- /**
583
- * Checkout a path from the staging index.
584
- */
585
- private async checkoutPathFromIndex(path: string): Promise<void> {
586
- // Find the entry in staging
587
- let found = false;
588
- for await (const entry of this.staging.entries()) {
589
- if (entry.path !== path) continue;
590
-
591
- // Handle conflict stages
592
- if (entry.stage !== 0) {
593
- if (this.stage && entry.stage === this.stage) {
594
- // Replace with specified stage
595
- const editor = this.staging.createEditor();
596
- editor.add(
597
- new UpdateStagingEntry(path, entry.objectId, entry.mode, {
598
- size: entry.size,
599
- mtime: Date.now(),
600
- }),
601
- );
602
- await editor.finish();
603
- found = true;
604
- break;
605
- }
606
- continue;
607
- }
608
-
609
- found = true;
610
- break;
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);
611
1507
  }
612
1508
 
613
- if (!found) {
614
- throw new PathNotInIndexError(path);
615
- }
1509
+ return this.updateRefsForSwitch(switchTo, updated, removed, sparseWarnings);
616
1510
  }
617
1511
 
618
1512
  /**
619
- * Checkout a path from a tree.
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.
620
1515
  */
621
- private async checkoutPathFromTree(path: string, treeId: ObjectId): Promise<void> {
622
- // Navigate tree to find the entry
623
- const parts = path.split("/");
624
- let currentTreeId = treeId;
625
-
626
- for (let i = 0; i < parts.length; i++) {
627
- const name = parts[i];
628
- const entry = await this.trees.getEntry(currentTreeId, name);
629
-
630
- if (!entry) {
631
- throw new PathNotFoundInTreeError(path);
632
- }
633
-
634
- if (i < parts.length - 1) {
635
- if (entry.mode !== FileMode.TREE) {
636
- throw new NotADirectoryError(parts.slice(0, i + 1).join("/"));
637
- }
638
- currentTreeId = entry.id;
639
- } else {
640
- // Found the file - update staging
641
- const editor = this.staging.createEditor();
642
- editor.add(
643
- new UpdateStagingEntry(path, entry.id, entry.mode, {
644
- size: 0,
645
- mtime: Date.now(),
646
- }),
647
- );
648
- await editor.finish();
649
- }
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);
650
1545
  }
651
- }
652
-
653
- /**
654
- * Get all paths from staging or tree.
655
- */
656
- private async getAllPaths(sourceTreeId?: ObjectId): Promise<string[]> {
657
- const paths: string[] = [];
658
1546
 
659
- if (sourceTreeId) {
660
- // Get all paths from tree
661
- await this.collectTreePaths(sourceTreeId, "", paths);
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);
662
1552
  } else {
663
- // Get all paths from staging
664
- for await (const entry of this.staging.entries()) {
665
- if (entry.stage === 0 && !paths.includes(entry.path)) {
666
- paths.push(entry.path);
667
- }
668
- }
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);
669
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();
670
1568
 
671
- return paths;
672
- }
673
-
674
- /**
675
- * Collect all paths from a tree recursively.
676
- */
677
- private async collectTreePaths(treeId: ObjectId, prefix: string, paths: string[]): Promise<void> {
678
- for await (const entry of this.trees.loadTree(treeId)) {
679
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
1569
+ // Get the ref we checked out
1570
+ const ref = await this.refsStore.resolve("HEAD");
680
1571
 
681
- if (entry.mode === FileMode.TREE) {
682
- await this.collectTreePaths(entry.id, path, paths);
683
- } else {
684
- paths.push(path);
685
- }
686
- }
1572
+ return {
1573
+ status: CheckoutStatus.OK,
1574
+ updated,
1575
+ removed,
1576
+ conflicts: [],
1577
+ ref: ref ?? null,
1578
+ ...(sparseWarnings.length > 0 ? { warnings: sparseWarnings } : {}),
1579
+ };
687
1580
  }
688
1581
 
689
1582
  /**
@@ -706,36 +1599,159 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
706
1599
  }
707
1600
 
708
1601
  /**
709
- * 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
710
1607
  */
711
- private async resolveTreeId(refName: string): Promise<ObjectId | undefined> {
712
- const commitId = await this.resolveCommitId(refName);
713
- if (!commitId) return undefined;
714
- 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") };
715
1613
  }
716
1614
 
717
1615
  /**
718
- * 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`.
719
1619
  */
720
- private async resolveCommitId(refName: string): Promise<ObjectId | undefined> {
721
- // Try as branch
722
- let ref = await this.refsStore.resolve(`refs/heads/${refName}`);
723
- if (ref?.objectId) return ref.objectId;
724
-
725
- // Try as tag
726
- ref = await this.refsStore.resolve(`refs/tags/${refName}`);
727
- if (ref?.objectId) return ref.objectId;
728
-
729
- // Try as direct ref (HEAD, etc.)
730
- ref = await this.refsStore.resolve(refName);
731
- 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
+ }
732
1632
 
733
- // Try as commit ID
734
- if (await this.commits.has(refName)) {
735
- 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");
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
+ };
736
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
+ }
737
1736
 
738
- 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
+ }
739
1755
  }
740
1756
 
741
1757
  /**
@@ -757,3 +1773,34 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
757
1773
  }
758
1774
  }
759
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
+ }