@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
@@ -0,0 +1,1603 @@
1
+ /**
2
+ * The applier of `git apply` (apply.c): finds where each hunk applies (offsets, context
3
+ * reduction, whitespace fuzz), applies binary patches, checks the preimage against the
4
+ * worktree and the index, falls back to a three-way merge, and writes the results, the
5
+ * rejects and the index. The storage it works on is behind {@link ApplyIO}.
6
+ */
7
+
8
+ import { decodeGitBinaryDelta } from "@statewalker/vcs-utils";
9
+ import { statSummary } from "../../results/diff-output.js";
10
+ import { ApplyParser, linelen } from "./apply-parse.js";
11
+ import {
12
+ BINARY_DELTA,
13
+ BINARY_LITERAL,
14
+ type FilePatch,
15
+ isGitlink,
16
+ isLink,
17
+ isRegular,
18
+ newFilePatch,
19
+ S_IFMT,
20
+ S_IFREG,
21
+ } from "./apply-types.js";
22
+ import { bytesToLatin1, cQuote, latin1ToBytes } from "./latin1.js";
23
+ import { isGitSpace, WS_BLANK_AT_EOF, wsBlankLine, wsFixCopy } from "./whitespace.js";
24
+
25
+ const LINE_COMMON = 1;
26
+ const LINE_PATCHED = 2;
27
+
28
+ interface Line {
29
+ len: number;
30
+ hash: number;
31
+ flag: number;
32
+ /** The line itself (lines of a {@link Target} only) */
33
+ text?: string;
34
+ /**
35
+ * Bytes of the image after the line that belong to no line (a postimage whose lines
36
+ * were cut keeps them in its buffer, as git's `update_image` copies it whole)
37
+ */
38
+ extra?: string;
39
+ }
40
+
41
+ interface Image {
42
+ buf: string;
43
+ lines: Line[];
44
+ }
45
+
46
+ function hashLine(s: string, start: number, len: number): number {
47
+ let h = 0;
48
+ for (let i = 0; i < len; i++) {
49
+ const c = s.charCodeAt(start + i);
50
+ if (!isGitSpace(c)) h = (Math.imul(h, 3) + (c & 0xff)) >>> 0;
51
+ }
52
+ return h & 0xffffff;
53
+ }
54
+
55
+ function addLine(img: Image, s: string, start: number, len: number, flag: number): void {
56
+ img.lines.push({ len, hash: hashLine(s, start, len), flag });
57
+ }
58
+
59
+ function prepareImage(buf: string, lineTable: boolean): Image {
60
+ const img: Image = { buf, lines: [] };
61
+ if (!lineTable) return img;
62
+ let cp = 0;
63
+ while (cp < buf.length) {
64
+ const nl = buf.indexOf("\n", cp);
65
+ const next = nl < 0 ? buf.length : nl + 1;
66
+ addLine(img, buf, cp, next - cp, 0);
67
+ cp = next;
68
+ }
69
+ return img;
70
+ }
71
+
72
+ function removeFirstLine(img: Image): void {
73
+ const first = img.lines.shift() as Line;
74
+ img.buf = img.buf.slice(first.len);
75
+ }
76
+
77
+ function removeLastLine(img: Image): void {
78
+ const last = img.lines.pop() as Line;
79
+ img.buf = img.buf.slice(0, img.buf.length - last.len);
80
+ }
81
+
82
+ const isSpaceAt = (s: string, i: number) => isGitSpace(s.charCodeAt(i));
83
+
84
+ /**
85
+ * The lines of a target image in a gap buffer: replacing lines costs the distance from
86
+ * the previous replacement, not the size of the image, so hunks applied in order make
87
+ * the whole patch linear (git's `update_image` moves the rest of the image each time).
88
+ */
89
+ class LineTable {
90
+ private items: (Line | undefined)[];
91
+ private gapStart: number;
92
+ private gapEnd: number;
93
+
94
+ constructor(lines: Line[]) {
95
+ this.items = lines;
96
+ this.gapStart = lines.length;
97
+ this.gapEnd = lines.length;
98
+ }
99
+
100
+ get length(): number {
101
+ return this.items.length - (this.gapEnd - this.gapStart);
102
+ }
103
+
104
+ at(i: number): Line {
105
+ return (
106
+ i < this.gapStart ? this.items[i] : this.items[i + this.gapEnd - this.gapStart]
107
+ ) as Line;
108
+ }
109
+
110
+ /** Replaces `remove` lines at `at` with `insert`. */
111
+ splice(at: number, remove: number, insert: Line[]): void {
112
+ const items = this.items;
113
+ if (at < this.gapStart) {
114
+ while (this.gapStart > at) items[--this.gapEnd] = items[--this.gapStart];
115
+ } else {
116
+ while (this.gapStart < at) items[this.gapStart++] = items[this.gapEnd++];
117
+ }
118
+ for (let i = 0; i < remove; i++) items[this.gapEnd + i] = undefined;
119
+ this.gapEnd += remove;
120
+ if (this.gapEnd - this.gapStart < insert.length) {
121
+ const gap = insert.length + (this.length >> 1) + 16;
122
+ const grown: (Line | undefined)[] = new Array(this.length + gap);
123
+ for (let i = 0; i < this.gapStart; i++) grown[i] = items[i];
124
+ const tail = items.length - this.gapEnd;
125
+ for (let i = 0; i < tail; i++) grown[grown.length - tail + i] = items[this.gapEnd + i];
126
+ this.gapEnd = grown.length - tail;
127
+ this.items = grown;
128
+ }
129
+ for (const line of insert) this.items[this.gapStart++] = line;
130
+ }
131
+ }
132
+
133
+ /** The image a patch is applied to (`struct image` of the preimage file). */
134
+ class Target {
135
+ lines: LineTable;
136
+ private text: string | undefined;
137
+ /** Bytes before the first line that belong to no line (see {@link Line.extra}) */
138
+ private lead = "";
139
+
140
+ constructor(buf: string, lineTable: boolean) {
141
+ const lines: Line[] = [];
142
+ if (lineTable) {
143
+ let cp = 0;
144
+ while (cp < buf.length) {
145
+ const nl = buf.indexOf("\n", cp);
146
+ const next = nl < 0 ? buf.length : nl + 1;
147
+ lines.push({
148
+ len: next - cp,
149
+ hash: hashLine(buf, cp, next - cp),
150
+ flag: 0,
151
+ text: buf.slice(cp, next),
152
+ });
153
+ cp = next;
154
+ }
155
+ }
156
+ this.lines = new LineTable(lines);
157
+ this.text = buf;
158
+ }
159
+
160
+ /** The whole content. */
161
+ get buf(): string {
162
+ if (this.text === undefined) {
163
+ const parts: string[] = [this.lead];
164
+ for (let i = 0; i < this.lines.length; i++) {
165
+ const line = this.lines.at(i);
166
+ parts.push(line.text as string);
167
+ if (line.extra) parts.push(line.extra);
168
+ }
169
+ this.text = parts.join("");
170
+ }
171
+ return this.text;
172
+ }
173
+
174
+ /** Replaces the content, without a line table (a binary or merged result). */
175
+ set buf(content: string) {
176
+ this.text = content;
177
+ this.lines = new LineTable([]);
178
+ this.lead = "";
179
+ }
180
+
181
+ lineText(i: number): string {
182
+ return this.lines.at(i).text as string;
183
+ }
184
+
185
+ /**
186
+ * Whether the content from line `lno` on starts with `s` (`exact`: is `s`), git's
187
+ * `memcmp` of the preimage at the line's offset.
188
+ */
189
+ textStartsWith(lno: number, s: string, exact: boolean): boolean {
190
+ let pos = 0;
191
+ const n = this.lines.length;
192
+ for (let i = lno; i < n; i++) {
193
+ if (pos >= s.length) return !exact;
194
+ const t = this.lineText(i);
195
+ const rest = s.length - pos;
196
+ if (t.length > rest) return !exact && t.slice(0, rest) === s.slice(pos);
197
+ if (!s.startsWith(t, pos)) return false;
198
+ pos += t.length;
199
+ }
200
+ return pos === s.length;
201
+ }
202
+
203
+ /**
204
+ * Replaces `remove` lines at `at` with `insert`, then `extra` bytes that belong to no
205
+ * line (they follow the last inserted line, or the line before `at`).
206
+ */
207
+ replaceLines(at: number, remove: number, insert: Line[], extra = ""): void {
208
+ this.lines.splice(at, remove, insert);
209
+ if (extra) {
210
+ const end = at + insert.length;
211
+ if (end > 0) {
212
+ const line = this.lines.at(end - 1);
213
+ line.extra = (line.extra ?? "") + extra;
214
+ } else this.lead += extra;
215
+ }
216
+ this.text = undefined;
217
+ }
218
+ }
219
+
220
+ /** An index entry as the applier sees it (stage 0 unless said otherwise). */
221
+ export interface ApplyIndexEntry {
222
+ mode: number;
223
+ oid: string;
224
+ intentToAdd?: boolean;
225
+ stage?: number;
226
+ }
227
+
228
+ /** The storage `git apply` reads and writes; names are binary strings. */
229
+ export interface ApplyIO {
230
+ /** lstat of a worktree path: its mode (S_IFREG|perm, S_IFLNK, S_IFDIR), none when absent */
231
+ lstat(name: string): Promise<{ mode: number } | undefined>;
232
+ /**
233
+ * The worktree file's content as git would stage it (a link: its target); `keepCrlf`
234
+ * skips the line-ending conversion (`CONV_EOL_KEEP_CRLF`), otherwise CRLF in the index
235
+ * does not hold it back (`CONV_EOL_RENORMALIZE`)
236
+ */
237
+ readWorktree(name: string, mode: number, keepCrlf: boolean): Promise<string | undefined>;
238
+ /**
239
+ * Why lstat of a missing worktree path fails, as strerror (`ENOTDIR` when a leading path
240
+ * is a file); "No such file or directory" when not given
241
+ */
242
+ missingReason?(name: string): Promise<string>;
243
+ /** Whether a leading directory of the path is a symlink in the worktree */
244
+ hasSymlinkLeadingPath(name: string): Promise<boolean>;
245
+ /** The mode git would stage for the worktree file (`ce_mode_from_stat`) */
246
+ modeFromStat(name: string, entry: ApplyIndexEntry | undefined, stMode: number): number;
247
+ /** Whether the worktree file still matches the index entry (`ie_match_stat`) */
248
+ matchesIndex(name: string, entry: ApplyIndexEntry): Promise<boolean>;
249
+ /** Checks the entry out to the worktree (`checkout_target`); false on failure */
250
+ checkout(name: string, entry: ApplyIndexEntry): Promise<boolean>;
251
+ readBlob(oid: string): Promise<string | undefined>;
252
+ hasObject(oid: string): Promise<boolean>;
253
+ writeBlob(content: string): Promise<string>;
254
+ hashBlob(content: string): Promise<string>;
255
+ /** The blob a (possibly abbreviated) id names */
256
+ resolveBlob(prefix: string): Promise<string | undefined>;
257
+ /** `ll_merge` of three blobs; conflicts > 0 for a conflicted result, undefined on failure */
258
+ merge(
259
+ name: string,
260
+ base: string,
261
+ ours: string,
262
+ theirs: string,
263
+ variant: "ours" | "theirs" | "union" | undefined,
264
+ ): Promise<{ content: string; conflicts: number; binary?: boolean } | undefined>;
265
+ /**
266
+ * Removes a worktree file (a gitlink: its directory when empty) and, with `rmdirEmpty`,
267
+ * the directories it leaves empty (`remove_or_warn`, `remove_path`); a warning on failure
268
+ */
269
+ removeWorktree(name: string, mode: number, rmdirEmpty: boolean): Promise<string | undefined>;
270
+ /** Writes a worktree file (smudged), creating directories; an error message on failure */
271
+ createWorktree(name: string, mode: number, content: string): Promise<string | undefined>;
272
+ writeReject(name: string, content: string): Promise<void>;
273
+ /** Stat data of a written file for its index entry */
274
+ statOf(name: string): Promise<Record<string, number> | undefined>;
275
+ /** Whether symlinks can be created (`core.symlinks`) */
276
+ hasSymlinks: boolean;
277
+ trustExecutableBit: boolean;
278
+ /** Whether the path is safe to have in the index (`verify_path`) */
279
+ verifyPath(name: string, mode: number): boolean;
280
+ }
281
+
282
+ type FnState = FilePatch | "deleted" | "to-be-deleted";
283
+
284
+ /** Options of {@link ApplyEngine.applyAll}. */
285
+ export interface ApplyInput {
286
+ /** The patch bytes as a binary string */
287
+ text: string;
288
+ /** Its name in messages: the file name, `<stdin>` by default */
289
+ name: string;
290
+ /** Whether it was named on the command line (whitespace default mode per file) */
291
+ fromFile: boolean;
292
+ }
293
+
294
+ /** One applier run (apply.c's `apply_state` plus the patch list). */
295
+ export class ApplyEngine extends ApplyParser {
296
+ threeway = false;
297
+ cached = false;
298
+ checkIndex = false;
299
+ updateIndex = false;
300
+ itaOnly = false;
301
+ unsafePaths = false;
302
+ applyWithReject = false;
303
+ allowOverlap = false;
304
+ noAdd = false;
305
+ unidiffZero = false;
306
+ inaccurateEof = false;
307
+ recount = false;
308
+ allowEmpty = false;
309
+ diffstat = false;
310
+ numstat = false;
311
+ summary = false;
312
+ lineTermination = "\n";
313
+ pContext = Number.MAX_SAFE_INTEGER;
314
+ wsIgnoreChange = false;
315
+ whitespaceOptionGiven = false;
316
+ configWhitespace?: string;
317
+ mergeVariant?: "ours" | "theirs" | "union";
318
+ appliedAfterFixingWs = 0;
319
+ maxChange = 0;
320
+ maxLen = 0;
321
+ /** Paths of the patch list written with conflicts, for the caller (am) */
322
+ conflictedPaths: string[] = [];
323
+
324
+ private fnTable = new Map<string, FnState>();
325
+ private removedSymlinks = new Set<string>();
326
+ private keptSymlinks = new Set<string>();
327
+ /** Index changes: a name's entries (all stages) replaced, or removed (empty list) */
328
+ readonly indexChanges = new Map<
329
+ string,
330
+ (ApplyIndexEntry & { stat?: Record<string, number> })[]
331
+ >();
332
+
333
+ constructor(
334
+ private readonly io: ApplyIO,
335
+ private readonly indexOf: (name: string) => ApplyIndexEntry | undefined,
336
+ private readonly wsRuleOfName: (name: string) => Promise<number>,
337
+ private readonly wildmatch: (pattern: string, text: string) => boolean,
338
+ /** The names of the stage-0 index entries (for the file/directory checks) */
339
+ private readonly indexNames: () => Iterable<string> = () => [],
340
+ ) {
341
+ super();
342
+ }
343
+
344
+ private sortedIndexNames?: string[];
345
+
346
+ /** Whether the name is an entry of the index as changed so far (at the stage). */
347
+ private hasIndexName(name: string, stage: number): boolean {
348
+ const changed = this.indexChanges.get(name);
349
+ if (changed) return changed.some((e) => (e.stage ?? 0) === stage);
350
+ return stage === 0 && this.indexOf(name) !== undefined;
351
+ }
352
+
353
+ /**
354
+ * `check_file_directory_conflict` of `add_index_entry` without `ADD_CACHE_OK_TO_REPLACE`:
355
+ * whether an entry (at the stage) of the index as changed so far is below the name
356
+ * (`has_file_name`) or one of its leading directories (`has_dir_name`).
357
+ */
358
+ private fileDirectoryConflict(name: string, stage: number): boolean {
359
+ for (let at = name.lastIndexOf("/"); at > 0; at = name.lastIndexOf("/", at - 1)) {
360
+ if (this.hasIndexName(name.slice(0, at), stage)) return true;
361
+ }
362
+ const prefix = `${name}/`;
363
+ for (const [n, entries] of this.indexChanges) {
364
+ if (n.startsWith(prefix) && entries.some((e) => (e.stage ?? 0) === stage)) return true;
365
+ }
366
+ if (stage !== 0) return false;
367
+ if (!this.sortedIndexNames) {
368
+ this.sortedIndexNames = [...this.indexNames()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
369
+ }
370
+ const names = this.sortedIndexNames;
371
+ let lo = 0;
372
+ let hi = names.length;
373
+ while (lo < hi) {
374
+ const mid = (lo + hi) >> 1;
375
+ if ((names[mid] as string) < prefix) lo = mid + 1;
376
+ else hi = mid;
377
+ }
378
+ for (let i = lo; i < names.length && (names[i] as string).startsWith(prefix); i++) {
379
+ if (!this.indexChanges.has(names[i] as string)) return true;
380
+ }
381
+ return false;
382
+ }
383
+
384
+ /** `add_index_entry(..., ADD_CACHE_OK_TO_ADD)` of entries at one name; 0 or -1. */
385
+ private addIndexEntries(
386
+ name: string,
387
+ entries: (ApplyIndexEntry & { stat?: Record<string, number> })[],
388
+ ): number {
389
+ for (const e of entries) {
390
+ if (this.fileDirectoryConflict(name, e.stage ?? 0)) {
391
+ this.error(`'${name}' appears as both a file and as a directory`);
392
+ return this.error(`unable to add cache entry for ${name}`);
393
+ }
394
+ }
395
+ this.setIndex(name, entries);
396
+ return 0;
397
+ }
398
+
399
+ private indexEntry(name: string): ApplyIndexEntry | undefined {
400
+ const changed = this.indexChanges.get(name);
401
+ if (changed) return changed.find((e) => !e.stage);
402
+ return this.indexOf(name);
403
+ }
404
+
405
+ // ---------------------------------------------------------------- matching
406
+
407
+ private updatePrePostImages(preimage: Image, postimage: Image, buf: string): void {
408
+ const fixed = prepareImage(buf, true);
409
+ for (let i = 0; i < fixed.lines.length; i++)
410
+ (fixed.lines[i] as Line).flag = preimage.lines[i]?.flag ?? 0;
411
+ preimage.buf = fixed.buf;
412
+ preimage.lines = fixed.lines;
413
+ let fixedAt = 0;
414
+ let insertPos = 0;
415
+ let reduced = 0;
416
+ let ctx = 0;
417
+ let post = postimage.buf;
418
+ for (let i = 0; i < postimage.lines.length; i++) {
419
+ const line = postimage.lines[i] as Line;
420
+ if (!(line.flag & LINE_COMMON)) {
421
+ insertPos += line.len;
422
+ continue;
423
+ }
424
+ while (ctx < preimage.lines.length && !((preimage.lines[ctx] as Line).flag & LINE_COMMON)) {
425
+ fixedAt += (preimage.lines[ctx] as Line).len;
426
+ ctx++;
427
+ }
428
+ if (preimage.lines.length <= ctx) {
429
+ // the line's bytes stay in the buffer (strbuf_splice is not run for it)
430
+ reduced++;
431
+ continue;
432
+ }
433
+ const lLen = (preimage.lines[ctx] as Line).len;
434
+ post =
435
+ post.slice(0, insertPos) +
436
+ preimage.buf.slice(fixedAt, fixedAt + lLen) +
437
+ post.slice(insertPos + line.len);
438
+ insertPos += lLen;
439
+ fixedAt += lLen;
440
+ line.len = lLen;
441
+ ctx++;
442
+ }
443
+ postimage.buf = post;
444
+ postimage.lines.length -= reduced;
445
+ }
446
+
447
+ private lineByLineFuzzyMatch(
448
+ img: Target,
449
+ preimage: Image,
450
+ postimage: Image,
451
+ currentLno: number,
452
+ preimageLimit: number,
453
+ ): boolean {
454
+ let preoff = 0;
455
+ let i = 0;
456
+ const matched: string[] = [];
457
+ for (; i < preimageLimit; i++) {
458
+ const prelen = (preimage.lines[i] as Line).len;
459
+ const t = img.lineText(currentLno + i);
460
+ if (!fuzzyMatchLines(t, 0, t.length, preimage.buf, preoff, prelen)) return false;
461
+ matched.push(t);
462
+ preoff += prelen;
463
+ }
464
+ const preimageEof = preoff;
465
+ for (; i < preimage.lines.length; i++) preoff += (preimage.lines[i] as Line).len;
466
+ for (let b = preimageEof; b < preoff; b++) if (!isSpaceAt(preimage.buf, b)) return false;
467
+ const fixed = matched.join("") + preimage.buf.slice(preimageEof, preoff);
468
+ this.updatePrePostImages(preimage, postimage, fixed);
469
+ return true;
470
+ }
471
+
472
+ private matchFragment(
473
+ img: Target,
474
+ preimage: Image,
475
+ postimage: Image,
476
+ currentLno: number,
477
+ wsRule: number,
478
+ matchBeginning: boolean,
479
+ matchEnd: boolean,
480
+ ): boolean {
481
+ let preimageLimit: number;
482
+ if (preimage.lines.length + currentLno <= img.lines.length) {
483
+ preimageLimit = preimage.lines.length;
484
+ if (matchEnd && preimage.lines.length + currentLno !== img.lines.length) return false;
485
+ } else if (this.wsErrorAction === "fix" && wsRule & WS_BLANK_AT_EOF) {
486
+ preimageLimit = img.lines.length - currentLno;
487
+ } else return false;
488
+ if (matchBeginning && currentLno) return false;
489
+ for (let i = 0; i < preimageLimit; i++) {
490
+ const il = img.lines.at(currentLno + i);
491
+ if (il.flag & LINE_PATCHED || (preimage.lines[i] as Line).hash !== il.hash) return false;
492
+ }
493
+ if (preimageLimit === preimage.lines.length) {
494
+ if (img.textStartsWith(currentLno, preimage.buf, matchEnd)) return true;
495
+ } else {
496
+ let end = 0;
497
+ for (let i = 0; i < preimageLimit; i++) end += (preimage.lines[i] as Line).len;
498
+ let b = 0;
499
+ for (; b < end; b++) if (!isSpaceAt(preimage.buf, b)) break;
500
+ if (b === end) return false;
501
+ }
502
+ if (this.wsIgnoreChange) {
503
+ return this.lineByLineFuzzyMatch(img, preimage, postimage, currentLno, preimageLimit);
504
+ }
505
+ if (this.wsErrorAction !== "fix") return false;
506
+ let fixed = "";
507
+ let orig = 0;
508
+ let i = 0;
509
+ for (; i < preimageLimit; i++) {
510
+ const oldlen = (preimage.lines[i] as Line).len;
511
+ const a = wsFixCopy(preimage.buf.slice(orig, orig + oldlen), wsRule).text;
512
+ const b = wsFixCopy(img.lineText(currentLno + i), wsRule).text;
513
+ fixed += a;
514
+ if (a !== b) return false;
515
+ orig += oldlen;
516
+ }
517
+ for (; i < preimage.lines.length; i++) {
518
+ const oldlen = (preimage.lines[i] as Line).len;
519
+ const a = wsFixCopy(preimage.buf.slice(orig, orig + oldlen), wsRule).text;
520
+ for (let j = 0; j < a.length; j++) if (!isSpaceAt(a, j)) return false;
521
+ fixed += a;
522
+ orig += oldlen;
523
+ }
524
+ this.updatePrePostImages(preimage, postimage, fixed);
525
+ return true;
526
+ }
527
+
528
+ private findPos(
529
+ img: Target,
530
+ preimage: Image,
531
+ postimage: Image,
532
+ line: number,
533
+ wsRule: number,
534
+ matchBeginning: boolean,
535
+ matchEnd: boolean,
536
+ ): number {
537
+ const nr = img.lines.length;
538
+ if (this.allowOverlap && matchBeginning && matchEnd && nr - preimage.lines.length !== 0)
539
+ matchBeginning = false;
540
+ if (matchBeginning) line = 0;
541
+ else if (matchEnd) line = nr - preimage.lines.length;
542
+ if (line < 0 || line > nr) line = nr;
543
+ let backwardsLno = line;
544
+ let forwardsLno = line;
545
+ let currentLno = line;
546
+ for (let i = 0; ; i++) {
547
+ if (
548
+ this.matchFragment(img, preimage, postimage, currentLno, wsRule, matchBeginning, matchEnd)
549
+ )
550
+ return currentLno;
551
+ for (;;) {
552
+ if (backwardsLno === 0 && forwardsLno === nr) return -1;
553
+ if (i & 1) {
554
+ if (backwardsLno === 0) {
555
+ i++;
556
+ continue;
557
+ }
558
+ backwardsLno--;
559
+ currentLno = backwardsLno;
560
+ } else {
561
+ if (forwardsLno === nr) {
562
+ i++;
563
+ continue;
564
+ }
565
+ forwardsLno++;
566
+ currentLno = forwardsLno;
567
+ }
568
+ break;
569
+ }
570
+ }
571
+ }
572
+
573
+ private updateImage(img: Target, appliedPos: number, preimage: Image, postimage: Image): void {
574
+ let preimageLimit = preimage.lines.length;
575
+ if (preimageLimit > img.lines.length - appliedPos)
576
+ preimageLimit = img.lines.length - appliedPos;
577
+ const inserted: Line[] = [];
578
+ let off = 0;
579
+ for (const l of postimage.lines) {
580
+ inserted.push({
581
+ len: l.len,
582
+ hash: l.hash,
583
+ flag: this.allowOverlap ? l.flag : l.flag | LINE_PATCHED,
584
+ text: postimage.buf.slice(off, off + l.len),
585
+ });
586
+ off += l.len;
587
+ }
588
+ // the postimage's bytes past its lines (none unless its lines were cut): git copies the
589
+ // whole buffer, the bytes belong to no line of the image
590
+ img.replaceLines(appliedPos, preimageLimit, inserted, postimage.buf.slice(off));
591
+ }
592
+
593
+ private applyOneFragment(
594
+ img: Target,
595
+ frag: FilePatch["fragments"][number],
596
+ inaccurateEof: boolean,
597
+ wsRule: number,
598
+ nth: number,
599
+ ): boolean {
600
+ const patch = frag.patch;
601
+ let size = frag.size;
602
+ let old = "";
603
+ let newlines = "";
604
+ let newBlankLinesAtEnd = 0;
605
+ let foundNewBlankLinesAtEnd = 0;
606
+ let hunkLinenr = frag.linenr;
607
+ const preimage: Image = { buf: "", lines: [] };
608
+ const postimage: Image = { buf: "", lines: [] };
609
+ let at = 0;
610
+ while (size > 0) {
611
+ const len = linelen(patch, at, size);
612
+ if (!len) break;
613
+ let plen = len - 1;
614
+ if (len < size && patch[at + len] === "\\") plen--;
615
+ let first = patch[at] as string;
616
+ if (this.applyInReverse) {
617
+ if (first === "-") first = "+";
618
+ else if (first === "+") first = "-";
619
+ }
620
+ let addedBlankLine = false;
621
+ let isBlankContext = false;
622
+ const body = patch.slice(at + 1, at + 1 + Math.max(plen, 0));
623
+ switch (first) {
624
+ case "\n":
625
+ if (plen < 0) break;
626
+ old += "\n";
627
+ newlines += "\n";
628
+ addLine(preimage, "\n", 0, 1, LINE_COMMON);
629
+ addLine(postimage, "\n", 0, 1, LINE_COMMON);
630
+ isBlankContext = true;
631
+ break;
632
+ case " ":
633
+ case "-":
634
+ case "+": {
635
+ if (first === " " && plen && wsRule & WS_BLANK_AT_EOF && wsBlankLine(body))
636
+ isBlankContext = true;
637
+ if (first !== "+") {
638
+ addLine(preimage, body, 0, plen, first === " " ? LINE_COMMON : 0);
639
+ old += body;
640
+ if (first === "-") break;
641
+ }
642
+ if (first === "+" && this.noAdd) break;
643
+ let added: string;
644
+ if (first !== "+" || !this.whitespaceError || this.wsErrorAction !== "fix") {
645
+ added = body;
646
+ } else {
647
+ const f = wsFixCopy(body, wsRule);
648
+ added = f.text;
649
+ if (f.fixed) this.appliedAfterFixingWs++;
650
+ }
651
+ newlines += added;
652
+ addLine(postimage, added, 0, added.length, first === "+" ? 0 : LINE_COMMON);
653
+ if (first === "+" && wsRule & WS_BLANK_AT_EOF && wsBlankLine(body)) addedBlankLine = true;
654
+ break;
655
+ }
656
+ case "@":
657
+ case "\\":
658
+ break;
659
+ default:
660
+ if (this.verbosity > 0) this.error(`invalid start of line: '${first}'`);
661
+ return true;
662
+ }
663
+ if (addedBlankLine) {
664
+ if (!newBlankLinesAtEnd) foundNewBlankLinesAtEnd = hunkLinenr;
665
+ newBlankLinesAtEnd++;
666
+ } else if (!isBlankContext) newBlankLinesAtEnd = 0;
667
+ at += len;
668
+ size -= len;
669
+ hunkLinenr++;
670
+ }
671
+ if (inaccurateEof && old.endsWith("\n") && newlines.endsWith("\n")) {
672
+ old = old.slice(0, -1);
673
+ newlines = newlines.slice(0, -1);
674
+ (preimage.lines[preimage.lines.length - 1] as Line).len--;
675
+ (postimage.lines[postimage.lines.length - 1] as Line).len--;
676
+ }
677
+ let leading = frag.leading;
678
+ let trailing = frag.trailing;
679
+ let matchBeginning = !frag.oldpos || (frag.oldpos === 1 && !this.unidiffZero);
680
+ let matchEnd = !this.unidiffZero && !trailing;
681
+ let pos = frag.newpos ? frag.newpos - 1 : 0;
682
+ preimage.buf = old;
683
+ postimage.buf = newlines;
684
+ let appliedPos: number;
685
+ for (;;) {
686
+ appliedPos = this.findPos(img, preimage, postimage, pos, wsRule, matchBeginning, matchEnd);
687
+ if (appliedPos >= 0) break;
688
+ if (leading <= this.pContext && trailing <= this.pContext) break;
689
+ if (matchBeginning || matchEnd) {
690
+ matchBeginning = matchEnd = false;
691
+ continue;
692
+ }
693
+ if (leading >= trailing) {
694
+ removeFirstLine(preimage);
695
+ removeFirstLine(postimage);
696
+ pos--;
697
+ leading--;
698
+ }
699
+ if (trailing > leading) {
700
+ removeLastLine(preimage);
701
+ removeLastLine(postimage);
702
+ trailing--;
703
+ }
704
+ }
705
+ if (appliedPos >= 0) {
706
+ if (
707
+ newBlankLinesAtEnd &&
708
+ preimage.lines.length + appliedPos >= img.lines.length &&
709
+ wsRule & WS_BLANK_AT_EOF &&
710
+ this.wsErrorAction !== "nowarn"
711
+ ) {
712
+ this.recordWsError(WS_BLANK_AT_EOF, "+", foundNewBlankLinesAtEnd);
713
+ if (this.wsErrorAction === "fix") {
714
+ while (newBlankLinesAtEnd--) removeLastLine(postimage);
715
+ }
716
+ if (this.wsErrorAction === "error") this.apply = false;
717
+ }
718
+ if (this.verbosity > 0 && appliedPos !== pos) {
719
+ let offset = appliedPos - pos;
720
+ if (this.applyInReverse) offset = -offset;
721
+ const lines = offset === 1 ? "line" : "lines";
722
+ this.stderr += `Hunk #${nth} succeeded at ${appliedPos + 1} (offset ${offset} ${lines}).\n`;
723
+ }
724
+ if ((leading !== frag.leading || trailing !== frag.trailing) && this.verbosity > -1)
725
+ this.stderr += `Context reduced to (${leading}/${trailing}) to apply fragment at ${appliedPos + 1}\n`;
726
+ this.updateImage(img, appliedPos, preimage, postimage);
727
+ } else if (this.verbosity > 0) {
728
+ this.error(`while searching for:\n${old}`);
729
+ }
730
+ return appliedPos < 0;
731
+ }
732
+
733
+ private applyBinaryFragment(img: Target, patch: FilePatch): number {
734
+ let fragment = patch.fragments[0];
735
+ const name = patch.newName ?? patch.oldName;
736
+ if (!fragment) return this.error(`missing binary patch data for '${name}'`);
737
+ if (this.applyInReverse) {
738
+ if (!patch.fragments[1])
739
+ return this.error(
740
+ `cannot reverse-apply a binary patch without the reverse hunk to '${name}'`,
741
+ );
742
+ fragment = patch.fragments[1];
743
+ }
744
+ if (fragment.binaryMethod === BINARY_DELTA) {
745
+ try {
746
+ const out = decodeGitBinaryDelta(latin1ToBytes(img.buf), latin1ToBytes(fragment.patch));
747
+ img.buf = bytesToLatin1(out);
748
+ return 0;
749
+ } catch {
750
+ return -1;
751
+ }
752
+ }
753
+ if (fragment.binaryMethod === BINARY_LITERAL) {
754
+ img.buf = fragment.patch;
755
+ return 0;
756
+ }
757
+ return -1;
758
+ }
759
+
760
+ private async applyBinary(img: Target, patch: FilePatch): Promise<number> {
761
+ const name = patch.oldName ?? patch.newName;
762
+ const hex = /^[0-9a-f]{40}$/;
763
+ if (!hex.test(patch.oldOidPrefix) || !hex.test(patch.newOidPrefix))
764
+ return this.error(`cannot apply binary patch to '${name}' without full index line`);
765
+ if (patch.oldName !== null) {
766
+ const oid = await this.io.hashBlob(img.buf);
767
+ if (oid !== patch.oldOidPrefix)
768
+ return this.error(
769
+ `the patch applies to '${name}' (${oid}), which does not match the current contents.`,
770
+ );
771
+ } else if (img.buf.length) {
772
+ return this.error(`the patch applies to an empty '${name}' but it is not empty`);
773
+ }
774
+ if (/^0+$/.test(patch.newOidPrefix)) {
775
+ img.buf = "";
776
+ return 0;
777
+ }
778
+ if (await this.io.hasObject(patch.newOidPrefix)) {
779
+ const result = await this.io.readBlob(patch.newOidPrefix);
780
+ if (result === undefined)
781
+ return this.error(
782
+ `the necessary postimage ${patch.newOidPrefix} for '${name}' cannot be read`,
783
+ );
784
+ img.buf = result;
785
+ } else {
786
+ if (this.applyBinaryFragment(img, patch))
787
+ return this.error(`binary patch does not apply to '${name}'`);
788
+ const oid = await this.io.hashBlob(img.buf);
789
+ if (oid !== patch.newOidPrefix)
790
+ return this.error(
791
+ `binary patch to '${name}' creates incorrect result (expecting ${patch.newOidPrefix}, got ${oid})`,
792
+ );
793
+ }
794
+ return 0;
795
+ }
796
+
797
+ private async applyFragments(img: Target, patch: FilePatch): Promise<number> {
798
+ const name = patch.oldName ?? patch.newName;
799
+ if (patch.isBinary) return this.applyBinary(img, patch);
800
+ let nth = 0;
801
+ for (const frag of patch.fragments) {
802
+ nth++;
803
+ if (this.applyOneFragment(img, frag, patch.inaccurateEof, patch.wsRule, nth)) {
804
+ this.error(`patch failed: ${name}:${frag.oldpos}`);
805
+ if (!this.applyWithReject) return -1;
806
+ frag.rejected = true;
807
+ }
808
+ }
809
+ return 0;
810
+ }
811
+
812
+ // ---------------------------------------------------------------- the tree
813
+
814
+ private async readBlobObject(oid: string, mode: number): Promise<string | undefined> {
815
+ if (isGitlink(mode)) return `Subproject commit ${oid}\n`;
816
+ return this.io.readBlob(oid);
817
+ }
818
+
819
+ private addToFnTable(patch: FilePatch): void {
820
+ if (patch.newName !== null) this.fnTable.set(patch.newName, patch);
821
+ if (patch.newName === null || patch.isRename)
822
+ this.fnTable.set(patch.oldName as string, "deleted");
823
+ }
824
+
825
+ private prepareFnTable(list: FilePatch[]): void {
826
+ for (const patch of list) {
827
+ if (patch.newName === null || patch.isRename)
828
+ this.fnTable.set(patch.oldName as string, "to-be-deleted");
829
+ }
830
+ }
831
+
832
+ private previousPatch(patch: FilePatch): { previous?: FilePatch; gone: boolean } {
833
+ if (patch.isCopy || patch.isRename) return { gone: false };
834
+ const previous = patch.oldName === null ? undefined : this.fnTable.get(patch.oldName);
835
+ if (!previous || previous === "to-be-deleted") return { gone: false };
836
+ if (previous === "deleted") return { gone: true };
837
+ return { previous, gone: false };
838
+ }
839
+
840
+ /** `load_patch_target`: 0, 1 for a submodule patch without the index, -1 on error. */
841
+ private async loadPatchTarget(
842
+ out: { buf: string },
843
+ entry: ApplyIndexEntry | undefined,
844
+ stMode: number,
845
+ patch: FilePatch,
846
+ name: string | null,
847
+ expectedMode: number,
848
+ ): Promise<number> {
849
+ if (this.cached || this.checkIndex) {
850
+ if (entry) {
851
+ const data = await this.readBlobObject(entry.oid, entry.mode);
852
+ if (data === undefined) return this.error(`failed to read ${name}`);
853
+ out.buf = data;
854
+ }
855
+ } else if (name !== null) {
856
+ if (isGitlink(expectedMode)) {
857
+ if (entry) {
858
+ out.buf = (await this.readBlobObject(entry.oid, entry.mode)) ?? "";
859
+ return 0;
860
+ }
861
+ return 1;
862
+ }
863
+ if (await this.io.hasSymlinkLeadingPath(name))
864
+ return this.error(`reading from '${name}' beyond a symbolic link`);
865
+ const data = await this.io.readWorktree(name, stMode, patch.crlfInOld);
866
+ if (data === undefined) return this.error(`failed to read ${name}`);
867
+ out.buf = data;
868
+ }
869
+ return 0;
870
+ }
871
+
872
+ private async loadPreimage(
873
+ patch: FilePatch,
874
+ stMode: number,
875
+ entry: ApplyIndexEntry | undefined,
876
+ ): Promise<Target | undefined> {
877
+ const { previous, gone } = this.previousPatch(patch);
878
+ if (gone) {
879
+ this.error(`path ${patch.oldName} has been renamed/deleted`);
880
+ return undefined;
881
+ }
882
+ const out = { buf: "" };
883
+ if (previous) out.buf = previous.result ?? "";
884
+ else {
885
+ const status = await this.loadPatchTarget(
886
+ out,
887
+ entry,
888
+ stMode,
889
+ patch,
890
+ patch.oldName,
891
+ patch.oldMode,
892
+ );
893
+ if (status < 0) return undefined;
894
+ if (status === 1) patch.fragments = [];
895
+ }
896
+ return new Target(out.buf, !patch.isBinary);
897
+ }
898
+
899
+ private async loadCurrent(patch: FilePatch): Promise<Target | undefined> {
900
+ const name = patch.newName as string;
901
+ const entry = this.indexEntry(name);
902
+ if (!entry) {
903
+ this.error(`${name}: does not exist in index`);
904
+ return undefined;
905
+ }
906
+ let st = await this.io.lstat(name);
907
+ if (!st) {
908
+ if (!(await this.io.checkout(name, entry))) {
909
+ this.error(`cannot checkout ${name}`);
910
+ return undefined;
911
+ }
912
+ st = await this.io.lstat(name);
913
+ }
914
+ if (!(await this.io.matchesIndex(name, entry))) {
915
+ this.error(`${name}: does not match index`);
916
+ return undefined;
917
+ }
918
+ const out = { buf: "" };
919
+ const status = await this.loadPatchTarget(
920
+ out,
921
+ entry,
922
+ st?.mode ?? 0,
923
+ patch,
924
+ name,
925
+ patch.newMode,
926
+ );
927
+ if (status) return undefined;
928
+ return new Target(out.buf, !patch.isBinary);
929
+ }
930
+
931
+ private async tryThreeway(
932
+ image: Target,
933
+ patch: FilePatch,
934
+ stMode: number,
935
+ entry: ApplyIndexEntry | undefined,
936
+ ): Promise<number> {
937
+ if (
938
+ patch.isDelete ||
939
+ isGitlink(patch.oldMode) ||
940
+ isGitlink(patch.newMode) ||
941
+ (patch.isNew && !patch.directToThreeway) ||
942
+ (patch.isRename && !patch.linesAdded && !patch.linesDeleted)
943
+ )
944
+ return -1;
945
+ let preOid: string;
946
+ let pre = "";
947
+ if (patch.isNew) preOid = await this.io.writeBlob("");
948
+ else {
949
+ const resolved = await this.io.resolveBlob(patch.oldOidPrefix);
950
+ const data = resolved ? await this.readBlobObject(resolved, patch.oldMode) : undefined;
951
+ if (!resolved || data === undefined)
952
+ return this.error("repository lacks the necessary blob to perform 3-way merge.");
953
+ preOid = resolved;
954
+ pre = data;
955
+ }
956
+ if (this.verbosity > -1 && patch.directToThreeway)
957
+ this.stderr += "Performing three-way merge...\n";
958
+ const tmp = new Target(pre, true);
959
+ if ((await this.applyFragments(tmp, patch)) < 0) return -1;
960
+ const postOid = await this.io.writeBlob(tmp.buf);
961
+ let ours: Target | undefined;
962
+ if (patch.isNew) {
963
+ ours = await this.loadCurrent(patch);
964
+ if (!ours) return this.error(`cannot read the current contents of '${patch.newName}'`);
965
+ } else {
966
+ ours = await this.loadPreimage(patch, stMode, entry);
967
+ if (!ours) return this.error(`cannot read the current contents of '${patch.oldName}'`);
968
+ }
969
+ const ourOid = await this.io.writeBlob(ours.buf);
970
+ let status: number;
971
+ if (preOid === ourOid) {
972
+ image.buf = (await this.io.readBlob(postOid)) ?? "";
973
+ status = 0;
974
+ } else if (preOid === postOid || ourOid === postOid) {
975
+ image.buf = (await this.io.readBlob(ourOid)) ?? "";
976
+ status = 0;
977
+ } else {
978
+ const merged = await this.io.merge(
979
+ patch.newName as string,
980
+ preOid,
981
+ ourOid,
982
+ postOid,
983
+ this.mergeVariant,
984
+ );
985
+ if (merged?.binary)
986
+ this.warning(`Cannot merge binary files: ${patch.newName} (ours vs. theirs)`);
987
+ if (!merged || merged.binary) {
988
+ if (this.verbosity > -1) this.stderr += "Failed to perform three-way merge...\n";
989
+ return -1;
990
+ }
991
+ image.buf = merged.content;
992
+ status = merged.conflicts > 0 ? 1 : 0;
993
+ }
994
+ if (status) {
995
+ patch.conflictedThreeway = true;
996
+ patch.threewayStage = [patch.isNew ? null : preOid, ourOid, postOid];
997
+ if (this.verbosity > -1)
998
+ this.stderr += `Applied patch to '${patch.newName}' with conflicts.\n`;
999
+ } else if (this.verbosity > -1) {
1000
+ this.stderr += `Applied patch to '${patch.newName}' cleanly.\n`;
1001
+ }
1002
+ return 0;
1003
+ }
1004
+
1005
+ private async applyData(
1006
+ patch: FilePatch,
1007
+ stMode: number,
1008
+ entry: ApplyIndexEntry | undefined,
1009
+ ): Promise<number> {
1010
+ const image = await this.loadPreimage(patch, stMode, entry);
1011
+ if (!image) return -1;
1012
+ if (!this.threeway || (await this.tryThreeway(image, patch, stMode, entry)) < 0) {
1013
+ if (this.verbosity > -1 && this.threeway && !patch.directToThreeway)
1014
+ this.stderr += "Falling back to direct application...\n";
1015
+ if (patch.directToThreeway || (await this.applyFragments(image, patch)) < 0) return -1;
1016
+ }
1017
+ patch.result = image.buf;
1018
+ this.addToFnTable(patch);
1019
+ if (0 < patch.isDelete && patch.result.length)
1020
+ return this.error("removal patch leaves file contents");
1021
+ return 0;
1022
+ }
1023
+
1024
+ private async checkPreimage(
1025
+ patch: FilePatch,
1026
+ ): Promise<{ status: number; entry?: ApplyIndexEntry; stMode: number }> {
1027
+ const oldName = patch.oldName;
1028
+ let stMode = 0;
1029
+ let fileMode = 0;
1030
+ let missing = false;
1031
+ if (oldName === null) return { status: 0, stMode: 0 };
1032
+ const { previous, gone } = this.previousPatch(patch);
1033
+ if (gone) return { status: this.error(`path ${oldName} has been renamed/deleted`), stMode: 0 };
1034
+ if (previous) stMode = previous.newMode;
1035
+ else if (!this.cached) {
1036
+ const st = await this.io.lstat(oldName);
1037
+ if (st) fileMode = st.mode;
1038
+ else missing = true;
1039
+ }
1040
+ let entry: ApplyIndexEntry | undefined;
1041
+ const isNew = (): { status: number; stMode: number } => {
1042
+ patch.isNew = 1;
1043
+ patch.isDelete = 0;
1044
+ patch.oldName = null;
1045
+ return { status: 0, stMode: 0 };
1046
+ };
1047
+ if (this.checkIndex && !previous) {
1048
+ entry = this.indexEntry(oldName);
1049
+ if (!entry) {
1050
+ if (patch.isNew < 0) return isNew();
1051
+ return { status: this.error(`${oldName}: does not exist in index`), stMode: 0 };
1052
+ }
1053
+ if (missing && !this.cached) {
1054
+ if (!(await this.io.checkout(oldName, entry)))
1055
+ return { status: this.error(`cannot checkout ${oldName}`), stMode: 0 };
1056
+ fileMode = (await this.io.lstat(oldName))?.mode ?? 0;
1057
+ missing = false;
1058
+ }
1059
+ if (!this.cached && !(await this.io.matchesIndex(oldName, entry)))
1060
+ return { status: this.error(`${oldName}: does not match index`), stMode: 0 };
1061
+ if (this.cached) stMode = entry.mode;
1062
+ } else if (missing) {
1063
+ if (patch.isNew < 0) return isNew();
1064
+ const reason = (await this.io.missingReason?.(oldName)) ?? "No such file or directory";
1065
+ return { status: this.error(`${oldName}: ${reason}`), stMode: 0 };
1066
+ }
1067
+ if (!this.cached && !previous) {
1068
+ if (this.io.trustExecutableBit || !isRegular(fileMode))
1069
+ stMode = this.io.modeFromStat(oldName, entry, fileMode);
1070
+ else if (entry) stMode = entry.mode;
1071
+ else stMode = patch.oldMode;
1072
+ }
1073
+ if (patch.isNew < 0) patch.isNew = 0;
1074
+ if (!patch.oldMode) patch.oldMode = stMode;
1075
+ if ((stMode ^ patch.oldMode) & S_IFMT)
1076
+ return { status: this.error(`${oldName}: wrong type`), stMode: 0 };
1077
+ if (stMode !== patch.oldMode)
1078
+ this.warning(
1079
+ `${oldName} has type ${stMode.toString(8)}, expected ${patch.oldMode.toString(8)}`,
1080
+ );
1081
+ if (!patch.newMode && !patch.isDelete) patch.newMode = stMode;
1082
+ return { status: 0, entry, stMode: fileMode || stMode };
1083
+ }
1084
+
1085
+ /** `check_to_create`: 0, 1 in index, 2 in worktree, 3 in index as ITA. */
1086
+ private async checkToCreate(name: string, okIfExists: boolean): Promise<number> {
1087
+ if (this.checkIndex && (!okIfExists || !this.cached)) {
1088
+ const entry = this.indexEntry(name);
1089
+ if (entry) {
1090
+ if (!okIfExists && !entry.intentToAdd) return 1;
1091
+ if (!this.cached && entry.intentToAdd) return 3;
1092
+ }
1093
+ }
1094
+ if (this.cached) return 0;
1095
+ const st = await this.io.lstat(name);
1096
+ if (st) {
1097
+ if ((st.mode & S_IFMT) === 0o040000 || okIfExists) return 0;
1098
+ if (await this.io.hasSymlinkLeadingPath(name)) return 0;
1099
+ return 2;
1100
+ }
1101
+ return 0;
1102
+ }
1103
+
1104
+ private prepareSymlinkChanges(list: FilePatch[]): void {
1105
+ for (const patch of list) {
1106
+ if (patch.oldName !== null && isLink(patch.oldMode) && (patch.isRename || patch.isDelete))
1107
+ this.removedSymlinks.add(patch.oldName);
1108
+ if (patch.newName !== null && isLink(patch.newMode)) this.keptSymlinks.add(patch.newName);
1109
+ }
1110
+ }
1111
+
1112
+ private async pathIsBeyondSymlink(name: string): Promise<boolean> {
1113
+ let len = name.length;
1114
+ for (;;) {
1115
+ while (--len > 0 && name[len] !== "/");
1116
+ if (len <= 0) break;
1117
+ const dir = name.slice(0, len);
1118
+ if (this.keptSymlinks.has(dir)) return true;
1119
+ if (this.removedSymlinks.has(dir)) continue;
1120
+ if (this.checkIndex) {
1121
+ const entry = this.indexEntry(dir);
1122
+ if (entry && isLink(entry.mode)) return true;
1123
+ } else {
1124
+ const st = await this.io.lstat(dir);
1125
+ if (st && isLink(st.mode)) return true;
1126
+ }
1127
+ }
1128
+ return false;
1129
+ }
1130
+
1131
+ private checkUnsafePath(patch: FilePatch): number {
1132
+ let oldName: string | null = null;
1133
+ let newName: string | null = null;
1134
+ if (patch.isDelete) oldName = patch.oldName;
1135
+ else if (!patch.isNew && !patch.isCopy) oldName = patch.oldName;
1136
+ if (!patch.isDelete) newName = patch.newName;
1137
+ if (oldName !== null && !this.io.verifyPath(oldName, patch.oldMode))
1138
+ return this.error(`invalid path '${oldName}'`);
1139
+ if (newName !== null && !this.io.verifyPath(newName, patch.newMode))
1140
+ return this.error(`invalid path '${newName}'`);
1141
+ return 0;
1142
+ }
1143
+
1144
+ private async checkPatch(patch: FilePatch): Promise<number> {
1145
+ patch.rejected = true;
1146
+ const pre = await this.checkPreimage(patch);
1147
+ if (pre.status) return pre.status;
1148
+ const oldName = patch.oldName;
1149
+ const newName = patch.newName;
1150
+ const name = oldName ?? newName;
1151
+ const t = newName === null ? undefined : this.fnTable.get(newName);
1152
+ const okIfExists = t === "deleted" || t === "to-be-deleted";
1153
+ if (newName !== null && (0 < patch.isNew || patch.isRename || patch.isCopy)) {
1154
+ const err = await this.checkToCreate(newName, okIfExists);
1155
+ if (err && this.threeway) patch.directToThreeway = true;
1156
+ else if (err === 1) return this.error(`${newName}: already exists in index`);
1157
+ else if (err === 3) return this.error(`${newName}: does not match index`);
1158
+ else if (err === 2) return this.error(`${newName}: already exists in working directory`);
1159
+ if (!patch.newMode) patch.newMode = 0 < patch.isNew ? S_IFREG | 0o644 : patch.oldMode;
1160
+ }
1161
+ if (newName !== null && oldName !== null) {
1162
+ if (!patch.newMode) patch.newMode = patch.oldMode;
1163
+ if ((patch.oldMode ^ patch.newMode) & S_IFMT) {
1164
+ const nm = patch.newMode.toString(8);
1165
+ const om = patch.oldMode.toString(8);
1166
+ if (oldName === newName)
1167
+ return this.error(`new mode (${nm}) of ${newName} does not match old mode (${om})`);
1168
+ return this.error(
1169
+ `new mode (${nm}) of ${newName} does not match old mode (${om}) of ${oldName}`,
1170
+ );
1171
+ }
1172
+ }
1173
+ if (!this.unsafePaths && this.checkUnsafePath(patch)) return -128;
1174
+ if (!patch.isDelete && newName !== null && (await this.pathIsBeyondSymlink(newName)))
1175
+ return this.error(`affected file '${newName}' is beyond a symbolic link`);
1176
+ if ((await this.applyData(patch, pre.stMode, pre.entry)) < 0)
1177
+ return this.error(`${name}: patch does not apply`);
1178
+ patch.rejected = false;
1179
+ return 0;
1180
+ }
1181
+
1182
+ private sayPatchName(format: (name: string) => string, patch: FilePatch): void {
1183
+ let shown: string;
1184
+ if (patch.oldName !== null && patch.newName !== null && patch.oldName !== patch.newName)
1185
+ shown = `${this.quote(patch.oldName)} => ${this.quote(patch.newName)}`;
1186
+ else shown = this.quote((patch.newName ?? patch.oldName) as string);
1187
+ this.stderr += `${format(shown)}\n`;
1188
+ }
1189
+
1190
+ private async checkPatchList(list: FilePatch[]): Promise<number> {
1191
+ let err = 0;
1192
+ this.prepareSymlinkChanges(list);
1193
+ this.prepareFnTable(list);
1194
+ for (const patch of list) {
1195
+ if (this.verbosity > 0) this.sayPatchName((n) => `Checking patch ${n}...`, patch);
1196
+ const res = await this.checkPatch(patch);
1197
+ if (res === -128) return -128;
1198
+ err |= res;
1199
+ }
1200
+ return err;
1201
+ }
1202
+
1203
+ // ---------------------------------------------------------------- output
1204
+
1205
+ private showStats(patch: FilePatch): void {
1206
+ let qname = this.quote((patch.newName ?? patch.oldName) as string);
1207
+ let max = this.maxLen;
1208
+ if (max > 50) max = 50;
1209
+ if (qname.length > max) {
1210
+ const from = qname.length + 3 - max;
1211
+ let cp = qname.indexOf("/", from);
1212
+ if (cp < 0) cp = from;
1213
+ qname = `...${qname.slice(cp)}`;
1214
+ }
1215
+ if (patch.isBinary) {
1216
+ this.stdout += ` ${qname.padEnd(max)} | Bin\n`;
1217
+ return;
1218
+ }
1219
+ this.stdout += ` ${qname.padEnd(max)} |`;
1220
+ max = max + this.maxChange > 70 ? 70 - max : this.maxChange;
1221
+ let add = patch.linesAdded;
1222
+ let del = patch.linesDeleted;
1223
+ if (this.maxChange > 0) {
1224
+ const total = Math.trunc(
1225
+ ((add + del) * max + Math.trunc(this.maxChange / 2)) / this.maxChange,
1226
+ );
1227
+ add = Math.trunc((add * max + Math.trunc(this.maxChange / 2)) / this.maxChange);
1228
+ del = total - add;
1229
+ }
1230
+ const n = String(patch.linesAdded + patch.linesDeleted).padStart(5);
1231
+ this.stdout += `${n} ${"+".repeat(Math.max(0, Math.min(add, 70)))}${"-".repeat(Math.max(0, Math.min(del, 70)))}\n`;
1232
+ }
1233
+
1234
+ private statPatchList(list: FilePatch[]): void {
1235
+ let adds = 0;
1236
+ let dels = 0;
1237
+ for (const patch of list) {
1238
+ adds += patch.linesAdded;
1239
+ dels += patch.linesDeleted;
1240
+ this.showStats(patch);
1241
+ }
1242
+ this.stdout += statSummary(list.length, adds, dels);
1243
+ }
1244
+
1245
+ private numstatPatchList(list: FilePatch[]): void {
1246
+ for (const patch of list) {
1247
+ const name = (patch.newName ?? patch.oldName) as string;
1248
+ this.stdout += patch.isBinary ? "-\t-\t" : `${patch.linesAdded}\t${patch.linesDeleted}\t`;
1249
+ this.stdout += this.lineTermination === "\n" ? this.quote(name) : name;
1250
+ this.stdout += this.lineTermination;
1251
+ }
1252
+ }
1253
+
1254
+ private summaryPatchList(list: FilePatch[]): void {
1255
+ const o6 = (m: number) => m.toString(8).padStart(6, "0");
1256
+ const fileModeName = (what: string, mode: number, name: string) => {
1257
+ this.stdout += mode ? ` ${what} mode ${o6(mode)} ${name}\n` : ` ${what} ${name}\n`;
1258
+ };
1259
+ const modeChange = (p: FilePatch, showName: boolean) => {
1260
+ if (p.oldMode && p.newMode && p.oldMode !== p.newMode) {
1261
+ this.stdout += showName
1262
+ ? ` mode change ${o6(p.oldMode)} => ${o6(p.newMode)} ${p.newName}\n`
1263
+ : ` mode change ${o6(p.oldMode)} => ${o6(p.newMode)}\n`;
1264
+ }
1265
+ };
1266
+ for (const p of list) {
1267
+ if (p.isNew) fileModeName("create", p.newMode, p.newName as string);
1268
+ else if (p.isDelete) fileModeName("delete", p.oldMode, p.oldName as string);
1269
+ else if (p.isRename || p.isCopy) {
1270
+ const what = p.isRename ? "rename" : "copy";
1271
+ const oldFull = p.oldName as string;
1272
+ const newFull = p.newName as string;
1273
+ let o = 0;
1274
+ let n = 0;
1275
+ for (;;) {
1276
+ const so = oldFull.indexOf("/", o);
1277
+ const sn = newFull.indexOf("/", n);
1278
+ if (
1279
+ so < 0 ||
1280
+ sn < 0 ||
1281
+ so - o !== sn - n ||
1282
+ oldFull.slice(o, so) !== newFull.slice(n, sn)
1283
+ )
1284
+ break;
1285
+ o = so + 1;
1286
+ n = sn + 1;
1287
+ }
1288
+ if (o) {
1289
+ this.stdout += ` ${what} ${oldFull.slice(0, o)}{${oldFull.slice(o)} => ${newFull.slice(n)}} (${p.score}%)\n`;
1290
+ } else this.stdout += ` ${what} ${oldFull} => ${newFull} (${p.score}%)\n`;
1291
+ modeChange(p, false);
1292
+ } else if (p.score) {
1293
+ this.stdout += ` rewrite ${p.newName} (${p.score}%)\n`;
1294
+ modeChange(p, false);
1295
+ } else modeChange(p, true);
1296
+ }
1297
+ }
1298
+
1299
+ private patchStats(patch: FilePatch): void {
1300
+ const lines = patch.linesAdded + patch.linesDeleted;
1301
+ if (lines > this.maxChange) this.maxChange = lines;
1302
+ for (const name of [patch.oldName, patch.newName]) {
1303
+ if (name === null) continue;
1304
+ const len = this.quote(name).length;
1305
+ if (len > this.maxLen) this.maxLen = len;
1306
+ }
1307
+ }
1308
+
1309
+ // ---------------------------------------------------------------- writing
1310
+
1311
+ private setIndex(
1312
+ name: string,
1313
+ entries: (ApplyIndexEntry & { stat?: Record<string, number> })[],
1314
+ ): void {
1315
+ this.indexChanges.set(name, entries);
1316
+ }
1317
+
1318
+ private async removeFile(patch: FilePatch, rmdirEmpty: boolean): Promise<number> {
1319
+ const name = patch.oldName as string;
1320
+ if (this.updateIndex && !this.itaOnly) this.setIndex(name, []);
1321
+ if (!this.cached) {
1322
+ const warning = await this.io.removeWorktree(name, patch.oldMode, rmdirEmpty);
1323
+ if (warning) this.warning(warning);
1324
+ }
1325
+ return 0;
1326
+ }
1327
+
1328
+ private async addIndexFile(name: string, mode: number, buf: string): Promise<number> {
1329
+ if (this.itaOnly) {
1330
+ // set_object_name_for_intent_to_add_entry: the empty blob it names is written
1331
+ await this.io.writeBlob("");
1332
+ return this.addIndexEntries(name, [
1333
+ { mode, oid: "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", intentToAdd: true },
1334
+ ]);
1335
+ }
1336
+ if (isGitlink(mode)) {
1337
+ const m = /^Subproject commit ([0-9a-f]{40})/.exec(buf);
1338
+ if (!m) return this.error(`corrupt patch for submodule ${name}`);
1339
+ return this.addIndexEntries(name, [{ mode, oid: m[1] as string }]);
1340
+ }
1341
+ let stat: Record<string, number> | undefined;
1342
+ if (!this.cached) {
1343
+ stat = await this.io.statOf(name);
1344
+ if (!stat)
1345
+ return this.error(`unable to stat newly created file '${name}': No such file or directory`);
1346
+ }
1347
+ const oid = await this.io.writeBlob(buf);
1348
+ return this.addIndexEntries(name, [{ mode, oid, ...(stat ? { stat } : {}) }]);
1349
+ }
1350
+
1351
+ private async createFile(patch: FilePatch): Promise<number> {
1352
+ const name = patch.newName as string;
1353
+ let mode = patch.newMode;
1354
+ const buf = patch.result ?? "";
1355
+ if (!mode) mode = S_IFREG | 0o644;
1356
+ if (!this.cached) {
1357
+ if (await this.pathIsBeyondSymlink(name))
1358
+ return this.error(`affected file '${name}' is beyond a symbolic link`);
1359
+ const failure = await this.io.createWorktree(name, mode, buf);
1360
+ if (failure) return this.error(failure);
1361
+ }
1362
+ if (patch.conflictedThreeway) {
1363
+ if (!this.updateIndex) return 0;
1364
+ const m = patch.newMode ? patch.newMode : S_IFREG | 0o644;
1365
+ const entries: ApplyIndexEntry[] = [];
1366
+ patch.threewayStage.forEach((oid, i) => {
1367
+ if (oid) entries.push({ mode: m, oid, stage: i + 1 });
1368
+ });
1369
+ // remove_file_from_index, then each stage added
1370
+ this.setIndex(name, []);
1371
+ return this.addIndexEntries(name, entries);
1372
+ }
1373
+ if (this.checkIndex || (this.itaOnly && patch.isNew > 0))
1374
+ return this.addIndexFile(name, mode, buf);
1375
+ return 0;
1376
+ }
1377
+
1378
+ private async writeOutOneResult(patch: FilePatch, phase: number): Promise<number> {
1379
+ if (patch.isDelete > 0) return phase === 0 ? this.removeFile(patch, true) : 0;
1380
+ if (patch.isNew > 0 || patch.isCopy) return phase === 1 ? this.createFile(patch) : 0;
1381
+ if (phase === 0) return this.removeFile(patch, patch.isRename);
1382
+ return this.createFile(patch);
1383
+ }
1384
+
1385
+ private async writeOutOneReject(patch: FilePatch): Promise<number> {
1386
+ const cnt = patch.fragments.filter((f) => f.rejected).length;
1387
+ if (!cnt) {
1388
+ if (this.verbosity > 0) this.sayPatchName((n) => `Applied patch ${n} cleanly.`, patch);
1389
+ return 0;
1390
+ }
1391
+ const rejects = cnt === 1 ? "reject" : "rejects";
1392
+ if (this.verbosity > -1)
1393
+ this.sayPatchName((n) => `Applying patch ${n} with ${cnt} ${rejects}...`, patch);
1394
+ const name = patch.newName as string;
1395
+ let rej = `diff a/${name} b/${name}\t(rejected hunks)\n`;
1396
+ patch.fragments.forEach((frag, i) => {
1397
+ if (!frag.rejected) {
1398
+ if (this.verbosity > -1) this.stderr += `Hunk #${i + 1} applied cleanly.\n`;
1399
+ return;
1400
+ }
1401
+ if (this.verbosity > -1) this.stderr += `Rejected hunk #${i + 1}.\n`;
1402
+ rej += frag.patch.slice(0, frag.size);
1403
+ if (!frag.patch.slice(0, frag.size).endsWith("\n")) rej += "\n";
1404
+ });
1405
+ await this.io.writeReject(`${name}.rej`, rej);
1406
+ return -1;
1407
+ }
1408
+
1409
+ private async writeOutResults(list: FilePatch[]): Promise<number> {
1410
+ let errs = 0;
1411
+ const cpath: string[] = [];
1412
+ for (let phase = 0; phase < 2; phase++) {
1413
+ for (const l of list) {
1414
+ if (l.rejected) errs = 1;
1415
+ else {
1416
+ if (await this.writeOutOneResult(l, phase)) return -1;
1417
+ if (phase === 1) {
1418
+ if (await this.writeOutOneReject(l)) errs = 1;
1419
+ if (l.conflictedThreeway) {
1420
+ cpath.push(l.newName as string);
1421
+ errs = 1;
1422
+ }
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ if (cpath.length) {
1428
+ cpath.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1429
+ if (this.verbosity > -1) for (const p of cpath) this.stderr += `U ${p}\n`;
1430
+ this.conflictedPaths.push(...cpath);
1431
+ }
1432
+ return errs;
1433
+ }
1434
+
1435
+ /** `apply_patch` of one input: -128 fatal, -1 not applied, 0 applied, 1 applied partly. */
1436
+ async applyPatch(input: ApplyInput): Promise<number> {
1437
+ this.patchInputFile = input.name;
1438
+ this.linenr = 1;
1439
+ const buf = input.text;
1440
+ const list: FilePatch[] = [];
1441
+ let skipped = 0;
1442
+ let offset = 0;
1443
+ try {
1444
+ while (offset < buf.length) {
1445
+ const patch = newFilePatch();
1446
+ patch.inaccurateEof = this.inaccurateEof;
1447
+ patch.recount = this.recount;
1448
+ const nr = await this.parseChunk(buf, offset, buf.length - offset, patch, async (p) => {
1449
+ if (!this.usePatch(p, this.wildmatch)) return 0;
1450
+ return this.wsRuleOfName((p.newName ?? p.oldName) as string);
1451
+ });
1452
+ if (nr < 0) {
1453
+ if (nr === -128) return -128;
1454
+ break;
1455
+ }
1456
+ if (this.applyInReverse) reversePatch(patch);
1457
+ if (this.usePatch(patch, this.wildmatch)) {
1458
+ this.patchStats(patch);
1459
+ if (!list.length || !this.applyInReverse) list.push(patch);
1460
+ else list.unshift(patch);
1461
+ } else {
1462
+ if (this.verbosity > 0) this.sayPatchName((n) => `Skipped patch '${n}'.`, patch);
1463
+ skipped++;
1464
+ }
1465
+ offset += nr;
1466
+ }
1467
+ if (!list.length && !skipped) {
1468
+ if (!this.allowEmpty) {
1469
+ this.error('No valid patches in input (allow with "--allow-empty")');
1470
+ return -128;
1471
+ }
1472
+ return 0;
1473
+ }
1474
+ if (this.whitespaceError && this.wsErrorAction === "error") this.apply = false;
1475
+ this.updateIndex = (this.checkIndex || this.itaOnly) && this.apply;
1476
+ if (this.check || this.apply) {
1477
+ const r = await this.checkPatchList(list);
1478
+ if (r === -128) return -128;
1479
+ if (r < 0 && !this.applyWithReject) return -1;
1480
+ }
1481
+ if (this.apply) {
1482
+ const w = await this.writeOutResults(list);
1483
+ if (w < 0) return -128;
1484
+ if (w > 0) return this.applyWithReject ? -1 : 1;
1485
+ }
1486
+ if (this.diffstat && this.verbosity > -1) this.statPatchList(list);
1487
+ if (this.numstat && this.verbosity > -1) this.numstatPatchList(list);
1488
+ if (this.summary && this.verbosity > -1) this.summaryPatchList(list);
1489
+ return 0;
1490
+ } finally {
1491
+ this.fnTable.clear();
1492
+ }
1493
+ }
1494
+
1495
+ /**
1496
+ * The file patches of an input, parsed only (what `--build-fake-ancestor` reads); a
1497
+ * negative status when the input does not parse.
1498
+ */
1499
+ async parsePatches(input: ApplyInput): Promise<FilePatch[] | number> {
1500
+ this.patchInputFile = input.name;
1501
+ this.linenr = 1;
1502
+ const buf = input.text;
1503
+ const list: FilePatch[] = [];
1504
+ let offset = 0;
1505
+ while (offset < buf.length) {
1506
+ const patch = newFilePatch();
1507
+ const nr = await this.parseChunk(buf, offset, buf.length - offset, patch, async () => 0);
1508
+ if (nr < 0) {
1509
+ if (nr === -128) return -128;
1510
+ break;
1511
+ }
1512
+ if (this.applyInReverse) reversePatch(patch);
1513
+ if (this.usePatch(patch, this.wildmatch)) list.push(patch);
1514
+ offset += nr;
1515
+ }
1516
+ return list;
1517
+ }
1518
+
1519
+ /** The whitespace action when none was asked for (`set_default_whitespace_mode`). */
1520
+ setDefaultWhitespaceMode(): void {
1521
+ if (!this.whitespaceOptionGiven && this.configWhitespace === undefined)
1522
+ this.wsErrorAction = this.apply ? "warn" : "nowarn";
1523
+ }
1524
+
1525
+ /**
1526
+ * `apply_all_patches`: applies each input; the exit status (0, 1, 128). `wroteIndex` says
1527
+ * whether the caller must write the index changes.
1528
+ */
1529
+ async applyAll(inputs: ApplyInput[]): Promise<{ status: number; writeIndex: boolean }> {
1530
+ let errs = 0;
1531
+ const end = (res: number) => ({
1532
+ status: res > -1 ? res : res === -1 ? 1 : 128,
1533
+ writeIndex: false,
1534
+ });
1535
+ for (const input of inputs) {
1536
+ this.setDefaultWhitespaceMode();
1537
+ const res = await this.applyPatch(input);
1538
+ if (res < 0) return end(res);
1539
+ errs |= res;
1540
+ }
1541
+ if (this.whitespaceError) {
1542
+ if (this.squelchWhitespaceErrors && this.squelchWhitespaceErrors < this.whitespaceError) {
1543
+ const squelched = this.whitespaceError - this.squelchWhitespaceErrors;
1544
+ this.warning(`squelched ${squelched} whitespace error${squelched === 1 ? "" : "s"}`);
1545
+ }
1546
+ const n = this.whitespaceError;
1547
+ if (this.wsErrorAction === "error") {
1548
+ this.error(
1549
+ n === 1 ? "1 line adds whitespace errors." : `${n} lines add whitespace errors.`,
1550
+ );
1551
+ return end(-128);
1552
+ }
1553
+ const fixed = this.appliedAfterFixingWs;
1554
+ if (fixed && this.apply)
1555
+ this.warning(
1556
+ fixed === 1
1557
+ ? "1 line applied after fixing whitespace errors."
1558
+ : `${fixed} lines applied after fixing whitespace errors.`,
1559
+ );
1560
+ else
1561
+ this.warning(
1562
+ n === 1 ? "1 line adds whitespace errors." : `${n} lines add whitespace errors.`,
1563
+ );
1564
+ }
1565
+ return { status: errs ? 1 : 0, writeIndex: this.updateIndex };
1566
+ }
1567
+ }
1568
+
1569
+ function reversePatch(p: FilePatch): void {
1570
+ [p.newName, p.oldName] = [p.oldName, p.newName];
1571
+ if (p.newMode || p.isDelete) [p.newMode, p.oldMode] = [p.oldMode, p.newMode];
1572
+ [p.isNew, p.isDelete] = [p.isDelete, p.isNew];
1573
+ [p.linesAdded, p.linesDeleted] = [p.linesDeleted, p.linesAdded];
1574
+ [p.oldOidPrefix, p.newOidPrefix] = [p.newOidPrefix, p.oldOidPrefix];
1575
+ for (const f of p.fragments) {
1576
+ [f.newpos, f.oldpos] = [f.oldpos, f.newpos];
1577
+ [f.newlines, f.oldlines] = [f.oldlines, f.newlines];
1578
+ }
1579
+ }
1580
+
1581
+ function fuzzyMatchLines(
1582
+ s1: string,
1583
+ a1: number,
1584
+ n1: number,
1585
+ s2: string,
1586
+ a2: number,
1587
+ n2: number,
1588
+ ): boolean {
1589
+ let end1 = a1 + n1;
1590
+ let end2 = a2 + n2;
1591
+ while (a1 < end1 && (s1[end1 - 1] === "\r" || s1[end1 - 1] === "\n")) end1--;
1592
+ while (a2 < end2 && (s2[end2 - 1] === "\r" || s2[end2 - 1] === "\n")) end2--;
1593
+ while (a1 < end1 && a2 < end2) {
1594
+ if (isSpaceAt(s1, a1)) {
1595
+ if (!isSpaceAt(s2, a2)) return false;
1596
+ while (a1 < end1 && isSpaceAt(s1, a1)) a1++;
1597
+ while (a2 < end2 && isSpaceAt(s2, a2)) a2++;
1598
+ } else if (s1[a1++] !== s2[a2++]) return false;
1599
+ }
1600
+ return a1 === end1 && a2 === end2;
1601
+ }
1602
+
1603
+ export { cQuote };