@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
@@ -18,18 +18,20 @@
18
18
  *
19
19
  * Commands report as git's process does: {@link HistoryResult} holds the exit status (255
20
20
  * after git's `error:` lines), stdout (the ref updates of `--dry-run`, split's hunk
21
- * selection) and stderr. git's other subcommands (`fixup`, `drop`, `squash`) are not here
22
- * yet.
21
+ * selection) and stderr. `git history fixup` (2.55) is {@link HistoryFixupCommand}, `drop`
22
+ * (2.56) {@link HistoryDropCommand}, `squash` (git master) {@link HistorySquashCommand}.
23
23
  */
24
24
 
25
25
  import type { Commit, ObjectId } from "@statewalker/vcs-core";
26
26
  import { EMPTY_TREE_ID, FileMode } from "@statewalker/vcs-core";
27
+ import { parseGitBool } from "@statewalker/vcs-utils";
27
28
  import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
28
29
  import { tryReadFile } from "@statewalker/vcs-utils/files";
29
- import type { WorktreeAdmin } from "@statewalker/vcs-working-tree";
30
-
30
+ import type { Worktree, WorktreeAdmin } from "@statewalker/vcs-working-tree";
31
+ import { RevisionError } from "../errors/index.js";
31
32
  import { GitCommand } from "../git-command.js";
32
33
  import { ChangeType } from "../results/diff-entry.js";
34
+ import { RebaseAction } from "../results/rebase-result.js";
33
35
  import type { Status, StatusFileEntry } from "../results/status-result.js";
34
36
  import {
35
37
  PATCH_MODES,
@@ -39,10 +41,33 @@ import {
39
41
  type TemporaryIndex,
40
42
  } from "./add-patch/index.js";
41
43
  import type { CommitEditor } from "./commit-command.js";
44
+ import { coreBool } from "./core-config.js";
42
45
  import { DiffCommand } from "./diff-command.js";
43
46
  import type { LogResult } from "./log-command.js";
44
- import { flatTree, OperationState, storeFlatTree } from "./merge-support.js";
47
+ import { configValue, conflictStyleOf } from "./merge-config.js";
48
+ import { ortConfigOptions } from "./merge-drivers.js";
49
+ import {
50
+ flatTree,
51
+ OperationState,
52
+ readIndex,
53
+ storeFlatTree,
54
+ storeFlatTreeOver,
55
+ subjectOf,
56
+ switchTrees,
57
+ treeDelta,
58
+ } from "./merge-support.js";
45
59
  import { commentPrefixOf, stripspace } from "./message-cleanup.js";
60
+ import { ortResultEntries } from "./ort-merge.js";
61
+ import { mergeStoredTrees, storedBase } from "./ort-recursive.js";
62
+ import {
63
+ combinedMessage,
64
+ commentLines,
65
+ messageBody,
66
+ rearrangeSquash,
67
+ squashTexts,
68
+ subjectLength,
69
+ type TodoItem,
70
+ } from "./rebase-todo.js";
46
71
  import { RevListCommand } from "./rev-list-command.js";
47
72
  import { SigningFailedError, signRequestOf } from "./signing.js";
48
73
  import { formatStatusText } from "./status-format.js";
@@ -65,12 +90,22 @@ export interface HistoryResult {
65
90
  updates: HistoryRefUpdate[];
66
91
  }
67
92
 
93
+ /**
94
+ * What happens to a replayed commit whose change is already there (replay.c's
95
+ * `replay_empty_commit_action`): dropped, kept as an empty commit, or the command refused.
96
+ */
97
+ export type HistoryEmptyAction = "drop" | "keep" | "abort";
98
+
68
99
  /** Which refs move: every descendant branch (git's default), or HEAD alone. */
69
100
  export type HistoryUpdateRefs = "branches" | "head";
70
101
 
71
102
  /** One of git's `error()` returns: the command stops with its lines. */
72
103
  class HistoryFailure extends Error {
73
- constructor(readonly lines: string[]) {
104
+ constructor(
105
+ readonly lines: string[],
106
+ /** the process's status: 255 for `error()` returns */
107
+ readonly exitCode = 255,
108
+ ) {
74
109
  super(lines.join("\n"));
75
110
  this.name = "HistoryFailure";
76
111
  }
@@ -162,7 +197,7 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
162
197
  } catch (error) {
163
198
  if (!(error instanceof HistoryFailure)) throw error;
164
199
  for (const line of error.lines) this.stderr += `${line}\n`;
165
- exitCode = 255;
200
+ exitCode = error.exitCode;
166
201
  }
167
202
  return { exitCode, stdout: this.stdout, stderr: this.stderr, updates };
168
203
  }
@@ -238,7 +273,8 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
238
273
 
239
274
  /**
240
275
  * commit_tree_ext: a commit of `tree` over `parents` with `original`'s author and the
241
- * message given (default: `original`'s), edited first when `edit` names the action;
276
+ * message given (`template`, default: `original`'s), edited first (unless `edit` is false)
277
+ * for `action`;
242
278
  * undefined when the editor failed or the message came back empty (git's lines are in
243
279
  * stderr).
244
280
  */
@@ -248,9 +284,11 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
248
284
  oldTree: ObjectId,
249
285
  tree: ObjectId,
250
286
  action: string,
287
+ edit = true,
288
+ template?: string,
251
289
  ): Promise<ObjectId | undefined> {
252
- const body = original.message.replace(/^(?:[ \t\r]*\n)+/, "");
253
- const message = await this.editMessage(body, oldTree, tree, action);
290
+ const body = template ?? original.message.replace(/^(?:[ \t\r]*\n)+/, "");
291
+ const message = edit ? await this.editMessage(body, oldTree, tree, action) : body;
254
292
  if (message === undefined) return undefined;
255
293
  return this.writeCommit({
256
294
  tree,
@@ -398,6 +436,26 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
398
436
  descendants: LogResult[],
399
437
  reflogMessage: string,
400
438
  ): Promise<HistoryRefUpdate[]> {
439
+ const updates = await this.pendingUpdates(original, rewritten, descendants, "abort");
440
+ if (!updates) fail("error: failed replaying descendants");
441
+ return this.applyPendingUpdates(
442
+ updates as HistoryRefUpdate[],
443
+ reflogMessage,
444
+ "error: failed replaying descendants",
445
+ );
446
+ }
447
+
448
+ /**
449
+ * compute_pending_ref_updates: the descendants replayed onto `rewritten` (replay.c's
450
+ * `replay_revisions`), then the refs at `original` itself moved to `rewritten`, in git's
451
+ * order; undefined when a replay conflicted or failed (its `error:` lines are in stderr).
452
+ */
453
+ protected async pendingUpdates(
454
+ original: ObjectId,
455
+ rewritten: ObjectId,
456
+ descendants: LogResult[],
457
+ empty: HistoryEmptyAction,
458
+ ): Promise<HistoryRefUpdate[] | undefined> {
401
459
  const headRef = await this.refsStore.get("HEAD");
402
460
  const detached = !headRef || !("target" in headRef);
403
461
  const decorations = await this.decorations();
@@ -412,7 +470,8 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
412
470
  for (const commit of descendants) {
413
471
  const parent = commit.parents[0];
414
472
  const base = (parent && mapped.get(parent)) ?? rewritten;
415
- const replayed = await this.replay(commit, base);
473
+ const replayed = await this.pickCommit(commit, base, empty);
474
+ if (replayed === undefined) return undefined;
416
475
  mapped.set(commit.id, replayed);
417
476
  for (const d of decorations.get(commit.id) ?? []) {
418
477
  if (d.head && !detached) continue;
@@ -420,25 +479,51 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
420
479
  updates.push({ ref: d.name, oldId: commit.id, newId: replayed });
421
480
  }
422
481
  }
423
- // compute_pending_ref_updates: the refs at the rewritten commit itself
482
+ // the refs at the rewritten commit itself
424
483
  for (const d of decorations.get(original) ?? []) {
425
484
  if (this.updateRefs === "head" && !d.head) continue;
426
485
  if (this.updateRefs === "branches" && d.head && !detached) continue;
427
486
  updates.push({ ref: d.name, oldId: original, newId: rewritten });
428
487
  }
488
+ return updates;
489
+ }
490
+
491
+ /**
492
+ * apply_pending_ref_updates: the updates printed (`--dry-run`) or made in one transaction;
493
+ * `failure` is the subcommand's line after a failed transaction.
494
+ */
495
+ protected async applyPendingUpdates(
496
+ updates: HistoryRefUpdate[],
497
+ reflogMessage: string,
498
+ failure: string,
499
+ ): Promise<HistoryRefUpdate[]> {
429
500
  if (this.dryRun) {
430
501
  for (const u of updates) this.stdout += `update ${u.ref} ${u.newId} ${u.oldId}\n`;
431
502
  return updates;
432
503
  }
433
- await this.applyUpdates(updates, reflogMessage);
504
+ await this.applyUpdates(updates, reflogMessage, failure);
434
505
  return updates;
435
506
  }
436
507
 
508
+ /** Whether `--dry-run` was given. */
509
+ protected get isDryRun(): boolean {
510
+ return this.dryRun;
511
+ }
512
+
513
+ /** `--update-refs`'s mode. */
514
+ protected get refsMode(): HistoryUpdateRefs {
515
+ return this.updateRefs;
516
+ }
517
+
437
518
  /**
438
519
  * One transaction (ours: the refs under `refs/`, then a detached HEAD, which our stores
439
520
  * do not batch with other refs).
440
521
  */
441
- private async applyUpdates(updates: HistoryRefUpdate[], message: string): Promise<void> {
522
+ private async applyUpdates(
523
+ updates: HistoryRefUpdate[],
524
+ message: string,
525
+ failure: string,
526
+ ): Promise<void> {
442
527
  const log = this.reflogLine(message);
443
528
  const refs = updates.filter((u) => u.ref !== "HEAD");
444
529
  const head = updates.filter((u) => u.ref === "HEAD");
@@ -452,7 +537,7 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
452
537
  const rejected = result.rejected[0];
453
538
  fail(
454
539
  `error: failed to commit ref transaction: cannot lock ref '${rejected?.name ?? ""}'`,
455
- "error: failed replaying descendants",
540
+ failure,
456
541
  );
457
542
  }
458
543
  }
@@ -482,13 +567,64 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
482
567
  }
483
568
 
484
569
  /**
485
- * pick_regular_commit onto `base`, whose tree is the picked commit's parent's (the
486
- * rewrite keeps the trees), so the merge's result is the picked commit's tree: a commit
487
- * with its author and message, a new committer, its extra headers but its signature.
570
+ * pick_regular_commit onto `base` (replay.c): the commit's change merged onto `base` with
571
+ * merge-ort, as git replays it (`base` and the commit's parent as the sides' labels). When
572
+ * `base` has the parent's tree (reword and split keep the trees) the merge's result is
573
+ * the commit's own tree, taken as it is. Returns the new commit, `base` itself for a
574
+ * commit that became empty under `--empty=drop`, or undefined on a conflict or a refusal
575
+ * (git's `error:` line in stderr).
488
576
  */
489
- private async replay(commit: Commit, base: ObjectId): Promise<ObjectId> {
577
+ private async pickCommit(
578
+ commit: Commit & { id: ObjectId },
579
+ base: ObjectId,
580
+ empty: HistoryEmptyAction,
581
+ ): Promise<ObjectId | undefined> {
582
+ const parent = commit.parents[0];
583
+ const emptyTree = this.objectFormat.emptyTreeId ?? EMPTY_TREE_ID;
584
+ const parentTree = parent !== undefined ? await this.commits.getTree(parent) : emptyTree;
585
+ const baseTree = await this.commits.getTree(base);
586
+ if (baseTree === parentTree) return this.replay(commit, base, commit.tree);
587
+ const pickName = await this.abbreviateObjectId(commit.id);
588
+ const baseName = await this.abbreviateObjectId(base);
589
+ const trees = this.trees;
590
+ const blobs = this.blobs;
591
+ const worktree = this.worktreeOrNone();
592
+ const ancestorLabel = parent !== undefined ? `parent of ${pickName}` : "empty tree";
593
+ const merge = await mergeStoredTrees(
594
+ { trees, blobs },
595
+ storedBase(parentTree, ancestorLabel, () => flatTree(trees, parentTree)),
596
+ baseTree,
597
+ commit.tree,
598
+ {
599
+ style: conflictStyleOf(this.workingCopy),
600
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
601
+ ...ortConfigOptions(this.workingCopy, worktree),
602
+ oursLabel: baseName,
603
+ theirsLabel: pickName,
604
+ baseLabel: ancestorLabel,
605
+ },
606
+ );
607
+ // merge-ort writes its result tree (and conflicted blobs) whether clean or not
608
+ const target = await ortResultEntries(blobs, merge);
609
+ const resultTree = await storeFlatTreeOver(trees, baseTree, merge.ours, target);
610
+ if (!merge.clean) return undefined;
611
+ if (resultTree === baseTree && commit.tree !== parentTree) {
612
+ if (empty === "drop") return base;
613
+ if (empty === "abort") {
614
+ this.stderr += `error: commit ${commit.id} became empty after replay\n`;
615
+ return undefined;
616
+ }
617
+ }
618
+ return this.replay(commit, base, resultTree);
619
+ }
620
+
621
+ /**
622
+ * create_commit: `tree` over `base` with the commit's author and message, a new
623
+ * committer, its extra headers but its signature.
624
+ */
625
+ private async replay(commit: Commit, base: ObjectId, tree: ObjectId): Promise<ObjectId> {
490
626
  const id = await this.writeCommit({
491
- tree: commit.tree,
627
+ tree,
492
628
  parents: [base],
493
629
  author: commit.author,
494
630
  committer: this.resolveCommitter(),
@@ -498,8 +634,30 @@ export abstract class HistoryCommandBase extends GitCommand<HistoryResult> {
498
634
  if (!id) fail("error: failed to write commit object", "error: failed replaying descendants");
499
635
  return id as ObjectId;
500
636
  }
637
+
638
+ /** The worktree, none in a bare repository. */
639
+ protected worktreeOrNone(): Worktree | undefined {
640
+ try {
641
+ return this.worktreeAccess;
642
+ } catch {
643
+ return undefined;
644
+ }
645
+ }
501
646
  }
502
647
 
648
+ /** parse_opt_empty's death while the options are parsed (exit 128), else undefined. */
649
+ const checkEmptyAction = (empty: string): HistoryResult | undefined =>
650
+ empty === "drop" || empty === "keep" || empty === "abort"
651
+ ? undefined
652
+ : {
653
+ exitCode: 128,
654
+ stdout: "",
655
+ stderr:
656
+ `fatal: unrecognized '--empty=' action '${empty}'; ` +
657
+ `valid values are "drop", "keep", and "abort".\n`,
658
+ updates: [],
659
+ };
660
+
503
661
  const typeOf = (mode: number | undefined) =>
504
662
  mode === undefined
505
663
  ? undefined
@@ -615,3 +773,777 @@ export class HistorySplitCommand extends HistoryCommandBase {
615
773
  return this.updateReferences(id, second as ObjectId, descendants, `split: updating ${name}`);
616
774
  }
617
775
  }
776
+
777
+ /**
778
+ * `git history drop <commit>` (git 2.56+): the commit removed, its descendants replayed onto
779
+ * its parent through replay.c's merging pick, the refs on them (and on the commit) moved.
780
+ * When HEAD's branch (or a detached HEAD) moves to another tree, the index and worktree
781
+ * follow as `git checkout` would switch them (builtin/history.c's `update_worktree`, a
782
+ * two-way unpack-trees): local changes in the way refuse the whole drop before any ref
783
+ * moves, `--dry-run` included (untracked files in the way are found only by the switch
784
+ * itself, after the refs moved, as git's dry run without update finds none). A replay that
785
+ * conflicts changes nothing.
786
+ *
787
+ * @example
788
+ * ```typescript
789
+ * const result = await git.historyDrop().addArgument("HEAD~").call();
790
+ * // result.exitCode 0; result.updates: the refs moved
791
+ * ```
792
+ */
793
+ export class HistoryDropCommand extends HistoryCommandBase {
794
+ private empty = "drop";
795
+
796
+ /**
797
+ * `--empty=(drop|keep|abort)` (default `drop`): what happens to a descendant whose change
798
+ * the drop leaves empty. Another value is git's death (exit 128).
799
+ */
800
+ setEmpty(empty: HistoryEmptyAction | string): this {
801
+ this.checkCallable();
802
+ this.empty = empty;
803
+ return this;
804
+ }
805
+
806
+ override async call(): Promise<HistoryResult> {
807
+ return checkEmptyAction(this.empty) ?? super.call();
808
+ }
809
+
810
+ protected async run(): Promise<HistoryRefUpdate[]> {
811
+ if (this.args.length !== 1) fail("error: command expects a single revision");
812
+ const name = this.args[0] as string;
813
+ const originalId = await this.commitNamed(name);
814
+ if (!originalId) fail(`error: commit cannot be found: ${name}`);
815
+ const id = originalId as ObjectId;
816
+ const original = await this.loadCommit(id);
817
+ if (original.parents.length === 0) {
818
+ fail(`error: cannot drop root commit ${name}: it has no parent to replay onto`);
819
+ } else if (original.parents.length > 1) {
820
+ fail(`error: cannot drop merge commit: ${name}`);
821
+ }
822
+ const descendants = await this.descendants(id);
823
+ const rewritten = original.parents[0] as ObjectId;
824
+ const updates = await this.pendingUpdates(
825
+ id,
826
+ rewritten,
827
+ descendants,
828
+ this.empty as HistoryEmptyAction,
829
+ );
830
+ if (!updates) fail("error: failed replaying descendants");
831
+ const pending = updates as HistoryRefUpdate[];
832
+ // the index and worktree are checked (a dry run of the switch) before any ref moves
833
+ const worktree = this.worktreeOrNone();
834
+ const move = worktree ? await this.headTreeChange(pending) : undefined;
835
+ if (worktree && move) {
836
+ const refused = await this.updateWorktree(worktree, move, true);
837
+ if (refused) {
838
+ fail(...refused, "error: dropping this commit would overwrite local changes; aborting");
839
+ }
840
+ }
841
+ await this.applyPendingUpdates(
842
+ pending,
843
+ `drop: dropping ${name}`,
844
+ "error: failed to update references",
845
+ );
846
+ if (worktree && move && !this.isDryRun) {
847
+ const refused = await this.updateWorktree(worktree, move, false);
848
+ if (refused) {
849
+ fail(...refused, `error: could not update working tree to new commit ${move.to}`);
850
+ }
851
+ }
852
+ return pending;
853
+ }
854
+
855
+ /**
856
+ * find_head_tree_change: HEAD's update (its branch's, or a detached HEAD's) when it moves
857
+ * HEAD to another tree.
858
+ */
859
+ private async headTreeChange(
860
+ updates: HistoryRefUpdate[],
861
+ ): Promise<{ from: ObjectId; to: ObjectId; fromTree?: ObjectId; toTree?: ObjectId } | undefined> {
862
+ const head = await this.refsStore.get("HEAD");
863
+ if (!head) fail("error: cannot look up HEAD");
864
+ const target = head && "target" in head ? head.target : "HEAD";
865
+ const update = updates.find((u) => u.ref === target);
866
+ if (!update) return undefined;
867
+ const fromTree = await this.commits.getTree(update.oldId);
868
+ const toTree = await this.commits.getTree(update.newId);
869
+ if (!fromTree || !toTree) fail("error: cannot resolve tree for HEAD");
870
+ if (fromTree === toTree) return undefined;
871
+ return { from: update.oldId, to: update.newId, fromTree, toTree };
872
+ }
873
+
874
+ /**
875
+ * update_worktree (reset_working_tree's two-way unpack-trees, "checkout"'s messages): the
876
+ * index and worktree switched from the old HEAD's tree to the new one, or only checked;
877
+ * git's refusal lines, else undefined.
878
+ */
879
+ private async updateWorktree(
880
+ worktree: Worktree,
881
+ move: { fromTree?: ObjectId; toTree?: ObjectId },
882
+ checkOnly: boolean,
883
+ ): Promise<string[] | undefined> {
884
+ const delta = await treeDelta(this.trees, move.fromTree, move.toTree);
885
+ const refused = await switchTrees(
886
+ {
887
+ workingCopy: this.workingCopy,
888
+ worktree,
889
+ staging: this.staging,
890
+ blobs: this.blobs,
891
+ trees: this.trees,
892
+ },
893
+ delta.from,
894
+ delta.to,
895
+ {
896
+ action: "checkout",
897
+ operation: "drop",
898
+ targetTree: move.toTree,
899
+ checkOnly,
900
+ // the dry run is unpack-trees without update: untracked files in the way are not
901
+ // looked for, so git refuses them only in the real switch, after the refs moved
902
+ ...(checkOnly ? { update: false } : {}),
903
+ },
904
+ );
905
+ return refused ? refused.message.split("\n") : undefined;
906
+ }
907
+ }
908
+
909
+ /**
910
+ * `git history fixup <commit>` (git 2.55+): the staged changes (the index against HEAD)
911
+ * merged into the commit with merge-ort, HEAD's tree as the base, the commit's tree and the
912
+ * index's as the sides (as a cherry-pick of the staged changes), the commit rewritten with
913
+ * its author and message (edited under {@link setReeditMessage}), its descendants replayed
914
+ * through replay.c's merging pick and the refs on them moved. The index and worktree are
915
+ * left as they are, and a bare repository is refused. A merge that conflicts changes
916
+ * nothing; a commit the changes leave empty follows {@link setEmpty}.
917
+ *
918
+ * @example
919
+ * ```typescript
920
+ * await git.add().addFilepattern("file.txt").call();
921
+ * const result = await git.historyFixup().addArgument("HEAD~2").call();
922
+ * // result.exitCode 0; result.updates: the refs moved
923
+ * ```
924
+ */
925
+ export class HistoryFixupCommand extends HistoryCommandBase {
926
+ private empty = "drop";
927
+ private reedit = false;
928
+
929
+ /**
930
+ * `--empty=(drop|keep|abort)` (default `drop`): a commit the fixup leaves empty is dropped
931
+ * (its descendants replayed onto its parent; a root commit refuses), kept, or refused, and
932
+ * so is a descendant the replay leaves empty. Another value is git's death (exit 128).
933
+ */
934
+ setEmpty(empty: HistoryEmptyAction | string): this {
935
+ this.checkCallable();
936
+ this.empty = empty;
937
+ return this;
938
+ }
939
+
940
+ /** `--reedit-message`: the commit's message goes through the editor (see `setEditor`). */
941
+ setReeditMessage(reedit = true): this {
942
+ this.checkCallable();
943
+ this.reedit = reedit;
944
+ return this;
945
+ }
946
+
947
+ override async call(): Promise<HistoryResult> {
948
+ return checkEmptyAction(this.empty) ?? super.call();
949
+ }
950
+
951
+ protected async run(): Promise<HistoryRefUpdate[]> {
952
+ if (this.args.length !== 1) fail("error: command expects a single revision");
953
+ const name = this.args[0] as string;
954
+ if (!this.worktreeOrNone()) fail("error: cannot run fixup in a bare repository");
955
+ const originalId = await this.commitNamed(name);
956
+ if (!originalId) fail(`error: commit cannot be found: ${name}`);
957
+ const id = originalId as ObjectId;
958
+ const headId = await this.commitNamed("HEAD");
959
+ if (!headId) fail("error: cannot look up HEAD");
960
+ const headTree = await this.commits.getTree(headId as ObjectId);
961
+ if (!headTree) fail("error: cannot get tree for HEAD");
962
+ const { index, unmerged } = await readIndex(this.staging);
963
+ if (!(await this.indexHasChanges(headTree as ObjectId, index, unmerged))) {
964
+ fail("error: nothing to fixup: no staged changes");
965
+ }
966
+ if (unmerged.length > 0) {
967
+ // write_in_core_index_as_tree: git's BUG() (an abort) on unmerged entries
968
+ return this.unmergedBug(unmerged);
969
+ }
970
+ // write_in_core_index_as_tree: the trees stored, the index file left as it is
971
+ const indexTree = await this.staging.writeTree(this.trees);
972
+ const original = await this.loadCommit(id);
973
+ const originalTree = original.tree;
974
+ const trees = this.trees;
975
+ const blobs = this.blobs;
976
+ const merge = await mergeStoredTrees(
977
+ { trees, blobs },
978
+ storedBase(headTree as ObjectId, "HEAD", () => flatTree(trees, headTree as ObjectId)),
979
+ originalTree,
980
+ indexTree,
981
+ {
982
+ style: conflictStyleOf(this.workingCopy),
983
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
984
+ ...ortConfigOptions(this.workingCopy, this.worktreeOrNone()),
985
+ oursLabel: name,
986
+ theirsLabel: "staged",
987
+ baseLabel: "HEAD",
988
+ },
989
+ );
990
+ // merge-ort writes its result tree (and conflicted blobs) whether clean or not
991
+ const target = await ortResultEntries(blobs, merge);
992
+ const resultTree = await storeFlatTreeOver(trees, originalTree, merge.ours, target);
993
+ if (!merge.clean) fail("error: fixup would produce conflicts; aborting");
994
+ let rewritten: ObjectId | undefined;
995
+ let skip = false;
996
+ if (resultTree === (await this.firstParentTree(original))) {
997
+ if (this.empty === "drop") {
998
+ rewritten = original.parents[0];
999
+ if (!rewritten) {
1000
+ fail(`error: cannot drop root commit ${name}: it has no parent to replay onto`);
1001
+ }
1002
+ skip = true;
1003
+ } else if (this.empty === "abort") {
1004
+ fail(`error: fixup makes commit ${name} empty`);
1005
+ }
1006
+ }
1007
+ const descendants = await this.descendants(id);
1008
+ if (!skip) {
1009
+ rewritten = await this.rewriteCommit(
1010
+ original,
1011
+ original.parents,
1012
+ originalTree,
1013
+ resultTree,
1014
+ "fixup",
1015
+ this.reedit,
1016
+ );
1017
+ if (!rewritten) fail("error: failed writing fixed-up commit");
1018
+ }
1019
+ const updates = await this.pendingUpdates(
1020
+ id,
1021
+ rewritten as ObjectId,
1022
+ descendants,
1023
+ this.empty as HistoryEmptyAction,
1024
+ );
1025
+ if (!updates) fail("error: failed replaying descendants");
1026
+ return this.applyPendingUpdates(
1027
+ updates as HistoryRefUpdate[],
1028
+ `fixup: updating ${name}`,
1029
+ "error: failed replaying descendants",
1030
+ );
1031
+ }
1032
+
1033
+ /**
1034
+ * repo_index_has_changes: whether the index differs from HEAD's tree (diff-index --cached
1035
+ * with intent-to-add entries visible, as new empty files, and unmerged paths as changes).
1036
+ */
1037
+ private async indexHasChanges(
1038
+ headTree: ObjectId,
1039
+ index: Map<string, { mode: number; objectId: ObjectId; intentToAdd?: boolean }>,
1040
+ unmerged: string[],
1041
+ ): Promise<boolean> {
1042
+ if (unmerged.length > 0) return true;
1043
+ const head = await flatTree(this.trees, headTree, { asIndex: true });
1044
+ if (head.size !== index.size) return true;
1045
+ for (const [path, entry] of index) {
1046
+ const other = head.get(path);
1047
+ if (!other || entry.intentToAdd) return true;
1048
+ if (other.mode !== entry.mode || other.objectId !== entry.objectId) return true;
1049
+ }
1050
+ return false;
1051
+ }
1052
+
1053
+ /** git's BUG() in write_in_core_index_as_tree: its lines, the abort's status (134). */
1054
+ private unmergedBug(paths: string[]): never {
1055
+ throw new HistoryFailure(
1056
+ [
1057
+ "BUG: there are unmerged index entries:",
1058
+ ...paths.map((p) => `BUG: ${p}`),
1059
+ "BUG: unmerged index entries when writing in-core index",
1060
+ ],
1061
+ 134,
1062
+ );
1063
+ }
1064
+ }
1065
+
1066
+ /** builtin/history.c's flags of the commits a squash walks (SQUASH_SEEN, SQUASH_AMEND_TARGET). */
1067
+ const SQUASH_SEEN = 1;
1068
+ const SQUASH_AMEND_TARGET = 4;
1069
+
1070
+ /** The autosquash prefixes (is_autosquash_subject). */
1071
+ const isAutosquashSubject = (s: string) =>
1072
+ s.startsWith("amend!") || s.startsWith("fixup!") || s.startsWith("squash!");
1073
+
1074
+ /** skip_one_autosquash_prefix: the text after one prefix and its spaces, else undefined. */
1075
+ function skipOneAutosquashPrefix(s: string): string | undefined {
1076
+ for (const prefix of ["amend!", "fixup!", "squash!"]) {
1077
+ if (s.startsWith(prefix)) return s.slice(prefix.length).replace(/^ +/, "");
1078
+ }
1079
+ return undefined;
1080
+ }
1081
+
1082
+ /** truncate_message_to_subject: the text up to its first blank line, its newline kept. */
1083
+ function truncateToSubject(message: string): string {
1084
+ const eos = message.indexOf("\n\n");
1085
+ return eos >= 0 ? message.slice(0, eos + 1) : message;
1086
+ }
1087
+
1088
+ /** strbuf_complete_line */
1089
+ const completeLine = (text: string) => (text && !text.endsWith("\n") ? `${text}\n` : text);
1090
+
1091
+ /** Byte order of git paths and ref names. */
1092
+ function compareBytes(a: Uint8Array, b: Uint8Array): number {
1093
+ const n = Math.min(a.length, b.length);
1094
+ for (let i = 0; i < n; i++) {
1095
+ const d = (a[i] as number) - (b[i] as number);
1096
+ if (d !== 0) return d;
1097
+ }
1098
+ return a.length - b.length;
1099
+ }
1100
+
1101
+ /** git's isspace, from the start. */
1102
+ const trimStart = (text: string) => text.replace(/^[ \t\n\v\f\r]+/, "");
1103
+
1104
+ /** git's 32-bit FNV-1 `strhash` over the UTF-8 bytes. */
1105
+ function strhash(text: string): number {
1106
+ let hash = 0x811c9dc5;
1107
+ for (const c of encodeGitPath(text)) hash = (Math.imul(hash, 0x01000193) ^ c) >>> 0;
1108
+ return hash;
1109
+ }
1110
+
1111
+ /**
1112
+ * The keys of a strmap (hashmap.c keyed by `strhash`: 64 buckets growing fourfold past 80%
1113
+ * load, each new entry first in its bucket) in the order its iteration visits them, the keys
1114
+ * added in this order.
1115
+ */
1116
+ function strmapOrder(keys: Iterable<string>): string[] {
1117
+ let table: { hash: number; key: string }[][] = Array.from({ length: 64 }, () => []);
1118
+ let count = 0;
1119
+ for (const key of keys) {
1120
+ const hash = strhash(key);
1121
+ table[hash & (table.length - 1)]?.unshift({ hash, key });
1122
+ count++;
1123
+ if (count > Math.floor((table.length * 80) / 100)) {
1124
+ const size = table.length * 4;
1125
+ const old = table;
1126
+ table = Array.from({ length: size }, () => []);
1127
+ for (const bucket of old) for (const x of bucket) table[x.hash & (size - 1)]?.unshift(x);
1128
+ }
1129
+ }
1130
+ return table.flat().map((x) => x.key);
1131
+ }
1132
+
1133
+ /** The walk options setup_squash_revisions resets (with its warning) or takes as they are. */
1134
+ const WALK_REF_OPTIONS =
1135
+ /^--(?:all|branches|tags|remotes|not|glob=.*|exclude=.*|(?:branches|tags|remotes)=.*)$/;
1136
+
1137
+ /** builtin/history.c's subject_data: what the subjects of the walked commits decide. */
1138
+ interface SquashSubjects {
1139
+ /** subject (the base's without one autosquash prefix) → flags, in insertion order */
1140
+ subjects: Map<string, number>;
1141
+ subject: string;
1142
+ /** the message from its subject on (find_commit_subject) */
1143
+ message: string;
1144
+ squashMessage: string;
1145
+ edit: boolean;
1146
+ }
1147
+
1148
+ /**
1149
+ * `git history squash <revision-range>` (git master): the commits of the range (a `<base>..<tip>`
1150
+ * walked as `--reverse --topo-order --full-history --ancestry-path`, other walk options
1151
+ * ignored with git's warning) folded into one commit over the oldest commit's parents, with
1152
+ * the tip's tree, the oldest commit's author and a message built from theirs: with
1153
+ * {@link setEdit} (the default) every message goes through the editor as `rebase -i` lists
1154
+ * a squash chain (`fixup!`/`squash!`/`amend!` commits grouped under their targets); with
1155
+ * `setEdit(false)` the oldest commit's message, `amend!` and `squash!` commits aimed at it
1156
+ * replacing or extending it. The descendants of the tip are replayed onto the result and
1157
+ * the branches on them moved; trees do not change, so neither do the index and worktree.
1158
+ * Merges inside the range fold when their other parents are in the range (or are parents
1159
+ * of the oldest commit); a branch pointing into the range refuses the squash unless
1160
+ * `--update-refs=head`.
1161
+ *
1162
+ * @example
1163
+ * ```typescript
1164
+ * const result = await git.historySquash().addArgument("main~3..main").setEdit(false).call();
1165
+ * // result.exitCode 0; result.updates: the refs moved
1166
+ * ```
1167
+ */
1168
+ export class HistorySquashCommand extends HistoryCommandBase {
1169
+ private edit = true;
1170
+ private readonly flags = new Map<ObjectId, number>();
1171
+
1172
+ /** `--[no-]edit` (default on): the combined message goes through the editor. */
1173
+ setEdit(edit = true): this {
1174
+ this.checkCallable();
1175
+ this.edit = edit;
1176
+ return this;
1177
+ }
1178
+
1179
+ protected async run(): Promise<HistoryRefUpdate[]> {
1180
+ if (this.args.length === 0) fail("error: command expects a revision range");
1181
+ const reflogMessage = `squash: updating ${this.args.join(" ")}`;
1182
+ const { oldest, tip, message } = await this.resolveSquashRange();
1183
+ const descendants = await this.descendants(tip.id);
1184
+ const baseTree = (await this.loadCommit(oldest.parents[0] as ObjectId)).tree;
1185
+ const rewritten = await this.rewriteCommit(
1186
+ oldest,
1187
+ oldest.parents,
1188
+ baseTree,
1189
+ tip.tree,
1190
+ "squash",
1191
+ this.edit,
1192
+ message,
1193
+ );
1194
+ if (!rewritten) fail("error: failed writing squashed commit");
1195
+ return this.updateReferences(tip.id, rewritten as ObjectId, descendants, reflogMessage);
1196
+ }
1197
+
1198
+ /**
1199
+ * setup_squash_revisions: the walk of the range; git's warning when an option would change
1200
+ * how it walks (the option then ignored).
1201
+ */
1202
+ private async squashRevisions(): Promise<RevListCommand> {
1203
+ const revs = new RevListCommand(this.workingCopy)
1204
+ .setReverse(true)
1205
+ .setOrder("topo")
1206
+ .setFullHistory(true)
1207
+ .setAncestryPath(true);
1208
+ let reverse = true;
1209
+ let sort = "graph";
1210
+ let boundary = false;
1211
+ const unknown: string[] = [];
1212
+ // RevListCommand reads its ref-option list apart from its mixed list, so with `--not` or
1213
+ // a ref option every revision goes to the ordered one (setup_revisions reads one argv)
1214
+ const ordered = this.args.some((arg) => WALK_REF_OPTIONS.test(arg));
1215
+ for (const arg of this.args) {
1216
+ if (arg === "--reverse") reverse = !reverse;
1217
+ else if (arg === "--topo-order") sort = "graph";
1218
+ else if (arg === "--date-order") sort = "date";
1219
+ else if (arg === "--author-date-order") sort = "author";
1220
+ else if (arg === "--boundary") boundary = true;
1221
+ else if (arg === "--full-history" || arg === "--ancestry-path") {
1222
+ // what the walk already does
1223
+ } else if (arg.startsWith("--ancestry-path=")) {
1224
+ revs.addAncestryPath(arg.slice("--ancestry-path=".length));
1225
+ } else if (WALK_REF_OPTIONS.test(arg)) revs.addRevision(arg);
1226
+ else if (!arg.startsWith("-") || arg === "-" || arg === "--") {
1227
+ if (ordered && arg !== "--") revs.addRevision(arg);
1228
+ else revs.addArgument(arg);
1229
+ } else unknown.push(arg);
1230
+ }
1231
+ let resolved: Awaited<ReturnType<RevListCommand["resolve"]>>;
1232
+ try {
1233
+ resolved = await revs.resolve();
1234
+ } catch (error) {
1235
+ if (error instanceof RevisionError) throw new HistoryFailure(error.message.split("\n"), 128);
1236
+ throw error;
1237
+ }
1238
+ for (const warning of resolved.warnings) this.stderr += `${warning}\n`;
1239
+ if (unknown.length > 0) fail(`error: unrecognized argument: ${unknown[0]}`);
1240
+ if (!reverse || sort !== "graph" || boundary) {
1241
+ this.stderr +=
1242
+ "warning: ignoring rev-list options that would change how the range is walked\n";
1243
+ }
1244
+ // a squash needs a base to reparent onto
1245
+ if (!resolved.entries.some((e) => e.exclude)) {
1246
+ fail("error: not a '<base>..<tip>' revision range");
1247
+ }
1248
+ return revs;
1249
+ }
1250
+
1251
+ /**
1252
+ * resolve_squash_range: the oldest commit and the single tip of the range (every parent
1253
+ * after the oldest commit selected, or a parent of the oldest commit), the subjects
1254
+ * checked, branches pointing into the range refused, and the message to commit.
1255
+ */
1256
+ private async resolveSquashRange(): Promise<{
1257
+ oldest: LogResult;
1258
+ tip: LogResult;
1259
+ message: string;
1260
+ }> {
1261
+ const revs = await this.squashRevisions();
1262
+ const data: SquashSubjects = {
1263
+ subjects: new Map(),
1264
+ subject: "",
1265
+ message: "",
1266
+ squashMessage: "",
1267
+ edit: this.edit,
1268
+ };
1269
+ const todo: ObjectId[] = [];
1270
+ const withCommit: ObjectId[] = [];
1271
+ const tips = new Set<ObjectId>();
1272
+ let oldest: LogResult | undefined;
1273
+ let tip: LogResult | undefined;
1274
+ let tipCount = 0;
1275
+ for await (const commit of await revs.call()) {
1276
+ if (this.edit) todo.push(commit.id);
1277
+ if (commit.parents.length === 0) fail("error: cannot squash down to root commit");
1278
+ if (oldest) {
1279
+ for (const parent of commit.parents) {
1280
+ let seen = ((this.flags.get(parent) ?? 0) & SQUASH_SEEN) !== 0;
1281
+ // parents that match the parents of the squashed commit
1282
+ for (const q of oldest.parents) {
1283
+ if (seen) break;
1284
+ if (parent === q) {
1285
+ seen = true;
1286
+ withCommit.push(commit.id);
1287
+ }
1288
+ }
1289
+ if (!seen) {
1290
+ fail(
1291
+ `error: parent ${await this.abbreviateObjectId(parent)} of commit ` +
1292
+ `${await this.abbreviateObjectId(commit.id)} is outside the revision range`,
1293
+ );
1294
+ }
1295
+ if (tips.delete(parent)) tipCount--;
1296
+ }
1297
+ }
1298
+ if (!oldest) {
1299
+ withCommit.push(commit.id);
1300
+ oldest = commit;
1301
+ }
1302
+ await this.checkSubject(commit, data);
1303
+ tip = commit;
1304
+ this.flags.set(commit.id, (this.flags.get(commit.id) ?? 0) | SQUASH_SEEN);
1305
+ tips.add(commit.id);
1306
+ tipCount++;
1307
+ }
1308
+ if (tipCount === 0) fail("error: the revision range is empty");
1309
+ else if (tipCount !== 1) fail("error: the revision range contains more than one tip commit");
1310
+ else if (oldest === tip) {
1311
+ fail("error: the revision range holds a single commit; nothing to squash");
1312
+ }
1313
+ const first = oldest as LogResult;
1314
+ const last = tip as LogResult;
1315
+ if (this.refsMode === "branches") await this.refuseBranchesInRange(withCommit, last.id);
1316
+ let message = data.squashMessage;
1317
+ if (this.edit) message = await this.buildSquashMessage(todo);
1318
+ return { oldest: first, tip: last, message };
1319
+ }
1320
+
1321
+ /**
1322
+ * The branches that contain a commit of `withCommit` but not the tip (ref-filter's
1323
+ * `--contains`/`--no-contains`) refuse the squash: they could not be rewritten.
1324
+ */
1325
+ private async refuseBranchesInRange(withCommit: ObjectId[], tip: ObjectId): Promise<void> {
1326
+ const contains = async (id: ObjectId, c: ObjectId) =>
1327
+ id === c || (await this.commits.isAncestor(c, id));
1328
+ const names: string[] = [];
1329
+ for await (const ref of this.refsStore.list("refs/heads/")) {
1330
+ const id = (await this.refsStore.resolve(ref.name).catch(() => undefined))?.objectId;
1331
+ if (!id) continue;
1332
+ if (await contains(id, tip)) continue;
1333
+ let hit = false;
1334
+ for (const c of withCommit) {
1335
+ if (await contains(id, c)) {
1336
+ hit = true;
1337
+ break;
1338
+ }
1339
+ }
1340
+ if (hit) names.push(ref.name);
1341
+ }
1342
+ if (names.length === 0) return;
1343
+ const keyed = names.map((n) => ({ n, key: encodeGitPath(n) }));
1344
+ keyed.sort((a, b) => compareBytes(a.key, b.key));
1345
+ const lines = [
1346
+ "error: the following branches cannot be rewritten as descendants of the squashed commit:",
1347
+ ...keyed.map(({ n }) => ` ${n.slice("refs/heads/".length)}`),
1348
+ ];
1349
+ const advice = configValue(this.workingCopy, "advice.historyUpdateRefs");
1350
+ if (advice === undefined || (parseGitBool(advice) ?? true)) {
1351
+ lines.push(
1352
+ "hint: Use --update-refs=head to rewrite only the current branch and leave such branches untouched.",
1353
+ 'hint: Disable this message with "git config set --global advice.historyUpdateRefs false"',
1354
+ );
1355
+ }
1356
+ fail(...lines);
1357
+ }
1358
+
1359
+ /** squash_check_subject */
1360
+ private async checkSubject(commit: LogResult, data: SquashSubjects): Promise<void> {
1361
+ data.message = messageBody(commit.message);
1362
+ const eol = data.message.indexOf("\n");
1363
+ data.subject = eol < 0 ? data.message : data.message.slice(0, eol);
1364
+ if (data.subjects.size === 0) {
1365
+ data.squashMessage = completeLine(data.squashMessage + data.message);
1366
+ // a single autosquash prefix stripped, to squash `fixup! base` and `amend! base`
1367
+ const s = skipOneAutosquashPrefix(data.subject) ?? data.subject;
1368
+ data.subjects.set(s, SQUASH_AMEND_TARGET | SQUASH_SEEN);
1369
+ this.addFlags(commit.id, SQUASH_AMEND_TARGET);
1370
+ } else if (isAutosquashSubject(data.subject)) {
1371
+ await this.checkAutosquashSubject(commit, data);
1372
+ } else {
1373
+ data.subjects.set(data.subject, SQUASH_SEEN);
1374
+ }
1375
+ }
1376
+
1377
+ private addFlags(id: ObjectId, flags: number): void {
1378
+ this.flags.set(id, (this.flags.get(id) ?? 0) | flags);
1379
+ }
1380
+
1381
+ /** squash_check_autosquash_subject: the target of a `fixup!`/`squash!`/`amend!` commit. */
1382
+ private async checkAutosquashSubject(commit: LogResult, data: SquashSubjects): Promise<void> {
1383
+ // the prefixes skipped one at a time, to squash `a commit` with `fixup! fixup! a commit`
1384
+ let s: string | undefined = data.subject;
1385
+ for (let next = skipOneAutosquashPrefix(s); next !== undefined; ) {
1386
+ s = next;
1387
+ const flags = data.subjects.get(s) ?? 0;
1388
+ if (flags) return this.canAutosquash(commit, data, flags);
1389
+ next = skipOneAutosquashPrefix(s);
1390
+ }
1391
+ // `fixup! <hex object id>`, but not `fixup! HEAD^` or `fixup! main`
1392
+ const target = await this.commitNamed(s);
1393
+ if (target?.startsWith(s)) {
1394
+ let flags = (this.flags.get(target) ?? 0) & (SQUASH_SEEN | SQUASH_AMEND_TARGET);
1395
+ if (!flags) {
1396
+ const body = messageBody((await this.loadCommit(target)).message);
1397
+ const eol = body.indexOf("\n");
1398
+ flags = data.subjects.get(eol < 0 ? body : body.slice(0, eol)) ?? 0;
1399
+ }
1400
+ if (flags) return this.canAutosquash(commit, data, flags);
1401
+ }
1402
+ // subject prefix matches, in the strmap's order
1403
+ for (const key of strmapOrder(data.subjects.keys())) {
1404
+ let rest: string | undefined = skipOneAutosquashPrefix(data.subject);
1405
+ while (rest !== undefined) {
1406
+ if (key.startsWith(rest)) {
1407
+ return this.canAutosquash(commit, data, data.subjects.get(key) ?? 0);
1408
+ }
1409
+ rest = skipOneAutosquashPrefix(rest);
1410
+ }
1411
+ }
1412
+ fail(
1413
+ `error: cannot squash ${await this.abbreviateObjectId(commit.id)} (${data.subject}): ` +
1414
+ "its target is not being squashed",
1415
+ );
1416
+ }
1417
+
1418
+ /** squash_check_can_autosquash */
1419
+ private async canAutosquash(
1420
+ commit: LogResult,
1421
+ data: SquashSubjects,
1422
+ flags: number,
1423
+ ): Promise<void> {
1424
+ this.addFlags(commit.id, flags & SQUASH_AMEND_TARGET);
1425
+ if (data.subject.startsWith("amend!")) await this.amendMessage(commit, data, flags);
1426
+ else if (data.subject.startsWith("squash!"))
1427
+ await this.squashSquashMessage(commit, data, flags);
1428
+ }
1429
+
1430
+ /** squash_amend_message: an `amend!` commit's body replaces the base's message. */
1431
+ private async amendMessage(
1432
+ commit: LogResult,
1433
+ data: SquashSubjects,
1434
+ flags: number,
1435
+ ): Promise<void> {
1436
+ const body = trimStart(data.message.slice(data.subject.length));
1437
+ const name = await this.abbreviateObjectId(commit.id);
1438
+ if (!body) {
1439
+ this.stderr += `warning: ignoring ${name} (${data.subject}): message body is empty\n`;
1440
+ return;
1441
+ }
1442
+ if (data.edit) return;
1443
+ if (!(flags & SQUASH_AMEND_TARGET)) {
1444
+ fail(
1445
+ `error: cannot squash ${name} (${data.subject}) that does not target base commit ` +
1446
+ "without '--edit'",
1447
+ );
1448
+ }
1449
+ let sq = data.squashMessage;
1450
+ if (sq.startsWith("squash!")) {
1451
+ fail(
1452
+ `error: squashing ${name} (${data.subject}) would overwrite 'squash!' message, ` +
1453
+ "please combine them using '--edit'",
1454
+ );
1455
+ }
1456
+ if (sq.startsWith("fixup!")) sq = `amend${sq.slice(5)}`;
1457
+ sq = sq.startsWith("amend!") ? `${truncateToSubject(sq)}\n` : "";
1458
+ data.squashMessage = completeLine(sq + body);
1459
+ }
1460
+
1461
+ /** squash_squash_message: a `squash!` commit's body appended to a `squash!` message. */
1462
+ private async squashSquashMessage(
1463
+ commit: LogResult,
1464
+ data: SquashSubjects,
1465
+ flags: number,
1466
+ ): Promise<void> {
1467
+ const body = trimStart(data.message.slice(data.subject.length));
1468
+ if (data.edit) return;
1469
+ const name = await this.abbreviateObjectId(commit.id);
1470
+ if (!(flags & SQUASH_AMEND_TARGET)) {
1471
+ fail(
1472
+ `error: cannot squash ${name} (${data.subject}) that does not target base commit ` +
1473
+ "without '--edit'",
1474
+ );
1475
+ }
1476
+ let sq = data.squashMessage;
1477
+ if (sq.startsWith("fixup!")) sq = `squash${truncateToSubject(sq).slice(5)}`;
1478
+ if (!sq.startsWith("squash!")) {
1479
+ fail(
1480
+ `error: squashing ${name} (${data.subject}) would discard its message, please ` +
1481
+ "combine them using '--edit'",
1482
+ );
1483
+ }
1484
+ data.squashMessage = completeLine(`${sq}\n${body}`);
1485
+ }
1486
+
1487
+ /**
1488
+ * build_squash_message: the walked commits as a todo list rearranged as `--autosquash`
1489
+ * does, their messages under sequencer.c's headers (`# This is a combination of N
1490
+ * commits.`), a skipped message commented out, a squashing one's autosquash subject too.
1491
+ */
1492
+ private async buildSquashMessage(todo: ObjectId[]): Promise<string> {
1493
+ const comment = commentPrefixOf(this.workingCopy);
1494
+ const messages = new Map<ObjectId, string>();
1495
+ const messageOf = async (id: ObjectId) => {
1496
+ let m = messages.get(id);
1497
+ if (m === undefined) {
1498
+ m = (await this.loadCommit(id)).message;
1499
+ messages.set(id, m);
1500
+ }
1501
+ return m;
1502
+ };
1503
+ // todo_list_rearrange_squash takes a named target only when the list has it before
1504
+ const items = await rearrangeSquash(
1505
+ todo.map((id): TodoItem => ({ action: RebaseAction.PICK, id })),
1506
+ async (id) => subjectOf(await messageOf(id)),
1507
+ (name) => this.commitNamed(name),
1508
+ );
1509
+ if (!items) fail("error: could not prepare the squash message");
1510
+ const list = items as TodoItem[];
1511
+ // amend_replaces_target
1512
+ const amendReplacesTarget = (target: number) => {
1513
+ for (let i = target + 1; i < list.length && list[i]?.action !== RebaseAction.PICK; i++) {
1514
+ if (list[i]?.action === RebaseAction.SQUASH) return false;
1515
+ if (list[i]?.replaceMessage) return true;
1516
+ }
1517
+ return false;
1518
+ };
1519
+ let out = "";
1520
+ for (const [i, item] of list.entries()) {
1521
+ const squashing = item.action === RebaseAction.SQUASH || item.replaceMessage === true;
1522
+ const skip = item.action === RebaseAction.PICK ? amendReplacesTarget(i) : !squashing;
1523
+ const body = messageBody(await messageOf(item.id));
1524
+ let commented = 0;
1525
+ if (skip) commented = body.length;
1526
+ else if (squashing) {
1527
+ // squash_subject_comment_len
1528
+ if (body.startsWith("amend!") || body.startsWith("squash!") || body.startsWith("fixup!")) {
1529
+ commented = subjectLength(body);
1530
+ }
1531
+ }
1532
+ if (i === 0) out += `${comment} ${combinedMessage(list.length)}`;
1533
+ out += `\n${comment} `;
1534
+ const n = i + 1;
1535
+ out +=
1536
+ n === 1
1537
+ ? skip
1538
+ ? squashTexts.skipFirstMessage
1539
+ : squashTexts.firstMessage
1540
+ : skip
1541
+ ? squashTexts.skipNthMessage(n)
1542
+ : squashTexts.nthMessage(n);
1543
+ out += "\n\n";
1544
+ out = commentLines(out, body.slice(0, commented), comment);
1545
+ out = completeLine(out + body.slice(commented));
1546
+ }
1547
+ return out;
1548
+ }
1549
+ }