@statewalker/vcs-commands 0.14.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 (265) 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/remote-archive-command.d.ts +4 -1
  5. package/dist/commands/archive/remote-archive-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts +14 -2
  7. package/dist/commands/branch-command.d.ts.map +1 -1
  8. package/dist/commands/cat-file/batch-format.d.ts +8 -12
  9. package/dist/commands/cat-file/batch-format.d.ts.map +1 -1
  10. package/dist/commands/cat-file/cat-file-command.d.ts +39 -5
  11. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  12. package/dist/commands/check-ignore-command.d.ts.map +1 -1
  13. package/dist/commands/checkout-command.d.ts +4 -0
  14. package/dist/commands/checkout-command.d.ts.map +1 -1
  15. package/dist/commands/checkout-paths.d.ts +9 -0
  16. package/dist/commands/checkout-paths.d.ts.map +1 -1
  17. package/dist/commands/cherry-pick-command.d.ts +3 -0
  18. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  19. package/dist/commands/clean-interactive.d.ts +0 -9
  20. package/dist/commands/clean-interactive.d.ts.map +1 -1
  21. package/dist/commands/clone-command.d.ts +2 -0
  22. package/dist/commands/clone-command.d.ts.map +1 -1
  23. package/dist/commands/column/column-config.d.ts +23 -0
  24. package/dist/commands/column/column-config.d.ts.map +1 -0
  25. package/dist/commands/column/column-layout.d.ts +129 -0
  26. package/dist/commands/column/column-layout.d.ts.map +1 -0
  27. package/dist/commands/column/index.d.ts +3 -0
  28. package/dist/commands/column/index.d.ts.map +1 -0
  29. package/dist/commands/column-command.d.ts +59 -0
  30. package/dist/commands/column-command.d.ts.map +1 -0
  31. package/dist/commands/comment-char-config.d.ts +15 -0
  32. package/dist/commands/comment-char-config.d.ts.map +1 -1
  33. package/dist/commands/commit-command.d.ts +21 -2
  34. package/dist/commands/commit-command.d.ts.map +1 -1
  35. package/dist/commands/config-command.d.ts +12 -0
  36. package/dist/commands/config-command.d.ts.map +1 -1
  37. package/dist/commands/credential-helper.d.ts +214 -0
  38. package/dist/commands/credential-helper.d.ts.map +1 -0
  39. package/dist/commands/default-branch.d.ts +17 -1
  40. package/dist/commands/default-branch.d.ts.map +1 -1
  41. package/dist/commands/diff-color-config.d.ts +4 -0
  42. package/dist/commands/diff-color-config.d.ts.map +1 -1
  43. package/dist/commands/diff-command.d.ts +12 -0
  44. package/dist/commands/diff-command.d.ts.map +1 -1
  45. package/dist/commands/fast-export/fast-export-command.d.ts +89 -2
  46. package/dist/commands/fast-export/fast-export-command.d.ts.map +1 -1
  47. package/dist/commands/fast-export/fast-import-command.d.ts +113 -8
  48. package/dist/commands/fast-export/fast-import-command.d.ts.map +1 -1
  49. package/dist/commands/fast-export/fast-stream-support.d.ts +0 -9
  50. package/dist/commands/fast-export/fast-stream-support.d.ts.map +1 -1
  51. package/dist/commands/fetch-command.d.ts +21 -0
  52. package/dist/commands/fetch-command.d.ts.map +1 -1
  53. package/dist/commands/git-hooks.d.ts +28 -0
  54. package/dist/commands/git-hooks.d.ts.map +1 -1
  55. package/dist/commands/history-command.d.ts +173 -7
  56. package/dist/commands/history-command.d.ts.map +1 -1
  57. package/dist/commands/index-host.d.ts +19 -0
  58. package/dist/commands/index-host.d.ts.map +1 -1
  59. package/dist/commands/index-refresh.d.ts +36 -0
  60. package/dist/commands/index-refresh.d.ts.map +1 -0
  61. package/dist/commands/index.d.ts +9 -0
  62. package/dist/commands/index.d.ts.map +1 -1
  63. package/dist/commands/index.js +7 -6
  64. package/dist/commands/init-command.d.ts +20 -0
  65. package/dist/commands/init-command.d.ts.map +1 -1
  66. package/dist/commands/local-transport.d.ts +29 -1
  67. package/dist/commands/local-transport.d.ts.map +1 -1
  68. package/dist/commands/log-command.d.ts +7 -0
  69. package/dist/commands/log-command.d.ts.map +1 -1
  70. package/dist/commands/log-output.d.ts +11 -0
  71. package/dist/commands/log-output.d.ts.map +1 -1
  72. package/dist/commands/maintenance-schedule-command.d.ts +122 -0
  73. package/dist/commands/maintenance-schedule-command.d.ts.map +1 -0
  74. package/dist/commands/merge-command.d.ts +2 -0
  75. package/dist/commands/merge-command.d.ts.map +1 -1
  76. package/dist/commands/merge-index-command.d.ts +42 -0
  77. package/dist/commands/merge-index-command.d.ts.map +1 -0
  78. package/dist/commands/merge-one-file.d.ts +129 -0
  79. package/dist/commands/merge-one-file.d.ts.map +1 -0
  80. package/dist/commands/merge-support.d.ts +21 -2
  81. package/dist/commands/merge-support.d.ts.map +1 -1
  82. package/dist/commands/object-disk-info.d.ts +35 -0
  83. package/dist/commands/object-disk-info.d.ts.map +1 -0
  84. package/dist/commands/octopus-merge.d.ts +3 -3
  85. package/dist/commands/octopus-merge.d.ts.map +1 -1
  86. package/dist/commands/promisor-remote.d.ts.map +1 -1
  87. package/dist/commands/pull-command.d.ts +55 -7
  88. package/dist/commands/pull-command.d.ts.map +1 -1
  89. package/dist/commands/push-command.d.ts +18 -1
  90. package/dist/commands/push-command.d.ts.map +1 -1
  91. package/dist/commands/range-diff/range-diff-command.d.ts +37 -1
  92. package/dist/commands/range-diff/range-diff-command.d.ts.map +1 -1
  93. package/dist/commands/rebase-command.d.ts +13 -1
  94. package/dist/commands/rebase-command.d.ts.map +1 -1
  95. package/dist/commands/ref-filter/for-each-ref-command.d.ts +3 -2
  96. package/dist/commands/ref-filter/for-each-ref-command.d.ts.map +1 -1
  97. package/dist/commands/ref-filter/ref-filter.d.ts.map +1 -1
  98. package/dist/commands/ref-filter/ref-format.d.ts +26 -1
  99. package/dist/commands/ref-filter/ref-format.d.ts.map +1 -1
  100. package/dist/commands/ref-filter/ref-listing-command.d.ts +9 -0
  101. package/dist/commands/ref-filter/ref-listing-command.d.ts.map +1 -1
  102. package/dist/commands/remote-transport.d.ts +27 -0
  103. package/dist/commands/remote-transport.d.ts.map +1 -1
  104. package/dist/commands/repack-command.d.ts +18 -2
  105. package/dist/commands/repack-command.d.ts.map +1 -1
  106. package/dist/commands/repo-command.d.ts +2 -7
  107. package/dist/commands/repo-command.d.ts.map +1 -1
  108. package/dist/commands/reset-command.d.ts +4 -1
  109. package/dist/commands/reset-command.d.ts.map +1 -1
  110. package/dist/commands/restore-command.d.ts.map +1 -1
  111. package/dist/commands/rev-list-command.d.ts +65 -0
  112. package/dist/commands/rev-list-command.d.ts.map +1 -1
  113. package/dist/commands/revert-command.d.ts +3 -0
  114. package/dist/commands/revert-command.d.ts.map +1 -1
  115. package/dist/commands/revision-filenames.d.ts.map +1 -1
  116. package/dist/commands/revision-range.d.ts +17 -0
  117. package/dist/commands/revision-range.d.ts.map +1 -1
  118. package/dist/commands/revision-resolver.d.ts +12 -0
  119. package/dist/commands/revision-resolver.d.ts.map +1 -1
  120. package/dist/commands/serve-repository.d.ts +17 -1
  121. package/dist/commands/serve-repository.d.ts.map +1 -1
  122. package/dist/commands/served-lazy-fetch.d.ts +61 -0
  123. package/dist/commands/served-lazy-fetch.d.ts.map +1 -0
  124. package/dist/commands/signing.d.ts +10 -4
  125. package/dist/commands/signing.d.ts.map +1 -1
  126. package/dist/commands/status-color-config.d.ts +33 -0
  127. package/dist/commands/status-color-config.d.ts.map +1 -0
  128. package/dist/commands/status-command.d.ts +15 -0
  129. package/dist/commands/status-command.d.ts.map +1 -1
  130. package/dist/commands/status-format.d.ts +46 -4
  131. package/dist/commands/status-format.d.ts.map +1 -1
  132. package/dist/commands/tag-command.d.ts +15 -1
  133. package/dist/commands/tag-command.d.ts.map +1 -1
  134. package/dist/commands/tree-restore.d.ts +14 -0
  135. package/dist/commands/tree-restore.d.ts.map +1 -1
  136. package/dist/commands/verify-command.d.ts +22 -2
  137. package/dist/commands/verify-command.d.ts.map +1 -1
  138. package/dist/commands/worktree-add-command.d.ts.map +1 -1
  139. package/dist/commands/worktree-overwrite-checks.d.ts +31 -6
  140. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  141. package/dist/{commands-C9M78Chn.js → commands-DT3VEv50.js} +14879 -16703
  142. package/dist/errors/commit-errors.d.ts +23 -3
  143. package/dist/errors/commit-errors.d.ts.map +1 -1
  144. package/dist/errors/git-api-error.d.ts +6 -0
  145. package/dist/errors/git-api-error.d.ts.map +1 -1
  146. package/dist/errors/index.js +30 -4
  147. package/dist/{fsck-C4US3l0B.js → fsck-BZ508Elg.js} +1 -1
  148. package/dist/git-command.d.ts +33 -1
  149. package/dist/git-command.d.ts.map +1 -1
  150. package/dist/git.d.ts +104 -1
  151. package/dist/git.d.ts.map +1 -1
  152. package/dist/index.js +8 -7
  153. package/dist/{remote-transport-C43eykfK.js → local-transport-D98U6p4d.js} +184 -683
  154. package/dist/{maintenance-run-command-CoJFKr2p.js → maintenance-run-command-DZFnbnbo.js} +2285 -79
  155. package/dist/remote-config/remote-config-store.d.ts +6 -0
  156. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  157. package/dist/remote-transport-zvSqwpOB.js +4865 -0
  158. package/dist/results/cherry-pick-result.d.ts +4 -3
  159. package/dist/results/cherry-pick-result.d.ts.map +1 -1
  160. package/dist/results/diff-output.d.ts +7 -0
  161. package/dist/results/diff-output.d.ts.map +1 -1
  162. package/dist/results/diff-words.d.ts +14 -3
  163. package/dist/results/diff-words.d.ts.map +1 -1
  164. package/dist/results/index.js +1 -1
  165. package/dist/results/line-prefix-sink.d.ts +50 -0
  166. package/dist/results/line-prefix-sink.d.ts.map +1 -0
  167. package/dist/results/merge-result.d.ts +4 -3
  168. package/dist/results/merge-result.d.ts.map +1 -1
  169. package/dist/results/rebase-result.d.ts +5 -0
  170. package/dist/results/rebase-result.d.ts.map +1 -1
  171. package/dist/results/revert-result.d.ts +4 -3
  172. package/dist/results/revert-result.d.ts.map +1 -1
  173. package/dist/{results-B0CWLCAp.js → results-rF81cQse.js} +1425 -202
  174. package/dist/transport-command.d.ts +10 -0
  175. package/dist/transport-command.d.ts.map +1 -1
  176. package/package.json +12 -12
  177. package/src/commands/add-command.ts +15 -2
  178. package/src/commands/add-patch/patch-backend.ts +6 -44
  179. package/src/commands/archive/remote-archive-command.ts +10 -3
  180. package/src/commands/branch-command.ts +57 -4
  181. package/src/commands/cat-file/batch-format.ts +17 -18
  182. package/src/commands/cat-file/cat-file-command.ts +181 -15
  183. package/src/commands/check-ignore-command.ts +61 -17
  184. package/src/commands/checkout-command.ts +149 -21
  185. package/src/commands/checkout-index-command.ts +2 -1
  186. package/src/commands/checkout-paths.ts +13 -0
  187. package/src/commands/cherry-pick-command.ts +9 -0
  188. package/src/commands/clean-interactive.ts +20 -74
  189. package/src/commands/clone-command.ts +13 -0
  190. package/src/commands/column/column-config.ts +63 -0
  191. package/src/commands/column/column-layout.ts +396 -0
  192. package/src/commands/column/index.ts +2 -0
  193. package/src/commands/column-command.ts +171 -0
  194. package/src/commands/comment-char-config.ts +42 -0
  195. package/src/commands/commit-command.ts +61 -21
  196. package/src/commands/config-command.ts +28 -0
  197. package/src/commands/credential-helper.ts +807 -0
  198. package/src/commands/default-branch.ts +38 -0
  199. package/src/commands/diff-color-config.ts +23 -10
  200. package/src/commands/diff-command.ts +25 -2
  201. package/src/commands/fast-export/fast-export-command.ts +661 -35
  202. package/src/commands/fast-export/fast-import-command.ts +694 -94
  203. package/src/commands/fast-export/fast-stream-support.ts +18 -1
  204. package/src/commands/fetch-command.ts +103 -14
  205. package/src/commands/git-hooks.ts +85 -0
  206. package/src/commands/history-command.ts +952 -20
  207. package/src/commands/index-host.ts +51 -0
  208. package/src/commands/index-refresh.ts +121 -0
  209. package/src/commands/index.ts +9 -0
  210. package/src/commands/init-command.ts +34 -1
  211. package/src/commands/legacy-remotes.ts +4 -20
  212. package/src/commands/local-transport.ts +130 -9
  213. package/src/commands/log-command.ts +39 -1
  214. package/src/commands/log-output.ts +31 -4
  215. package/src/commands/maintenance-schedule-command.ts +418 -0
  216. package/src/commands/merge-command.ts +10 -0
  217. package/src/commands/merge-index-command.ts +202 -0
  218. package/src/commands/merge-one-file.ts +451 -0
  219. package/src/commands/merge-support.ts +127 -11
  220. package/src/commands/object-disk-info.ts +169 -0
  221. package/src/commands/octopus-merge.ts +37 -128
  222. package/src/commands/promisor-remote.ts +14 -3
  223. package/src/commands/pull-command.ts +173 -27
  224. package/src/commands/push-command.ts +50 -5
  225. package/src/commands/range-diff/range-diff-command.ts +86 -3
  226. package/src/commands/rebase-command.ts +46 -1
  227. package/src/commands/ref-filter/for-each-ref-command.ts +4 -3
  228. package/src/commands/ref-filter/ref-filter.ts +59 -4
  229. package/src/commands/ref-filter/ref-format.ts +83 -10
  230. package/src/commands/ref-filter/ref-listing-command.ts +30 -0
  231. package/src/commands/remote-command.ts +2 -2
  232. package/src/commands/remote-transport.ts +66 -3
  233. package/src/commands/repack-command.ts +75 -9
  234. package/src/commands/repo-command.ts +6 -70
  235. package/src/commands/reset-command.ts +11 -1
  236. package/src/commands/restore-command.ts +1 -0
  237. package/src/commands/rev-list-command.ts +205 -3
  238. package/src/commands/revert-command.ts +9 -0
  239. package/src/commands/revision-filenames.ts +32 -4
  240. package/src/commands/revision-range.ts +2 -2
  241. package/src/commands/revision-resolver.ts +21 -1
  242. package/src/commands/serve-repository.ts +34 -8
  243. package/src/commands/served-lazy-fetch.ts +164 -0
  244. package/src/commands/signing.ts +18 -10
  245. package/src/commands/status-color-config.ts +92 -0
  246. package/src/commands/status-command.ts +50 -2
  247. package/src/commands/status-format.ts +198 -50
  248. package/src/commands/tag-command.ts +57 -2
  249. package/src/commands/tree-restore.ts +17 -0
  250. package/src/commands/verify-command.ts +84 -12
  251. package/src/commands/worktree-add-command.ts +2 -0
  252. package/src/commands/worktree-overwrite-checks.ts +75 -14
  253. package/src/errors/commit-errors.ts +31 -3
  254. package/src/errors/git-api-error.ts +7 -0
  255. package/src/git-command.ts +105 -4
  256. package/src/git.ts +153 -0
  257. package/src/remote-config/remote-config-store.ts +16 -0
  258. package/src/results/cherry-pick-result.ts +4 -3
  259. package/src/results/diff-output.ts +8 -0
  260. package/src/results/diff-words.ts +160 -32
  261. package/src/results/line-prefix-sink.ts +102 -0
  262. package/src/results/merge-result.ts +4 -3
  263. package/src/results/rebase-result.ts +5 -0
  264. package/src/results/revert-result.ts +4 -3
  265. package/src/transport-command.ts +48 -2
@@ -0,0 +1,202 @@
1
+ /**
2
+ * `git merge-index [-o] [-q] <merge-program> (-a | [--] <file>...)` (builtin/merge-index.c):
3
+ * a merge program run for each unmerged path of the index.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * // git merge-index git-merge-one-file -a
8
+ * const r = await git.mergeIndex().setArguments(["git-merge-one-file", "-a"]).call();
9
+ * // r.exitCode 0 when every path merged
10
+ *
11
+ * // git merge-index -o ./my-merge.sh -- file1 file2
12
+ * await git.mergeIndex().setArguments(["-o", "./my-merge.sh", "--", "file1", "file2"]).call();
13
+ * ```
14
+ */
15
+
16
+ import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
17
+ import type { StagingEntry } from "@statewalker/vcs-working-tree";
18
+
19
+ import { WorktreeError } from "../errors/index.js";
20
+ import { GitCommand } from "../git-command.js";
21
+ import type { PlumbingTextOutput } from "./check-ref-format-command.js";
22
+ import { MergeOneFileCommand } from "./merge-one-file.js";
23
+
24
+ const USAGE = "git merge-index [-o] [-q] <merge-program> (-a | [--] [<filename>...])";
25
+
26
+ /** A death (`die()`): git's message without `fatal: `. */
27
+ class Death extends Error {}
28
+
29
+ /** The program's failure ending the run without `-o` (`exit(1)` under `-q`). */
30
+ class Stop extends Error {}
31
+
32
+ /**
33
+ * Runs a merge program over the index's unmerged paths as `git merge-index` does.
34
+ *
35
+ * The arguments are git's ({@link setArguments}): `-o` then `-q` (in that order only), the
36
+ * program, then paths and `-a` in the order given (`--` makes the rest paths). For each path
37
+ * with conflict stages the program gets the base, ours and theirs ids, the path and the three
38
+ * modes (an absent stage's id and mode empty); a path merged already (stage 0) is skipped, one
39
+ * the index lacks is git's death (`git merge-index: <path> not in the cache`, exit 128). A
40
+ * program that fails stops the run (`merge program failed`, exit 128; exit 1 under `-q`),
41
+ * unless `-o`: the others still run and the exit status is the number of failures (128 with
42
+ * the message unless `-q`).
43
+ *
44
+ * `git-merge-one-file` runs in process ({@link MergeOneFileCommand}); any other program runs
45
+ * through the host's hook runner as git runs it, without a shell, from the worktree's top
46
+ * (with none, it cannot start). The program's stdout and stderr are the command's.
47
+ */
48
+ export class MergeIndexCommand extends GitCommand<PlumbingTextOutput> {
49
+ private args: string[] = [];
50
+ private compatibility: "2.43" | "2.56" = "2.56";
51
+
52
+ /** git's arguments after `merge-index`. */
53
+ setArguments(args: readonly string[]): this {
54
+ this.checkCallable();
55
+ this.args = [...args];
56
+ return this;
57
+ }
58
+
59
+ /** The git version followed: 2.43 takes `-h` alone as too few arguments. */
60
+ setCompatibility(compatibility: "2.43" | "2.56"): this {
61
+ this.checkCallable();
62
+ this.compatibility = compatibility;
63
+ return this;
64
+ }
65
+
66
+ async call(): Promise<PlumbingTextOutput> {
67
+ this.checkCallable();
68
+ this.setCallable(false);
69
+ const argv = ["merge-index", ...this.args];
70
+ let stdout = "";
71
+ let stderr = "";
72
+ const done = (exitCode: number): PlumbingTextOutput => ({ exitCode, stdout, stderr });
73
+ if (
74
+ this.compatibility !== "2.43" &&
75
+ argv.length === 2 &&
76
+ (argv[1] === "-h" || argv[1] === "--help-all")
77
+ ) {
78
+ stdout += `usage: ${USAGE}\n`;
79
+ return done(0);
80
+ }
81
+ if (argv.length < 3) {
82
+ stderr += `usage: ${USAGE}\n`;
83
+ return done(129);
84
+ }
85
+ try {
86
+ await this.readCurrentIndex(false);
87
+ } catch (error) {
88
+ // a bare repository's working copy has no index here (git reads `$GIT_INDEX_FILE`
89
+ // and fails in merge-one-file's cd_to_toplevel instead): refused as a death
90
+ if (!(error instanceof WorktreeError)) throw error;
91
+ stderr += `fatal: ${error.message}\n`;
92
+ return done(128);
93
+ }
94
+ const entries: StagingEntry[] = [];
95
+ const list = this.staging.entryList?.();
96
+ if (list) entries.push(...list);
97
+ else for await (const e of this.staging.entries()) entries.push(e);
98
+
99
+ let i = 1;
100
+ let oneShot = false;
101
+ let quiet = false;
102
+ if (argv[i] === "-o") {
103
+ oneShot = true;
104
+ i++;
105
+ }
106
+ if (argv[i] === "-q") {
107
+ quiet = true;
108
+ i++;
109
+ }
110
+ const pgm = argv[i++] ?? "";
111
+ let err = 0;
112
+
113
+ const run = async (args: string[]): Promise<boolean> => {
114
+ if (pgm === "git-merge-one-file") {
115
+ const r = await new MergeOneFileCommand(this.workingCopy)
116
+ .shareHooksOf(this)
117
+ .setArguments(args)
118
+ .call();
119
+ stdout += r.stdout;
120
+ stderr += r.stderr;
121
+ return r.exitCode === 0;
122
+ }
123
+ const r = await this.hooks.runArgv("merge-index", [pgm, ...args]);
124
+ if (!r || r.startError) {
125
+ stderr += `${
126
+ r?.startError ??
127
+ (pgm.includes("/")
128
+ ? `fatal: cannot exec '${pgm}': No such file or directory`
129
+ : `error: cannot run ${pgm}: No such file or directory`)
130
+ }\n`;
131
+ return false;
132
+ }
133
+ stdout += r.stdout;
134
+ stderr += r.stderr;
135
+ return r.exitCode === 0;
136
+ };
137
+
138
+ /** merge_entry: the stages of `path` from `pos`, the program run; how many it found. */
139
+ const mergeEntry = async (pos: number, path: string): Promise<number> => {
140
+ if (pos >= entries.length) throw new Death(`git merge-index: ${path} not in the cache`);
141
+ const args = ["", "", "", path, "", "", ""];
142
+ let found = 0;
143
+ for (let p = pos; p < entries.length; p++) {
144
+ const e = entries[p] as StagingEntry;
145
+ if (e.path !== path) break;
146
+ found++;
147
+ const stage = e.stage;
148
+ args[stage - 1] = e.objectId;
149
+ args[stage + 3] = e.mode.toString(8);
150
+ }
151
+ if (!found) throw new Death(`git merge-index: ${path} not in the cache`);
152
+ if (!(await run(args))) {
153
+ if (oneShot) err++;
154
+ else {
155
+ if (!quiet) throw new Death("merge program failed");
156
+ throw new Stop();
157
+ }
158
+ }
159
+ return found;
160
+ };
161
+
162
+ try {
163
+ let forceFile = false;
164
+ for (; i < argv.length; i++) {
165
+ const arg = argv[i] as string;
166
+ if (!forceFile && arg.startsWith("-")) {
167
+ if (arg === "--") {
168
+ forceFile = true;
169
+ continue;
170
+ }
171
+ if (arg === "-a") {
172
+ for (let k = 0; k < entries.length; k++) {
173
+ const e = entries[k] as StagingEntry;
174
+ if (!e.stage) continue;
175
+ k += (await mergeEntry(k, e.path)) - 1;
176
+ }
177
+ continue;
178
+ }
179
+ throw new Death(`git merge-index: unknown option ${arg}`);
180
+ }
181
+ // merge_one_path: a path at stage 0 is merged already
182
+ const pos = entries.findIndex((e) => compareGitPaths(e.path, arg) >= 0);
183
+ const at = pos < 0 ? entries.length : pos;
184
+ const first = entries[at];
185
+ if (first && first.path === arg && first.stage === 0) continue;
186
+ await mergeEntry(at, arg);
187
+ }
188
+ } catch (error) {
189
+ if (error instanceof Death) {
190
+ stderr += `fatal: ${error.message}\n`;
191
+ return done(128);
192
+ }
193
+ if (error instanceof Stop) return done(1);
194
+ throw error;
195
+ }
196
+ if (err && !quiet) {
197
+ stderr += "fatal: merge program failed\n";
198
+ return done(128);
199
+ }
200
+ return done(err & 0xff);
201
+ }
202
+ }
@@ -0,0 +1,451 @@
1
+ /**
2
+ * git-merge-one-file (git-merge-one-file.sh, the same script in 2.43 and 2.5x): git's
3
+ * default per-path merge program, run by `git merge-index` for each unmerged path with its
4
+ * three stage ids, the path and the three modes (an absent stage empty).
5
+ *
6
+ * {@link planOneFile} is the script's `case` statement over the stages, computed in memory:
7
+ * what it prints, what it puts in the index and the worktree, and whether it fails. The
8
+ * octopus strategy applies the plan to its in-memory merge; {@link MergeOneFileCommand}
9
+ * applies it as the script does, through `git update-index` and `git checkout-index`.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * // git merge-one-file <base> <ours> <theirs> file 100644 100644 100644
14
+ * const r = await git.mergeOneFile().setArguments([base, ours, theirs, "file", "100644", "100644", "100644"]).call();
15
+ * // r.exitCode 0, r.stdout "Auto-merging file\n"
16
+ * ```
17
+ */
18
+
19
+ import { type Blobs, EMPTY_BLOB_ID, type ObjectId } from "@statewalker/vcs-core";
20
+ import { type ConflictStyle, mergeLines } from "@statewalker/vcs-utils";
21
+ import { decodeGitPath } from "@statewalker/vcs-utils/encoding";
22
+ import { collect } from "@statewalker/vcs-utils/streams";
23
+ import type { Worktree } from "@statewalker/vcs-working-tree";
24
+
25
+ import { CheckoutIndexFailedError, UpdateIndexFailedError } from "../errors/index.js";
26
+ import { GitCommand } from "../git-command.js";
27
+ import { isBinaryContent } from "../rename/index.js";
28
+ import type { PlumbingTextOutput } from "./check-ref-format-command.js";
29
+ import { CheckoutIndexCommand } from "./checkout-index-command.js";
30
+ import { conflictStyleOf } from "./merge-config.js";
31
+ import { readBlob } from "./ort-merge.js";
32
+ import { UpdateIndexCommand } from "./update-index-command.js";
33
+
34
+ /** One path's stages as git-merge-one-file gets them: ids and octal modes, "" when absent. */
35
+ export interface OneFileStages {
36
+ path: string;
37
+ /** `$1 $2 $3`: the base, ours, theirs */
38
+ ids: [string, string, string];
39
+ /** `$5 $6 $7` */
40
+ modes: [string, string, string];
41
+ }
42
+
43
+ /** What git-merge-one-file does for one path. */
44
+ export type OneFilePlan =
45
+ /** Leaves the path unmerged (exit 1), printing `errors` */
46
+ | { kind: "fail"; output: string[]; errors: string[] }
47
+ /**
48
+ * `git update-index --remove`: deleted in both, or in one and unchanged in the other;
49
+ * `unlink`: ours was there, its file is removed first (with its emptied directories)
50
+ */
51
+ | { kind: "remove"; output: string[]; unlink: boolean }
52
+ /**
53
+ * `git update-index --add --cacheinfo`: added on one side or identically in both;
54
+ * `checkout`: the file written too (`git checkout-index -u -f`), refused when a file is
55
+ * already there (`untracked`)
56
+ */
57
+ | {
58
+ kind: "add";
59
+ output: string[];
60
+ mode: string;
61
+ id: string;
62
+ checkout: boolean;
63
+ untracked: boolean;
64
+ }
65
+ /**
66
+ * A content merge: the worktree file is ours (`checkout-index --stage=2`) holding
67
+ * `content` (the merge's result, or ours when merge-file failed); `message` is the
68
+ * `ERROR: <message> in <path>` that leaves the path unmerged, "" when the merged file is
69
+ * added to the index (`git update-index`). `temporary` are unpack-file's files (ours,
70
+ * theirs, base) with what they hold, `errors` what was printed before the message.
71
+ */
72
+ | {
73
+ kind: "merge";
74
+ output: string[];
75
+ errors: string[];
76
+ content: Uint8Array;
77
+ /** Ours could not be unpacked: `cat` of its empty name fails after the checkout */
78
+ oursMissing?: boolean;
79
+ /** The blob `content` is when it is ours unchanged */
80
+ contentId?: ObjectId;
81
+ message: string;
82
+ temporary: { name: string; content: Uint8Array }[];
83
+ };
84
+
85
+ /** What the planner reads. */
86
+ export interface OneFileContext {
87
+ blobs: Blobs;
88
+ style?: ConflictStyle;
89
+ /** The next temporary file name, as `mkstemp` gives unpack-file's (`.merge_file_XXXXXX`) */
90
+ tempName: () => string;
91
+ }
92
+
93
+ /** git-merge-one-file's `case "${1:-.}${2:-.}${3:-.}"`, computed in memory. */
94
+ export async function planOneFile(
95
+ ctx: OneFileContext,
96
+ stages: OneFileStages,
97
+ ): Promise<OneFilePlan> {
98
+ const { path } = stages;
99
+ const [s1, s2, s3] = stages.ids;
100
+ const [m5, m6, m7] = stages.modes;
101
+ const key = `${s1 || "."}${s2 || "."}${s3 || "."}`;
102
+ const output: string[] = [];
103
+ const fail = (...errors: string[]): OneFilePlan => ({ kind: "fail", output, errors });
104
+ // deleted in both, or deleted in one and unchanged in the other
105
+ if (key === `${s1}..` || key === `${s1}.${s1}` || key === `${s1}${s1}.`) {
106
+ if ((!m6 && m5 !== m7) || (!m7 && m5 !== m6)) {
107
+ return fail(
108
+ `ERROR: File ${path} deleted on one branch but had its`,
109
+ "ERROR: permissions changed on the other.",
110
+ );
111
+ }
112
+ if (s2) output.push(`Removing ${path}`);
113
+ return { kind: "remove", output, unlink: s2 !== "" };
114
+ }
115
+ // added in one
116
+ if (key === `.${s2}.`) {
117
+ return { kind: "add", output, mode: m6, id: s2, checkout: false, untracked: false };
118
+ }
119
+ if (key === `..${s3}`) {
120
+ output.push(`Adding ${path}`);
121
+ return { kind: "add", output, mode: m7, id: s3, checkout: true, untracked: true };
122
+ }
123
+ // added in both, identically
124
+ if (key === `.${s3}${s2}`) {
125
+ if (m6 !== m7) {
126
+ return fail(
127
+ `ERROR: File ${path} added identically in both branches,`,
128
+ `ERROR: but permissions conflict ${m6}->${m7}.`,
129
+ );
130
+ }
131
+ output.push(`Adding ${path}`);
132
+ return { kind: "add", output, mode: m6, id: s2, checkout: true, untracked: false };
133
+ }
134
+ // modified in both, but differently
135
+ if (key === `${s1}${s2}${s3}` || key === `.${s2}${s3}`) {
136
+ const modes = `,${m6},${m7},`;
137
+ if (modes.includes(",120000,"))
138
+ return fail(`ERROR: ${path}: Not merging symbolic link changes.`);
139
+ if (modes.includes(",160000,")) {
140
+ return fail(`ERROR: ${path}: Not merging conflicting submodule changes.`);
141
+ }
142
+ const errors: string[] = [];
143
+ // `$(git unpack-file <id>)`: a temporary file holding the blob, or "" when unpack-file
144
+ // dies on a blob it cannot read
145
+ const unpack = async (
146
+ id: string,
147
+ ): Promise<{ name: string; content: Uint8Array } | undefined> => {
148
+ if (!(await ctx.blobs.has(id))) {
149
+ errors.push(`fatal: unable to read blob object ${id}`);
150
+ return undefined;
151
+ }
152
+ const content = await readBlob(ctx.blobs, id);
153
+ return { name: ctx.tempName(), content };
154
+ };
155
+ const src1 = await unpack(s2);
156
+ const src2 = await unpack(s3);
157
+ let orig: { name: string; content: Uint8Array } | undefined;
158
+ if (!s1) {
159
+ output.push(`Added ${path} in both, but differently.`);
160
+ // the base is `$(git hash-object /dev/null)`, which nothing may have stored
161
+ orig = await unpack(ctx.blobs.objectFormat?.emptyBlobId ?? EMPTY_BLOB_ID);
162
+ } else {
163
+ output.push(`Auto-merging ${path}`);
164
+ orig = await unpack(s1);
165
+ }
166
+ const temporary = [src1, src2, orig].filter((t) => t !== undefined);
167
+ let content = src1?.content ?? new Uint8Array(0);
168
+ let contentId: ObjectId | undefined = src1 ? s2 : undefined;
169
+ let failed = true;
170
+ // `git merge-file <src1> <orig> <src2>` reads its files in order and stops at the first
171
+ // it cannot read or that is binary
172
+ const files = [src1, orig, src2];
173
+ const refused = files.findIndex((f) => !f || isBinaryContent(f.content));
174
+ if (refused >= 0) {
175
+ const f = files[refused];
176
+ errors.push(
177
+ f
178
+ ? `error: Cannot merge binary files: ${f.name}`
179
+ : "error: Could not stat : No such file or directory",
180
+ );
181
+ } else if (src1 && src2 && orig) {
182
+ const merged = mergeLines(orig.content, src1.content, src2.content, {
183
+ oursLabel: src1.name,
184
+ baseLabel: orig.name,
185
+ theirsLabel: src2.name,
186
+ style: ctx.style,
187
+ algorithm: "myers",
188
+ level: "zealous-alnum",
189
+ });
190
+ content = merged.content;
191
+ contentId = undefined;
192
+ failed = merged.conflicts > 0;
193
+ src1.content = content;
194
+ }
195
+ let message = failed || !s1 ? "content conflict" : "";
196
+ if (m6 !== m7) {
197
+ message = `${message ? `${message}, ` : ""}permissions conflict: ${m5}->${m6},${m7}`;
198
+ }
199
+ return {
200
+ kind: "merge",
201
+ output,
202
+ errors,
203
+ content,
204
+ ...(contentId ? { contentId } : {}),
205
+ ...(src1 ? {} : { oursMissing: true }),
206
+ message,
207
+ temporary,
208
+ };
209
+ }
210
+ return fail(`ERROR: ${path}: Not handling case ${s1} -> ${s2} -> ${s3}`);
211
+ }
212
+
213
+ const TEMP_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
214
+
215
+ /** A name as `mkstemp` gives unpack-file's temporary files. */
216
+ export function mkstempName(): string {
217
+ const bytes = crypto.getRandomValues(new Uint8Array(6));
218
+ let suffix = "";
219
+ for (const b of bytes) suffix += TEMP_CHARS[b % TEMP_CHARS.length];
220
+ return `.merge_file_${suffix}`;
221
+ }
222
+
223
+ const USAGE = "<orig blob> <our blob> <their blob> <path> <orig mode> <our mode> <their mode>";
224
+ const LONG_USAGE = `usage: git merge-one-file ${USAGE}\n\nusage: git merge-one-file ${USAGE}\n\nBlob ids and modes should be empty for missing files.\n`;
225
+
226
+ /**
227
+ * `git merge-one-file <orig blob> <our blob> <their blob> <path> <orig mode> <our mode>
228
+ * <their mode>` (git-merge-one-file.sh), from the worktree's top.
229
+ *
230
+ * Trivial cases are resolved in the index: a path deleted in both or in one side and
231
+ * unchanged in the other is removed (with its file when ours had it), one added on one side
232
+ * or identically in both is added (and checked out when theirs). Otherwise the three are
233
+ * merged as `git merge-file` merges them (`merge.conflictStyle`, conflict markers labelled
234
+ * with unpack-file's temporary names): the worktree file is ours holding the result, added
235
+ * to the index when the merge is clean. Failures print git's `ERROR:` lines and give exit
236
+ * status 1, the path left unmerged. Never throws for git's failures: the result is the
237
+ * script's exit status, stdout and stderr.
238
+ */
239
+ export class MergeOneFileCommand extends GitCommand<PlumbingTextOutput> {
240
+ private args: string[] = [];
241
+
242
+ /** The script's arguments (seven; an absent stage's id and mode empty). */
243
+ setArguments(args: readonly string[]): this {
244
+ this.checkCallable();
245
+ this.args = [...args];
246
+ return this;
247
+ }
248
+
249
+ async call(): Promise<PlumbingTextOutput> {
250
+ this.checkCallable();
251
+ this.setCallable(false);
252
+ return runMergeOneFile(this, this.args);
253
+ }
254
+
255
+ /** @internal What the shared runner needs of this command. */
256
+ get oneFileHost(): OneFileHost {
257
+ return {
258
+ worktree: this.worktreeAccess,
259
+ blobs: this.blobs,
260
+ style: () => conflictStyleOf(this.workingCopy),
261
+ updateIndex: () => new UpdateIndexCommand(this.workingCopy).shareHooksOf(this),
262
+ checkoutIndex: () => new CheckoutIndexCommand(this.workingCopy).shareHooksOf(this),
263
+ };
264
+ }
265
+ }
266
+
267
+ /** @internal What running git-merge-one-file needs. */
268
+ export interface OneFileHost {
269
+ worktree: Worktree | undefined;
270
+ blobs: Blobs;
271
+ style: () => ConflictStyle;
272
+ updateIndex: () => UpdateIndexCommand;
273
+ checkoutIndex: () => CheckoutIndexCommand;
274
+ }
275
+
276
+ class Out {
277
+ stdout = "";
278
+ stderr = "";
279
+ line(text: string) {
280
+ this.stdout += `${text}\n`;
281
+ }
282
+ error(text: string) {
283
+ this.stderr += `${text}\n`;
284
+ }
285
+ done(exitCode: number): PlumbingTextOutput {
286
+ return { exitCode, stdout: this.stdout, stderr: this.stderr };
287
+ }
288
+ }
289
+
290
+ /** A child `git update-index` or `git checkout-index`: its exit status, output appended. */
291
+ async function child(
292
+ out: Out,
293
+ run: () => Promise<{ exitCode: number; output: string; errors: string }>,
294
+ ): Promise<number> {
295
+ try {
296
+ const r = await run();
297
+ out.stdout += r.output;
298
+ out.stderr += r.errors;
299
+ return r.exitCode;
300
+ } catch (error) {
301
+ if (error instanceof UpdateIndexFailedError || error instanceof CheckoutIndexFailedError) {
302
+ out.stdout += error.output ?? "";
303
+ out.stderr += `${error.message}\n`;
304
+ return error.exitCode;
305
+ }
306
+ throw error;
307
+ }
308
+ }
309
+
310
+ /** git-merge-one-file.sh over a worktree: the plan applied as the script does. */
311
+ export async function runMergeOneFile(
312
+ command: { oneFileHost: OneFileHost },
313
+ args: readonly string[],
314
+ ): Promise<PlumbingTextOutput> {
315
+ const host = command.oneFileHost;
316
+ const out = new Out();
317
+ // git-sh-setup: `-h` first prints the long usage
318
+ if (args[0] === "-h") {
319
+ out.stdout += LONG_USAGE;
320
+ return out.done(0);
321
+ }
322
+ // cd_to_toplevel, then require_work_tree
323
+ const worktree = host.worktree;
324
+ if (!worktree) {
325
+ out.error("fatal: this operation must be run in a work tree");
326
+ out.error("Cannot chdir to , the toplevel of the working tree");
327
+ return out.done(1);
328
+ }
329
+ if (args.length !== 7) {
330
+ out.stdout += LONG_USAGE;
331
+ return out.done(1);
332
+ }
333
+ const [s1 = "", s2 = "", s3 = "", path = "", m5 = "", m6 = "", m7 = ""] = args;
334
+ const plan = await planOneFile(
335
+ { blobs: host.blobs, style: host.style(), tempName: mkstempName },
336
+ { path, ids: [s1, s2, s3], modes: [m5, m6, m7] },
337
+ );
338
+ for (const line of plan.output) out.line(line);
339
+ const removeFromIndex = () =>
340
+ child(out, () => host.updateIndex().setRemove().addPath(path).call());
341
+ const hexLength = host.blobs.objectFormat?.hexLength ?? 40;
342
+ const addToIndex = async (mode: string, id: string): Promise<number> => {
343
+ // update-index's `--cacheinfo <mode> <id> <path>`: `strtoul_ui(mode, 8)` then
344
+ // `get_oid_hex(id)`, dying with the argument that failed
345
+ const refuse = (arg: string) => {
346
+ out.error(`fatal: git update-index: --cacheinfo cannot add ${arg}`);
347
+ return 128;
348
+ };
349
+ const octal = /^[ \t\n\v\f\r]*\+?([0-7]+)$/.exec(mode);
350
+ const value = octal ? Number.parseInt(octal[1] as string, 8) : Number.NaN;
351
+ if (!octal || value > 0xffffffff) return refuse(mode);
352
+ const hex = id.slice(0, hexLength);
353
+ if (hex.length !== hexLength || !/^[0-9a-fA-F]+$/.test(hex)) return refuse(id);
354
+ return child(out, () =>
355
+ host.updateIndex().setAdd().addCacheInfo(value, hex.toLowerCase(), path).call(),
356
+ );
357
+ };
358
+ const checkout = (stage?: 2) =>
359
+ child(out, () => {
360
+ const cmd = host.checkoutIndex().setForce().addPath(path);
361
+ return (stage ? cmd.setStage(stage) : cmd.setUpdateIndex()).call();
362
+ });
363
+ switch (plan.kind) {
364
+ case "fail":
365
+ for (const line of plan.errors) out.error(line);
366
+ return out.done(1);
367
+ case "remove": {
368
+ if (plan.unlink && (await isRegularFile(worktree, path))) {
369
+ await worktree.remove(path);
370
+ // rmdir -p of the path's directory, quietly stopping at the first that is not empty
371
+ let dir = path.slice(0, Math.max(0, path.lastIndexOf("/")));
372
+ while (dir) {
373
+ if (!(await removeIfEmpty(worktree, dir))) break;
374
+ dir = dir.slice(0, Math.max(0, dir.lastIndexOf("/")));
375
+ }
376
+ }
377
+ return out.done(await removeFromIndex());
378
+ }
379
+ case "add": {
380
+ if (plan.untracked && (await isRegularFile(worktree, path))) {
381
+ out.error(`ERROR: untracked ${path} is overwritten by the merge.`);
382
+ return out.done(1);
383
+ }
384
+ const status = await addToIndex(plan.mode, plan.id);
385
+ if (status !== 0 || !plan.checkout) return out.done(status);
386
+ return out.done(await checkout());
387
+ }
388
+ case "merge": {
389
+ for (const line of plan.errors) out.error(line);
390
+ // `git checkout-index -f --stage=2 -- <path> && cat <ours> ><path> || exit 1`
391
+ if ((await checkout(2)) !== 0) {
392
+ for (const t of plan.temporary) {
393
+ await worktree.writeContent(t.name, t.content, { raw: true, mode: 0o100600 });
394
+ }
395
+ return out.done(1);
396
+ }
397
+ if (plan.oursMissing) {
398
+ // `cat ""` fails: the script exits with the temporary files left
399
+ out.error("cat: '': No such file or directory");
400
+ for (const t of plan.temporary) {
401
+ await worktree.writeContent(t.name, t.content, { raw: true, mode: 0o100600 });
402
+ }
403
+ return out.done(1);
404
+ }
405
+ const mode = (await worktree.getEntry(path))?.mode ?? 0o100644;
406
+ await worktree.writeContent(path, plan.content, { raw: true, mode: Number(mode) });
407
+ if (plan.message) {
408
+ out.error(`ERROR: ${plan.message} in ${path}`);
409
+ return out.done(1);
410
+ }
411
+ return out.done(await child(out, () => host.updateIndex().addPath(path).call()));
412
+ }
413
+ }
414
+ }
415
+
416
+ /**
417
+ * The shell's `test -f`: a regular file, a symbolic link followed to what it names (relative
418
+ * targets resolved inside the worktree, at most 40 links; an absolute target, which the
419
+ * worktree cannot reach portably, counts as no file).
420
+ */
421
+ async function isRegularFile(worktree: Worktree, path: string): Promise<boolean> {
422
+ let current = path;
423
+ for (let links = 0; links <= 40; links++) {
424
+ const entry = await worktree.getEntry(current).catch(() => undefined);
425
+ if (!entry || entry.isDirectory) return false;
426
+ const type = Number(entry.mode) & 0o170000;
427
+ if (type === 0o100000) return true;
428
+ if (type !== 0o120000) return false;
429
+ const target = decodeGitPath(await collect(worktree.readContent(current)));
430
+ if (!target || target.startsWith("/")) return false;
431
+ const parts = current.split("/").slice(0, -1);
432
+ for (const part of target.split("/")) {
433
+ if (part === "" || part === ".") continue;
434
+ if (part === "..") {
435
+ if (parts.length === 0) return false;
436
+ parts.pop();
437
+ } else parts.push(part);
438
+ }
439
+ if (parts.length === 0) return false;
440
+ current = parts.join("/");
441
+ }
442
+ return false;
443
+ }
444
+
445
+ async function removeIfEmpty(worktree: Worktree, dir: string): Promise<boolean> {
446
+ try {
447
+ return (await worktree.removeEmptyDirectory?.(dir)) ?? false;
448
+ } catch {
449
+ return false;
450
+ }
451
+ }