@statewalker/vcs-commands 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (561) hide show
  1. package/README.md +123 -8
  2. package/dist/commands/add-command.d.ts +265 -34
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/add-patch/add-interactive.d.ts +46 -0
  5. package/dist/commands/add-patch/add-interactive.d.ts.map +1 -0
  6. package/dist/commands/add-patch/add-patch.d.ts +139 -0
  7. package/dist/commands/add-patch/add-patch.d.ts.map +1 -0
  8. package/dist/commands/add-patch/index.d.ts +6 -0
  9. package/dist/commands/add-patch/index.d.ts.map +1 -0
  10. package/dist/commands/add-patch/patch-backend.d.ts +80 -0
  11. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -0
  12. package/dist/commands/add-patch/patch-modes.d.ts +71 -0
  13. package/dist/commands/add-patch/patch-modes.d.ts.map +1 -0
  14. package/dist/commands/add-patch/patch-session.d.ts +49 -0
  15. package/dist/commands/add-patch/patch-session.d.ts.map +1 -0
  16. package/dist/commands/am/am-command.d.ts +175 -0
  17. package/dist/commands/am/am-command.d.ts.map +1 -0
  18. package/dist/commands/am/index.d.ts +3 -0
  19. package/dist/commands/am/index.d.ts.map +1 -0
  20. package/dist/commands/am/mailinfo.d.ts +58 -0
  21. package/dist/commands/am/mailinfo.d.ts.map +1 -0
  22. package/dist/commands/am/patch-format.d.ts +24 -0
  23. package/dist/commands/am/patch-format.d.ts.map +1 -0
  24. package/dist/commands/apply/apply-command.d.ts +153 -0
  25. package/dist/commands/apply/apply-command.d.ts.map +1 -0
  26. package/dist/commands/apply/apply-engine.d.ts +195 -0
  27. package/dist/commands/apply/apply-engine.d.ts.map +1 -0
  28. package/dist/commands/apply/apply-parse.d.ts +86 -0
  29. package/dist/commands/apply/apply-parse.d.ts.map +1 -0
  30. package/dist/commands/apply/apply-types.d.ts +70 -0
  31. package/dist/commands/apply/apply-types.d.ts.map +1 -0
  32. package/dist/commands/apply/index.d.ts +6 -0
  33. package/dist/commands/apply/index.d.ts.map +1 -0
  34. package/dist/commands/apply/latin1.d.ts +32 -0
  35. package/dist/commands/apply/latin1.d.ts.map +1 -0
  36. package/dist/commands/apply/whitespace.d.ts +58 -0
  37. package/dist/commands/apply/whitespace.d.ts.map +1 -0
  38. package/dist/commands/attributes-source.d.ts +26 -0
  39. package/dist/commands/attributes-source.d.ts.map +1 -0
  40. package/dist/commands/backfill-command.d.ts +110 -0
  41. package/dist/commands/backfill-command.d.ts.map +1 -0
  42. package/dist/commands/bisect/bisect-checkout.d.ts +64 -0
  43. package/dist/commands/bisect/bisect-checkout.d.ts.map +1 -0
  44. package/dist/commands/bisect/bisect-command.d.ts +201 -0
  45. package/dist/commands/bisect/bisect-command.d.ts.map +1 -0
  46. package/dist/commands/bisect/bisect-engine.d.ts +219 -0
  47. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -0
  48. package/dist/commands/bisect/bisect-graph.d.ts +127 -0
  49. package/dist/commands/bisect/bisect-graph.d.ts.map +1 -0
  50. package/dist/commands/bisect/bisect-quote.d.ts +27 -0
  51. package/dist/commands/bisect/bisect-quote.d.ts.map +1 -0
  52. package/dist/commands/bisect/index.d.ts +5 -0
  53. package/dist/commands/bisect/index.d.ts.map +1 -0
  54. package/dist/commands/blame-command.d.ts +122 -131
  55. package/dist/commands/blame-command.d.ts.map +1 -1
  56. package/dist/commands/branch-command.d.ts +52 -2
  57. package/dist/commands/branch-command.d.ts.map +1 -1
  58. package/dist/commands/branch-tracking.d.ts +98 -0
  59. package/dist/commands/branch-tracking.d.ts.map +1 -0
  60. package/dist/commands/checkout-command.d.ts +299 -34
  61. package/dist/commands/checkout-command.d.ts.map +1 -1
  62. package/dist/commands/checkout-paths.d.ts +124 -0
  63. package/dist/commands/checkout-paths.d.ts.map +1 -0
  64. package/dist/commands/cherry-pick-command.d.ts +50 -42
  65. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  66. package/dist/commands/clean-command.d.ts +67 -4
  67. package/dist/commands/clean-command.d.ts.map +1 -1
  68. package/dist/commands/clone-command.d.ts +179 -7
  69. package/dist/commands/clone-command.d.ts.map +1 -1
  70. package/dist/commands/commit-command.d.ts +311 -17
  71. package/dist/commands/commit-command.d.ts.map +1 -1
  72. package/dist/commands/core-config.d.ts +93 -0
  73. package/dist/commands/core-config.d.ts.map +1 -0
  74. package/dist/commands/date-format.d.ts +58 -0
  75. package/dist/commands/date-format.d.ts.map +1 -0
  76. package/dist/commands/describe-command.d.ts.map +1 -1
  77. package/dist/commands/diff-command.d.ts +377 -30
  78. package/dist/commands/diff-command.d.ts.map +1 -1
  79. package/dist/commands/diff-textconv.d.ts +40 -0
  80. package/dist/commands/diff-textconv.d.ts.map +1 -0
  81. package/dist/commands/fetch-command.d.ts +244 -23
  82. package/dist/commands/fetch-command.d.ts.map +1 -1
  83. package/dist/commands/format-patch-command.d.ts +164 -0
  84. package/dist/commands/format-patch-command.d.ts.map +1 -0
  85. package/dist/commands/fsck/fetch-fsck.d.ts +60 -0
  86. package/dist/commands/fsck/fetch-fsck.d.ts.map +1 -0
  87. package/dist/commands/fsck/fsck-command.d.ts +225 -0
  88. package/dist/commands/fsck/fsck-command.d.ts.map +1 -0
  89. package/dist/commands/fsck/fsck-loose.d.ts +68 -0
  90. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -0
  91. package/dist/commands/fsck/fsck-msg-ids.d.ts +122 -0
  92. package/dist/commands/fsck/fsck-msg-ids.d.ts.map +1 -0
  93. package/dist/commands/fsck/fsck-object-checks.d.ts +148 -0
  94. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -0
  95. package/dist/commands/fsck/fsck-object-table.d.ts +132 -0
  96. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -0
  97. package/dist/commands/fsck/fsck-pack.d.ts +115 -0
  98. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -0
  99. package/dist/commands/fsck/index.d.ts +6 -0
  100. package/dist/commands/fsck/index.d.ts.map +1 -0
  101. package/dist/commands/fsck/verify-pack-command.d.ts +81 -0
  102. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -0
  103. package/dist/commands/gc-command.d.ts +43 -0
  104. package/dist/commands/gc-command.d.ts.map +1 -1
  105. package/dist/commands/git-date.d.ts +66 -0
  106. package/dist/commands/git-date.d.ts.map +1 -0
  107. package/dist/commands/git-describe.d.ts +67 -0
  108. package/dist/commands/git-describe.d.ts.map +1 -0
  109. package/dist/commands/git-hooks.d.ts +416 -0
  110. package/dist/commands/git-hooks.d.ts.map +1 -0
  111. package/dist/commands/git-ident.d.ts +128 -0
  112. package/dist/commands/git-ident.d.ts.map +1 -0
  113. package/dist/commands/hook-command.d.ts +96 -0
  114. package/dist/commands/hook-command.d.ts.map +1 -0
  115. package/dist/commands/index-adder.d.ts +231 -0
  116. package/dist/commands/index-adder.d.ts.map +1 -0
  117. package/dist/commands/index-host.d.ts +86 -0
  118. package/dist/commands/index-host.d.ts.map +1 -0
  119. package/dist/commands/index.d.ts +55 -0
  120. package/dist/commands/index.d.ts.map +1 -1
  121. package/dist/commands/index.js +3 -2
  122. package/dist/commands/init-command.d.ts +12 -1
  123. package/dist/commands/init-command.d.ts.map +1 -1
  124. package/dist/commands/local-clone.d.ts +60 -0
  125. package/dist/commands/local-clone.d.ts.map +1 -0
  126. package/dist/commands/local-transport.d.ts +117 -0
  127. package/dist/commands/local-transport.d.ts.map +1 -0
  128. package/dist/commands/log-command.d.ts +216 -24
  129. package/dist/commands/log-command.d.ts.map +1 -1
  130. package/dist/commands/log-graph.d.ts +120 -0
  131. package/dist/commands/log-graph.d.ts.map +1 -0
  132. package/dist/commands/log-output.d.ts +323 -0
  133. package/dist/commands/log-output.d.ts.map +1 -0
  134. package/dist/commands/ls-remote-command.d.ts +23 -7
  135. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  136. package/dist/commands/mailmap.d.ts +31 -0
  137. package/dist/commands/mailmap.d.ts.map +1 -0
  138. package/dist/commands/merge-bases.d.ts +85 -0
  139. package/dist/commands/merge-bases.d.ts.map +1 -0
  140. package/dist/commands/merge-command.d.ts +209 -74
  141. package/dist/commands/merge-command.d.ts.map +1 -1
  142. package/dist/commands/merge-config.d.ts +13 -0
  143. package/dist/commands/merge-config.d.ts.map +1 -0
  144. package/dist/commands/merge-drivers.d.ts +130 -0
  145. package/dist/commands/merge-drivers.d.ts.map +1 -0
  146. package/dist/commands/merge-support.d.ts +252 -0
  147. package/dist/commands/merge-support.d.ts.map +1 -0
  148. package/dist/commands/message-cleanup.d.ts +86 -0
  149. package/dist/commands/message-cleanup.d.ts.map +1 -0
  150. package/dist/commands/mv-command.d.ts +94 -0
  151. package/dist/commands/mv-command.d.ts.map +1 -0
  152. package/dist/commands/notes-command.d.ts +256 -0
  153. package/dist/commands/notes-command.d.ts.map +1 -0
  154. package/dist/commands/notes-commands.d.ts +41 -0
  155. package/dist/commands/notes-commands.d.ts.map +1 -0
  156. package/dist/commands/notes-merge-command.d.ts +105 -0
  157. package/dist/commands/notes-merge-command.d.ts.map +1 -0
  158. package/dist/commands/notes-support.d.ts +125 -0
  159. package/dist/commands/notes-support.d.ts.map +1 -0
  160. package/dist/commands/notes-tree.d.ts +106 -0
  161. package/dist/commands/notes-tree.d.ts.map +1 -0
  162. package/dist/commands/object-id-input.d.ts +20 -0
  163. package/dist/commands/object-id-input.d.ts.map +1 -0
  164. package/dist/commands/octopus-merge.d.ts +59 -0
  165. package/dist/commands/octopus-merge.d.ts.map +1 -0
  166. package/dist/commands/ort-merge.d.ts +126 -0
  167. package/dist/commands/ort-merge.d.ts.map +1 -0
  168. package/dist/commands/ort-recursive.d.ts +53 -0
  169. package/dist/commands/ort-recursive.d.ts.map +1 -0
  170. package/dist/commands/pack-refs-command.d.ts +20 -0
  171. package/dist/commands/pack-refs-command.d.ts.map +1 -1
  172. package/dist/commands/patch-id.d.ts +41 -0
  173. package/dist/commands/patch-id.d.ts.map +1 -0
  174. package/dist/commands/pathspec-attributes.d.ts +64 -0
  175. package/dist/commands/pathspec-attributes.d.ts.map +1 -0
  176. package/dist/commands/pathspec.d.ts +324 -0
  177. package/dist/commands/pathspec.d.ts.map +1 -0
  178. package/dist/commands/post-index-change.d.ts +33 -0
  179. package/dist/commands/post-index-change.d.ts.map +1 -0
  180. package/dist/commands/pretty-format.d.ts +222 -0
  181. package/dist/commands/pretty-format.d.ts.map +1 -0
  182. package/dist/commands/promisor-remote.d.ts +80 -0
  183. package/dist/commands/promisor-remote.d.ts.map +1 -0
  184. package/dist/commands/pull-command.d.ts +41 -8
  185. package/dist/commands/pull-command.d.ts.map +1 -1
  186. package/dist/commands/push-command.d.ts +24 -8
  187. package/dist/commands/push-command.d.ts.map +1 -1
  188. package/dist/commands/read-tree-command.d.ts +112 -0
  189. package/dist/commands/read-tree-command.d.ts.map +1 -0
  190. package/dist/commands/rebase-command.d.ts +507 -75
  191. package/dist/commands/rebase-command.d.ts.map +1 -1
  192. package/dist/commands/rebase-todo.d.ts +130 -0
  193. package/dist/commands/rebase-todo.d.ts.map +1 -0
  194. package/dist/commands/ref-decoration-filter.d.ts +53 -0
  195. package/dist/commands/ref-decoration-filter.d.ts.map +1 -0
  196. package/dist/commands/reflog-messages.d.ts +98 -0
  197. package/dist/commands/reflog-messages.d.ts.map +1 -0
  198. package/dist/commands/remote-command.d.ts +146 -6
  199. package/dist/commands/remote-command.d.ts.map +1 -1
  200. package/dist/commands/remote-transport.d.ts +120 -0
  201. package/dist/commands/remote-transport.d.ts.map +1 -0
  202. package/dist/commands/reset-command.d.ts +161 -7
  203. package/dist/commands/reset-command.d.ts.map +1 -1
  204. package/dist/commands/restore-command.d.ts +103 -0
  205. package/dist/commands/restore-command.d.ts.map +1 -0
  206. package/dist/commands/rev-list-command.d.ts +78 -0
  207. package/dist/commands/rev-list-command.d.ts.map +1 -0
  208. package/dist/commands/rev-parse-command.d.ts +80 -0
  209. package/dist/commands/rev-parse-command.d.ts.map +1 -0
  210. package/dist/commands/revert-command.d.ts +46 -38
  211. package/dist/commands/revert-command.d.ts.map +1 -1
  212. package/dist/commands/revision-filenames.d.ts +95 -0
  213. package/dist/commands/revision-filenames.d.ts.map +1 -0
  214. package/dist/commands/revision-range.d.ts +67 -0
  215. package/dist/commands/revision-range.d.ts.map +1 -0
  216. package/dist/commands/revision-resolver.d.ts +321 -0
  217. package/dist/commands/revision-resolver.d.ts.map +1 -0
  218. package/dist/commands/rm-command.d.ts +69 -7
  219. package/dist/commands/rm-command.d.ts.map +1 -1
  220. package/dist/commands/sequencer-pick.d.ts +191 -0
  221. package/dist/commands/sequencer-pick.d.ts.map +1 -0
  222. package/dist/commands/sequencer-support.d.ts +125 -0
  223. package/dist/commands/sequencer-support.d.ts.map +1 -0
  224. package/dist/commands/serve-repository.d.ts +52 -0
  225. package/dist/commands/serve-repository.d.ts.map +1 -0
  226. package/dist/commands/sparse-checkout-command.d.ts +190 -0
  227. package/dist/commands/sparse-checkout-command.d.ts.map +1 -0
  228. package/dist/commands/sparse-checkout-support.d.ts +268 -0
  229. package/dist/commands/sparse-checkout-support.d.ts.map +1 -0
  230. package/dist/commands/stash-apply-command.d.ts +69 -13
  231. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  232. package/dist/commands/stash-create-command.d.ts +214 -26
  233. package/dist/commands/stash-create-command.d.ts.map +1 -1
  234. package/dist/commands/stash-drop-command.d.ts +10 -2
  235. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  236. package/dist/commands/stash-list-command.d.ts +2 -4
  237. package/dist/commands/stash-list-command.d.ts.map +1 -1
  238. package/dist/commands/stash-working-tree.d.ts +95 -0
  239. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  240. package/dist/commands/status-command.d.ts +320 -28
  241. package/dist/commands/status-command.d.ts.map +1 -1
  242. package/dist/commands/status-format.d.ts +155 -0
  243. package/dist/commands/status-format.d.ts.map +1 -0
  244. package/dist/commands/status-header.d.ts +64 -0
  245. package/dist/commands/status-header.d.ts.map +1 -0
  246. package/dist/commands/strerror.d.ts +7 -0
  247. package/dist/commands/strerror.d.ts.map +1 -0
  248. package/dist/commands/submodule-config.d.ts +38 -0
  249. package/dist/commands/submodule-config.d.ts.map +1 -0
  250. package/dist/commands/submodule-summary-command.d.ts +80 -0
  251. package/dist/commands/submodule-summary-command.d.ts.map +1 -0
  252. package/dist/commands/submodule-summary.d.ts +150 -0
  253. package/dist/commands/submodule-summary.d.ts.map +1 -0
  254. package/dist/commands/switch-command.d.ts +132 -0
  255. package/dist/commands/switch-command.d.ts.map +1 -0
  256. package/dist/commands/tag-command.d.ts +23 -2
  257. package/dist/commands/tag-command.d.ts.map +1 -1
  258. package/dist/commands/tracking-info.d.ts +64 -0
  259. package/dist/commands/tracking-info.d.ts.map +1 -0
  260. package/dist/commands/trailers.d.ts +73 -0
  261. package/dist/commands/trailers.d.ts.map +1 -0
  262. package/dist/commands/tree-restore.d.ts +137 -6
  263. package/dist/commands/tree-restore.d.ts.map +1 -1
  264. package/dist/commands/untracked-cache-support.d.ts +53 -0
  265. package/dist/commands/untracked-cache-support.d.ts.map +1 -0
  266. package/dist/commands/worktree-add-command.d.ts +108 -0
  267. package/dist/commands/worktree-add-command.d.ts.map +1 -0
  268. package/dist/commands/worktree-list-command.d.ts +69 -0
  269. package/dist/commands/worktree-list-command.d.ts.map +1 -0
  270. package/dist/commands/worktree-lock-command.d.ts +44 -0
  271. package/dist/commands/worktree-lock-command.d.ts.map +1 -0
  272. package/dist/commands/worktree-overwrite-checks.d.ts +204 -0
  273. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  274. package/dist/commands/worktree-prune-command.d.ts +48 -0
  275. package/dist/commands/worktree-prune-command.d.ts.map +1 -0
  276. package/dist/commands/worktree-remove-command.d.ts +59 -0
  277. package/dist/commands/worktree-remove-command.d.ts.map +1 -0
  278. package/dist/commands/worktree-repair-command.d.ts +35 -0
  279. package/dist/commands/worktree-repair-command.d.ts.map +1 -0
  280. package/dist/commands/worktree-support.d.ts +64 -0
  281. package/dist/commands/worktree-support.d.ts.map +1 -0
  282. package/dist/commands-DnmlfwGV.js +61620 -0
  283. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  284. package/dist/core-commands/index.d.ts +0 -3
  285. package/dist/core-commands/index.d.ts.map +1 -1
  286. package/dist/errors/add-errors.d.ts +55 -0
  287. package/dist/errors/add-errors.d.ts.map +1 -1
  288. package/dist/errors/checkout-errors.d.ts +29 -0
  289. package/dist/errors/checkout-errors.d.ts.map +1 -1
  290. package/dist/errors/command-errors.d.ts +77 -0
  291. package/dist/errors/command-errors.d.ts.map +1 -1
  292. package/dist/errors/commit-errors.d.ts +9 -0
  293. package/dist/errors/commit-errors.d.ts.map +1 -1
  294. package/dist/errors/git-api-error.d.ts +59 -2
  295. package/dist/errors/git-api-error.d.ts.map +1 -1
  296. package/dist/errors/index.d.ts +1 -0
  297. package/dist/errors/index.d.ts.map +1 -1
  298. package/dist/errors/index.js +371 -19
  299. package/dist/errors/rebase-errors.d.ts +9 -0
  300. package/dist/errors/rebase-errors.d.ts.map +1 -1
  301. package/dist/errors/ref-errors.d.ts +32 -0
  302. package/dist/errors/ref-errors.d.ts.map +1 -1
  303. package/dist/errors/transport-errors.d.ts +12 -2
  304. package/dist/errors/transport-errors.d.ts.map +1 -1
  305. package/dist/errors/worktree-errors.d.ts +35 -0
  306. package/dist/errors/worktree-errors.d.ts.map +1 -0
  307. package/dist/git-command-DxvwPrPB.js +7612 -0
  308. package/dist/git-command.d.ts +422 -32
  309. package/dist/git-command.d.ts.map +1 -1
  310. package/dist/git.d.ts +326 -5
  311. package/dist/git.d.ts.map +1 -1
  312. package/dist/index.d.ts +1 -1
  313. package/dist/index.d.ts.map +1 -1
  314. package/dist/index.js +5 -5
  315. package/dist/remote-config/index.d.ts +1 -0
  316. package/dist/remote-config/index.d.ts.map +1 -1
  317. package/dist/remote-config/remote-config-store.d.ts +123 -3
  318. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  319. package/dist/remote-config/remote-refs.d.ts +41 -0
  320. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  321. package/dist/rename/detect-renames.d.ts +148 -0
  322. package/dist/rename/detect-renames.d.ts.map +1 -0
  323. package/dist/rename/git-similarity.d.ts +44 -0
  324. package/dist/rename/git-similarity.d.ts.map +1 -0
  325. package/dist/rename/index.d.ts +2 -0
  326. package/dist/rename/index.d.ts.map +1 -1
  327. package/dist/results/binary-patch.d.ts +11 -0
  328. package/dist/results/binary-patch.d.ts.map +1 -0
  329. package/dist/results/blame-format.d.ts +55 -0
  330. package/dist/results/blame-format.d.ts.map +1 -0
  331. package/dist/results/cherry-pick-result.d.ts +10 -0
  332. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  333. package/dist/results/clone-result.d.ts +16 -0
  334. package/dist/results/clone-result.d.ts.map +1 -1
  335. package/dist/results/combined-diff.d.ts +77 -0
  336. package/dist/results/combined-diff.d.ts.map +1 -0
  337. package/dist/results/diff-entry.d.ts +32 -0
  338. package/dist/results/diff-entry.d.ts.map +1 -1
  339. package/dist/results/diff-formatter.d.ts +34 -60
  340. package/dist/results/diff-formatter.d.ts.map +1 -1
  341. package/dist/results/diff-order.d.ts +25 -0
  342. package/dist/results/diff-order.d.ts.map +1 -0
  343. package/dist/results/diff-output.d.ts +249 -0
  344. package/dist/results/diff-output.d.ts.map +1 -0
  345. package/dist/results/fetch-result.d.ts +24 -1
  346. package/dist/results/fetch-result.d.ts.map +1 -1
  347. package/dist/results/index.d.ts +5 -0
  348. package/dist/results/index.d.ts.map +1 -1
  349. package/dist/results/index.js +2 -252
  350. package/dist/results/merge-result.d.ts +15 -1
  351. package/dist/results/merge-result.d.ts.map +1 -1
  352. package/dist/results/pull-result.d.ts +12 -3
  353. package/dist/results/pull-result.d.ts.map +1 -1
  354. package/dist/results/push-result.d.ts +42 -0
  355. package/dist/results/push-result.d.ts.map +1 -1
  356. package/dist/results/quote-path.d.ts +27 -0
  357. package/dist/results/quote-path.d.ts.map +1 -0
  358. package/dist/results/rebase-result.d.ts +28 -1
  359. package/dist/results/rebase-result.d.ts.map +1 -1
  360. package/dist/results/revert-result.d.ts +10 -0
  361. package/dist/results/revert-result.d.ts.map +1 -1
  362. package/dist/results/stash-result.d.ts +5 -0
  363. package/dist/results/stash-result.d.ts.map +1 -1
  364. package/dist/results/status-result.d.ts +143 -18
  365. package/dist/results/status-result.d.ts.map +1 -1
  366. package/dist/results-BZGa2Z3I.js +2934 -0
  367. package/dist/transport-command.d.ts +56 -1
  368. package/dist/transport-command.d.ts.map +1 -1
  369. package/package.json +15 -10
  370. package/src/commands/add-command.ts +1291 -224
  371. package/src/commands/add-patch/add-interactive.ts +941 -0
  372. package/src/commands/add-patch/add-patch.ts +1169 -0
  373. package/src/commands/add-patch/index.ts +5 -0
  374. package/src/commands/add-patch/patch-backend.ts +239 -0
  375. package/src/commands/add-patch/patch-modes.ts +249 -0
  376. package/src/commands/add-patch/patch-session.ts +159 -0
  377. package/src/commands/am/am-command.ts +1111 -0
  378. package/src/commands/am/index.ts +2 -0
  379. package/src/commands/am/mailinfo.ts +1015 -0
  380. package/src/commands/am/patch-format.ts +121 -0
  381. package/src/commands/apply/apply-command.ts +832 -0
  382. package/src/commands/apply/apply-engine.ts +1603 -0
  383. package/src/commands/apply/apply-parse.ts +1209 -0
  384. package/src/commands/apply/apply-types.ts +112 -0
  385. package/src/commands/apply/index.ts +5 -0
  386. package/src/commands/apply/latin1.ts +171 -0
  387. package/src/commands/apply/whitespace.ts +260 -0
  388. package/src/commands/attributes-source.ts +96 -0
  389. package/src/commands/backfill-command.ts +694 -0
  390. package/src/commands/bisect/bisect-checkout.ts +217 -0
  391. package/src/commands/bisect/bisect-command.ts +788 -0
  392. package/src/commands/bisect/bisect-engine.ts +1079 -0
  393. package/src/commands/bisect/bisect-graph.ts +595 -0
  394. package/src/commands/bisect/bisect-quote.ts +92 -0
  395. package/src/commands/bisect/index.ts +4 -0
  396. package/src/commands/blame-command.ts +711 -986
  397. package/src/commands/branch-command.ts +354 -32
  398. package/src/commands/branch-tracking.ts +331 -0
  399. package/src/commands/checkout-command.ts +1426 -297
  400. package/src/commands/checkout-paths.ts +784 -0
  401. package/src/commands/cherry-pick-command.ts +156 -396
  402. package/src/commands/clean-command.ts +532 -85
  403. package/src/commands/clone-command.ts +826 -55
  404. package/src/commands/commit-command.ts +1781 -166
  405. package/src/commands/core-config.ts +196 -0
  406. package/src/commands/date-format.ts +668 -0
  407. package/src/commands/describe-command.ts +2 -0
  408. package/src/commands/diff-command.ts +1898 -110
  409. package/src/commands/diff-textconv.ts +50 -0
  410. package/src/commands/fetch-command.ts +1038 -79
  411. package/src/commands/format-patch-command.ts +969 -0
  412. package/src/commands/fsck/fetch-fsck.ts +229 -0
  413. package/src/commands/fsck/fsck-command.ts +3347 -0
  414. package/src/commands/fsck/fsck-loose.ts +287 -0
  415. package/src/commands/fsck/fsck-msg-ids.ts +176 -0
  416. package/src/commands/fsck/fsck-object-checks.ts +1044 -0
  417. package/src/commands/fsck/fsck-object-table.ts +363 -0
  418. package/src/commands/fsck/fsck-pack.ts +604 -0
  419. package/src/commands/fsck/index.ts +5 -0
  420. package/src/commands/fsck/verify-pack-command.ts +249 -0
  421. package/src/commands/gc-command.ts +147 -1
  422. package/src/commands/git-date.ts +895 -0
  423. package/src/commands/git-describe.ts +316 -0
  424. package/src/commands/git-hooks.ts +1472 -0
  425. package/src/commands/git-ident.ts +344 -0
  426. package/src/commands/hook-command.ts +247 -0
  427. package/src/commands/index-adder.ts +706 -0
  428. package/src/commands/index-host.ts +291 -0
  429. package/src/commands/index.ts +83 -0
  430. package/src/commands/init-command.ts +60 -11
  431. package/src/commands/local-clone.ts +183 -0
  432. package/src/commands/local-transport.ts +762 -0
  433. package/src/commands/log-command.ts +1915 -170
  434. package/src/commands/log-graph.ts +671 -0
  435. package/src/commands/log-output.ts +1359 -0
  436. package/src/commands/ls-remote-command.ts +101 -58
  437. package/src/commands/mailmap.ts +129 -0
  438. package/src/commands/merge-bases.ts +296 -0
  439. package/src/commands/merge-command.ts +1386 -491
  440. package/src/commands/merge-config.ts +25 -0
  441. package/src/commands/merge-drivers.ts +306 -0
  442. package/src/commands/merge-support.ts +1198 -0
  443. package/src/commands/message-cleanup.ts +275 -0
  444. package/src/commands/mv-command.ts +976 -0
  445. package/src/commands/notes-command.ts +890 -0
  446. package/src/commands/notes-commands.ts +87 -0
  447. package/src/commands/notes-merge-command.ts +768 -0
  448. package/src/commands/notes-support.ts +402 -0
  449. package/src/commands/notes-tree.ts +602 -0
  450. package/src/commands/object-id-input.ts +27 -0
  451. package/src/commands/octopus-merge.ts +377 -0
  452. package/src/commands/ort-merge.ts +1660 -0
  453. package/src/commands/ort-recursive.ts +160 -0
  454. package/src/commands/pack-refs-command.ts +39 -22
  455. package/src/commands/patch-id.ts +196 -0
  456. package/src/commands/pathspec-attributes.ts +162 -0
  457. package/src/commands/pathspec.ts +1199 -0
  458. package/src/commands/post-index-change.ts +62 -0
  459. package/src/commands/pretty-format.ts +1431 -0
  460. package/src/commands/promisor-remote.ts +298 -0
  461. package/src/commands/pull-command.ts +207 -22
  462. package/src/commands/push-command.ts +236 -23
  463. package/src/commands/read-tree-command.ts +857 -0
  464. package/src/commands/rebase-command.ts +3808 -371
  465. package/src/commands/rebase-todo.ts +584 -0
  466. package/src/commands/ref-decoration-filter.ts +118 -0
  467. package/src/commands/reflog-messages.ts +177 -0
  468. package/src/commands/remote-command.ts +500 -19
  469. package/src/commands/remote-transport.ts +383 -0
  470. package/src/commands/reset-command.ts +828 -91
  471. package/src/commands/restore-command.ts +350 -0
  472. package/src/commands/rev-list-command.ts +167 -0
  473. package/src/commands/rev-parse-command.ts +277 -0
  474. package/src/commands/revert-command.ts +152 -399
  475. package/src/commands/revision-filenames.ts +254 -0
  476. package/src/commands/revision-range.ts +222 -0
  477. package/src/commands/revision-resolver.ts +1379 -0
  478. package/src/commands/rm-command.ts +613 -67
  479. package/src/commands/sequencer-pick.ts +869 -0
  480. package/src/commands/sequencer-support.ts +869 -0
  481. package/src/commands/serve-repository.ts +125 -0
  482. package/src/commands/sparse-checkout-command.ts +1389 -0
  483. package/src/commands/sparse-checkout-support.ts +793 -0
  484. package/src/commands/stash-apply-command.ts +692 -124
  485. package/src/commands/stash-create-command.ts +752 -89
  486. package/src/commands/stash-drop-command.ts +67 -6
  487. package/src/commands/stash-list-command.ts +10 -4
  488. package/src/commands/stash-working-tree.ts +387 -0
  489. package/src/commands/status-command.ts +1426 -97
  490. package/src/commands/status-format.ts +775 -0
  491. package/src/commands/status-header.ts +330 -0
  492. package/src/commands/strerror.ts +29 -0
  493. package/src/commands/submodule-config.ts +94 -0
  494. package/src/commands/submodule-summary-command.ts +334 -0
  495. package/src/commands/submodule-summary.ts +446 -0
  496. package/src/commands/switch-command.ts +402 -0
  497. package/src/commands/tag-command.ts +129 -41
  498. package/src/commands/tracking-info.ts +201 -0
  499. package/src/commands/trailers.ts +417 -0
  500. package/src/commands/tree-restore.ts +344 -15
  501. package/src/commands/untracked-cache-support.ts +194 -0
  502. package/src/commands/worktree-add-command.ts +458 -0
  503. package/src/commands/worktree-list-command.ts +208 -0
  504. package/src/commands/worktree-lock-command.ts +96 -0
  505. package/src/commands/worktree-overwrite-checks.ts +641 -0
  506. package/src/commands/worktree-prune-command.ts +99 -0
  507. package/src/commands/worktree-remove-command.ts +186 -0
  508. package/src/commands/worktree-repair-command.ts +59 -0
  509. package/src/commands/worktree-support.ts +214 -0
  510. package/src/core-commands/add.command.impl.ts +9 -5
  511. package/src/core-commands/index.ts +0 -8
  512. package/src/errors/add-errors.ts +45 -0
  513. package/src/errors/checkout-errors.ts +46 -2
  514. package/src/errors/command-errors.ts +101 -1
  515. package/src/errors/commit-errors.ts +18 -2
  516. package/src/errors/git-api-error.ts +82 -2
  517. package/src/errors/index.ts +1 -0
  518. package/src/errors/merge-errors.ts +2 -2
  519. package/src/errors/rebase-errors.ts +12 -0
  520. package/src/errors/ref-errors.ts +56 -2
  521. package/src/errors/remote-errors.ts +2 -2
  522. package/src/errors/stash-errors.ts +1 -1
  523. package/src/errors/transport-errors.ts +20 -4
  524. package/src/errors/worktree-errors.ts +49 -0
  525. package/src/git-command.ts +1218 -118
  526. package/src/git.ts +552 -11
  527. package/src/index.ts +1 -1
  528. package/src/remote-config/index.ts +1 -0
  529. package/src/remote-config/remote-config-store.ts +326 -16
  530. package/src/remote-config/remote-refs.ts +119 -0
  531. package/src/rename/detect-renames.ts +711 -0
  532. package/src/rename/git-similarity.ts +116 -0
  533. package/src/rename/index.ts +2 -0
  534. package/src/results/binary-patch.ts +401 -0
  535. package/src/results/blame-format.ts +239 -0
  536. package/src/results/cherry-pick-result.ts +10 -0
  537. package/src/results/clone-result.ts +18 -0
  538. package/src/results/combined-diff.ts +585 -0
  539. package/src/results/diff-entry.ts +35 -0
  540. package/src/results/diff-formatter.ts +152 -288
  541. package/src/results/diff-order.ts +64 -0
  542. package/src/results/diff-output.ts +1051 -0
  543. package/src/results/fetch-result.ts +24 -1
  544. package/src/results/index.ts +5 -0
  545. package/src/results/merge-result.ts +15 -1
  546. package/src/results/pull-result.ts +12 -3
  547. package/src/results/push-result.ts +43 -0
  548. package/src/results/quote-path.ts +103 -0
  549. package/src/results/rebase-result.ts +37 -0
  550. package/src/results/revert-result.ts +10 -0
  551. package/src/results/stash-result.ts +6 -0
  552. package/src/results/status-result.ts +288 -27
  553. package/src/transport-command.ts +139 -2
  554. package/dist/commands-BpeXZTC3.js +0 -10278
  555. package/dist/core-commands/checkout.command.d.ts +0 -103
  556. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  557. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  558. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  559. package/dist/status-result-BapZoQaR.js +0 -411
  560. package/src/core-commands/checkout.command.impl.ts +0 -564
  561. package/src/core-commands/checkout.command.ts +0 -125
@@ -1,57 +1,417 @@
1
- import type { FileModeValue, ObjectId, TreeEntry } from "@statewalker/vcs-core";
1
+ import {
2
+ EMPTY_TREE_ID,
3
+ type FileModeValue,
4
+ type ObjectId,
5
+ type TreeEntry,
6
+ TreeEntryCursor,
7
+ } from "@statewalker/vcs-core";
8
+ import { ByteSink, parseGitBool, type XdiffAlgorithm } from "@statewalker/vcs-utils";
9
+ import { compareGitPaths, decodeGitPath } from "@statewalker/vcs-utils/encoding";
10
+ import {
11
+ type AttributesIndex,
12
+ collectChunks,
13
+ compareWithWorktree,
14
+ expandUserPath,
15
+ type GitHostEnvironment,
16
+ readCleanContent,
17
+ type Staging,
18
+ smudgeContent,
19
+ type Worktree,
20
+ type WorktreeEntry,
21
+ withWorktreeEntries,
22
+ } from "@statewalker/vcs-working-tree";
2
23
 
24
+ import { NoHeadError, RefNotFoundError } from "../errors/index.js";
3
25
  import { GitCommand } from "../git-command.js";
26
+ import { RemoteConfigStore } from "../remote-config/index.js";
27
+ import {
28
+ DEFAULT_RENAME_LIMIT,
29
+ detectRenames,
30
+ findFollowSource,
31
+ scorePercent,
32
+ } from "../rename/index.js";
33
+ import { writeCombinedDiff } from "../results/combined-diff.js";
34
+ import { ChangeType, type DiffEntry } from "../results/diff-entry.js";
35
+ import { diffEntryToPair } from "../results/diff-formatter.js";
36
+ import { orderByPatterns, parseOrderFile } from "../results/diff-order.js";
4
37
  import {
5
- ChangeType,
6
- createAddEntry,
7
- createDeleteEntry,
8
- createModifyEntry,
9
- type DiffEntry,
10
- } from "../results/diff-entry.js";
38
+ blobSide,
39
+ computeDiffstat,
40
+ contentSide,
41
+ type DiffDriver,
42
+ type DiffFilePair,
43
+ type DiffOutputOptions,
44
+ type DiffstatFile,
45
+ type DiffstatOptions,
46
+ diffDriverOf,
47
+ formatNameOnly,
48
+ formatNameStatus,
49
+ formatNumstat,
50
+ formatShortstat,
51
+ formatStat,
52
+ formatSummary,
53
+ writePairPatch,
54
+ } from "../results/diff-output.js";
55
+ import { quotePath } from "../results/quote-path.js";
56
+ import { bareAttributesResolver } from "./attributes-source.js";
57
+ import { worktreeModeTrust } from "./core-config.js";
58
+ import { textconvRunnerOf } from "./diff-textconv.js";
59
+ import { matchPathspec, type PathspecItem, parsePathspecItem } from "./pathspec.js";
60
+ import { PathspecAttributes } from "./pathspec-attributes.js";
61
+ import { readSubmoduleDirt, type SubmoduleDirt } from "./status-command.js";
62
+ import {
63
+ isSubmoduleIgnoreMode,
64
+ parseGitmodules,
65
+ type SubmoduleIgnoreMode,
66
+ } from "./submodule-config.js";
67
+ import {
68
+ openSubmoduleRepository,
69
+ readDiffSubmoduleConfig,
70
+ type SubmoduleDiffFormat,
71
+ showSubmoduleDiffSummary,
72
+ submoduleHeader,
73
+ } from "./submodule-summary.js";
74
+
75
+ /** An index without in-tree attributes files: the attribute stack of a diff of two trees. */
76
+ const WITHOUT_INDEX_ATTRIBUTES: { direction: "checkin"; index: AttributesIndex } = {
77
+ direction: "checkin",
78
+ index: { attributesBlob: () => undefined },
79
+ };
80
+
81
+ /** The output formats of {@link DiffCommand.callText} */
82
+ /**
83
+ * The outputs whose diff git prefetches (diffcore_std's `output_formats_to_prefetch`: the
84
+ * diffstat kinds, the patch, `--dirstat`)
85
+ */
86
+ const PREFETCH_FORMATS = new Set<string>(["patch", "stat", "numstat", "shortstat"]);
87
+
88
+ /**
89
+ * The repository blobs of a diff's pairs (git's `diff_add_if_missing`: each side whose id is
90
+ * known, no submodule), in queue order, old side first.
91
+ */
92
+ function prefetchIds(entries: readonly DiffEntry[]): ObjectId[] {
93
+ const out: ObjectId[] = [];
94
+ const add = (id: ObjectId | undefined, mode: number | undefined) => {
95
+ if (id && id !== NULL_ID && mode !== GITLINK && mode !== undefined && mode !== 0) out.push(id);
96
+ };
97
+ for (const e of entries) {
98
+ if (e.unmerged) continue;
99
+ if (!e.readOld) add(e.oldId, e.oldMode);
100
+ if (!e.readNew && !e.newIdUnknown) add(e.newId, e.newMode);
101
+ }
102
+ return out;
103
+ }
104
+
105
+ export type DiffOutputFormat =
106
+ | "patch"
107
+ | "stat"
108
+ | "numstat"
109
+ | "shortstat"
110
+ | "summary"
111
+ | "name-only"
112
+ | "name-status";
113
+
114
+ /** Options of the text output that `git diff` takes on its command line */
115
+ export interface DiffTextOptions
116
+ extends Omit<DiffOutputOptions, "driver" | "algorithm" | "indentHeuristic"> {
117
+ /** `--diff-algorithm` (default `diff.algorithm`, else myers) */
118
+ algorithm?: XdiffAlgorithm;
119
+ /** `--indent-heuristic` / `--no-indent-heuristic` (default `diff.indentHeuristic`, true) */
120
+ indentHeuristic?: boolean;
121
+ /**
122
+ * `--abbrev=<n>`: the `index` lines' ids at least n digits, clamped as git clamps it (below
123
+ * 4, 0 too, is 4; above 40 is 40); the combined diffs of conflicted paths ignore it, as
124
+ * git's do
125
+ */
126
+ abbrev?: number;
127
+ /** `--stat=...` widths (default width 80, as git without a terminal) */
128
+ stat?: DiffstatOptions;
129
+ /**
130
+ * Score renames counting a last line without a newline, as git 2.50 and later (default
131
+ * true); false scores them as older git
132
+ */
133
+ renameCountLastSpan?: boolean;
134
+ /**
135
+ * With whitespace-ignoring options (`-w`, `-b`, `--ignore-space-at-eol`,
136
+ * `--ignore-cr-at-eol`), `--name-only` and `--name-status` list only the files whose patch
137
+ * shows a change, as git 2.5x does (default true; false lists every changed file, as
138
+ * older git)
139
+ */
140
+ namesFromContents?: boolean;
141
+ /**
142
+ * `--no-prefix`: no `a/` and `b/` prefixes (default `diff.noprefix`); `srcPrefix` and
143
+ * `dstPrefix` still apply on top, as if given after it
144
+ */
145
+ noPrefix?: boolean;
146
+ /**
147
+ * `--default-prefix`: `a/` and `b/`, whatever `diff.noprefix`, `diff.mnemonicPrefix`,
148
+ * `diff.srcPrefix` and `diff.dstPrefix` say; it wins over `noPrefix`, and `srcPrefix` /
149
+ * `dstPrefix` still apply on top
150
+ */
151
+ defaultPrefix?: boolean;
152
+ /**
153
+ * `diff.noprefix` is not read (`git format-patch` ignores it, honouring only
154
+ * `format.noprefix`, which it passes as `noPrefix`); the other prefix settings still apply
155
+ */
156
+ ignoreConfigNoPrefix?: boolean;
157
+ /**
158
+ * `-O<orderfile>`: show the files in the order of the file's glob patterns (default
159
+ * `diff.orderFile`); a relative path is read from the worktree's root, through the host
160
+ * environment when it leaves the worktree (`../x`)
161
+ */
162
+ orderFile?: string;
163
+ /**
164
+ * `--submodule=<format>`: a submodule's change as a `Subproject commit` patch (`short`),
165
+ * the commits between its two sides (`log`), or the diff of its content (`diff`); default
166
+ * `diff.submodule`, else `short`
167
+ */
168
+ submoduleFormat?: SubmoduleDiffFormat;
169
+ /**
170
+ * Whether the diff configuration of the porcelain commands is read (`git_diff_ui_config`:
171
+ * `diff.submodule`, its warnings and failures); default true. Plumbing (`diff-tree`) and
172
+ * `format-patch` (whose `git_format_config` skips `diff.submodule`) read none.
173
+ */
174
+ uiConfig?: boolean;
175
+ /**
176
+ * `--textconv` / `--no-textconv`: run `diff.<driver>.textconv` on both sides of a patch
177
+ * (default true, as `git diff`); it takes a runner registered with
178
+ * `installTextconvRunner`, without one no textconv applies
179
+ */
180
+ textconv?: boolean;
181
+ /**
182
+ * `-R`: the two sides swapped (an addition shows as a deletion, the new side first), their
183
+ * prefixes with them (`diff --git b/f a/f`). Combined diffs of conflicted paths are not swapped.
184
+ */
185
+ reverse?: boolean;
186
+ }
187
+
188
+ /** An entry with its two sides swapped (`diff -R`). */
189
+ function reverseEntry(entry: DiffEntry): DiffEntry {
190
+ if (entry.unmerged) return entry;
191
+ const changeType =
192
+ entry.changeType === ChangeType.ADD
193
+ ? ChangeType.DELETE
194
+ : entry.changeType === ChangeType.DELETE
195
+ ? ChangeType.ADD
196
+ : entry.changeType;
197
+ const out: DiffEntry = { changeType };
198
+ if (entry.newPath !== undefined) out.oldPath = entry.newPath;
199
+ if (entry.oldPath !== undefined) out.newPath = entry.oldPath;
200
+ if (entry.newId !== undefined) out.oldId = entry.newId;
201
+ if (entry.oldId !== undefined) out.newId = entry.oldId;
202
+ if (entry.newMode !== undefined) out.oldMode = entry.newMode;
203
+ if (entry.oldMode !== undefined) out.newMode = entry.oldMode;
204
+ if (entry.readNew) out.readOld = entry.readNew;
205
+ if (entry.readOld) out.readNew = entry.readOld;
206
+ if (entry.score !== undefined) out.score = entry.score;
207
+ return out;
208
+ }
209
+
210
+ /** What a diff compares, for `diff.mnemonicPrefix` */
211
+ type DiffSides = "trees" | "cached" | "commit-worktree" | "index-worktree";
212
+
213
+ /** git's mnemonic prefixes (`diff_set_mnemonic_prefix`) of each comparison */
214
+ const MNEMONIC_PREFIXES: Record<DiffSides, [string, string] | undefined> = {
215
+ // builtin_diff_tree sets none: builtin_diff's own fallback, a/ and b/
216
+ trees: undefined,
217
+ // run_diff_index
218
+ cached: ["c/", "i/"],
219
+ "commit-worktree": ["c/", "w/"],
220
+ // run_diff_files
221
+ "index-worktree": ["i/", "w/"],
222
+ };
223
+
224
+ /** One side of a path in a tree, the index or the worktree */
225
+ interface Side {
226
+ mode: number;
227
+ id: ObjectId;
228
+ read?: () => Promise<Uint8Array>;
229
+ /** A submodule with changes of its own in the worktree ("Subproject commit <id>-dirty") */
230
+ dirty?: boolean;
231
+ /** Which changes of its own such a submodule holds (for `--submodule=log`) */
232
+ dirt?: SubmoduleDirt;
233
+ /**
234
+ * A worktree submodule at another commit than its index entry: git's diff-index (and
235
+ * diff-files) gives such a side the null id, filled from the worktree only when a patch is
236
+ * printed (`get_stat_data`, `diff_fill_oid_info`). The pair is reported whatever the other
237
+ * side holds (`show_modified`), and no exact rename pairs with it.
238
+ */
239
+ unknownId?: boolean;
240
+ }
241
+
242
+ /** An index entry, of any stage */
243
+ type StageEntry = Parameters<typeof compareWithWorktree>[1];
244
+
245
+ /** The worktree side of an index entry, as diff-files sees it; undefined when deleted */
246
+ type WorktreeCompare = (entry: StageEntry) => Promise<Side | undefined>;
247
+
248
+ /** A conflicted path `git diff` shows as a combined diff: stages 2 and 3 against the file */
249
+ interface CombinedEntry {
250
+ path: string;
251
+ ours: StageEntry;
252
+ theirs: StageEntry;
253
+ }
254
+
255
+ /** `diff.ignoreSubmodules` (git's `--ignore-submodules`); undefined when unset or invalid */
256
+ function submoduleIgnoreValue(
257
+ value: string | undefined,
258
+ ): "none" | "untracked" | "dirty" | "all" | undefined {
259
+ const v = value?.trim().toLowerCase();
260
+ return v === "none" || v === "untracked" || v === "dirty" || v === "all" ? v : undefined;
261
+ }
262
+
263
+ const S_IFMT = 0o170000;
264
+ const GITLINK = 0o160000;
265
+ const NULL_ID = "0".repeat(40);
266
+ const encoder = new TextEncoder();
267
+
268
+ /** The chunks as one array. */
269
+ function concatChunks(chunks: Uint8Array[]): Uint8Array {
270
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
271
+ let at = 0;
272
+ for (const c of chunks) {
273
+ out.set(c, at);
274
+ at += c.length;
275
+ }
276
+ return out;
277
+ }
278
+
279
+ /** git's path order: bytes, as `strcmp` */
280
+ function compareBytes(a: string, b: string): number {
281
+ return compareGitPaths(a, b);
282
+ }
283
+
284
+ /** A git boolean (`git_config_bool`), undefined when unset or not one. */
285
+ const boolValue = (v: string | undefined): boolean | undefined => parseGitBool(v);
286
+
287
+ function intValue(value: string | undefined): number | undefined {
288
+ const m = value?.trim().match(/^(-?\d+)([kmg]?)$/i);
289
+ if (!m) return undefined;
290
+ const unit = { "": 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3 }[m[2].toLowerCase()] ?? 1;
291
+ return Number(m[1]) * unit;
292
+ }
11
293
 
12
294
  /**
13
- * Show changes between commits, trees, and staging.
295
+ * `git diff --abbrev=<n>` as revision.c's handle_revision_opt takes it (before diff.c sees
296
+ * it; setup_revisions copies it to the diff options): below 4 (0 too) is 4, above 40 is 40
297
+ */
298
+ function abbrevOption(value: number | undefined): number | undefined {
299
+ if (value === undefined || Number.isNaN(value)) return undefined;
300
+ return Math.min(40, Math.max(4, Math.trunc(value)));
301
+ }
302
+
303
+ /** `diff.renames` as git_config_rename reads it: `copies`/`copy` detect copies too. */
304
+ function renamesValue(value: string | undefined): boolean | "copies" | undefined {
305
+ if (value === undefined) return undefined;
306
+ const v = value.trim().toLowerCase();
307
+ if (v === "copies" || v === "copy") return "copies";
308
+ return boolValue(v);
309
+ }
310
+
311
+ const ALGORITHMS: readonly string[] = ["myers", "minimal", "patience", "histogram"];
312
+ const algorithmValue = (v: string | undefined): XdiffAlgorithm | undefined => {
313
+ const s = v?.trim().toLowerCase();
314
+ if (s === "default") return "myers";
315
+ return s && ALGORITHMS.includes(s) ? (s as XdiffAlgorithm) : undefined;
316
+ };
317
+
318
+ /**
319
+ * Show changes between commits, trees, the index and the worktree.
320
+ *
321
+ * Equivalent to `git diff`:
322
+ * - `setOldTree(a).setNewTree(b)`: `git diff a b`
323
+ * - `setCached(true)` (with `setOldTree(a)`): `git diff --cached [a]` (HEAD by default)
324
+ * - nothing set: `git diff`, the index against the worktree
325
+ * - `setOldTree(a)` alone: `git diff a`, a commit against the worktree
326
+ *
327
+ * Without a worktree, the last two compare with HEAD's tree.
14
328
  *
15
- * Equivalent to `git diff`.
329
+ * `call()` gives the changed paths; `callText()` prints them as git does (patch, `--stat`,
330
+ * `--numstat`, `--shortstat`, `--name-only`, `--name-status`), byte for byte, reading
331
+ * `diff.algorithm`, `diff.indentHeuristic`, `diff.context`, `diff.interHunkContext`,
332
+ * `diff.renames`, `diff.renameLimit`, `diff.statNameWidth`, `diff.statGraphWidth`,
333
+ * `core.quotePath`, `core.bigFileThreshold`, `core.abbrev`, `diff.ignoreSubmodules`,
334
+ * `diff.noprefix`, `diff.mnemonicPrefix`, `diff.srcPrefix`, `diff.dstPrefix`,
335
+ * `diff.orderFile` and the `diff` attribute's drivers (`diff.<driver>.xfuncname`,
336
+ * `.funcname`, `.binary`, `.algorithm`, `.textconv`, `.cachetextconv`, builtin drivers).
16
337
  *
17
- * Based on JGit's DiffCommand.
338
+ * The prefixes follow git's porcelain: `diff.mnemonicPrefix` gives `i/` and `w/` for the
339
+ * index against the worktree, `c/` and `w/` for a commit against it, `c/` and `i/` for
340
+ * `--cached`, and `a/` and `b/` between two trees. Textconv runs through the runner the host
341
+ * registers with `installTextconvRunner` (running a command is not portable); without one no
342
+ * textconv applies, as `git diff --no-textconv`; it reads a blob as checkout writes it
343
+ * (smudged) and a worktree file as it is, as git's `prepare_temp_file`. A relative order
344
+ * file is read from the worktree's root (one outside it, `../x`, through the host
345
+ * environment).
346
+ *
347
+ * As git: a conflicted path is, in `git diff`, the combined diff (`diff --cc`) of stages 2
348
+ * and 3 against the worktree file, printed before the other files (in the other formats, an
349
+ * unmerged entry and stage 2 against the worktree), and in `git diff A` the worktree file;
350
+ * a submodule with changes of its own is `Subproject commit <id>-dirty`; `index` lines
351
+ * abbreviate ids as git does; a revision that names nothing throws `RefNotFoundError`.
18
352
  *
19
353
  * @example
20
354
  * ```typescript
21
355
  * // Compare two commits
22
- * const entries = await git.diff()
23
- * .setOldTree(commitA)
24
- * .setNewTree(commitB)
25
- * .call();
356
+ * const entries = await git.diff().setOldTree(commitA).setNewTree(commitB).call();
26
357
  *
27
- * // Compare HEAD to staging
28
- * const staged = await git.diff()
29
- * .setCached(true)
30
- * .call();
358
+ * // `git diff --cached --stat`
359
+ * const stat = await git.diff().setCached(true).callText("stat");
31
360
  *
32
- * // Filter by path prefix
33
- * const srcChanges = await git.diff()
34
- * .setOldTree(commitA)
35
- * .setNewTree(commitB)
36
- * .setPathFilter("src/")
37
- * .call();
361
+ * // `git diff -U1 -w`
362
+ * const patch = await git.diff().setOptions({ context: 1, ignoreWhitespace: true }).callText();
38
363
  *
39
- * for (const entry of entries) {
40
- * console.log(`${entry.changeType}: ${entry.newPath ?? entry.oldPath}`);
41
- * }
364
+ * // `git diff --no-prefix -O order.txt --no-textconv`
365
+ * await git.diff().setOptions({ noPrefix: true, orderFile: "order.txt", textconv: false }).callText();
42
366
  * ```
43
367
  */
44
368
  export class DiffCommand extends GitCommand<DiffEntry[]> {
45
369
  private oldTree?: string;
46
370
  private newTree?: string;
47
371
  private cached = false;
372
+ /** revs->combine_merges: a conflicted path as its combined diff (`git diff`'s default) */
373
+ private combineMerges = true;
374
+ /**
375
+ * diffopt.flags.dirty_submodules: a submodule at another commit checked for dirt too
376
+ * (default: when a patch is printed, as `diff_setup_done` sets it; always for `call()`)
377
+ */
378
+ private dirtySubmodules?: boolean;
379
+ /** `diff.submodule` (its last value git knows), read by the text outputs */
380
+ private configuredSubmoduleFormat?: SubmoduleDiffFormat;
381
+ private readonly configWarnings: string[] = [];
382
+ /** {@link dirtySubmodules} for the comparison being collected */
383
+ private dirtyThisCall = true;
384
+ /** The `ignore` setting of each submodule's path (see `submoduleIgnores`) */
385
+ private submoduleIgnoreMap?: Promise<Map<string, "none" | "untracked" | "dirty" | "all">>;
48
386
  private pathFilter?: string;
387
+ private pathspecItems?: PathspecItem[];
388
+ private renames?: boolean;
389
+ private renameLimit?: number;
390
+ private textOptions: DiffTextOptions = {};
391
+ /** `--ignore-submodules=<when>`: overrides the submodule configuration */
392
+ private ignoreSubmodulesOverride?: SubmoduleIgnoreMode;
393
+ /** The index read instead of the working copy's (see {@link setTemporaryIndex}) */
394
+ private temporaryIndex?: Staging;
395
+ /** Intent-to-add entries are in the index as empty files (plumbing's `diff-index --cached`) */
396
+ private intentToAddVisible = false;
397
+
398
+ /**
399
+ * Show intent-to-add entries in a `--cached` comparison as the empty files they name, as
400
+ * plumbing's `diff-index --cached` does (porcelain `git diff` sets `ita_invisible_in_index`).
401
+ *
402
+ * @internal
403
+ */
404
+ setIntentToAddVisible(visible: boolean): this {
405
+ this.checkCallable();
406
+ this.intentToAddVisible = visible;
407
+ return this;
408
+ }
49
409
 
50
410
  /**
51
411
  * Set the old (base) tree/commit for comparison.
52
412
  *
53
413
  * Can be a commit ID, branch name, tag name, or tree ID.
54
- * If not set, defaults to HEAD.
414
+ * If not set, defaults to HEAD (or the index, for the worktree diff).
55
415
  *
56
416
  * @param refOrId Commit-ish or tree ID
57
417
  */
@@ -65,8 +425,8 @@ export class DiffCommand extends GitCommand<DiffEntry[]> {
65
425
  * Set the new tree/commit for comparison.
66
426
  *
67
427
  * Can be a commit ID, branch name, tag name, or tree ID.
68
- * If not set and cached=true, compares to staging.
69
- * If not set and cached=false, compares to HEAD.
428
+ * If not set and cached=true, compares to the index; otherwise to the worktree (HEAD's
429
+ * tree when there is none).
70
430
  *
71
431
  * @param refOrId Commit-ish or tree ID
72
432
  */
@@ -77,7 +437,80 @@ export class DiffCommand extends GitCommand<DiffEntry[]> {
77
437
  }
78
438
 
79
439
  /**
80
- * Compare HEAD to staging area instead of working tree.
440
+ * Whether a conflicted path is shown as its combined diff (`diff --cc` of stages 2 and 3
441
+ * against the file, `git diff`'s default) or, as git's `diff-files -p` and the unstaged
442
+ * diff of `git status -vv` show it, listed as unmerged (`* Unmerged path <path>`) and
443
+ * diffed as its stage 2 against the file.
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * const text = await git.diff().setCombineMerges(false).callText("patch");
448
+ * ```
449
+ */
450
+ setCombineMerges(combine: boolean): this {
451
+ this.checkCallable();
452
+ this.combineMerges = combine;
453
+ return this;
454
+ }
455
+
456
+ /**
457
+ * How a submodule's change is shown in the patch (`--submodule=<format>`): `short` (the
458
+ * default, unless `diff.submodule` says otherwise) as a `Subproject commit` patch, `log`
459
+ * as the commits between its two sides (`Submodule sub 1234567..89abcde:` and ` > subject`
460
+ * lines, git's `show_submodule_diff_summary`), `diff` as the diff of the submodule's own
461
+ * files, their paths under the submodule's (`show_submodule_inline_diff`).
462
+ */
463
+ setSubmoduleFormat(format: SubmoduleDiffFormat): this {
464
+ this.checkCallable();
465
+ this.textOptions = { ...this.textOptions, submoduleFormat: format };
466
+ return this;
467
+ }
468
+
469
+ /**
470
+ * `--ignore-submodules=<when>`: what of submodules to ignore, whatever
471
+ * `diff.ignoreSubmodules` and `submodule.<name>.ignore` say (`all`: their changes; `dirty`:
472
+ * their worktrees; `untracked`: untracked files in them; `none`: nothing).
473
+ */
474
+ setIgnoreSubmodules(mode: SubmoduleIgnoreMode): this {
475
+ this.checkCallable();
476
+ this.ignoreSubmodulesOverride = mode;
477
+ return this;
478
+ }
479
+
480
+ /**
481
+ * Whether a submodule whose worktree is at another commit than its entry is also checked
482
+ * for changes of its own (`Subproject commit <id>-dirty`), as git's patch output does
483
+ * (`diff_setup_done` sets `dirty_submodules` for it). `git status -v` diffs without it:
484
+ * only a submodule at its entry's commit is shown dirty there.
485
+ */
486
+ setDirtySubmodules(dirty: boolean): this {
487
+ this.checkCallable();
488
+ this.dirtySubmodules = dirty;
489
+ return this;
490
+ }
491
+
492
+ /**
493
+ * What git prints on stderr reading its diff configuration, once a text output was made:
494
+ * `warning: Unknown value for 'diff.submodule' config variable: '<value>'` for each value
495
+ * of `diff.submodule` it does not know.
496
+ */
497
+ get warnings(): readonly string[] {
498
+ return this.configWarnings;
499
+ }
500
+
501
+ /**
502
+ * git_diff_ui_config, which `git diff` (and log, show) runs before any option is read:
503
+ * `diff.submodule`, its warnings, and the failure of a variable without a value.
504
+ */
505
+ private readUiConfig(): void {
506
+ if (this.textOptions.uiConfig === false) return;
507
+ const { format, warnings } = readDiffSubmoduleConfig(this.workingCopy);
508
+ this.configuredSubmoduleFormat = format;
509
+ this.configWarnings.splice(0, this.configWarnings.length, ...warnings);
510
+ }
511
+
512
+ /**
513
+ * Compare HEAD (or the old tree) to the index instead of the worktree.
81
514
  *
82
515
  * Equivalent to `git diff --cached` or `git diff --staged`.
83
516
  *
@@ -89,6 +522,20 @@ export class DiffCommand extends GitCommand<DiffEntry[]> {
89
522
  return this;
90
523
  }
91
524
 
525
+ /**
526
+ * Reads `index` instead of the working copy's index, as git run with `GIT_INDEX_FILE`
527
+ * pointing at a temporary index (`stash -p`'s index of HEAD's tree). The diff only reads it.
528
+ */
529
+ setTemporaryIndex(index: Staging): this {
530
+ this.checkCallable();
531
+ this.temporaryIndex = index;
532
+ return this;
533
+ }
534
+
535
+ protected override get staging(): Staging {
536
+ return this.temporaryIndex ?? super.staging;
537
+ }
538
+
92
539
  /**
93
540
  * Filter results to only paths starting with this prefix.
94
541
  *
@@ -100,118 +547,1428 @@ export class DiffCommand extends GitCommand<DiffEntry[]> {
100
547
  return this;
101
548
  }
102
549
 
550
+ /**
551
+ * Limit the comparison to a pathspec, as `git diff -- <pathspec>...` (and `git log -p --
552
+ * <pathspec>`) does: paths from the top, with wildcards and magic (see `LogCommand.addPath`).
553
+ */
554
+ setPathspec(paths: string[]): this {
555
+ this.checkCallable();
556
+ this.pathspecItems = paths.map((p) => parsePathspecItem(p, { attr: true }));
557
+ if (this.pathspecItems.length > 0 && this.pathspecItems.every((i) => i.exclude)) {
558
+ this.pathspecItems.push(parsePathspecItem("."));
559
+ }
560
+ return this;
561
+ }
562
+
563
+ /**
564
+ * Detect renames (`-M`, `--no-renames`). Default: off for `call()` (each path as added and
565
+ * deleted), `diff.renames` (default on) for `callText()`.
566
+ */
567
+ setRenames(renames: boolean): this {
568
+ this.checkCallable();
569
+ this.renames = renames;
570
+ return this;
571
+ }
572
+
573
+ /** `-l<n>`: the rename limit (default `diff.renameLimit`, 1000) */
574
+ setRenameLimit(limit: number): this {
575
+ this.checkCallable();
576
+ this.renameLimit = limit;
577
+ return this;
578
+ }
579
+
580
+ /** `diff` stores no objects: its abbreviations read each loose fan-out directory once */
581
+ protected override writesNoObjects(): boolean {
582
+ return true;
583
+ }
584
+
585
+ /** Text output options: context, algorithm, whitespace, `--stat` widths, ... */
586
+ setOptions(options: DiffTextOptions): this {
587
+ this.checkCallable();
588
+ this.textOptions = { ...this.textOptions, ...options };
589
+ return this;
590
+ }
591
+
103
592
  /**
104
593
  * Execute the diff.
105
594
  *
106
- * @returns List of diff entries representing changes
595
+ * @returns List of diff entries representing changes, in git's path order
107
596
  */
108
597
  async call(): Promise<DiffEntry[]> {
109
598
  this.checkCallable();
110
599
  this.setCallable(false);
600
+ this.dirtyThisCall = this.dirtySubmodules ?? true;
601
+ return (await this.collect(this.renames ?? false)).entries;
602
+ }
603
+
604
+ /**
605
+ * Execute the diff and print it as `git diff` does, in the given format.
606
+ *
607
+ * The output is bytes; the text decodes them as paths decode ({@link decodeGitPath}):
608
+ * UTF-8, and each byte that is no UTF-8 (a path printed raw with `core.quotePath=false`,
609
+ * or file content in another encoding) as the lone surrogate U+DC00 + byte, never U+FFFD.
610
+ * So `encodeGitPath(await callText())` is exactly {@link callBytes}, and a path cut from
611
+ * the text is the path's string as trees and the index hold it.
612
+ */
613
+ async callText(format: DiffOutputFormat = "patch"): Promise<string> {
614
+ return decodeGitPath(await this.callBytes(format));
615
+ }
616
+
617
+ /** {@link callText} as bytes (file content that is not UTF-8 kept as it is). */
618
+ async callBytes(format: DiffOutputFormat = "patch"): Promise<Uint8Array> {
619
+ this.checkCallable();
620
+ this.setCallable(false);
621
+ const config = this.config;
622
+ const renames = this.renames ?? renamesValue(config.value("diff.renames")) ?? true;
623
+ this.dirtyThisCall = this.dirtySubmodules ?? format === "patch";
624
+ this.readUiConfig();
625
+ return this.inOneOperation(async () => {
626
+ const collected = await this.collect(
627
+ renames,
628
+ format === "patch",
629
+ PREFETCH_FORMATS.has(format),
630
+ );
631
+ const sink = new ByteSink();
632
+ await this.writeFormats(sink, [format], collected);
633
+ return sink.bytes();
634
+ });
635
+ }
111
636
 
112
- // Resolve old tree
113
- const oldTreeId = await this.resolveTreeId(this.oldTree ?? "HEAD");
637
+ /**
638
+ * The diffstat of the comparison, one file per pair in git's order (`compute_diffstat` of
639
+ * the diff queue, as a `DIFF_FORMAT_CALLBACK` consumer sees it): an unmerged path as a
640
+ * file with `isUnmerged` and no counts, followed by what the diff holds for it besides.
641
+ * No renames unless {@link setRenames} asks, no textconv.
642
+ */
643
+ async callDiffstat(): Promise<DiffstatFile[]> {
644
+ this.checkCallable();
645
+ this.setCallable(false);
646
+ this.dirtyThisCall = this.dirtySubmodules ?? false;
647
+ return this.inOneOperation(() => this.diffstatFiles());
648
+ }
114
649
 
115
- // Resolve new tree
116
- let newTreeId: ObjectId;
117
- if (this.newTree) {
118
- newTreeId = await this.resolveTreeId(this.newTree);
119
- } else if (this.cached) {
120
- // Compare to staging area
121
- newTreeId = await this.staging.writeTree(this.trees);
122
- } else {
123
- // Default: compare HEAD to HEAD (no changes)
124
- // In a real implementation with working tree, this would compare to working tree
125
- const headRef = await this.refsStore.resolve("HEAD");
126
- if (!headRef?.objectId) {
127
- return [];
650
+ /** {@link callDiffstat}'s files. */
651
+ private async diffstatFiles(): Promise<DiffstatFile[]> {
652
+ const collected = await this.collect(this.renames ?? false, false);
653
+ const entries = await this.ordered(collected.entries);
654
+ this.textOptions = { ...this.textOptions, textconv: false };
655
+ const options = this.outputOptions();
656
+ const files: DiffstatFile[] = [];
657
+ for (const entry of entries) {
658
+ if (entry.unmerged) {
659
+ files.push({
660
+ name: entry.oldPath ?? entry.newPath ?? "",
661
+ isRenamed: false,
662
+ isBinary: false,
663
+ isUnmerged: true,
664
+ added: 0,
665
+ deleted: 0,
666
+ });
667
+ } else files.push(...(await computeDiffstat([diffEntryToPair(entry, this.blobs)], options)));
668
+ }
669
+ return files;
670
+ }
671
+
672
+ /**
673
+ * Several formats of one comparison in the order git's `diff_flush` prints them (`git log
674
+ * --stat -p`): `--name-only`/`--name-status`, then `--numstat`, `--stat`, `--shortstat`,
675
+ * then the patch, after a blank line when something came before it. Undefined when
676
+ * nothing differs (git's empty diff queue, which `git log` shows no diff for).
677
+ *
678
+ * `follow` is `--follow`'s path: the comparison is limited to it, and when it is added, a
679
+ * file it was renamed from is looked for among the other side's paths (tree-diff.c's
680
+ * try_to_follow_renames); `followPath` is then the path followed from there on, and
681
+ * `followChange` whether it was a rename or a copy.
682
+ */
683
+ async callFormats(
684
+ formats: DiffOutputFormat[],
685
+ follow?: string,
686
+ ): Promise<{
687
+ bytes?: Uint8Array;
688
+ followPath?: string;
689
+ followChange?: ChangeType.RENAME | ChangeType.COPY;
690
+ }> {
691
+ this.checkCallable();
692
+ this.setCallable(false);
693
+ const config = this.config;
694
+ const renames = this.renames ?? renamesValue(config.value("diff.renames")) ?? true;
695
+ this.dirtyThisCall = this.dirtySubmodules ?? formats.includes("patch");
696
+ this.readUiConfig();
697
+ return this.inOneOperation(async () => {
698
+ let followPath = follow;
699
+ let followChange: ChangeType.RENAME | ChangeType.COPY | undefined;
700
+ let collected: { entries: DiffEntry[]; combined: CombinedEntry[] };
701
+ if (follow !== undefined) {
702
+ const spec = this.pathspecItems;
703
+ this.pathspecItems = [parsePathspecItem(`:(literal)${follow}`)];
704
+ collected = await this.collect(false, false);
705
+ const only = collected.entries[0];
706
+ if (collected.entries.length === 1 && only?.changeType === ChangeType.ADD) {
707
+ this.pathspecItems = spec;
708
+ const found = await this.followSource(only);
709
+ if (found) {
710
+ collected = { entries: [found], combined: [] };
711
+ followPath = found.oldPath;
712
+ followChange = found.changeType as ChangeType.RENAME | ChangeType.COPY;
713
+ }
714
+ }
715
+ } else {
716
+ collected = await this.collect(
717
+ renames,
718
+ formats.includes("patch"),
719
+ formats.some((f) => PREFETCH_FORMATS.has(f)),
720
+ );
721
+ }
722
+ const followed = {
723
+ ...(followPath !== undefined ? { followPath } : {}),
724
+ ...(followChange !== undefined ? { followChange } : {}),
725
+ };
726
+ if (collected.entries.length === 0 && collected.combined.length === 0) return followed;
727
+ const sink = new ByteSink();
728
+ await this.writeFormats(sink, formats, collected);
729
+ return { bytes: sink.bytes(), ...followed };
730
+ });
731
+ }
732
+
733
+ /**
734
+ * tree-diff.c's try_to_follow_renames for the path a comparison of two trees adds: copies
735
+ * found harder, every path of the old tree a source (see `findFollowSource`); the rename
736
+ * or copy found, undefined for none.
737
+ */
738
+ private async followSource(added: DiffEntry): Promise<DiffEntry | undefined> {
739
+ const path = added.newPath;
740
+ if (path === undefined || added.newId === undefined) return undefined;
741
+ const oldSide = await this.treeSide(this.oldTree ?? "HEAD", this.oldTree === undefined);
742
+ if (oldSide.size === 0) return undefined;
743
+ const newSide = this.newTree ? await this.treeSide(this.newTree) : new Map<string, Side>();
744
+ const sources = [...oldSide].map(([p, side]) => ({ path: p, mode: side.mode, id: side.id }));
745
+ const deleted = new Set(sources.filter((c) => !newSide.has(c.path)).map((c) => c.path));
746
+ const readBlob = async (id: ObjectId) => collectChunks((await this.blobs.load(id)) ?? []);
747
+ const found = await findFollowSource(
748
+ sources,
749
+ { path, mode: added.newMode ?? 0o100644, id: added.newId },
750
+ deleted,
751
+ {
752
+ countLastSpan: this.textOptions.renameCountLastSpan,
753
+ size: async (c) => {
754
+ try {
755
+ return await this.blobs.size(c.id);
756
+ } catch {
757
+ return undefined;
758
+ }
759
+ },
760
+ load: (c) => readBlob(c.id),
761
+ },
762
+ );
763
+ if (!found) return undefined;
764
+ const source = oldSide.get(found.from) as Side;
765
+ return {
766
+ changeType: found.renamed ? ChangeType.RENAME : ChangeType.COPY,
767
+ oldPath: found.from,
768
+ newPath: path,
769
+ oldId: source.id,
770
+ newId: added.newId,
771
+ oldMode: source.mode as FileModeValue,
772
+ newMode: added.newMode as FileModeValue,
773
+ score: scorePercent(found.score),
774
+ };
775
+ }
776
+
777
+ /** The formats of the collected comparison, in diff_flush's order */
778
+ private async writeFormats(
779
+ sink: ByteSink,
780
+ formats: DiffOutputFormat[],
781
+ collected: { entries: DiffEntry[]; combined: CombinedEntry[] },
782
+ ): Promise<void> {
783
+ const config = this.config;
784
+ const { combined } = collected;
785
+ const ordered = await this.ordered(collected.entries);
786
+ const entries = this.textOptions.reverse ? ordered.map(reverseEntry) : ordered;
787
+ const options = this.outputOptions();
788
+ Object.assign(options, this.prefixes());
789
+ if (this.textOptions.reverse) {
790
+ // diff -R swaps the prefixes with the sides (`diff --git b/f a/f`)
791
+ [options.srcPrefix, options.dstPrefix] = [
792
+ options.dstPrefix ?? "b/",
793
+ options.srcPrefix ?? "a/",
794
+ ];
795
+ }
796
+ const pairs: DiffFilePair[] = [];
797
+ const unmerged = new Set<DiffFilePair>();
798
+ for (const entry of entries) {
799
+ // an unmerged path: only its name is printed
800
+ const pair: DiffFilePair = entry.unmerged
801
+ ? {
802
+ status: "M",
803
+ old: contentSide(entry.oldPath ?? "", 0, NULL_ID, async () => new Uint8Array(0)),
804
+ }
805
+ : this.withTextconvInputs(diffEntryToPair(entry, this.blobs), entry);
806
+ if (entry.unmerged) unmerged.add(pair);
807
+ pairs.push(pair);
808
+ }
809
+ const quote = options.quotePath;
810
+ const order: DiffOutputFormat[] = [
811
+ "name-only",
812
+ "name-status",
813
+ "numstat",
814
+ "stat",
815
+ "shortstat",
816
+ "summary",
817
+ "patch",
818
+ ];
819
+ // run_diff_files prints the combined diff (`diff --cc`) of a conflicted path as it finds
820
+ // it, before diff_flush prints any format of the rest
821
+ if (combined.length > 0 && formats.includes("patch")) {
822
+ // combine-diff.c's index lines take DEFAULT_ABBREV, whatever --abbrev says
823
+ let combinedLengths: ReadonlyMap<string, number> | undefined;
824
+ if (!options.fullIndex) {
825
+ const ids = new Set<string>([NULL_ID]);
826
+ for (const c of combined) {
827
+ ids.add(c.ours.objectId);
828
+ ids.add(c.theirs.objectId);
829
+ }
830
+ combinedLengths = await this.idAbbreviator().lengths(ids);
128
831
  }
129
- const headCommit = await this.commits.load(headRef.objectId);
130
- if (!headCommit) {
131
- return [];
832
+ for (const c of combined) await this.writeCombined(sink, c, options, combinedLengths);
833
+ }
834
+ // diff_flush of an empty queue prints nothing
835
+ if (pairs.length === 0) return;
836
+ let separator = false;
837
+ for (const format of order) {
838
+ if (!formats.includes(format)) continue;
839
+ if (format === "patch" && separator) sink.text("\n");
840
+ // diff_flush: an empty summary (is_summary_empty) prints nothing and asks no separator
841
+ if (format === "summary") {
842
+ const text = formatSummary(
843
+ pairs.filter((p) => !unmerged.has(p)),
844
+ quote,
845
+ );
846
+ if (text) {
847
+ sink.text(text);
848
+ separator = true;
849
+ }
850
+ continue;
851
+ }
852
+ separator = true;
853
+ switch (format) {
854
+ case "patch": {
855
+ const submoduleFormat =
856
+ this.textOptions.submoduleFormat ?? this.configuredSubmoduleFormat ?? "short";
857
+ if (submoduleFormat !== "short") {
858
+ options.submodulePatch = (out, pair, o) =>
859
+ this.writeSubmodulePatch(out, pair, o, submoduleFormat);
860
+ }
861
+ // index lines abbreviate as git does (core.abbrev, the repository's size, uniqueness)
862
+ if (!options.fullIndex) {
863
+ const ids = new Set<string>();
864
+ for (const pair of pairs) {
865
+ if (unmerged.has(pair)) continue;
866
+ ids.add(pair.old?.id ?? NULL_ID);
867
+ ids.add(pair.new?.id ?? NULL_ID);
868
+ }
869
+ // `--abbrev=<n>`: at least n digits
870
+ options.abbrevLengths = await this.idAbbreviator().lengths(ids, options.abbrev);
871
+ }
872
+ for (const pair of pairs) {
873
+ if (unmerged.has(pair)) {
874
+ sink.text(`* Unmerged path ${pair.new?.path ?? pair.old?.path}\n`);
875
+ } else await writePairPatch(sink, pair, options);
876
+ }
877
+ break;
878
+ }
879
+ case "name-only":
880
+ sink.text(
881
+ formatNameOnly(await this.shownNames(pairs, unmerged, options), { quotePath: quote }),
882
+ );
883
+ break;
884
+ case "name-status":
885
+ for (const pair of await this.shownNames(pairs, unmerged, options)) {
886
+ if (unmerged.has(pair)) {
887
+ sink.text(`U\t${quotePath(pair.new?.path ?? pair.old?.path ?? "", quote)}\n`);
888
+ } else sink.text(formatNameStatus([pair], { quotePath: quote }));
889
+ }
890
+ break;
891
+ default: {
892
+ const files = [];
893
+ for (const pair of pairs) {
894
+ if (unmerged.has(pair)) {
895
+ const name = pair.new?.path ?? pair.old?.path ?? "";
896
+ files.push({
897
+ name,
898
+ isRenamed: false,
899
+ isBinary: false,
900
+ isUnmerged: true,
901
+ added: 0,
902
+ deleted: 0,
903
+ });
904
+ } else files.push(...(await computeDiffstat([pair], options)));
905
+ }
906
+ const statOptions: DiffstatOptions = {
907
+ nameWidth: intValue(config.value("diff.statNameWidth")),
908
+ graphWidth: intValue(config.value("diff.statGraphWidth")),
909
+ ...this.textOptions.stat,
910
+ quotePath: quote,
911
+ };
912
+ if (format === "stat") sink.text(formatStat(files, statOptions));
913
+ else if (format === "numstat") sink.text(formatNumstat(files, { quotePath: quote }));
914
+ else sink.text(formatShortstat(files));
915
+ }
132
916
  }
133
- newTreeId = headCommit.tree;
134
917
  }
918
+ }
135
919
 
136
- // Perform tree comparison
137
- return this.diffTrees(oldTreeId, newTreeId);
920
+ /**
921
+ * builtin_diff's submodule branch: `--submodule=log` (show_submodule_diff_summary) or
922
+ * `--submodule=diff` (show_submodule_inline_diff) for a pair of submodules (or a submodule
923
+ * and nothing).
924
+ */
925
+ private async writeSubmodulePatch(
926
+ sink: ByteSink,
927
+ pair: DiffFilePair,
928
+ options: DiffOutputOptions,
929
+ format: SubmoduleDiffFormat,
930
+ ): Promise<void> {
931
+ const path = pair.old?.path ?? pair.new?.path ?? "";
932
+ const one = pair.old?.id ?? NULL_ID;
933
+ const two = pair.new?.id ?? NULL_ID;
934
+ const dirt = pair.new?.submoduleDirt;
935
+ // strbuf_add_unique_abbrev(..., DEFAULT_ABBREV): the superproject's abbreviation
936
+ const abbreviate = (id: ObjectId) => this.idAbbreviator().abbreviate(id);
937
+ const workingCopy = this.workingCopy;
938
+ if (format === "log") {
939
+ sink.text(await showSubmoduleDiffSummary({ workingCopy, path, one, two, dirt, abbreviate }));
940
+ return;
941
+ }
942
+ const sub = await openSubmoduleRepository(workingCopy, path);
943
+ const header = await submoduleHeader({ path, one, two, dirt, sub, abbreviate });
944
+ sink.text(header.text);
945
+ // a valid left and right commit (or none on that side) to diff
946
+ if (!(header.left || one === NULL_ID) || !(header.right || two === NULL_ID)) return;
947
+ if (!sub) return;
948
+ const failed = "(diff failed)\n";
949
+ // `git diff` runs in the submodule's directory: one that holds no repository of its own
950
+ // runs it in the superproject, which lacks the submodule's commits
951
+ if (!sub.populated && (await this.worktreeIfAny?.getEntry(path))?.isDirectory) {
952
+ sink.text(failed);
953
+ return;
954
+ }
955
+ const inner = new DiffCommand(sub.repository)
956
+ .setOldTree(header.left ? one : EMPTY_TREE_ID)
957
+ .setSubmoduleFormat("diff")
958
+ .setOptions({
959
+ srcPrefix: `${options.srcPrefix ?? "a/"}${path}/`,
960
+ dstPrefix: `${options.dstPrefix ?? "b/"}${path}/`,
961
+ });
962
+ // modified content: the submodule's worktree is diffed, not its commit
963
+ if (!dirt?.modified) inner.setNewTree(header.right ? two : EMPTY_TREE_ID);
964
+ try {
965
+ sink.push(await inner.callBytes("patch"));
966
+ } catch {
967
+ sink.text(failed);
968
+ }
969
+ }
970
+
971
+ /** The combined diff (`diff --cc`) of a conflicted path: stages 2 and 3 against the file */
972
+ private async writeCombined(
973
+ sink: ByteSink,
974
+ c: CombinedEntry,
975
+ options: DiffOutputOptions,
976
+ lengths: ReadonlyMap<string, number> | undefined,
977
+ ): Promise<void> {
978
+ const worktree = this.worktreeIfAny;
979
+ const driver = await options.driver?.(c.path);
980
+ // combine-diff.c's grab_blob: a gitlink's or a deleted side's content is not converted
981
+ const textconv = driver?.textconv;
982
+ const stage = async (e: StageEntry) => {
983
+ const side = blobSide(this.blobs, c.path, e.mode, e.objectId);
984
+ const convert = textconv && (e.mode & S_IFMT) !== GITLINK && e.objectId !== NULL_ID;
985
+ return {
986
+ id: e.objectId,
987
+ mode: e.mode,
988
+ content: convert
989
+ ? await textconv(await this.smudged(c.path, e.mode, side.read), c.path)
990
+ : await side.read(),
991
+ };
992
+ };
993
+ // the file as git reads it for the result: its real mode (canon_mode), cleaned content
994
+ let mode = 0;
995
+ let content: Uint8Array = new Uint8Array(0);
996
+ const file = await worktree?.getEntry(c.path);
997
+ if (worktree && file) {
998
+ if (file.isDirectory) {
999
+ mode = GITLINK;
1000
+ content = encoder.encode(`Subproject commit ${NULL_ID}\n`);
1001
+ } else {
1002
+ const kind = file.mode & S_IFMT;
1003
+ mode = kind === 0o120000 ? 0o120000 : file.mode & 0o111 ? 0o100755 : 0o100644;
1004
+ // a symbolic link's target is not converted; textconv reads the file as it is
1005
+ content =
1006
+ textconv && kind !== 0o120000
1007
+ ? await textconv(await collectChunks(worktree.readContent(c.path)), c.path)
1008
+ : await readCleanContent(worktree, c.path);
1009
+ }
1010
+ }
1011
+ writeCombinedDiff(
1012
+ sink,
1013
+ {
1014
+ path: c.path,
1015
+ parents: [await stage(c.ours), await stage(c.theirs)],
1016
+ result: { id: NULL_ID, mode, content },
1017
+ },
1018
+ {
1019
+ ...options,
1020
+ ...(textconv
1021
+ ? { binary: false }
1022
+ : driver?.binary !== undefined
1023
+ ? { binary: driver.binary }
1024
+ : {}),
1025
+ abbreviate: (id) => id.slice(0, options.fullIndex ? 40 : (lengths?.get(id) ?? 7)),
1026
+ },
1027
+ );
138
1028
  }
139
1029
 
140
1030
  /**
141
- * Resolve a ref to its tree ID.
1031
+ * The textconv input of a pair's sides, as git's `prepare_temp_file` writes it: a blob
1032
+ * smudged as checkout would write it (`convert_to_working_tree`), a worktree file's bytes
1033
+ * as they are (the entry's `readNew`, which reads it cleaned)
142
1034
  */
143
- private async resolveTreeId(refOrId: string): Promise<ObjectId> {
144
- // Try to resolve as a commit ref first
1035
+ private withTextconvInputs(pair: DiffFilePair, entry: DiffEntry): DiffFilePair {
1036
+ const worktree = this.worktreeIfAny;
1037
+ if (!worktree) return pair;
1038
+ const blob = (side: DiffFilePair["old"]) =>
1039
+ side && { ...side, readTextconvInput: () => this.smudged(side.path, side.mode, side.read) };
1040
+ const raw = (side: DiffFilePair["new"]) =>
1041
+ side && {
1042
+ ...side,
1043
+ readTextconvInput: () => collectChunks(worktree.readContent(side.path)),
1044
+ };
1045
+ return {
1046
+ ...pair,
1047
+ old: entry.readOld ? pair.old : blob(pair.old),
1048
+ new: entry.readNew ? raw(pair.new) : blob(pair.new),
1049
+ };
1050
+ }
1051
+
1052
+ /** A blob's content as checkout writes it to the worktree (the worktree's smudge filter) */
1053
+ private async smudged(
1054
+ path: string,
1055
+ mode: number,
1056
+ read: () => Promise<Uint8Array>,
1057
+ ): Promise<Uint8Array> {
1058
+ const content = await read();
1059
+ return collectChunks(
1060
+ await smudgeContent(this.worktreeIfAny?.contentFilter, path, content, mode),
1061
+ );
1062
+ }
1063
+
1064
+ /** The pairs `--name-only` lists: with whitespace options, those whose patch shows a change */
1065
+ private async shownNames(
1066
+ pairs: DiffFilePair[],
1067
+ unmerged: Set<DiffFilePair>,
1068
+ options: DiffOutputOptions,
1069
+ ): Promise<DiffFilePair[]> {
1070
+ const fromContents =
1071
+ (this.textOptions.namesFromContents ?? true) &&
1072
+ (options.ignoreWhitespace ||
1073
+ options.ignoreWhitespaceChange ||
1074
+ options.ignoreWhitespaceAtEol ||
1075
+ options.ignoreCrAtEol);
1076
+ if (!fromContents) return pairs;
1077
+ const shown: DiffFilePair[] = [];
1078
+ for (const pair of pairs) {
1079
+ if (unmerged.has(pair)) {
1080
+ shown.push(pair);
1081
+ continue;
1082
+ }
1083
+ const scratch = new ByteSink();
1084
+ await writePairPatch(scratch, pair, options);
1085
+ if (scratch.length > 0) shown.push(pair);
1086
+ }
1087
+ return shown;
1088
+ }
1089
+
1090
+ private get config(): RemoteConfigStore {
1091
+ return RemoteConfigStore.from(this.workingCopy);
1092
+ }
1093
+
1094
+ /** What this diff compares */
1095
+ private get sides(): DiffSides {
1096
+ if (this.newTree) return "trees";
1097
+ if (this.cached) return "cached";
1098
+ if (!this.worktreeIfAny) return "trees";
1099
+ return this.oldTree ? "commit-worktree" : "index-worktree";
1100
+ }
1101
+
1102
+ /**
1103
+ * The path prefixes, as git sets them: `diff.noprefix`, else `diff.srcPrefix` /
1104
+ * `diff.dstPrefix` (default `a/`, `b/`) unless `diff.mnemonicPrefix`; then the options;
1105
+ * a prefix left unset takes the comparison's mnemonic one, else `a/` / `b/`.
1106
+ */
1107
+ private prefixes(): { srcPrefix: string; dstPrefix: string } {
1108
+ const get = (key: string) => this.config.value(key);
1109
+ const configSrc = get("diff.srcPrefix");
1110
+ const configDst = get("diff.dstPrefix");
1111
+ let src: string | undefined;
1112
+ let dst: string | undefined;
1113
+ if (!this.textOptions.ignoreConfigNoPrefix && boolValue(get("diff.noprefix"))) {
1114
+ src = "";
1115
+ dst = "";
1116
+ } else if (!boolValue(get("diff.mnemonicPrefix"))) {
1117
+ src = configSrc ?? "a/";
1118
+ dst = configDst ?? "b/";
1119
+ }
1120
+ const options = this.textOptions;
1121
+ if (options.noPrefix) {
1122
+ src = "";
1123
+ dst = "";
1124
+ }
1125
+ // `--default-prefix` resets `diff.srcPrefix` / `diff.dstPrefix` too (git-diff(1))
1126
+ if (options.defaultPrefix) {
1127
+ src = "a/";
1128
+ dst = "b/";
1129
+ }
1130
+ if (options.srcPrefix !== undefined) src = options.srcPrefix;
1131
+ if (options.dstPrefix !== undefined) dst = options.dstPrefix;
1132
+ const mnemonic = MNEMONIC_PREFIXES[this.sides];
1133
+ return { srcPrefix: src ?? mnemonic?.[0] ?? "a/", dstPrefix: dst ?? mnemonic?.[1] ?? "b/" };
1134
+ }
1135
+
1136
+ /** The entries in the order of `-O<orderfile>` / `diff.orderFile` (diffcore_order) */
1137
+ private async ordered(entries: DiffEntry[]): Promise<DiffEntry[]> {
1138
+ const configured = this.config.value("diff.orderFile");
1139
+ const environment = (this.workingCopy.config as { environment?: GitHostEnvironment })
1140
+ ?.environment;
1141
+ // git reads the configuration first: a path it cannot expand fails even with -O
1142
+ const expanded = configured ? expandUserPath(configured, environment) : undefined;
1143
+ if (configured && expanded === undefined) {
1144
+ throw new Error(`failed to expand user dir in: '${configured}'`);
1145
+ }
1146
+ const orderFile = this.textOptions.orderFile ?? expanded;
1147
+ if (!orderFile || entries.length === 0) return entries;
1148
+ const content = await this.readOrderFile(orderFile, environment);
1149
+ if (!content) throw new Error(`failed to read orderfile '${orderFile}'`);
1150
+ // the path git orders a pair by: its second side's (`pair_pathtwo`)
1151
+ return orderByPatterns(entries, parseOrderFile(content), (e) => e.newPath ?? e.oldPath ?? "");
1152
+ }
1153
+
1154
+ /**
1155
+ * An order file, read as git reads it from its current directory (the worktree's root;
1156
+ * the git directory without a worktree): an absolute path through the host; a relative
1157
+ * one in the worktree, or through the host from the worktree's (the git directory's) host
1158
+ * path when it leaves the worktree (`..`) or there is no worktree
1159
+ */
1160
+ private async readOrderFile(
1161
+ path: string,
1162
+ environment: GitHostEnvironment | undefined,
1163
+ ): Promise<Uint8Array | undefined> {
1164
+ if (path.startsWith("/")) return environment?.readFile(path);
1165
+ const worktree = this.worktreeIfAny;
1166
+ if (!worktree || path.split("/").includes("..")) {
1167
+ const base = worktree
1168
+ ? (worktree as { hostPath?: string }).hostPath
1169
+ : (this.workingCopy.config as { hostGitDir?: string }).hostGitDir;
1170
+ if (!base) return worktree ? undefined : environment?.readFile(path);
1171
+ return environment?.readFile(resolveHostPath(base, path));
1172
+ }
145
1173
  try {
146
- const commitId = await this.resolveRef(refOrId);
147
- const commit = await this.commits.load(commitId);
148
- if (!commit) {
149
- // Assume it's a tree ID directly
150
- return refOrId;
1174
+ const entry = await worktree.getEntry(path);
1175
+ if (!entry || entry.isDirectory) return undefined;
1176
+ const chunks: Uint8Array[] = [];
1177
+ for await (const chunk of worktree.readContent(path)) chunks.push(chunk);
1178
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
1179
+ let at = 0;
1180
+ for (const c of chunks) {
1181
+ out.set(c, at);
1182
+ at += c.length;
151
1183
  }
152
- return commit.tree;
1184
+ return out;
153
1185
  } catch {
154
- // Assume it's a tree ID directly
155
- return refOrId;
1186
+ return undefined;
156
1187
  }
157
1188
  }
158
1189
 
159
1190
  /**
160
- * Compare two trees and return list of differences.
1191
+ * The worktree, or none in a bare repository, whose working copy refuses it (asked
1192
+ * without touching it): a diff of trees reads the bare attributes there.
161
1193
  */
162
- private async diffTrees(oldTreeId: ObjectId, newTreeId: ObjectId): Promise<DiffEntry[]> {
163
- const entries: DiffEntry[] = [];
1194
+ private get worktreeIfAny(): Worktree | undefined {
1195
+ return "worktree" in this.workingCopy ? this.worktreeAccess : undefined;
1196
+ }
164
1197
 
165
- // Collect entries from both trees
166
- const oldPaths = new Map<string, TreeEntry>();
167
- const newPaths = new Map<string, TreeEntry>();
1198
+ /** The output options: the setters', else the configuration's */
1199
+ private outputOptions(): DiffOutputOptions {
1200
+ const config = this.config;
1201
+ const get = (key: string) => config.value(key);
1202
+ const worktree = this.worktreeIfAny;
1203
+ const filter = worktree?.contentFilter as
1204
+ | {
1205
+ attributes?: (
1206
+ path: string,
1207
+ names?: readonly string[],
1208
+ context?: { direction: "checkin"; index?: AttributesIndex },
1209
+ ) => Promise<Map<string, true | false | string | undefined>>;
1210
+ }
1211
+ | undefined;
1212
+ // a diff of two trees reads no index (builtin/diff.c's builtin_diff_tree, `git log -p`,
1213
+ // `git show`): the in-tree attributes come from the worktree alone, never the index's
1214
+ const context = this.newTree !== undefined ? WITHOUT_INDEX_ATTRIBUTES : undefined;
1215
+ const drivers = new Map<string, Promise<DiffDriver | undefined>>();
1216
+ const runner =
1217
+ (this.textOptions.textconv ?? true) ? textconvRunnerOf(this.workingCopy) : undefined;
1218
+ const withTextconv = (found: DiffDriver | undefined): DiffDriver | undefined => {
1219
+ const command = found?.textconvCommand;
1220
+ if (!found || !runner || command === undefined) return found;
1221
+ const name = found.name ?? "";
1222
+ const cache = found.cacheTextconv ?? false;
1223
+ return {
1224
+ ...found,
1225
+ textconv: (content, path) => runner({ driver: name, command, path, content, cache }),
1226
+ };
1227
+ };
1228
+ const driver = filter?.attributes
1229
+ ? (path: string) => {
1230
+ let found = drivers.get(path);
1231
+ if (!found) {
1232
+ found = (async () => {
1233
+ const attrs = await filter.attributes?.(path, ["diff"], context);
1234
+ return withTextconv(diffDriverOf(attrs?.get("diff"), get));
1235
+ })();
1236
+ drivers.set(path, found);
1237
+ }
1238
+ return found;
1239
+ }
1240
+ : undefined;
1241
+ const {
1242
+ stat: _stat,
1243
+ renameCountLastSpan: _span,
1244
+ namesFromContents: _names,
1245
+ noPrefix: _noPrefix,
1246
+ defaultPrefix: _defaultPrefix,
1247
+ ignoreConfigNoPrefix: _ignoreConfigNoPrefix,
1248
+ orderFile: _orderFile,
1249
+ textconv: _textconv,
1250
+ abbrev: _abbrev,
1251
+ ...text
1252
+ } = this.textOptions;
1253
+ const abbrev = abbrevOption(this.textOptions.abbrev);
1254
+ return {
1255
+ context: intValue(get("diff.context")) ?? 3,
1256
+ interHunkContext: intValue(get("diff.interHunkContext")) ?? 0,
1257
+ quotePath: boolValue(get("core.quotePath")) ?? true,
1258
+ ...(intValue(get("core.bigFileThreshold")) !== undefined
1259
+ ? { bigFileThreshold: intValue(get("core.bigFileThreshold")) }
1260
+ : {}),
1261
+ ...text,
1262
+ ...(abbrev !== undefined ? { abbrev } : {}),
1263
+ algorithm: text.algorithm ?? algorithmValue(get("diff.algorithm")) ?? "myers",
1264
+ indentHeuristic: text.indentHeuristic ?? boolValue(get("diff.indentHeuristic")) ?? true,
1265
+ ...(driver ? { driver } : {}),
1266
+ };
1267
+ }
168
1268
 
169
- await this.collectTreeEntries(oldTreeId, "", oldPaths);
170
- await this.collectTreeEntries(newTreeId, "", newPaths);
1269
+ /**
1270
+ * The changed paths (and renames, when asked), in git's order, and the conflicted paths
1271
+ * `git diff` shows as combined diffs (`patch`: the patch format, where a path with both
1272
+ * stage 2 and stage 3 is one; elsewhere it is listed as unmerged and as its stage 2
1273
+ * against the worktree, as `diff-files` does).
1274
+ */
1275
+ private async collect(
1276
+ renames: boolean | "copies",
1277
+ patch = false,
1278
+ prefetch = false,
1279
+ ): Promise<{ entries: DiffEntry[]; combined: CombinedEntry[] }> {
1280
+ // repo_read_index: in a sparse checkout, a skip-worktree entry whose file is present is
1281
+ // read as in the checkout (in memory: diff writes no index)
1282
+ await this.clearPresentSkipWorktree();
1283
+ // a bare repository's working copy refuses its worktree (and index): asked without
1284
+ // touching them
1285
+ const bare = !("worktree" in this.workingCopy);
1286
+ const worktree = this.worktreeIfAny;
1287
+ // `:(attr:...)`: the attributes of the index's paths (match_pathspec_attrs), the trees'
1288
+ // read once their sides are known
1289
+ // without a worktree (a bare repository's diff of trees): the bare attributes, as log
1290
+ // reads them
1291
+ const attributes = !this.pathspecItems
1292
+ ? undefined
1293
+ : worktree
1294
+ ? PathspecAttributes.forWorktree(this.pathspecItems, worktree)
1295
+ : PathspecAttributes.forResolver(
1296
+ this.pathspecItems,
1297
+ bareAttributesResolver({
1298
+ workingCopy: this.workingCopy,
1299
+ trees: this.trees,
1300
+ blobs: this.blobs,
1301
+ revisions: () => this.revisionResolver(),
1302
+ }),
1303
+ );
1304
+ if (attributes && !bare) {
1305
+ const paths: string[] = [];
1306
+ for await (const entry of this.staging.entries()) paths.push(entry.path);
1307
+ await attributes.load(paths);
1308
+ }
1309
+ let oldSide: Map<string, Side>;
1310
+ let newSide: Map<string, Side>;
1311
+ const unmerged = new Map<string, DiffEntry[]>();
1312
+ const combined: CombinedEntry[] = [];
1313
+ if (this.newTree) {
1314
+ [oldSide, newSide] = await this.treePairSides(
1315
+ this.oldTree ?? "HEAD",
1316
+ this.oldTree === undefined,
1317
+ this.newTree,
1318
+ );
1319
+ } else if (this.cached) {
1320
+ oldSide = await this.treeSide(this.oldTree ?? "HEAD", this.oldTree === undefined);
1321
+ const index = await this.indexSide();
1322
+ newSide = index.sides;
1323
+ for (const path of index.unmerged.keys()) unmerged.set(path, []);
1324
+ } else if (worktree) {
1325
+ const run = async () => {
1326
+ if (this.oldTree) {
1327
+ // diff-index: a conflicted path is its worktree file, compared with the tree
1328
+ const old = await this.treeSide(this.oldTree);
1329
+ const wt = await this.worktreeSide(worktree, true);
1330
+ return [old, wt.sides] as const;
1331
+ }
1332
+ // the index side of the entries whose files differ (or are gone), and their files
1333
+ const indexSides = new Map<string, Side>();
1334
+ const wt = await this.worktreeSide(worktree, false, indexSides);
1335
+ for (const [path, stages] of wt.unmerged) {
1336
+ if (!this.matches(path)) continue;
1337
+ const ours = stages.get(2);
1338
+ const theirs = stages.get(3);
1339
+ if (patch && this.combineMerges && ours && theirs) {
1340
+ combined.push({ path, ours, theirs });
1341
+ continue;
1342
+ }
1343
+ unmerged.set(path, ours ? await this.againstStage(ours, wt.compare) : []);
1344
+ }
1345
+ return [indexSides, wt.sides] as const;
1346
+ };
1347
+ [oldSide, newSide] = worktree.batch ? await worktree.batch(run) : await run();
1348
+ } else {
1349
+ // no worktree: HEAD against HEAD (the old tree against HEAD)
1350
+ oldSide = await this.treeSide(this.oldTree ?? "HEAD", this.oldTree === undefined);
1351
+ newSide = await this.treeSide("HEAD", true);
1352
+ }
1353
+ // diff_change / diff_addremove: a submodule whose changes are ignored is left out (the
1354
+ // settings read only when a submodule changed: `git log -p` diffs once per commit)
1355
+ await attributes?.load([...oldSide.keys(), ...newSide.keys(), ...unmerged.keys()]);
1356
+ const paired = this.pairUp(oldSide, newSide, unmerged);
1357
+ const ignoreOf = paired.some((e) => e.oldMode === GITLINK || e.newMode === GITLINK)
1358
+ ? await this.submoduleIgnoreOf()
1359
+ : () => undefined;
1360
+ const entries = paired.filter((e) => {
1361
+ if (e.unmerged) return true;
1362
+ const oldLink = e.oldMode === GITLINK;
1363
+ const newLink = e.newMode === GITLINK;
1364
+ const gitlinkOnly =
1365
+ e.changeType === ChangeType.ADD
1366
+ ? newLink
1367
+ : e.changeType === ChangeType.DELETE
1368
+ ? oldLink
1369
+ : oldLink && newLink;
1370
+ return !gitlinkOnly || ignoreOf((e.newPath ?? e.oldPath) as string) !== "all";
1371
+ });
1372
+ // diffcore_std: an output that reads the blobs fetches a partial clone's absent ones in
1373
+ // one batch first (diff_queued_diff_prefetch), before rename detection
1374
+ if (prefetch) await this.blobs.prefetch?.(prefetchIds(entries));
1375
+ if (renames) await this.detectRenames(entries, renames === "copies");
1376
+ return { entries, combined };
1377
+ }
1378
+
1379
+ /**
1380
+ * What the submodule at a path ignores (git's `set_diffopt_flags_from_submodule_config`
1381
+ * over `diff.ignoreSubmodules`): its `submodule.<name>.ignore` (the configuration, else
1382
+ * `.gitmodules`), else `diff.ignoreSubmodules`; undefined when neither is set.
1383
+ */
1384
+ private async submoduleIgnoreOf(): Promise<
1385
+ (path: string) => "none" | "untracked" | "dirty" | "all" | undefined
1386
+ > {
1387
+ const override = this.ignoreSubmodulesOverride;
1388
+ if (override !== undefined) return () => override;
1389
+ const fallback = submoduleIgnoreValue(this.config.value("diff.ignoreSubmodules"));
1390
+ const own = await this.submoduleIgnores();
1391
+ return (path) => own.get(path) ?? fallback;
1392
+ }
171
1393
 
172
- // Find deleted and modified files
173
- for (const [path, oldEntry] of oldPaths) {
174
- if (this.pathFilter && !path.startsWith(this.pathFilter)) {
1394
+ /** `submodule.<name>.ignore` of each submodule `.gitmodules` names (the worktree's, else the index's). */
1395
+ private submoduleIgnores(): Promise<Map<string, "none" | "untracked" | "dirty" | "all">> {
1396
+ this.submoduleIgnoreMap ??= (async () => {
1397
+ const out = new Map<string, "none" | "untracked" | "dirty" | "all">();
1398
+ let text: string | undefined;
1399
+ try {
1400
+ const worktree = this.worktreeIfAny;
1401
+ const entry = worktree ? await worktree.getEntry(".gitmodules") : undefined;
1402
+ if (worktree && entry && !entry.isDirectory && entry.mode !== 0o120000) {
1403
+ const chunks: Uint8Array[] = [];
1404
+ for await (const chunk of worktree.readContent(".gitmodules")) chunks.push(chunk);
1405
+ text = new TextDecoder().decode(concatChunks(chunks));
1406
+ } else {
1407
+ const staged = await this.staging.getEntry(".gitmodules");
1408
+ if (staged && staged.mode !== 0o120000) {
1409
+ const chunks: Uint8Array[] = [];
1410
+ for await (const chunk of (await this.blobs.load(staged.objectId)) ?? []) {
1411
+ chunks.push(chunk);
1412
+ }
1413
+ text = new TextDecoder().decode(concatChunks(chunks));
1414
+ }
1415
+ }
1416
+ } catch {
1417
+ text = undefined;
1418
+ }
1419
+ if (!text) return out;
1420
+ for (const submodule of parseGitmodules(text)) {
1421
+ const configured = this.config.value(`submodule.${submodule.name}.ignore`)?.trim();
1422
+ const value = configured !== undefined ? configured : submodule.ignore?.trim();
1423
+ if (submodule.path && isSubmoduleIgnoreMode(value)) out.set(submodule.path, value);
1424
+ }
1425
+ return out;
1426
+ })();
1427
+ return this.submoduleIgnoreMap;
1428
+ }
1429
+
1430
+ /** diff-files on a conflicted path's stage 2 (`--ours`): its entry against the worktree */
1431
+ private async againstStage(stage: StageEntry, compare: WorktreeCompare): Promise<DiffEntry[]> {
1432
+ const path = stage.path;
1433
+ const side = await compare(stage);
1434
+ if (!side) {
1435
+ return [
1436
+ {
1437
+ changeType: ChangeType.DELETE,
1438
+ oldPath: path,
1439
+ oldId: stage.objectId,
1440
+ oldMode: stage.mode as FileModeValue,
1441
+ },
1442
+ ];
1443
+ }
1444
+ if (side.id === stage.objectId && side.mode === stage.mode && !side.dirty) return [];
1445
+ return [
1446
+ {
1447
+ changeType: ChangeType.MODIFY,
1448
+ oldPath: path,
1449
+ newPath: path,
1450
+ oldId: stage.objectId,
1451
+ newId: side.id,
1452
+ oldMode: stage.mode as FileModeValue,
1453
+ newMode: side.mode as FileModeValue,
1454
+ ...(side.read ? { readNew: side.read } : {}),
1455
+ ...(side.dirty ? { newDirtySubmodule: true } : {}),
1456
+ ...(side.dirt ? { newSubmoduleDirt: side.dirt } : {}),
1457
+ },
1458
+ ];
1459
+ }
1460
+
1461
+ private matches(path: string): boolean {
1462
+ if (this.pathFilter && !path.startsWith(this.pathFilter)) return false;
1463
+ return !this.pathspecItems || matchPathspec(this.pathspecItems, path, 0) > 0;
1464
+ }
1465
+
1466
+ /**
1467
+ * The entries of both sides in path order; an unmerged path is listed as such, followed by
1468
+ * the entries `unmerged` holds for it
1469
+ */
1470
+ private pairUp(
1471
+ oldSide: Map<string, Side>,
1472
+ newSide: Map<string, Side>,
1473
+ unmerged: Map<string, DiffEntry[]>,
1474
+ ): DiffEntry[] {
1475
+ const paths = new Set<string>([...oldSide.keys(), ...newSide.keys(), ...unmerged.keys()]);
1476
+ const sorted = [...paths].filter((p) => this.matches(p)).sort(compareBytes);
1477
+ const entries: DiffEntry[] = [];
1478
+ for (const path of sorted) {
1479
+ const extra = unmerged.get(path);
1480
+ if (extra) {
1481
+ entries.push({
1482
+ changeType: ChangeType.MODIFY,
1483
+ oldPath: path,
1484
+ newPath: path,
1485
+ unmerged: true,
1486
+ });
1487
+ entries.push(...extra);
175
1488
  continue;
176
1489
  }
1490
+ const a = oldSide.get(path);
1491
+ const b = newSide.get(path);
1492
+ if (a && !b) {
1493
+ entries.push({
1494
+ changeType: ChangeType.DELETE,
1495
+ oldPath: path,
1496
+ oldId: a.id,
1497
+ oldMode: a.mode as FileModeValue,
1498
+ });
1499
+ } else if (!a && b) {
1500
+ entries.push({
1501
+ changeType: ChangeType.ADD,
1502
+ newPath: path,
1503
+ newId: b.id,
1504
+ newMode: b.mode as FileModeValue,
1505
+ ...(b.read ? { readNew: b.read } : {}),
1506
+ ...(b.dirty ? { newDirtySubmodule: true } : {}),
1507
+ ...(b.dirt ? { newSubmoduleDirt: b.dirt } : {}),
1508
+ ...(b.unknownId ? { newIdUnknown: true } : {}),
1509
+ });
1510
+ } else if (a && b && (a.id !== b.id || a.mode !== b.mode || b.dirty || b.unknownId)) {
1511
+ // show_modified: a side of the null id differs from any (`M sub` even where the
1512
+ // submodule is back at the tree's commit)
1513
+ entries.push({
1514
+ changeType: ChangeType.MODIFY,
1515
+ oldPath: path,
1516
+ newPath: path,
1517
+ oldId: a.id,
1518
+ newId: b.id,
1519
+ oldMode: a.mode as FileModeValue,
1520
+ newMode: b.mode as FileModeValue,
1521
+ ...(b.read ? { readNew: b.read } : {}),
1522
+ ...(b.dirty ? { newDirtySubmodule: true } : {}),
1523
+ ...(b.dirt ? { newSubmoduleDirt: b.dirt } : {}),
1524
+ ...(b.unknownId ? { newIdUnknown: true } : {}),
1525
+ });
1526
+ }
1527
+ }
1528
+ return entries;
1529
+ }
177
1530
 
178
- const newEntry = newPaths.get(path);
179
- if (!newEntry) {
180
- // File was deleted
181
- entries.push(createDeleteEntry(path, oldEntry.id, oldEntry.mode as FileModeValue));
182
- } else if (oldEntry.id !== newEntry.id || oldEntry.mode !== newEntry.mode) {
183
- // File was modified
184
- entries.push(
185
- createModifyEntry(
186
- path,
187
- oldEntry.id,
188
- newEntry.id,
189
- oldEntry.mode as FileModeValue,
190
- newEntry.mode as FileModeValue,
191
- ),
192
- );
1531
+ /**
1532
+ * git's `diffcore_rename` over the added and deleted paths; `copies` (DIFF_DETECT_COPY,
1533
+ * `diff.renames=copies`): the modified paths are sources too, which stay (copied only)
1534
+ */
1535
+ private async detectRenames(entries: DiffEntry[], copies = false): Promise<void> {
1536
+ const sources = entries.filter(
1537
+ (e) =>
1538
+ e.changeType === ChangeType.DELETE ||
1539
+ (copies && e.changeType === ChangeType.MODIFY && !e.unmerged),
1540
+ );
1541
+ // a submodule of git's null id (diff-index of a moved one) matches no source exactly,
1542
+ // and gitlinks pair only exactly
1543
+ const destinations = entries.filter((e) => e.changeType === ChangeType.ADD && !e.newIdUnknown);
1544
+ if (sources.length === 0 || destinations.length === 0) return;
1545
+ const byPath = new Map<string, DiffEntry>();
1546
+ for (const e of sources) byPath.set(`s:${e.oldPath}`, e);
1547
+ for (const e of destinations) byPath.set(`d:${e.newPath}`, e);
1548
+ const readBlob = async (id: ObjectId) => {
1549
+ const chunks: Uint8Array[] = [];
1550
+ let size = 0;
1551
+ for await (const c of (await this.blobs.load(id)) ?? []) {
1552
+ chunks.push(c);
1553
+ size += c.length;
193
1554
  }
1555
+ const out = new Uint8Array(size);
1556
+ let at = 0;
1557
+ for (const c of chunks) {
1558
+ out.set(c, at);
1559
+ at += c.length;
1560
+ }
1561
+ return out;
1562
+ };
1563
+ const limit =
1564
+ this.renameLimit ?? intValue(this.config.value("diff.renameLimit")) ?? DEFAULT_RENAME_LIMIT;
1565
+ const pairs = await detectRenames(
1566
+ sources.map((e) => ({
1567
+ path: e.oldPath ?? "",
1568
+ mode: e.oldMode ?? 0,
1569
+ id: e.oldId ?? "",
1570
+ ...(e.changeType === ChangeType.MODIFY ? { kept: true } : {}),
1571
+ })),
1572
+ destinations.map((e) => ({ path: e.newPath ?? "", mode: e.newMode ?? 0, id: e.newId ?? "" })),
1573
+ {
1574
+ renameLimit: limit,
1575
+ countLastSpan: this.textOptions.renameCountLastSpan,
1576
+ copies,
1577
+ // a partial clone's absent blobs, fetched in one batch (a worktree file is no blob)
1578
+ prefetch: async (wanted) => {
1579
+ const ids: ObjectId[] = [];
1580
+ for (const { candidate: c, side } of wanted) {
1581
+ const e = byPath.get(`${side === "source" ? "s" : "d"}:${c.path}`);
1582
+ if (side === "destination" && e?.readNew) continue;
1583
+ if (c.mode !== GITLINK && c.id) ids.push(c.id);
1584
+ }
1585
+ await this.blobs.prefetch?.(ids);
1586
+ },
1587
+ size: async (c, role) => {
1588
+ const e = byPath.get(`${role === "source" ? "s" : "d"}:${c.path}`);
1589
+ if (role === "destination" && e?.readNew) return (await e.readNew()).length;
1590
+ try {
1591
+ return await this.blobs.size(c.id);
1592
+ } catch {
1593
+ return undefined;
1594
+ }
1595
+ },
1596
+ load: async (c, role) => {
1597
+ const e = byPath.get(`${role === "source" ? "s" : "d"}:${c.path}`);
1598
+ if (role === "destination" && e?.readNew) return e.readNew();
1599
+ return readBlob(c.id);
1600
+ },
1601
+ },
1602
+ );
1603
+ const drop = new Set<DiffEntry>();
1604
+ for (const pair of pairs) {
1605
+ const src = byPath.get(`s:${pair.from}`);
1606
+ const dst = byPath.get(`d:${pair.to}`);
1607
+ if (!src || !dst) continue;
1608
+ // a deleted source taken by a rename or copy is no deletion any more
1609
+ if (src.changeType === ChangeType.DELETE) drop.add(src);
1610
+ dst.changeType = pair.copy ? ChangeType.COPY : ChangeType.RENAME;
1611
+ dst.oldPath = src.oldPath;
1612
+ dst.oldId = src.oldId;
1613
+ dst.oldMode = src.oldMode;
1614
+ dst.score = scorePercent(pair.score);
1615
+ }
1616
+ if (drop.size > 0) {
1617
+ const kept = entries.filter((e) => !drop.has(e));
1618
+ entries.splice(0, entries.length, ...kept);
194
1619
  }
1620
+ }
195
1621
 
196
- // Find added files
197
- for (const [path, newEntry] of newPaths) {
198
- if (this.pathFilter && !path.startsWith(this.pathFilter)) {
1622
+ /**
1623
+ * The blobs of a commit's (or tree's) tree, by path. `implicitHead`: HEAD taken by default
1624
+ * (`--cached`, no worktree), an unborn HEAD then being the empty tree as git takes it;
1625
+ * anything else that does not resolve throws (git's "bad revision", exit 128).
1626
+ */
1627
+ private async treeSide(refOrId: string, implicitHead = false): Promise<Map<string, Side>> {
1628
+ const out = new Map<string, Side>();
1629
+ // the empty tree (a root commit's parent side), which a store need not hold
1630
+ if (refOrId === EMPTY_TREE_ID) return out;
1631
+ let treeId: ObjectId;
1632
+ try {
1633
+ treeId = await this.resolveTreeId(refOrId);
1634
+ } catch (e) {
1635
+ if (implicitHead && e instanceof NoHeadError) return out;
1636
+ throw e;
1637
+ }
1638
+ await this.collectTreeEntries(treeId, "", out);
1639
+ return out;
1640
+ }
1641
+
1642
+ /**
1643
+ * The entries of two trees that differ (diff_tree_oid): a subtree with the same id on both
1644
+ * sides, and a file the same on both, is left out without being read; what differs is
1645
+ * listed as {@link treeSide} lists it.
1646
+ */
1647
+ private async treePairSides(
1648
+ oldRef: string,
1649
+ implicitHead: boolean,
1650
+ newRef: string,
1651
+ ): Promise<[Map<string, Side>, Map<string, Side>]> {
1652
+ const oldSide = new Map<string, Side>();
1653
+ const newSide = new Map<string, Side>();
1654
+ const treeOf = async (ref: string, implicit: boolean): Promise<ObjectId | undefined> => {
1655
+ if (ref === EMPTY_TREE_ID) return undefined;
1656
+ // a tree's full id (as `git log -p` passes its commits' trees): read at once, its
1657
+ // entries kept for the comparison
1658
+ const trees = this.trees;
1659
+ if (/^[0-9a-f]{40}$/.test(ref)) {
1660
+ const known = trees.raw ? trees.raw(ref) : trees.entries?.(ref);
1661
+ if (known && (await known)) return ref;
1662
+ }
1663
+ try {
1664
+ return await this.resolveTreeId(ref);
1665
+ } catch (e) {
1666
+ if (implicit && e instanceof NoHeadError) return undefined;
1667
+ throw e;
1668
+ }
1669
+ };
1670
+ const a = await treeOf(oldRef, implicitHead);
1671
+ const b = await treeOf(newRef, false);
1672
+ await this.diffTreeSides(a, b, "", oldSide, newSide);
1673
+ return [oldSide, newSide];
1674
+ }
1675
+
1676
+ /**
1677
+ * tree-diff.c's walk of two trees in their stored order (git's `base_name_compare`): an
1678
+ * entry the same on both sides is skipped, two subtrees of one name are compared in turn,
1679
+ * and anything else is listed on its side (a subtree as its blobs).
1680
+ */
1681
+ private async diffTreeSides(
1682
+ a: ObjectId | undefined,
1683
+ b: ObjectId | undefined,
1684
+ prefix: string,
1685
+ oldSide: Map<string, Side>,
1686
+ newSide: Map<string, Side>,
1687
+ ): Promise<void> {
1688
+ if (a === b) return;
1689
+ if (this.trees.raw) return this.diffRawTrees(a, b, prefix, oldSide, newSide);
1690
+ const ea = a === undefined || a === EMPTY_TREE_ID ? [] : await this.treeEntries(a);
1691
+ const eb = b === undefined || b === EMPTY_TREE_ID ? [] : await this.treeEntries(b);
1692
+ let i = 0;
1693
+ let j = 0;
1694
+ while (i < ea.length || j < eb.length) {
1695
+ const x = ea[i];
1696
+ const y = eb[j];
1697
+ const order =
1698
+ x === undefined
1699
+ ? 1
1700
+ : y === undefined
1701
+ ? -1
1702
+ : compareEntryNames(x.name, isTreeMode(x.mode), y.name, isTreeMode(y.mode));
1703
+ if (order < 0) {
1704
+ const e = x as TreeEntry;
1705
+ await this.addSide(e, prefix ? `${prefix}/${e.name}` : e.name, oldSide);
1706
+ i++;
1707
+ } else if (order > 0) {
1708
+ const e = y as TreeEntry;
1709
+ await this.addSide(e, prefix ? `${prefix}/${e.name}` : e.name, newSide);
1710
+ j++;
1711
+ } else {
1712
+ const xe = x as TreeEntry;
1713
+ const ye = y as TreeEntry;
1714
+ i++;
1715
+ j++;
1716
+ // tree-diff.c compares the modes its walk reads: canonical, as the tree store reads
1717
+ // them (100664 is 100644)
1718
+ if (xe.id === ye.id && xe.mode === ye.mode) continue;
1719
+ const path = prefix ? `${prefix}/${xe.name}` : xe.name;
1720
+ if (isTreeMode(xe.mode) && isTreeMode(ye.mode)) {
1721
+ await this.diffTreeSides(xe.id, ye.id, path, oldSide, newSide);
1722
+ continue;
1723
+ }
1724
+ await this.addSide(xe, path, oldSide);
1725
+ await this.addSide(ye, path, newSide);
1726
+ }
1727
+ }
1728
+ }
1729
+
1730
+ /**
1731
+ * {@link diffTreeSides} over the trees' stored bytes: an entry the same on both sides is
1732
+ * passed over without being decoded (a missing tree reads as empty, as `treeEntries` has it)
1733
+ */
1734
+ private async diffRawTrees(
1735
+ a: ObjectId | undefined,
1736
+ b: ObjectId | undefined,
1737
+ prefix: string,
1738
+ oldSide: Map<string, Side>,
1739
+ newSide: Map<string, Side>,
1740
+ ): Promise<void> {
1741
+ if (a === b) return;
1742
+ const trees = this.trees;
1743
+ const read = async (id: ObjectId | undefined) =>
1744
+ id === undefined || id === EMPTY_TREE_ID ? NO_BYTES : ((await trees.raw?.(id)) ?? NO_BYTES);
1745
+ const x = new TreeEntryCursor(await read(a));
1746
+ const y = new TreeEntryCursor(await read(b));
1747
+ const pathOf = (name: string) => (prefix ? `${prefix}/${name}` : name);
1748
+ while (!x.done || !y.done) {
1749
+ const order = x.done ? 1 : y.done ? -1 : x.compare(y);
1750
+ if (order < 0) {
1751
+ await this.addRawSide(x, pathOf(x.name()), oldSide);
1752
+ x.next();
1753
+ } else if (order > 0) {
1754
+ await this.addRawSide(y, pathOf(y.name()), newSide);
1755
+ y.next();
1756
+ } else {
1757
+ if (!x.sameAs(y)) {
1758
+ const path = pathOf(x.name());
1759
+ if (x.isTree && y.isTree) await this.diffRawTrees(x.id(), y.id(), path, oldSide, newSide);
1760
+ else {
1761
+ await this.addRawSide(x, path, oldSide);
1762
+ await this.addRawSide(y, path, newSide);
1763
+ }
1764
+ }
1765
+ x.next();
1766
+ y.next();
1767
+ }
1768
+ }
1769
+ }
1770
+
1771
+ /** The entry a cursor is on, on one side: a blob as itself, a subtree as its blobs */
1772
+ private async addRawSide(
1773
+ c: TreeEntryCursor,
1774
+ path: string,
1775
+ side: Map<string, Side>,
1776
+ ): Promise<void> {
1777
+ if (c.isTree) await this.collectTreeEntries(c.id(), path, side);
1778
+ else side.set(path, { mode: c.mode, id: c.id() });
1779
+ }
1780
+
1781
+ /** A tree entry on one side: a blob as itself, a subtree as its blobs */
1782
+ private async addSide(e: TreeEntry, path: string, side: Map<string, Side>): Promise<void> {
1783
+ if (isTreeMode(e.mode)) await this.collectTreeEntries(e.id, path, side);
1784
+ else side.set(path, { mode: e.mode, id: e.id });
1785
+ }
1786
+
1787
+ /**
1788
+ * The index's stage-0 entries (intent-to-add ones left out: not in the index yet), and the
1789
+ * stages of its conflicted paths
1790
+ */
1791
+ private async indexSide(): Promise<{
1792
+ sides: Map<string, Side>;
1793
+ unmerged: Map<string, Map<number, StageEntry>>;
1794
+ }> {
1795
+ const sides = new Map<string, Side>();
1796
+ const unmerged = new Map<string, Map<number, StageEntry>>();
1797
+ for await (const entry of this.staging.entries()) {
1798
+ if (entry.stage !== 0) {
1799
+ let stages = unmerged.get(entry.path);
1800
+ if (!stages) {
1801
+ stages = new Map();
1802
+ unmerged.set(entry.path, stages);
1803
+ }
1804
+ stages.set(entry.stage, entry);
199
1805
  continue;
200
1806
  }
1807
+ if (entry.intentToAdd && !this.intentToAddVisible) continue;
1808
+ sides.set(entry.path, { mode: entry.mode, id: entry.objectId });
1809
+ }
1810
+ return { sides, unmerged };
1811
+ }
201
1812
 
202
- if (!oldPaths.has(path)) {
203
- entries.push(createAddEntry(path, newEntry.id, newEntry.mode as FileModeValue));
1813
+ /**
1814
+ * The worktree as `diff-files` and `diff-index` see it: each index entry's file, its
1815
+ * stat-clean entries taken from the index, changed ones read and hashed as `git add` would
1816
+ * store them; deleted files left out. A conflicted path's stages are handed back (and,
1817
+ * with `unmergedAsFiles`, its file is taken as diff-index takes it, against the lowest
1818
+ * stage); `compare` gives the worktree side of any entry.
1819
+ */
1820
+ private async worktreeSide(
1821
+ worktree: Worktree,
1822
+ unmergedAsFiles: boolean,
1823
+ changedOnly?: Map<string, Side>,
1824
+ ): Promise<{
1825
+ sides: Map<string, Side>;
1826
+ unmerged: Map<string, Map<number, StageEntry>>;
1827
+ compare: WorktreeCompare;
1828
+ }> {
1829
+ const sides = new Map<string, Side>();
1830
+ const unmerged = new Map<string, Map<number, StageEntry>>();
1831
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
1832
+ const indexTime = this.staging.getUpdateTime();
1833
+ const ignoreOf = await this.submoduleIgnoreOf();
1834
+ const compareWith = async (
1835
+ entry: StageEntry,
1836
+ current?: WorktreeEntry | null,
1837
+ ): Promise<Side | undefined> => {
1838
+ const indexSide: Side = { mode: entry.mode, id: entry.objectId };
1839
+ if (entry.skipWorktree || entry.assumeValid) return indexSide;
1840
+ const ignore = entry.mode === GITLINK ? ignoreOf(entry.path) : undefined;
1841
+ if (entry.mode === GITLINK && ignore === "all") return indexSide;
1842
+ const result = await compareWithWorktree(worktree, entry, { trust, indexTime }, current);
1843
+ if (result.kind === "deleted") return undefined;
1844
+ const mode = result.worktreeMode ?? entry.mode;
1845
+ if (mode === GITLINK) {
1846
+ const id = result.hashedId ?? entry.objectId;
1847
+ // a populated submodule with changes of its own: "-dirty" (untracked files count
1848
+ // only with diff.ignoreSubmodules=none, as git's default ignores them)
1849
+ let dirty = false;
1850
+ const dirt: SubmoduleDirt = {};
1851
+ // match_stat_with_submodule: one at another commit only with dirty_submodules
1852
+ if (
1853
+ entry.mode === GITLINK &&
1854
+ ignore !== "dirty" &&
1855
+ (this.dirtyThisCall || id === entry.objectId) &&
1856
+ result.worktreeEntry?.isDirectory
1857
+ ) {
1858
+ const found = await readSubmoduleDirt(worktree, entry.path, ignore !== "none");
1859
+ if (found.modified) dirt.modified = true;
1860
+ if (ignore === "none" && found.untracked) dirt.untracked = true;
1861
+ dirty = !!dirt.modified || !!dirt.untracked;
1862
+ }
1863
+ // ie_match_stat of a gitlink: another commit checked out than the entry's
1864
+ const moved = entry.mode === GITLINK && mode === GITLINK && id !== entry.objectId;
1865
+ if (!dirty) {
1866
+ if (!result.kind) return indexSide;
1867
+ if (!moved) return { mode, id };
1868
+ // its id is no stored object's to git (oid_valid unset): the diffstat compares
1869
+ // the "Subproject commit" lines, which may hold no change
1870
+ const content = encoder.encode(`Subproject commit ${id}\n`);
1871
+ return { mode, id, unknownId: true, read: async () => content };
1872
+ }
1873
+ const unknown = moved ? { unknownId: true } : {};
1874
+ const content = encoder.encode(`Subproject commit ${id}-dirty\n`);
1875
+ return { mode, id, dirty, dirt, ...unknown, read: async () => content };
204
1876
  }
1877
+ if (!result.kind && !entry.intentToAdd) return indexSide;
1878
+ const path = entry.path;
1879
+ const id = result.hashedId ?? (await worktree.computeHash(path));
1880
+ if (!entry.intentToAdd && id === entry.objectId && mode === entry.mode) return indexSide;
1881
+ let content: Promise<Uint8Array> | undefined;
1882
+ const read = () => {
1883
+ content ??= readCleanContent(worktree, path);
1884
+ return content;
1885
+ };
1886
+ return { mode, id, read };
1887
+ };
1888
+ const compare: WorktreeCompare = (entry) => compareWith(entry);
1889
+ // the stat pass: the files of the stage-0 entries compared, stat'ed a chunk at a time
1890
+ const stated = (entry: StageEntry) =>
1891
+ entry.stage === 0 &&
1892
+ !entry.skipWorktree &&
1893
+ !entry.assumeValid &&
1894
+ entry.mode !== GITLINK &&
1895
+ this.matches(entry.path);
1896
+ for await (const { item: entry, current } of withWorktreeEntries(
1897
+ worktree,
1898
+ this.staging.entries(),
1899
+ stated,
1900
+ )) {
1901
+ if (entry.stage !== 0) {
1902
+ let stages = unmerged.get(entry.path);
1903
+ if (!stages) {
1904
+ stages = new Map();
1905
+ unmerged.set(entry.path, stages);
1906
+ }
1907
+ stages.set(entry.stage, entry);
1908
+ continue;
1909
+ }
1910
+ if (!this.matches(entry.path)) continue;
1911
+ const side = await compareWith(entry, current);
1912
+ if (changedOnly && !entry.intentToAdd) {
1913
+ // diff-files: an entry its file still holds is no change on either side, left out
1914
+ // of both (the index side is the entry, as `indexSide` gives it)
1915
+ if (side && side.id === entry.objectId && side.mode === entry.mode && !side.dirty) {
1916
+ continue;
1917
+ }
1918
+ changedOnly.set(entry.path, { mode: entry.mode, id: entry.objectId });
1919
+ }
1920
+ if (!side) continue;
1921
+ if (entry.intentToAdd && side.id === entry.objectId && !side.read) continue;
1922
+ sides.set(entry.path, side);
205
1923
  }
1924
+ if (unmergedAsFiles) {
1925
+ for (const [path, stages] of unmerged) {
1926
+ if (!this.matches(path)) continue;
1927
+ const lowest = stages.get(1) ?? stages.get(2) ?? stages.get(3);
1928
+ if (!lowest) continue;
1929
+ // the stage's stat is no file's: the file is read and hashed
1930
+ const side = await compare(lowest);
1931
+ if (side) sides.set(path, side);
1932
+ }
1933
+ }
1934
+ return { sides, unmerged, compare };
1935
+ }
206
1936
 
207
- // Sort entries by path for consistent output
208
- entries.sort((a, b) => {
209
- const pathA = a.newPath ?? a.oldPath ?? "";
210
- const pathB = b.newPath ?? b.oldPath ?? "";
211
- return pathA.localeCompare(pathB);
212
- });
1937
+ /**
1938
+ * The tree of a commit-ish or a tree id; throws `NoHeadError` for an unborn HEAD and
1939
+ * `RefNotFoundError` for anything else that names no commit or tree.
1940
+ */
1941
+ private async resolveTreeId(refOrId: string): Promise<ObjectId> {
1942
+ // a full object id names that object, as get_oid takes it: no ref is looked up
1943
+ if (/^[0-9a-f]{40}$/.test(refOrId)) {
1944
+ const tree = await this.revisionResolver()
1945
+ .peelToType(refOrId, "tree")
1946
+ .catch(() => undefined);
1947
+ if (tree !== undefined) return tree;
1948
+ }
1949
+ let id: ObjectId;
1950
+ try {
1951
+ id = await this.resolveRevision(refOrId);
1952
+ } catch (e) {
1953
+ if (/^[0-9a-f]{40}$/.test(refOrId) && (await this.isTree(refOrId))) return refOrId;
1954
+ if (refOrId === "HEAD") throw new NoHeadError("HEAD cannot be resolved");
1955
+ if (e instanceof RefNotFoundError) {
1956
+ throw new RefNotFoundError(refOrId, `bad revision '${refOrId}'`);
1957
+ }
1958
+ throw e;
1959
+ }
1960
+ // a commit's tree, a tree, or a tag of either
1961
+ const tree = await this.revisionResolver().peelToType(id, "tree");
1962
+ if (tree !== undefined) return tree;
1963
+ throw new RefNotFoundError(refOrId, `bad revision '${refOrId}'`);
1964
+ }
213
1965
 
214
- return entries;
1966
+ private async isTree(id: ObjectId): Promise<boolean> {
1967
+ try {
1968
+ return await this.trees.has(id);
1969
+ } catch {
1970
+ return false;
1971
+ }
215
1972
  }
216
1973
 
217
1974
  /**
@@ -220,19 +1977,16 @@ export class DiffCommand extends GitCommand<DiffEntry[]> {
220
1977
  private async collectTreeEntries(
221
1978
  treeId: ObjectId,
222
1979
  prefix: string,
223
- entries: Map<string, TreeEntry>,
1980
+ entries: Map<string, Side>,
224
1981
  ): Promise<void> {
225
1982
  const TREE_MODE = 0o40000;
226
-
227
- for await (const entry of this.trees.loadTree(treeId)) {
1983
+ for (const entry of await this.treeEntries(treeId)) {
228
1984
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
229
-
230
- if (entry.mode === TREE_MODE) {
231
- // Recurse into subtree
1985
+ if ((entry.mode & S_IFMT) === TREE_MODE) {
232
1986
  await this.collectTreeEntries(entry.id, path, entries);
233
1987
  } else {
234
- // Blob entry
235
- entries.set(path, entry);
1988
+ // the mode as git's tree walk reads it (canon_mode), as the tree store reads it
1989
+ entries.set(path, { mode: entry.mode, id: entry.id });
236
1990
  }
237
1991
  }
238
1992
  }
@@ -255,3 +2009,37 @@ export function formatDiffEntry(entry: DiffEntry): string {
255
2009
  return `C${entry.score ?? 0}\t${entry.oldPath}\t${entry.newPath}`;
256
2010
  }
257
2011
  }
2012
+
2013
+ /** `path` relative to the host directory `base`, its `.` and `..` segments resolved */
2014
+ function resolveHostPath(base: string, path: string): string {
2015
+ const parts = base.replace(/\/+$/, "").split("/");
2016
+ for (const part of path.split("/")) {
2017
+ if (part === "..") {
2018
+ if (parts.length > 1) parts.pop();
2019
+ } else if (part !== "." && part !== "") parts.push(part);
2020
+ }
2021
+ return parts.join("/") || "/";
2022
+ }
2023
+
2024
+ /** The empty tree's content */
2025
+ const NO_BYTES = new Uint8Array(0);
2026
+
2027
+ /** Whether a tree entry's mode is a subtree's */
2028
+ function isTreeMode(mode: number): boolean {
2029
+ return (mode & S_IFMT) === 0o40000;
2030
+ }
2031
+
2032
+ /**
2033
+ * git's `base_name_compare` over names as trees hold them (decoded as {@link decodeGitPath}
2034
+ * decodes them): byte order, a subtree's name compared as if it ended in `/`.
2035
+ */
2036
+ function compareEntryNames(a: string, aTree: boolean, b: string, bTree: boolean): number {
2037
+ const n = a.length < b.length ? a.length : b.length;
2038
+ for (let k = 0; k < n; k++) {
2039
+ if (a.charCodeAt(k) !== b.charCodeAt(k)) return compareGitPaths(a, b);
2040
+ }
2041
+ // past the common part: the next character's code orders as its first byte would
2042
+ const ca = a.length > n ? a.charCodeAt(n) : aTree ? 0x2f : 0;
2043
+ const cb = b.length > n ? b.charCodeAt(n) : bTree ? 0x2f : 0;
2044
+ return ca - cb;
2045
+ }