@statewalker/vcs-commands 0.13.0 → 0.15.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 (304) hide show
  1. package/dist/commands/add-command.d.ts.map +1 -1
  2. package/dist/commands/add-patch/patch-backend.d.ts +1 -1
  3. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -1
  4. package/dist/commands/archive/archive-command.d.ts +6 -2
  5. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  6. package/dist/commands/archive/remote-archive-command.d.ts +27 -2
  7. package/dist/commands/archive/remote-archive-command.d.ts.map +1 -1
  8. package/dist/commands/archive/upload-archive-writer.d.ts +11 -5
  9. package/dist/commands/archive/upload-archive-writer.d.ts.map +1 -1
  10. package/dist/commands/branch-command.d.ts +14 -2
  11. package/dist/commands/branch-command.d.ts.map +1 -1
  12. package/dist/commands/bundle/bundle-format.d.ts +6 -1
  13. package/dist/commands/bundle/bundle-format.d.ts.map +1 -1
  14. package/dist/commands/bundle/bundle-uri-host.d.ts +12 -1
  15. package/dist/commands/bundle/bundle-uri-host.d.ts.map +1 -1
  16. package/dist/commands/bundle/bundle-uri.d.ts +7 -1
  17. package/dist/commands/bundle/bundle-uri.d.ts.map +1 -1
  18. package/dist/commands/bundle/bundle-verify.d.ts +4 -1
  19. package/dist/commands/bundle/bundle-verify.d.ts.map +1 -1
  20. package/dist/commands/cat-file/batch-format.d.ts +8 -12
  21. package/dist/commands/cat-file/batch-format.d.ts.map +1 -1
  22. package/dist/commands/cat-file/cat-file-command.d.ts +39 -5
  23. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  24. package/dist/commands/check-ignore-command.d.ts.map +1 -1
  25. package/dist/commands/checkout-command.d.ts +4 -0
  26. package/dist/commands/checkout-command.d.ts.map +1 -1
  27. package/dist/commands/checkout-paths.d.ts +9 -0
  28. package/dist/commands/checkout-paths.d.ts.map +1 -1
  29. package/dist/commands/cherry-pick-command.d.ts +3 -0
  30. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  31. package/dist/commands/clean-interactive.d.ts +0 -9
  32. package/dist/commands/clean-interactive.d.ts.map +1 -1
  33. package/dist/commands/clone-command.d.ts +17 -0
  34. package/dist/commands/clone-command.d.ts.map +1 -1
  35. package/dist/commands/column/column-config.d.ts +23 -0
  36. package/dist/commands/column/column-config.d.ts.map +1 -0
  37. package/dist/commands/column/column-layout.d.ts +129 -0
  38. package/dist/commands/column/column-layout.d.ts.map +1 -0
  39. package/dist/commands/column/index.d.ts +3 -0
  40. package/dist/commands/column/index.d.ts.map +1 -0
  41. package/dist/commands/column-command.d.ts +59 -0
  42. package/dist/commands/column-command.d.ts.map +1 -0
  43. package/dist/commands/comment-char-config.d.ts +15 -0
  44. package/dist/commands/comment-char-config.d.ts.map +1 -1
  45. package/dist/commands/commit-command.d.ts +30 -2
  46. package/dist/commands/commit-command.d.ts.map +1 -1
  47. package/dist/commands/config-command.d.ts +12 -0
  48. package/dist/commands/config-command.d.ts.map +1 -1
  49. package/dist/commands/credential-helper.d.ts +214 -0
  50. package/dist/commands/credential-helper.d.ts.map +1 -0
  51. package/dist/commands/default-branch.d.ts +33 -3
  52. package/dist/commands/default-branch.d.ts.map +1 -1
  53. package/dist/commands/diff-color-config.d.ts +4 -0
  54. package/dist/commands/diff-color-config.d.ts.map +1 -1
  55. package/dist/commands/diff-command.d.ts +12 -0
  56. package/dist/commands/diff-command.d.ts.map +1 -1
  57. package/dist/commands/fast-export/fast-export-command.d.ts +89 -2
  58. package/dist/commands/fast-export/fast-export-command.d.ts.map +1 -1
  59. package/dist/commands/fast-export/fast-import-command.d.ts +113 -8
  60. package/dist/commands/fast-export/fast-import-command.d.ts.map +1 -1
  61. package/dist/commands/fast-export/fast-stream-support.d.ts +0 -9
  62. package/dist/commands/fast-export/fast-stream-support.d.ts.map +1 -1
  63. package/dist/commands/fetch-command.d.ts +23 -1
  64. package/dist/commands/fetch-command.d.ts.map +1 -1
  65. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -1
  66. package/dist/commands/git-hooks.d.ts +31 -3
  67. package/dist/commands/git-hooks.d.ts.map +1 -1
  68. package/dist/commands/history-command.d.ts +173 -7
  69. package/dist/commands/history-command.d.ts.map +1 -1
  70. package/dist/commands/index-host.d.ts +19 -0
  71. package/dist/commands/index-host.d.ts.map +1 -1
  72. package/dist/commands/index-refresh.d.ts +36 -0
  73. package/dist/commands/index-refresh.d.ts.map +1 -0
  74. package/dist/commands/index.d.ts +9 -0
  75. package/dist/commands/index.d.ts.map +1 -1
  76. package/dist/commands/index.js +7 -6
  77. package/dist/commands/init-command.d.ts +20 -0
  78. package/dist/commands/init-command.d.ts.map +1 -1
  79. package/dist/commands/local-transport.d.ts +40 -2
  80. package/dist/commands/local-transport.d.ts.map +1 -1
  81. package/dist/commands/log-command.d.ts +7 -0
  82. package/dist/commands/log-command.d.ts.map +1 -1
  83. package/dist/commands/log-output.d.ts +11 -0
  84. package/dist/commands/log-output.d.ts.map +1 -1
  85. package/dist/commands/ls-tree-command.d.ts +10 -0
  86. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  87. package/dist/commands/maintenance-schedule-command.d.ts +122 -0
  88. package/dist/commands/maintenance-schedule-command.d.ts.map +1 -0
  89. package/dist/commands/merge-command.d.ts +13 -1
  90. package/dist/commands/merge-command.d.ts.map +1 -1
  91. package/dist/commands/merge-index-command.d.ts +42 -0
  92. package/dist/commands/merge-index-command.d.ts.map +1 -0
  93. package/dist/commands/merge-one-file.d.ts +129 -0
  94. package/dist/commands/merge-one-file.d.ts.map +1 -0
  95. package/dist/commands/merge-support.d.ts +40 -4
  96. package/dist/commands/merge-support.d.ts.map +1 -1
  97. package/dist/commands/object-disk-info.d.ts +35 -0
  98. package/dist/commands/object-disk-info.d.ts.map +1 -0
  99. package/dist/commands/octopus-merge.d.ts +3 -3
  100. package/dist/commands/octopus-merge.d.ts.map +1 -1
  101. package/dist/commands/plumbing-input.d.ts.map +1 -1
  102. package/dist/commands/promisor-remote-reply.d.ts +31 -4
  103. package/dist/commands/promisor-remote-reply.d.ts.map +1 -1
  104. package/dist/commands/promisor-remote.d.ts +8 -1
  105. package/dist/commands/promisor-remote.d.ts.map +1 -1
  106. package/dist/commands/pull-command.d.ts +55 -7
  107. package/dist/commands/pull-command.d.ts.map +1 -1
  108. package/dist/commands/push-command.d.ts +18 -1
  109. package/dist/commands/push-command.d.ts.map +1 -1
  110. package/dist/commands/range-diff/range-diff-command.d.ts +37 -1
  111. package/dist/commands/range-diff/range-diff-command.d.ts.map +1 -1
  112. package/dist/commands/rebase-command.d.ts +13 -1
  113. package/dist/commands/rebase-command.d.ts.map +1 -1
  114. package/dist/commands/ref-filter/for-each-ref-command.d.ts +3 -2
  115. package/dist/commands/ref-filter/for-each-ref-command.d.ts.map +1 -1
  116. package/dist/commands/ref-filter/index.d.ts +1 -0
  117. package/dist/commands/ref-filter/index.d.ts.map +1 -1
  118. package/dist/commands/ref-filter/peel-limit.d.ts +8 -0
  119. package/dist/commands/ref-filter/peel-limit.d.ts.map +1 -0
  120. package/dist/commands/ref-filter/ref-filter.d.ts.map +1 -1
  121. package/dist/commands/ref-filter/ref-format.d.ts +26 -1
  122. package/dist/commands/ref-filter/ref-format.d.ts.map +1 -1
  123. package/dist/commands/ref-filter/ref-listing-command.d.ts +9 -0
  124. package/dist/commands/ref-filter/ref-listing-command.d.ts.map +1 -1
  125. package/dist/commands/remote-transport.d.ts +27 -0
  126. package/dist/commands/remote-transport.d.ts.map +1 -1
  127. package/dist/commands/repack-command.d.ts +18 -2
  128. package/dist/commands/repack-command.d.ts.map +1 -1
  129. package/dist/commands/repo-command.d.ts +2 -7
  130. package/dist/commands/repo-command.d.ts.map +1 -1
  131. package/dist/commands/reset-command.d.ts +4 -1
  132. package/dist/commands/reset-command.d.ts.map +1 -1
  133. package/dist/commands/restore-command.d.ts.map +1 -1
  134. package/dist/commands/rev-list-command.d.ts +65 -0
  135. package/dist/commands/rev-list-command.d.ts.map +1 -1
  136. package/dist/commands/revert-command.d.ts +3 -0
  137. package/dist/commands/revert-command.d.ts.map +1 -1
  138. package/dist/commands/revision-filenames.d.ts.map +1 -1
  139. package/dist/commands/revision-range.d.ts +17 -0
  140. package/dist/commands/revision-range.d.ts.map +1 -1
  141. package/dist/commands/revision-resolver.d.ts +12 -0
  142. package/dist/commands/revision-resolver.d.ts.map +1 -1
  143. package/dist/commands/serve-repository.d.ts +21 -4
  144. package/dist/commands/serve-repository.d.ts.map +1 -1
  145. package/dist/commands/served-lazy-fetch.d.ts +61 -0
  146. package/dist/commands/served-lazy-fetch.d.ts.map +1 -0
  147. package/dist/commands/signing.d.ts +37 -4
  148. package/dist/commands/signing.d.ts.map +1 -1
  149. package/dist/commands/split-cmdline.d.ts +6 -0
  150. package/dist/commands/split-cmdline.d.ts.map +1 -0
  151. package/dist/commands/status-color-config.d.ts +33 -0
  152. package/dist/commands/status-color-config.d.ts.map +1 -0
  153. package/dist/commands/status-command.d.ts +15 -0
  154. package/dist/commands/status-command.d.ts.map +1 -1
  155. package/dist/commands/status-format.d.ts +46 -4
  156. package/dist/commands/status-format.d.ts.map +1 -1
  157. package/dist/commands/tag-command.d.ts +15 -1
  158. package/dist/commands/tag-command.d.ts.map +1 -1
  159. package/dist/commands/tree-restore.d.ts +14 -0
  160. package/dist/commands/tree-restore.d.ts.map +1 -1
  161. package/dist/commands/verify-command.d.ts +22 -2
  162. package/dist/commands/verify-command.d.ts.map +1 -1
  163. package/dist/commands/worktree-add-command.d.ts.map +1 -1
  164. package/dist/commands/worktree-overwrite-checks.d.ts +31 -6
  165. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  166. package/dist/{commands-CPceUCP2.js → commands-DT3VEv50.js} +15168 -16842
  167. package/dist/errors/commit-errors.d.ts +37 -1
  168. package/dist/errors/commit-errors.d.ts.map +1 -1
  169. package/dist/errors/git-api-error.d.ts +6 -0
  170. package/dist/errors/git-api-error.d.ts.map +1 -1
  171. package/dist/errors/index.js +44 -3
  172. package/dist/{fsck-tbrPZX2q.js → fsck-BZ508Elg.js} +2 -2
  173. package/dist/git-command.d.ts +33 -1
  174. package/dist/git-command.d.ts.map +1 -1
  175. package/dist/git.d.ts +104 -1
  176. package/dist/git.d.ts.map +1 -1
  177. package/dist/index.js +8 -7
  178. package/dist/{remote-transport-C0OSJtor.js → local-transport-D98U6p4d.js} +228 -692
  179. package/dist/{maintenance-run-command-UiSIaeP8.js → maintenance-run-command-DZFnbnbo.js} +2366 -108
  180. package/dist/remote-config/remote-config-store.d.ts +6 -0
  181. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  182. package/dist/remote-transport-zvSqwpOB.js +4865 -0
  183. package/dist/results/cherry-pick-result.d.ts +4 -3
  184. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  185. package/dist/results/diff-output.d.ts +7 -0
  186. package/dist/results/diff-output.d.ts.map +1 -1
  187. package/dist/results/diff-words.d.ts +14 -3
  188. package/dist/results/diff-words.d.ts.map +1 -1
  189. package/dist/results/index.js +1 -1
  190. package/dist/results/line-prefix-sink.d.ts +50 -0
  191. package/dist/results/line-prefix-sink.d.ts.map +1 -0
  192. package/dist/results/merge-result.d.ts +4 -3
  193. package/dist/results/merge-result.d.ts.map +1 -1
  194. package/dist/results/rebase-result.d.ts +5 -0
  195. package/dist/results/rebase-result.d.ts.map +1 -1
  196. package/dist/results/revert-result.d.ts +4 -3
  197. package/dist/results/revert-result.d.ts.map +1 -1
  198. package/dist/{results-CkS1p1CH.js → results-rF81cQse.js} +1788 -247
  199. package/dist/transport-command.d.ts +13 -0
  200. package/dist/transport-command.d.ts.map +1 -1
  201. package/package.json +21 -13
  202. package/src/commands/add-command.ts +15 -2
  203. package/src/commands/add-patch/patch-backend.ts +6 -44
  204. package/src/commands/archive/archive-command.ts +7 -3
  205. package/src/commands/archive/remote-archive-command.ts +45 -4
  206. package/src/commands/archive/upload-archive-writer.ts +34 -22
  207. package/src/commands/branch-command.ts +57 -4
  208. package/src/commands/bundle/bundle-format.ts +10 -2
  209. package/src/commands/bundle/bundle-uri-host.ts +71 -11
  210. package/src/commands/bundle/bundle-uri.ts +11 -4
  211. package/src/commands/bundle/bundle-verify.ts +4 -1
  212. package/src/commands/cat-file/batch-format.ts +17 -18
  213. package/src/commands/cat-file/cat-file-command.ts +182 -48
  214. package/src/commands/check-ignore-command.ts +110 -21
  215. package/src/commands/checkout-command.ts +149 -21
  216. package/src/commands/checkout-index-command.ts +2 -1
  217. package/src/commands/checkout-paths.ts +13 -0
  218. package/src/commands/cherry-pick-command.ts +9 -0
  219. package/src/commands/clean-interactive.ts +20 -74
  220. package/src/commands/clone-command.ts +102 -11
  221. package/src/commands/column/column-config.ts +63 -0
  222. package/src/commands/column/column-layout.ts +396 -0
  223. package/src/commands/column/index.ts +2 -0
  224. package/src/commands/column-command.ts +171 -0
  225. package/src/commands/comment-char-config.ts +42 -0
  226. package/src/commands/commit-command.ts +93 -18
  227. package/src/commands/config-command.ts +28 -0
  228. package/src/commands/credential-helper.ts +807 -0
  229. package/src/commands/default-branch.ts +57 -5
  230. package/src/commands/diff-color-config.ts +23 -10
  231. package/src/commands/diff-command.ts +25 -2
  232. package/src/commands/fast-export/fast-export-command.ts +661 -35
  233. package/src/commands/fast-export/fast-import-command.ts +694 -94
  234. package/src/commands/fast-export/fast-stream-support.ts +18 -1
  235. package/src/commands/fetch-command.ts +116 -16
  236. package/src/commands/fsck/fsck-object-checks.ts +3 -1
  237. package/src/commands/git-hooks.ts +96 -5
  238. package/src/commands/history-command.ts +952 -20
  239. package/src/commands/index-host.ts +51 -0
  240. package/src/commands/index-refresh.ts +121 -0
  241. package/src/commands/index.ts +9 -0
  242. package/src/commands/init-command.ts +57 -4
  243. package/src/commands/legacy-remotes.ts +4 -20
  244. package/src/commands/local-transport.ts +183 -18
  245. package/src/commands/log-command.ts +39 -1
  246. package/src/commands/log-output.ts +31 -4
  247. package/src/commands/ls-tree-command.ts +20 -12
  248. package/src/commands/maintenance-schedule-command.ts +418 -0
  249. package/src/commands/merge-command.ts +42 -8
  250. package/src/commands/merge-index-command.ts +202 -0
  251. package/src/commands/merge-one-file.ts +451 -0
  252. package/src/commands/merge-support.ts +169 -15
  253. package/src/commands/object-disk-info.ts +169 -0
  254. package/src/commands/octopus-merge.ts +37 -128
  255. package/src/commands/plumbing-input.ts +3 -1
  256. package/src/commands/promisor-remote-reply.ts +338 -56
  257. package/src/commands/promisor-remote.ts +39 -6
  258. package/src/commands/pull-command.ts +173 -27
  259. package/src/commands/push-command.ts +55 -6
  260. package/src/commands/range-diff/range-diff-command.ts +86 -3
  261. package/src/commands/read-tree-command.ts +2 -2
  262. package/src/commands/rebase-command.ts +46 -1
  263. package/src/commands/ref-filter/for-each-ref-command.ts +4 -3
  264. package/src/commands/ref-filter/index.ts +1 -0
  265. package/src/commands/ref-filter/peel-limit.ts +7 -0
  266. package/src/commands/ref-filter/ref-filter.ts +68 -7
  267. package/src/commands/ref-filter/ref-format.ts +85 -11
  268. package/src/commands/ref-filter/ref-listing-command.ts +30 -0
  269. package/src/commands/remote-command.ts +2 -2
  270. package/src/commands/remote-transport.ts +66 -3
  271. package/src/commands/repack-command.ts +75 -9
  272. package/src/commands/repo-command.ts +6 -70
  273. package/src/commands/reset-command.ts +11 -1
  274. package/src/commands/restore-command.ts +1 -0
  275. package/src/commands/rev-list-command.ts +205 -3
  276. package/src/commands/revert-command.ts +9 -0
  277. package/src/commands/revision-filenames.ts +32 -4
  278. package/src/commands/revision-range.ts +2 -2
  279. package/src/commands/revision-resolver.ts +21 -1
  280. package/src/commands/serve-repository.ts +42 -11
  281. package/src/commands/served-lazy-fetch.ts +164 -0
  282. package/src/commands/signing.ts +103 -12
  283. package/src/commands/split-cmdline.ts +32 -0
  284. package/src/commands/status-color-config.ts +92 -0
  285. package/src/commands/status-command.ts +50 -2
  286. package/src/commands/status-format.ts +198 -50
  287. package/src/commands/tag-command.ts +57 -2
  288. package/src/commands/tree-restore.ts +17 -0
  289. package/src/commands/verify-command.ts +84 -12
  290. package/src/commands/worktree-add-command.ts +2 -0
  291. package/src/commands/worktree-overwrite-checks.ts +75 -14
  292. package/src/errors/commit-errors.ts +52 -2
  293. package/src/errors/git-api-error.ts +7 -0
  294. package/src/git-command.ts +105 -4
  295. package/src/git.ts +153 -0
  296. package/src/remote-config/remote-config-store.ts +16 -0
  297. package/src/results/cherry-pick-result.ts +4 -3
  298. package/src/results/diff-output.ts +8 -0
  299. package/src/results/diff-words.ts +160 -32
  300. package/src/results/line-prefix-sink.ts +102 -0
  301. package/src/results/merge-result.ts +4 -3
  302. package/src/results/rebase-result.ts +5 -0
  303. package/src/results/revert-result.ts +4 -3
  304. package/src/transport-command.ts +79 -3
@@ -19,9 +19,23 @@
19
19
  */
20
20
 
21
21
  import type { ObjectId, TreeEntry } from "@statewalker/vcs-core";
22
- import { encodeGitPath } from "@statewalker/vcs-utils/encoding";
22
+ import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
23
+ import { DEFAULT_RENAME_LIMIT } from "../../rename/index.js";
24
+ import { ChangeType, type DiffEntry } from "../../results/diff-entry.js";
23
25
  import { quoteCStyleBody } from "../../results/quote-path.js";
26
+ import { DiffCommand } from "../diff-command.js";
27
+ import { approxidateCareful } from "../git-date.js";
28
+ import type { LogOrder, LogResult } from "../log-command.js";
24
29
  import { configValue } from "../merge-config.js";
30
+ import {
31
+ ALL_ENTRIES_INTERESTING,
32
+ ALL_ENTRIES_NOT_INTERESTING,
33
+ ENTRY_NOT_INTERESTING,
34
+ parsePathspecItem,
35
+ type TreePathspec,
36
+ treeEntryInteresting,
37
+ treePathspec,
38
+ } from "../pathspec.js";
25
39
  import { PlumbingCommand, PlumbingError } from "../plumbing-command.js";
26
40
  import { RevListCommand } from "../rev-list-command.js";
27
41
  import {
@@ -46,10 +60,15 @@ const NULL_SHA1 = "0".repeat(40);
46
60
 
47
61
  /** One changed path of a commit's diff against its parent (diff_filepair). */
48
62
  interface FilePair {
49
- status: "A" | "D" | "M" | "T";
63
+ /** `=`: an unchanged path `-C -C` lists (find_copies_harder), a copy source only */
64
+ status: "A" | "D" | "M" | "T" | "R" | "C" | "=";
50
65
  path: string;
51
66
  mode: number;
52
67
  id: ObjectId | undefined;
68
+ /** The old side's path (a rename's or copy's source), mode and id */
69
+ oldPath?: string;
70
+ oldMode?: number;
71
+ oldId?: ObjectId;
53
72
  }
54
73
 
55
74
  /**
@@ -147,7 +166,23 @@ function applyRefspecs(specs: readonly ExportRefspec[], name: string): string |
147
166
  * name get `reset` lines, annotated tags `tag` commands, at the end. Marks are numbered as
148
167
  * git numbers them, so the stream is git's byte for byte.
149
168
  *
150
- * Not supported: pathspecs, `--anonymize`, rename and copy detection (`-M`, `-C`).
169
+ * Paths after the revisions (`-- <path>...`, or {@link addPath}) limit the export as git's
170
+ * walk does: only commits changing them are written, with their parents rewritten past the
171
+ * others and their `M`/`D` lines limited to the paths; refs and tags of commits left out move
172
+ * to the nearest exported ancestor (git's `rewrite_commit`), or are reset to the null id when
173
+ * none is left. With `--import-marks`, paths imply `--full-tree`, as in git.
174
+ *
175
+ * `-M`, `-C` and `-C -C` ({@link setFindRenames}, {@link setFindCopies}) run diffcore's
176
+ * rename and copy detection over each commit's diff and write `R`/`C` lines as git does: a
177
+ * copy or rename whose source was already changed in the commit is written as the new
178
+ * file's `M` line, one that changes its content also gets one.
179
+ *
180
+ * `--anonymize` ({@link setAnonymize}) replaces paths (each component), ref names (after
181
+ * `refs/heads/`, `refs/tags/`, `refs/remotes/` or `refs/`), idents, commit and tag messages,
182
+ * blob contents and gitlink ids by git's counted tokens (`path0`, `ref1`, `User 2
183
+ * <user2@example.com>`, `subject 3`, `tag message 4`, `anonymous blob 5`), each kind
184
+ * numbered in the order git meets it, so the stream is git's byte for byte;
185
+ * `--anonymize-map` ({@link addAnonymizeMap}) keeps or maps given tokens.
151
186
  *
152
187
  * Version differences (`setCompatibility`): 2.43 finds a tag's signature only as a PGP
153
188
  * signature after a newline and words several messages with a capital letter; 2.5x knows
@@ -155,6 +190,17 @@ function applyRefspecs(specs: readonly ExportRefspec[], name: string): string |
155
190
  */
156
191
  export class FastExportCommand extends PlumbingCommand {
157
192
  private readonly revisions: string[] = [];
193
+ private readonly paths: string[] = [];
194
+ /** diff_options' `detect_rename`: the last of `-M`/`-C` wins, as git parses them. */
195
+ private detectRename?: "rename" | "copy";
196
+ /** diff_options' `rename_score`, as the last `-M`/`-C` gave it (`true`: the default). */
197
+ private renameScore: true | string = true;
198
+ private anonymize = false;
199
+ /** `--anonymize-map` tokens (anonymized_seeds) */
200
+ private readonly anonymizeSeeds = new Map<string, string>();
201
+ private anonymizeMapError?: string;
202
+ private anonymizer?: Anonymizer;
203
+ private findCopiesHarder = false;
158
204
  private progressEvery = 0;
159
205
  private signedTags: SignMode = "abort";
160
206
  private signedCommits: SignMode = "strip";
@@ -182,6 +228,10 @@ export class FastExportCommand extends PlumbingCommand {
182
228
  private readonly shown = new Set<ObjectId>();
183
229
  private progressCounter = 0;
184
230
  private quotePathFully = true;
231
+ /** The paths limiting the export, as tree-diff matches them */
232
+ private pathspec?: TreePathspec;
233
+ /** fast-export.c's rewrite_commit over the walk (the commit itself before it) */
234
+ private rewrite: (id: ObjectId) => ObjectId | null = (id) => id;
185
235
 
186
236
  private outputStream?: WritableStream<Uint8Array>;
187
237
 
@@ -203,13 +253,87 @@ export class FastExportCommand extends PlumbingCommand {
203
253
  }
204
254
  }
205
255
 
206
- /** A revision argument (`main`, `^v1`, `a..b`, `--all`, ...), as `git rev-list` reads it. */
256
+ /**
257
+ * An argument as git's `setup_revisions` reads it: a revision (`main`, `^v1`, `a..b`,
258
+ * `--all`, ...), `--`, or a path. As in git, the first `--` is fast-export's own (its
259
+ * option parser drops it), so paths after it must exist in the worktree (or look like a
260
+ * pathspec) as any argument that names no revision; only a second `--` takes them as given.
261
+ */
207
262
  addArgument(arg: string): this {
208
263
  this.checkCallable();
209
264
  this.revisions.push(arg);
210
265
  return this;
211
266
  }
212
267
 
268
+ /**
269
+ * `-M[<n>]` / `--find-renames[=<n>]`: renames written as `R` lines (`true` for the default
270
+ * 50% threshold, else git's `90%`, `9`, `.9`).
271
+ */
272
+ setFindRenames(value: boolean | string = true): this {
273
+ this.checkCallable();
274
+ if (value === false) {
275
+ this.detectRename = undefined;
276
+ return this;
277
+ }
278
+ // diff_opt_find_renames: the score is reset, the mode is renames whatever came before
279
+ this.renameScore = value;
280
+ this.detectRename = "rename";
281
+ return this;
282
+ }
283
+
284
+ /**
285
+ * `-C[<n>]` / `--find-copies[=<n>]`: renames and copies written as `R`/`C` lines; given
286
+ * twice, as git's `-C -C`, unchanged paths are copy sources too ({@link setFindCopiesHarder}).
287
+ */
288
+ setFindCopies(value: boolean | string = true): this {
289
+ this.checkCallable();
290
+ if (value === false) {
291
+ this.detectRename = undefined;
292
+ return this;
293
+ }
294
+ // diff_opt_find_copies: a second -C while copies are on finds them harder
295
+ this.renameScore = value;
296
+ if (this.detectRename === "copy") this.findCopiesHarder = true;
297
+ else this.detectRename = "copy";
298
+ return this;
299
+ }
300
+
301
+ /** `--find-copies-harder`: every path of the parent is a copy source. */
302
+ setFindCopiesHarder(harder: boolean): this {
303
+ this.checkCallable();
304
+ this.findCopiesHarder = harder;
305
+ return this;
306
+ }
307
+
308
+ /** `--anonymize`: paths, refs, idents, messages and contents replaced by git's tokens. */
309
+ setAnonymize(anonymize: boolean): this {
310
+ this.checkCallable();
311
+ this.anonymize = anonymize;
312
+ return this;
313
+ }
314
+
315
+ /**
316
+ * `--anonymize-map=<from>[:<to>]`: the path or ref component (or ident, message...) `from`
317
+ * is written as `to` (as itself without one); a later mapping of `from` wins. An empty
318
+ * token is git's option error (exit 129); without {@link setAnonymize} the run dies.
319
+ */
320
+ addAnonymizeMap(token: string): this {
321
+ this.checkCallable();
322
+ const delim = token.indexOf(":");
323
+ const key = delim < 0 ? token : token.slice(0, delim);
324
+ const value = delim < 0 ? token : token.slice(delim + 1);
325
+ if (!key || !value) this.anonymizeMapError ??= "error: --anonymize-map token cannot be empty";
326
+ else this.anonymizeSeeds.set(bin(key), bin(value));
327
+ return this;
328
+ }
329
+
330
+ /** A pathspec element limiting the export, taken as given (git's `-- -- <path>`). */
331
+ addPath(path: string): this {
332
+ this.checkCallable();
333
+ this.paths.push(path);
334
+ return this;
335
+ }
336
+
213
337
  /** `--progress=<n>`: a `progress <n> objects` line after every n objects. */
214
338
  setProgressEvery(every: number): this {
215
339
  this.checkCallable();
@@ -358,6 +482,12 @@ export class FastExportCommand extends PlumbingCommand {
358
482
  }
359
483
 
360
484
  protected async run(): Promise<number> {
485
+ if (this.anonymizeMapError) throw new PlumbingError(this.anonymizeMapError, 129);
486
+ this.walkOptions(this.setupArguments());
487
+ if (this.anonymizeSeeds.size > 0 && !this.anonymize) {
488
+ this.die("the option '--anonymize-map' requires '--anonymize'");
489
+ }
490
+ if (this.anonymize) this.anonymizer = new Anonymizer(this.anonymizeSeeds, this.objectFormat);
361
491
  const quote = configValue(this.workingCopy, "core.quotePath");
362
492
  this.quotePathFully = quote === undefined ? true : !/^(false|no|off|0)$/i.test(quote);
363
493
 
@@ -373,6 +503,15 @@ export class FastExportCommand extends PlumbingCommand {
373
503
 
374
504
  // the command line's entries (rev_cmdline_info), objects as named
375
505
  const parsed = await this.revList().setCommittish(false).resolve();
506
+ const paths = [...this.paths, ...parsed.paths];
507
+ if (paths.length > 0) {
508
+ const items = paths.map((p) => parsePathspecItem(p));
509
+ // parse_pathspec: only exclusions match everything else
510
+ if (items.every((i) => i.exclude)) items.push(parsePathspecItem("."));
511
+ this.pathspec = treePathspec(items);
512
+ }
513
+ // git: `if (import_filename && revs.prune_data.nr) full_tree = 1;`
514
+ if (this.importMarksPath !== undefined && paths.length > 0) this.fullTree = true;
376
515
  const extraRefs = new Map<string, ObjectId>();
377
516
  const tagRefs: { name: string; tag: ObjectId }[] = [];
378
517
  /** revision_sources set before the walk (get_tags_and_duplicates) */
@@ -433,8 +572,11 @@ export class FastExportCommand extends PlumbingCommand {
433
572
  }
434
573
 
435
574
  // the walk: git's --topo-order, reversed, with each commit's source
436
- const walk = this.revList().setOrder("topo").setReverse(true).setSource(true);
437
- const commits = this.revisions.length > 0 ? await walk.call() : [];
575
+ const walk = this.revList().setReverse(true).setSource(true).setParents(true);
576
+ // no revision named: nothing walked (fast-export sets no default revision)
577
+ const commits = parsed.entries.some((e) => !e.exclude)
578
+ ? await walk.call()
579
+ : ([] as LogResult[]);
438
580
  for await (const commit of commits) {
439
581
  if (this.shown.has(commit.id)) continue;
440
582
  let name = preset.get(commit.id);
@@ -444,12 +586,20 @@ export class FastExportCommand extends PlumbingCommand {
444
586
  name = (tip !== undefined ? preset.get(tip) : undefined) ?? source;
445
587
  }
446
588
  extraRefs.delete(name);
447
- await this.handleCommit(commit.id, name);
589
+ await this.handleCommit(commit.id, name, commit.parents);
448
590
  }
591
+ this.rewrite = (id) => walk.rewriteCommit(id);
449
592
 
450
593
  const sortedExtras = [...extraRefs.entries()].sort(([a], [b]) => compareBytes(a, b));
451
594
  for (let i = sortedExtras.length - 1; i >= 0; i--) {
452
- const [name, id] = sortedExtras[i] as [string, ObjectId];
595
+ const [realName, tip] = sortedExtras[i] as [string, ObjectId];
596
+ const name = this.anonymizer ? this.anonymizer.refname(realName) : realName;
597
+ // refs pointing to commits seen, or to their nearest exported ancestor
598
+ const id = this.rewrite(tip);
599
+ if (id === null) {
600
+ await this.out(`reset ${bin(name)}\nfrom ${NULL_SHA1}\n\n`);
601
+ continue;
602
+ }
453
603
  const mark = this.marks.get(id);
454
604
  if (!mark) {
455
605
  await this.out(`reset ${bin(name)}\nfrom ${this.referenceExcluded ? id : NULL_SHA1}\n\n`);
@@ -479,8 +629,141 @@ export class FastExportCommand extends PlumbingCommand {
479
629
 
480
630
  private revList(): RevListCommand {
481
631
  const cmd = new RevListCommand(this.workingCopy);
482
- for (const r of this.revisions) cmd.addRevision(r);
483
- return cmd;
632
+ const args = this.setupArguments();
633
+ const options = this.walkOptions(args);
634
+ if (this.paths.length > 0 && !args.includes("--")) args.push("--");
635
+ // cmd_fast_export sets topo_order before setup_revisions; --date-order changes the sort
636
+ let order: LogOrder = "topo";
637
+ args.forEach((a, i) => {
638
+ const apply = options.get(i);
639
+ if (apply) order = apply(cmd) ?? order;
640
+ else cmd.addArgument(a);
641
+ });
642
+ for (const p of this.paths) cmd.addArgument(p);
643
+ return cmd.setOrder(order);
644
+ }
645
+
646
+ /**
647
+ * The arguments setup_revisions gets: fast-export's parse_options stops at the first `--`,
648
+ * which it drops (what follows is read as more arguments: paths must then exist, unless a
649
+ * second `--` comes), or at `--end-of-options`, which git 2.44+ keeps for setup_revisions
650
+ * (`PARSE_OPT_KEEP_UNKNOWN_OPT`) and 2.43 drops; a `--` after it reaches setup_revisions.
651
+ */
652
+ private setupArguments(): string[] {
653
+ const args = [...this.revisions];
654
+ const stop = args.findIndex((a) => a === "--" || a === "--end-of-options");
655
+ if (stop >= 0 && (args[stop] === "--" || this.compatibility === "2.43")) args.splice(stop, 1);
656
+ return args;
657
+ }
658
+
659
+ /** setup_revisions left an option in argv: fast-export prints its usage (exit 129). */
660
+ private usage(): never {
661
+ throw new PlumbingError(
662
+ this.compatibility === "2.43"
663
+ ? "usage: git fast-export [<rev-list-opts>]"
664
+ : "usage: git fast-export [<options>] [<revision-range>] [[--] <path>...]",
665
+ 129,
666
+ );
667
+ }
668
+
669
+ /**
670
+ * The walk options setup_revisions reads among fast-export's arguments, before its own `--`
671
+ * and `--end-of-options`: by position, how each changes the walk (a sort order returned).
672
+ * Ref options (`--all`, `--glob <pattern>`...) stay revisions. Any other option is one
673
+ * setup_revisions leaves in argv, or one the walk cannot take yet: fast-export's usage.
674
+ * `--reverse` changes nothing: the walk is reversed after setup_revisions (`revs.reverse = 1`).
675
+ */
676
+ private walkOptions(
677
+ args: readonly string[],
678
+ ): Map<number, (cmd: RevListCommand) => LogOrder | undefined> {
679
+ const options = new Map<number, (cmd: RevListCommand) => LogOrder | undefined>();
680
+ const set = (i: number, f: (cmd: RevListCommand) => unknown, order?: LogOrder) =>
681
+ options.set(i, (cmd) => {
682
+ f(cmd);
683
+ return order;
684
+ });
685
+ const count = (value: string | undefined): number => {
686
+ if (value === undefined || !/^-?\d+$/.test(value)) this.usage();
687
+ return Number.parseInt(value, 10);
688
+ };
689
+ const date = (value: string) => approxidateCareful(value).timestamp;
690
+ for (let i = 0; i < args.length; i++) {
691
+ const arg = args[i] as string;
692
+ if (arg === "--" || arg === "--end-of-options") break;
693
+ if (!arg.startsWith("-") || arg === "-") continue;
694
+ if (/^--(all|not|branches|tags|remotes)(=.*)?$|^--(glob|exclude)=/s.test(arg)) continue;
695
+ if (arg === "--glob" || arg === "--exclude") {
696
+ i++; // parse_long_opt: the pattern is the next argument
697
+ continue;
698
+ }
699
+ switch (arg) {
700
+ case "--first-parent":
701
+ set(i, (cmd) => cmd.setFirstParent(true));
702
+ continue;
703
+ case "--reverse":
704
+ set(i, () => undefined);
705
+ continue;
706
+ case "--topo-order":
707
+ set(i, () => undefined, "topo");
708
+ continue;
709
+ case "--date-order":
710
+ set(i, () => undefined, "date");
711
+ continue;
712
+ case "--author-date-order":
713
+ set(i, () => undefined, "author-date");
714
+ continue;
715
+ case "--full-history":
716
+ set(i, (cmd) => cmd.setFullHistory(true));
717
+ continue;
718
+ case "--no-merges":
719
+ set(i, (cmd) => cmd.setNoMerges(true));
720
+ continue;
721
+ case "--simplify-merges":
722
+ set(i, (cmd) => cmd.setSimplifyMerges(true));
723
+ continue;
724
+ case "--ancestry-path":
725
+ set(i, (cmd) => cmd.setAncestryPath(true));
726
+ continue;
727
+ case "-n":
728
+ case "--max-count": {
729
+ const n = count(args[i + 1]);
730
+ set(i, (cmd) => cmd.setMaxCount(n));
731
+ options.set(i + 1, () => undefined);
732
+ i++;
733
+ continue;
734
+ }
735
+ }
736
+ const ancestry = /^--ancestry-path=(.*)$/s.exec(arg);
737
+ const maxCount = /^(?:--max-count=|-n)(.*)$/s.exec(arg) ?? /^-(\d+)$/.exec(arg);
738
+ const skip = /^--skip=(.*)$/s.exec(arg);
739
+ const m = /^--(since|after|max-age|until|before|min-age)(?:=(.*))?$/s.exec(arg);
740
+ if (ancestry) {
741
+ const c = ancestry[1] as string;
742
+ set(i, (cmd) => cmd.addAncestryPath(c));
743
+ } else if (maxCount) {
744
+ const n = count(maxCount[1]);
745
+ set(i, (cmd) => cmd.setMaxCount(n));
746
+ } else if (skip) {
747
+ const n = count(skip[1]);
748
+ set(i, (cmd) => cmd.setSkip(n));
749
+ } else if (m) {
750
+ const at = i;
751
+ let value = m[2];
752
+ if (value === undefined && !m[1]?.endsWith("-age")) {
753
+ value = args[i + 1];
754
+ options.set(i + 1, () => undefined);
755
+ i++;
756
+ }
757
+ if (value === undefined) this.usage();
758
+ const t = m[1]?.endsWith("-age") ? count(value) : date(value);
759
+ if (m[1] === "since" || m[1] === "after" || m[1] === "max-age") {
760
+ set(at, (cmd) => cmd.setSince(t));
761
+ } else set(at, (cmd) => cmd.setUntil(t));
762
+ } else {
763
+ this.usage();
764
+ }
765
+ }
766
+ return options;
484
767
  }
485
768
 
486
769
  private marksFilesOrDie(): FastMarksFiles {
@@ -542,9 +825,13 @@ export class FastExportCommand extends PlumbingCommand {
542
825
  private async exportBlob(id: ObjectId | undefined): Promise<void> {
543
826
  if (this.noData || id === undefined || /^0+$/.test(id)) return;
544
827
  if (this.shown.has(id)) return;
545
- const raw = await readObjectBytes(this.objects, id);
546
- if (!raw) this.die(`could not read blob ${id}`);
547
- const { bytes } = raw as { bytes: Uint8Array };
828
+ let bytes: Uint8Array;
829
+ if (this.anonymizer) bytes = latin1Bytes(this.anonymizer.blob());
830
+ else {
831
+ const raw = await readObjectBytes(this.objects, id);
832
+ if (!raw) this.die(`could not read blob ${id}`);
833
+ bytes = (raw as { bytes: Uint8Array }).bytes;
834
+ }
548
835
  const mark = this.markNext(id, false);
549
836
  let header = `blob\nmark :${mark}\n`;
550
837
  if (this.showOriginalIds) header += `original-oid ${id}\n`;
@@ -557,14 +844,19 @@ export class FastExportCommand extends PlumbingCommand {
557
844
  }
558
845
 
559
846
  /** print_path: C-quoted when needed, else in double quotes when it holds a space. */
560
- private pathText(path: string): string {
847
+ private pathText(name: string): string {
848
+ const path = this.anonymizer ? this.anonymizer.path(name) : name;
561
849
  const body = quoteCStyleBody(path, this.quotePathFully);
562
850
  if (body !== undefined) return latin1(encodeGitPath(`"${body}"`));
563
851
  const bytes = latin1(encodeGitPath(path));
564
852
  return bytes.includes(" ") ? `"${bytes}"` : bytes;
565
853
  }
566
854
 
567
- private async handleCommit(id: ObjectId, refname: string): Promise<void> {
855
+ private async handleCommit(
856
+ id: ObjectId,
857
+ refname: string,
858
+ walkParents?: readonly ObjectId[],
859
+ ): Promise<void> {
568
860
  const raw = await readObjectBytes(this.objects, id);
569
861
  if (!raw) this.die(`could not read commit ${id}`);
570
862
  const buffer = latin1((raw as { bytes: Uint8Array }).bytes);
@@ -572,16 +864,18 @@ export class FastExportCommand extends PlumbingCommand {
572
864
  let tree = "";
573
865
  const authorAt = buffer.indexOf("\nauthor ");
574
866
  if (authorAt < 0) this.die(`could not find author in commit ${id}`);
575
- const author = buffer.slice(authorAt + 1, lineEnd(buffer, authorAt + 1));
867
+ const authorLine = buffer.slice(authorAt + 1, lineEnd(buffer, authorAt + 1));
576
868
  let cursor = lineEnd(buffer, authorAt + 1);
577
869
  const committerAt = buffer.indexOf("\ncommitter ", cursor);
578
870
  if (committerAt < 0) this.die(`could not find committer in commit ${id}`);
579
- const committer = buffer.slice(committerAt + 1, lineEnd(buffer, committerAt + 1));
871
+ const committerLine = buffer.slice(committerAt + 1, lineEnd(buffer, committerAt + 1));
580
872
  cursor = lineEnd(buffer, committerAt + 1);
581
873
  for (const line of buffer.slice(0, authorAt + 1).split("\n")) {
582
874
  if (line.startsWith("tree ")) tree = line.slice(5);
583
875
  else if (line.startsWith("parent ")) parents.push(line.slice(7));
584
876
  }
877
+ // the parents as the walk has them (rewritten past the commits a pathspec leaves out)
878
+ if (walkParents) parents.splice(0, parents.length, ...walkParents);
585
879
 
586
880
  // the headers after the committer: encoding, then the signatures
587
881
  let encoding: string | undefined;
@@ -619,15 +913,25 @@ export class FastExportCommand extends PlumbingCommand {
619
913
 
620
914
  // the diff against the first parent, when it is exported (or referenced)
621
915
  const first = parents[0];
916
+ const ps = this.pathspec;
622
917
  const pairs =
623
918
  first !== undefined && (this.marks.has(first) || this.referenceExcluded) && !this.fullTree
624
- ? await this.diffTrees(await this.treeOf(first), tree)
625
- : await this.diffTrees(undefined, tree);
919
+ ? await this.diffTrees(await this.treeOf(first), tree, "", [], ps)
920
+ : await this.diffTrees(undefined, tree, "", [], ps);
626
921
  for (const p of pairs) if (p.mode !== GITLINK_MODE) await this.exportBlob(p.id);
627
-
922
+ const changes = await this.detectRenames(pairs);
923
+
924
+ let author = authorLine;
925
+ let committer = committerLine;
926
+ if (this.anonymizer) {
927
+ refname = this.anonymizer.refname(refname);
928
+ committer = this.anonymizer.identLine(committer);
929
+ author = this.anonymizer.identLine(author);
930
+ }
628
931
  const mark = this.markNext(id, true);
629
932
  let reencoded: string | undefined;
630
- if (encoding !== undefined) {
933
+ if (this.anonymizer) reencoded = this.anonymizer.commitMessage();
934
+ else if (encoding !== undefined) {
631
935
  if (this.reencode === "yes") reencoded = reencodeToUtf8(message ?? "", encoding);
632
936
  else if (this.reencode === "abort") {
633
937
  this.die(
@@ -674,28 +978,131 @@ export class FastExportCommand extends PlumbingCommand {
674
978
  const parentMark = this.marks.get(p);
675
979
  if (!parentMark && !this.referenceExcluded) continue;
676
980
  text += i === 0 ? "from " : "merge ";
677
- text += parentMark ? `:${parentMark}\n` : `${p}\n`;
981
+ text += parentMark ? `:${parentMark}\n` : `${this.anonymizer ? this.anonymizer.oid(p) : p}\n`;
678
982
  i++;
679
983
  }
680
984
  if (this.fullTree) text += "deleteall\n";
681
- text += this.fileChanges(pairs);
985
+ text += this.fileChanges(changes);
682
986
  text += "\n";
683
987
  await this.out(text);
684
988
  await this.showProgress();
685
989
  }
686
990
 
991
+ /**
992
+ * diffcore_std's rename and copy detection over the queue (`-M`, `-C`, `-C -C`); the
993
+ * queue itself without them. Unchanged pairs (`-C -C`) are copy sources only.
994
+ */
995
+ private async detectRenames(pairs: readonly FilePair[]): Promise<FilePair[]> {
996
+ const changed = pairs.filter((p) => p.status !== "=");
997
+ // diff_setup_done: find_copies_harder turns copy detection on, whatever -M said after it
998
+ const detect = this.findCopiesHarder ? "copy" : this.detectRename;
999
+ if (detect === undefined) return changed;
1000
+ const queue: DiffEntry[] = changed.map((p) => {
1001
+ if (p.status === "A") {
1002
+ return {
1003
+ changeType: ChangeType.ADD,
1004
+ newPath: p.path,
1005
+ newId: p.id,
1006
+ newMode: p.mode,
1007
+ } as DiffEntry;
1008
+ }
1009
+ if (p.status === "D") {
1010
+ return {
1011
+ changeType: ChangeType.DELETE,
1012
+ oldPath: p.path,
1013
+ oldId: p.oldId,
1014
+ oldMode: p.oldMode,
1015
+ } as DiffEntry;
1016
+ }
1017
+ return {
1018
+ changeType: ChangeType.MODIFY,
1019
+ oldPath: p.path,
1020
+ newPath: p.path,
1021
+ oldId: p.oldId,
1022
+ newId: p.id,
1023
+ oldMode: p.oldMode,
1024
+ newMode: p.mode,
1025
+ } as DiffEntry;
1026
+ });
1027
+ const sources = new Map<string, { mode: number; id: ObjectId }>();
1028
+ for (const p of pairs) {
1029
+ if (p.status === "=")
1030
+ sources.set(p.path, { mode: p.oldMode as number, id: p.oldId as ObjectId });
1031
+ }
1032
+ const diff = new DiffCommand(this.workingCopy)
1033
+ .setOptions({
1034
+ ...(detect === "rename"
1035
+ ? { findRenames: this.renameScore }
1036
+ : { findCopies: this.renameScore }),
1037
+ ...(this.findCopiesHarder ? { findCopiesHarder: true } : {}),
1038
+ })
1039
+ // fast-export reads only git_default_config: never diff.renameLimit
1040
+ .setRenameLimit(DEFAULT_RENAME_LIMIT);
1041
+ diff.setQueue(queue, {
1042
+ diffcore: true,
1043
+ ...(this.findCopiesHarder ? { copySources: async () => sources } : {}),
1044
+ });
1045
+ const entries = await diff.call();
1046
+ return entries.map((e): FilePair => {
1047
+ switch (e.changeType) {
1048
+ case ChangeType.ADD:
1049
+ return { status: "A", path: e.newPath as string, mode: e.newMode as number, id: e.newId };
1050
+ case ChangeType.DELETE:
1051
+ return {
1052
+ status: "D",
1053
+ path: e.oldPath as string,
1054
+ mode: e.oldMode as number,
1055
+ id: undefined,
1056
+ };
1057
+ case ChangeType.RENAME:
1058
+ case ChangeType.COPY:
1059
+ return {
1060
+ status: e.changeType === ChangeType.RENAME ? "R" : "C",
1061
+ path: e.newPath as string,
1062
+ mode: e.newMode as number,
1063
+ id: e.newId,
1064
+ oldPath: e.oldPath as string,
1065
+ oldMode: e.oldMode as number,
1066
+ oldId: e.oldId as ObjectId,
1067
+ };
1068
+ default:
1069
+ return { status: "M", path: e.newPath as string, mode: e.newMode as number, id: e.newId };
1070
+ }
1071
+ });
1072
+ }
1073
+
687
1074
  /** show_filemodify: the changes sorted depth first, files below a directory before it. */
688
1075
  private fileChanges(pairs: readonly FilePair[]): string {
689
- const sorted = [...pairs].sort((a, b) => depthFirst(a.path, b.path));
1076
+ // depth_first: by the old side's path, a rename after the other entries of its path
1077
+ const sorted = [...pairs].sort(
1078
+ (a, b) =>
1079
+ depthFirst(a.oldPath ?? a.path, b.oldPath ?? b.path) ||
1080
+ Number(a.status === "R") - Number(b.status === "R"),
1081
+ );
1082
+ /** The paths written so far (git's `changed`) */
1083
+ const changed = new Set<string>();
690
1084
  let text = "";
691
1085
  for (const p of sorted) {
692
1086
  if (p.status === "D") {
693
1087
  text += `D ${this.pathText(p.path)}\n`;
1088
+ changed.add(p.path);
694
1089
  continue;
695
1090
  }
1091
+ if (p.status === "R" || p.status === "C") {
1092
+ // declared only when its source was not changed already
1093
+ if (!changed.has(p.oldPath as string)) {
1094
+ text += `${p.status} ${this.pathText(p.oldPath as string)} ${this.pathText(p.path)}\n`;
1095
+ changed.add(p.path);
1096
+ if (p.oldId === p.id && p.oldMode === p.mode) continue;
1097
+ }
1098
+ }
1099
+ changed.add(p.path);
696
1100
  const mode = p.mode.toString(8).padStart(6, "0");
697
- const ref =
698
- this.noData || p.mode === GITLINK_MODE ? p.id : `:${this.marks.get(p.id as string) ?? 0}`;
1101
+ // links name objects of another repository: their id as it is (anonymized)
1102
+ let ref: string | undefined;
1103
+ if (this.noData || p.mode === GITLINK_MODE) {
1104
+ ref = this.anonymizer ? this.anonymizer.oid(p.id as string) : p.id;
1105
+ } else ref = `:${this.marks.get(p.id as string) ?? 0}`;
699
1106
  text += `M ${mode} ${ref} ${this.pathText(p.path)}\n`;
700
1107
  }
701
1108
  return text;
@@ -707,13 +1114,72 @@ export class FastExportCommand extends PlumbingCommand {
707
1114
  return text.startsWith("tree ") ? text.slice(5, text.indexOf("\n")) : "";
708
1115
  }
709
1116
 
1117
+ /**
1118
+ * The entries of `tree` under `prefix` the pathspec takes (tree-diff.c's skip_uninteresting),
1119
+ * with whether everything below each is taken (no more matching needed there).
1120
+ */
1121
+ private async interestingEntries(
1122
+ tree: ObjectId | undefined,
1123
+ prefix: string,
1124
+ ps: TreePathspec | undefined,
1125
+ ): Promise<{ entry: TreeEntry; all: boolean }[]> {
1126
+ const entries = tree ? await this.treeEntries(tree) : [];
1127
+ if (!ps) return entries.map((entry) => ({ entry, all: true }));
1128
+ const base = encodeGitPath(prefix);
1129
+ const out: { entry: TreeEntry; all: boolean }[] = [];
1130
+ for (const entry of entries) {
1131
+ const name = encodeGitPath(entry.name);
1132
+ const r = treeEntryInteresting(ps, name, 0, name.length, entry.mode, base);
1133
+ if (r === ALL_ENTRIES_NOT_INTERESTING) break;
1134
+ if (r <= ENTRY_NOT_INTERESTING) continue;
1135
+ out.push({ entry, all: r === ALL_ENTRIES_INTERESTING });
1136
+ }
1137
+ return out;
1138
+ }
1139
+
710
1140
  /** diff_tree_oid with `recursive`, in tree-diff order (no rename detection). */
711
1141
  private async diffTrees(
712
1142
  a: ObjectId | undefined,
713
1143
  b: ObjectId,
714
1144
  prefix = "",
715
1145
  out: FilePair[] = [],
1146
+ ps?: TreePathspec,
716
1147
  ): Promise<FilePair[]> {
1148
+ if (ps) {
1149
+ const left = await this.interestingEntries(a, prefix, ps);
1150
+ const right = await this.interestingEntries(b, prefix, ps);
1151
+ const key = ({ entry: e }: { entry: TreeEntry }) => (isTree(e.mode) ? `${e.name}/` : e.name);
1152
+ let i = 0;
1153
+ let j = 0;
1154
+ while (i < left.length || j < right.length) {
1155
+ const l = left[i];
1156
+ const r = right[j];
1157
+ const cmp = !l ? 1 : !r ? -1 : compareBytes(key(l), key(r));
1158
+ if (cmp < 0) {
1159
+ const { entry, all } = l as { entry: TreeEntry; all: boolean };
1160
+ await this.side(entry, "D", prefix, out, all ? undefined : ps);
1161
+ i++;
1162
+ } else if (cmp > 0) {
1163
+ const { entry, all } = r as { entry: TreeEntry; all: boolean };
1164
+ await this.side(entry, "A", prefix, out, all ? undefined : ps);
1165
+ j++;
1166
+ } else {
1167
+ const le = (l as { entry: TreeEntry }).entry;
1168
+ const { entry: re, all } = r as { entry: TreeEntry; all: boolean };
1169
+ i++;
1170
+ j++;
1171
+ const same = le.id === re.id && le.mode === re.mode;
1172
+ if (same && !this.findCopiesHarder) continue;
1173
+ const path = prefix + re.name;
1174
+ if (isTree(le.mode) && isTree(re.mode)) {
1175
+ await this.diffTrees(le.id, re.id, `${path}/`, out, all ? undefined : ps);
1176
+ continue;
1177
+ }
1178
+ out.push(this.changePair(le, re, path, same));
1179
+ }
1180
+ }
1181
+ return out;
1182
+ }
717
1183
  const left = a ? await this.treeEntries(a) : [];
718
1184
  const right = b ? await this.treeEntries(b) : [];
719
1185
  const key = (e: TreeEntry) => (isTree(e.mode) ? `${e.name}/` : e.name);
@@ -734,35 +1200,49 @@ export class FastExportCommand extends PlumbingCommand {
734
1200
  const re = r as TreeEntry;
735
1201
  i++;
736
1202
  j++;
737
- if (le.id === re.id && le.mode === re.mode) continue;
1203
+ const same = le.id === re.id && le.mode === re.mode;
1204
+ if (same && !this.findCopiesHarder) continue;
738
1205
  const path = prefix + re.name;
739
- if (isTree(le.mode)) {
1206
+ if (isTree(le.mode) && isTree(re.mode)) {
740
1207
  await this.diffTrees(le.id, re.id, `${path}/`, out);
741
1208
  continue;
742
1209
  }
743
- const typeChanged = (le.mode & 0o170000) !== (re.mode & 0o170000);
744
- out.push({ status: typeChanged ? "T" : "M", path, mode: re.mode, id: re.id });
1210
+ out.push(this.changePair(le, re, path, same));
745
1211
  }
746
1212
  }
747
1213
  return out;
748
1214
  }
749
1215
 
1216
+ /** A path both sides hold as non-trees (`=` when unchanged, listed by `-C -C`). */
1217
+ private changePair(le: TreeEntry, re: TreeEntry, path: string, same: boolean): FilePair {
1218
+ const typeChanged = (le.mode & 0o170000) !== (re.mode & 0o170000);
1219
+ return {
1220
+ status: same ? "=" : typeChanged ? "T" : "M",
1221
+ path,
1222
+ mode: re.mode,
1223
+ id: re.id,
1224
+ oldMode: le.mode,
1225
+ oldId: le.id,
1226
+ };
1227
+ }
1228
+
750
1229
  private async side(
751
1230
  e: TreeEntry,
752
1231
  status: "A" | "D",
753
1232
  prefix: string,
754
1233
  out: FilePair[],
1234
+ ps?: TreePathspec,
755
1235
  ): Promise<void> {
756
1236
  const path = prefix + e.name;
757
1237
  if (isTree(e.mode)) {
758
- for (const child of await this.treeEntries(e.id)) {
759
- await this.side(child, status, `${path}/`, out);
1238
+ for (const { entry, all } of await this.interestingEntries(e.id, `${path}/`, ps)) {
1239
+ await this.side(entry, status, `${path}/`, out, all ? undefined : ps);
760
1240
  }
761
1241
  return;
762
1242
  }
763
1243
  out.push(
764
1244
  status === "D"
765
- ? { status, path, mode: e.mode, id: undefined }
1245
+ ? { status, path, mode: e.mode, id: undefined, oldMode: e.mode, oldId: e.id }
766
1246
  : { status, path, mode: e.mode, id: e.id },
767
1247
  );
768
1248
  }
@@ -803,6 +1283,14 @@ export class FastExportCommand extends PlumbingCommand {
803
1283
  : "";
804
1284
  } else {
805
1285
  tagger = buf.slice(taggerAt + 1, lineEnd(buf, taggerAt + 1));
1286
+ if (this.anonymizer) tagger = this.anonymizer.identLine(tagger);
1287
+ }
1288
+ if (this.anonymizer) {
1289
+ name = this.anonymizer.refname(name);
1290
+ if (message !== undefined) {
1291
+ message = this.anonymizer.tagMessage(message.slice(0, messageSize));
1292
+ messageSize = message.length;
1293
+ }
806
1294
  }
807
1295
 
808
1296
  if (message !== undefined) {
@@ -845,8 +1333,14 @@ export class FastExportCommand extends PlumbingCommand {
845
1333
  "cannot export nested tags unless --mark-tags is specified.",
846
1334
  "Error: Cannot export nested tags unless --mark-tags is specified.",
847
1335
  );
848
- }
849
- taggedMark = this.marks.get(direct.id) ?? 0;
1336
+ } else if (direct.type === "commit") {
1337
+ const p = this.rewrite(direct.id);
1338
+ if (p === null) {
1339
+ await this.out(`reset ${bin(name)}\nfrom ${NULL_SHA1}\n\n`);
1340
+ return;
1341
+ }
1342
+ taggedMark = this.marks.get(p) ?? 0;
1343
+ } else taggedMark = this.marks.get(direct.id) ?? 0;
850
1344
  }
851
1345
  }
852
1346
 
@@ -863,11 +1357,143 @@ export class FastExportCommand extends PlumbingCommand {
863
1357
  }
864
1358
  }
865
1359
 
1360
+ /**
1361
+ * fast-export.c's anonymizers: each kind of token has its own counter and cache (git's
1362
+ * static counters and hashmaps), the `--anonymize-map` seeds looked up first. Strings are
1363
+ * binary (one character per byte), as the stream is.
1364
+ */
1365
+ class Anonymizer {
1366
+ private readonly counters = new Map<string, number>();
1367
+ private readonly caches = new Map<string, Map<string, string>>();
1368
+
1369
+ constructor(
1370
+ private readonly seeds: ReadonlyMap<string, string>,
1371
+ private readonly format: { hexLength: number },
1372
+ ) {}
1373
+
1374
+ private next(kind: string): number {
1375
+ const n = this.counters.get(kind) ?? 0;
1376
+ this.counters.set(kind, n + 1);
1377
+ return n;
1378
+ }
1379
+
1380
+ /** anonymize_str: the seed, else the cached token, else a new one */
1381
+ private token(kind: string, orig: string, generate: () => string): string {
1382
+ const seeded = this.seeds.get(orig);
1383
+ if (seeded !== undefined) return seeded;
1384
+ let cache = this.caches.get(kind);
1385
+ if (!cache) {
1386
+ cache = new Map();
1387
+ this.caches.set(kind, cache);
1388
+ }
1389
+ let anon = cache.get(orig);
1390
+ if (anon === undefined) {
1391
+ anon = generate();
1392
+ cache.set(orig, anon);
1393
+ }
1394
+ return anon;
1395
+ }
1396
+
1397
+ /** anonymize_path: each component on its own */
1398
+ private components(kind: string, path: string, prefix: string): string {
1399
+ return path
1400
+ .split("/")
1401
+ .map((c) => this.token(kind, c, () => `${prefix}${this.next(kind)}`))
1402
+ .join("/");
1403
+ }
1404
+
1405
+ /** print_path's anonymize_path (a decoded path in, a decoded path out) */
1406
+ path(path: string): string {
1407
+ return decodeBin(this.components("path", bin(path), "path"));
1408
+ }
1409
+
1410
+ /** anonymize_refname: `refs/heads/`, `refs/tags/`, `refs/remotes/` or `refs/` kept */
1411
+ refname(name: string): string {
1412
+ for (const prefix of ["refs/heads/", "refs/tags/", "refs/remotes/", "refs/"]) {
1413
+ if (name.startsWith(prefix)) {
1414
+ return prefix + decodeBin(this.components("ref", bin(name.slice(prefix.length)), "ref"));
1415
+ }
1416
+ }
1417
+ return decodeBin(this.components("ref", bin(name), "ref"));
1418
+ }
1419
+
1420
+ /** anonymize_blob: not cached (marks already name a blob once) */
1421
+ blob(): string {
1422
+ return `anonymous blob ${this.next("blob")}`;
1423
+ }
1424
+
1425
+ /** anonymize_commit_message */
1426
+ commitMessage(): string {
1427
+ return `subject ${this.next("subject")}\n\nbody\n`;
1428
+ }
1429
+
1430
+ /** anonymize_tag, cached by the message */
1431
+ tagMessage(message: string): string {
1432
+ return this.token("tag", message, () => `tag message ${this.next("tag")}`);
1433
+ }
1434
+
1435
+ /** anonymize_oid: generate_fake_oid's null id ending in a big-endian counter from 1 */
1436
+ oid(id: string): string {
1437
+ return this.token("oid", id, () => {
1438
+ const n = this.next("oid") + 1;
1439
+ return n.toString(16).padStart(8, "0").padStart(this.format.hexLength, "0");
1440
+ });
1441
+ }
1442
+
1443
+ /** anonymize_ident_line: `<header> User N <userN@example.com> <date> <tz>` */
1444
+ identLine(line: string): string {
1445
+ const space = line.indexOf(" ");
1446
+ const header = line.slice(0, space + 1);
1447
+ const ident = line.slice(space + 1);
1448
+ const split = splitIdentLine(ident);
1449
+ if (!split) return `${header}Malformed Ident <malformed@example.com> 0 -0000`;
1450
+ const anon = this.token("ident", ident.slice(0, split.mailEnd), () => {
1451
+ const n = this.next("ident");
1452
+ return `User ${n} <user${n}@example.com>`;
1453
+ });
1454
+ return `${header}${anon} ${ident.slice(split.dateBegin, split.tzEnd)}`;
1455
+ }
1456
+ }
1457
+
1458
+ /**
1459
+ * ident.c's split_ident_line, as far as anonymize_ident_line reads it: where the mail ends
1460
+ * and the date and zone lie; undefined when there is no mail or no date.
1461
+ */
1462
+ function splitIdentLine(
1463
+ line: string,
1464
+ ): { mailEnd: number; dateBegin: number; tzEnd: number } | undefined {
1465
+ const isSpace = (c: string | undefined) => c === " " || c === "\t" || c === "\n" || c === "\r";
1466
+ const lt = line.indexOf("<");
1467
+ if (lt < 0) return undefined;
1468
+ const mailEnd = line.indexOf(">", lt + 1);
1469
+ if (mailEnd < 0) return undefined;
1470
+ let cp = line.lastIndexOf(">");
1471
+ for (cp++; cp < line.length && isSpace(line[cp]); cp++);
1472
+ const digits = (from: number) => {
1473
+ let e = from;
1474
+ while (e < line.length && /[0-9]/.test(line[e] as string)) e++;
1475
+ return e;
1476
+ };
1477
+ const dateBegin = cp;
1478
+ const dateEnd = digits(cp);
1479
+ if (cp >= line.length || dateEnd === dateBegin) return undefined;
1480
+ for (cp = dateEnd; cp < line.length && isSpace(line[cp]); cp++);
1481
+ if (cp >= line.length || (line[cp] !== "+" && line[cp] !== "-")) return undefined;
1482
+ const tzEnd = digits(cp + 1);
1483
+ if (tzEnd === cp + 1) return undefined;
1484
+ return { mailEnd, dateBegin, tzEnd };
1485
+ }
1486
+
866
1487
  /** A name as the stream's bytes (a binary string). */
867
1488
  function bin(name: string): string {
868
1489
  return latin1(encodeGitPath(name));
869
1490
  }
870
1491
 
1492
+ /** A binary string back to a name (the inverse of {@link bin}). */
1493
+ function decodeBin(text: string): string {
1494
+ return decodeGitPath(latin1Bytes(text));
1495
+ }
1496
+
871
1497
  function isTree(mode: number): boolean {
872
1498
  return (mode & 0o170000) === TREE_MODE;
873
1499
  }