@statewalker/vcs-commands 0.8.0 → 0.9.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 (297) hide show
  1. package/dist/commands/add-command.d.ts +32 -0
  2. package/dist/commands/add-command.d.ts.map +1 -1
  3. package/dist/commands/add-patch/add-patch.d.ts +7 -0
  4. package/dist/commands/add-patch/add-patch.d.ts.map +1 -1
  5. package/dist/commands/add-patch/patch-backend.d.ts.map +1 -1
  6. package/dist/commands/am/am-command.d.ts +47 -0
  7. package/dist/commands/am/am-command.d.ts.map +1 -1
  8. package/dist/commands/apply/apply-command.d.ts +2 -0
  9. package/dist/commands/apply/apply-command.d.ts.map +1 -1
  10. package/dist/commands/apply/apply-parse.d.ts +7 -0
  11. package/dist/commands/apply/apply-parse.d.ts.map +1 -1
  12. package/dist/commands/apply/index.d.ts +1 -1
  13. package/dist/commands/apply/index.d.ts.map +1 -1
  14. package/dist/commands/blame-command.d.ts +303 -8
  15. package/dist/commands/blame-command.d.ts.map +1 -1
  16. package/dist/commands/blame-ignore.d.ts +48 -0
  17. package/dist/commands/blame-ignore.d.ts.map +1 -0
  18. package/dist/commands/check-mailmap-command.d.ts +49 -0
  19. package/dist/commands/check-mailmap-command.d.ts.map +1 -0
  20. package/dist/commands/checkout-command.d.ts +7 -0
  21. package/dist/commands/checkout-command.d.ts.map +1 -1
  22. package/dist/commands/checkout-paths.d.ts +4 -0
  23. package/dist/commands/checkout-paths.d.ts.map +1 -1
  24. package/dist/commands/cherry-command.d.ts +61 -0
  25. package/dist/commands/cherry-command.d.ts.map +1 -0
  26. package/dist/commands/cherry-pick-command.d.ts +23 -1
  27. package/dist/commands/cherry-pick-command.d.ts.map +1 -1
  28. package/dist/commands/clean-command.d.ts +32 -0
  29. package/dist/commands/clean-command.d.ts.map +1 -1
  30. package/dist/commands/clean-interactive.d.ts +56 -0
  31. package/dist/commands/clean-interactive.d.ts.map +1 -0
  32. package/dist/commands/clone-command.d.ts +116 -2
  33. package/dist/commands/clone-command.d.ts.map +1 -1
  34. package/dist/commands/commit-command.d.ts +50 -2
  35. package/dist/commands/commit-command.d.ts.map +1 -1
  36. package/dist/commands/describe-command.d.ts +71 -64
  37. package/dist/commands/describe-command.d.ts.map +1 -1
  38. package/dist/commands/diff-command.d.ts +118 -6
  39. package/dist/commands/diff-command.d.ts.map +1 -1
  40. package/dist/commands/fetch-command.d.ts +60 -0
  41. package/dist/commands/fetch-command.d.ts.map +1 -1
  42. package/dist/commands/fetch-multiple-command.d.ts +193 -0
  43. package/dist/commands/fetch-multiple-command.d.ts.map +1 -0
  44. package/dist/commands/format-patch-command.d.ts +28 -2
  45. package/dist/commands/format-patch-command.d.ts.map +1 -1
  46. package/dist/commands/git-describe.d.ts +77 -4
  47. package/dist/commands/git-describe.d.ts.map +1 -1
  48. package/dist/commands/git-hooks.d.ts +15 -1
  49. package/dist/commands/git-hooks.d.ts.map +1 -1
  50. package/dist/commands/index.d.ts +12 -0
  51. package/dist/commands/index.d.ts.map +1 -1
  52. package/dist/commands/index.js +5 -3
  53. package/dist/commands/init-command.d.ts +89 -0
  54. package/dist/commands/init-command.d.ts.map +1 -1
  55. package/dist/commands/line-log.d.ts +161 -0
  56. package/dist/commands/line-log.d.ts.map +1 -0
  57. package/dist/commands/log-command.d.ts +235 -6
  58. package/dist/commands/log-command.d.ts.map +1 -1
  59. package/dist/commands/log-graph.d.ts +4 -2
  60. package/dist/commands/log-graph.d.ts.map +1 -1
  61. package/dist/commands/log-output.d.ts +66 -1
  62. package/dist/commands/log-output.d.ts.map +1 -1
  63. package/dist/commands/mailmap.d.ts +24 -1
  64. package/dist/commands/mailmap.d.ts.map +1 -1
  65. package/dist/commands/merge-command.d.ts +51 -1
  66. package/dist/commands/merge-command.d.ts.map +1 -1
  67. package/dist/commands/merge-drivers.d.ts +2 -0
  68. package/dist/commands/merge-drivers.d.ts.map +1 -1
  69. package/dist/commands/merge-strategy-options.d.ts +69 -0
  70. package/dist/commands/merge-strategy-options.d.ts.map +1 -0
  71. package/dist/commands/merge-support.d.ts +10 -0
  72. package/dist/commands/merge-support.d.ts.map +1 -1
  73. package/dist/commands/message-cleanup.d.ts +2 -0
  74. package/dist/commands/message-cleanup.d.ts.map +1 -1
  75. package/dist/commands/name-rev-command.d.ts +65 -0
  76. package/dist/commands/name-rev-command.d.ts.map +1 -0
  77. package/dist/commands/name-rev.d.ts +110 -22
  78. package/dist/commands/name-rev.d.ts.map +1 -1
  79. package/dist/commands/octopus-merge.d.ts +26 -1
  80. package/dist/commands/octopus-merge.d.ts.map +1 -1
  81. package/dist/commands/ort-merge.d.ts +16 -0
  82. package/dist/commands/ort-merge.d.ts.map +1 -1
  83. package/dist/commands/ort-recursive.d.ts.map +1 -1
  84. package/dist/commands/patch-id.d.ts +58 -0
  85. package/dist/commands/patch-id.d.ts.map +1 -1
  86. package/dist/commands/pull-command.d.ts +182 -38
  87. package/dist/commands/pull-command.d.ts.map +1 -1
  88. package/dist/commands/push-command.d.ts +65 -0
  89. package/dist/commands/push-command.d.ts.map +1 -1
  90. package/dist/commands/range-diff/index.d.ts +4 -0
  91. package/dist/commands/range-diff/index.d.ts.map +1 -0
  92. package/dist/commands/range-diff/linear-assignment.d.ts +27 -0
  93. package/dist/commands/range-diff/linear-assignment.d.ts.map +1 -0
  94. package/dist/commands/range-diff/range-diff-command.d.ts +121 -0
  95. package/dist/commands/range-diff/range-diff-command.d.ts.map +1 -0
  96. package/dist/commands/range-diff/range-diff.d.ts +106 -0
  97. package/dist/commands/range-diff/range-diff.d.ts.map +1 -0
  98. package/dist/commands/read-tree-command.d.ts +14 -0
  99. package/dist/commands/read-tree-command.d.ts.map +1 -1
  100. package/dist/commands/rebase-command.d.ts +21 -2
  101. package/dist/commands/rebase-command.d.ts.map +1 -1
  102. package/dist/commands/remerge-diff.d.ts +59 -0
  103. package/dist/commands/remerge-diff.d.ts.map +1 -0
  104. package/dist/commands/remote-command.d.ts +41 -0
  105. package/dist/commands/remote-command.d.ts.map +1 -1
  106. package/dist/commands/remote-show-command.d.ts +204 -0
  107. package/dist/commands/remote-show-command.d.ts.map +1 -0
  108. package/dist/commands/reset-command.d.ts +19 -1
  109. package/dist/commands/reset-command.d.ts.map +1 -1
  110. package/dist/commands/restore-command.d.ts +7 -0
  111. package/dist/commands/restore-command.d.ts.map +1 -1
  112. package/dist/commands/rev-list-command.d.ts +75 -3
  113. package/dist/commands/rev-list-command.d.ts.map +1 -1
  114. package/dist/commands/revert-command.d.ts +22 -1
  115. package/dist/commands/revert-command.d.ts.map +1 -1
  116. package/dist/commands/revision-range.d.ts +2 -0
  117. package/dist/commands/revision-range.d.ts.map +1 -1
  118. package/dist/commands/sequencer-pick.d.ts +102 -1
  119. package/dist/commands/sequencer-pick.d.ts.map +1 -1
  120. package/dist/commands/sequencer-support.d.ts +10 -1
  121. package/dist/commands/sequencer-support.d.ts.map +1 -1
  122. package/dist/commands/shortlog-command.d.ts +109 -0
  123. package/dist/commands/shortlog-command.d.ts.map +1 -0
  124. package/dist/commands/shortlog.d.ts +151 -0
  125. package/dist/commands/shortlog.d.ts.map +1 -0
  126. package/dist/commands/status-command.d.ts +31 -2
  127. package/dist/commands/status-command.d.ts.map +1 -1
  128. package/dist/commands/submodule-commands.d.ts +90 -2
  129. package/dist/commands/submodule-commands.d.ts.map +1 -1
  130. package/dist/commands/submodule-fetch.d.ts +149 -0
  131. package/dist/commands/submodule-fetch.d.ts.map +1 -0
  132. package/dist/commands/submodule-model.d.ts +8 -0
  133. package/dist/commands/submodule-model.d.ts.map +1 -1
  134. package/dist/commands/submodule-unpack.d.ts +120 -0
  135. package/dist/commands/submodule-unpack.d.ts.map +1 -0
  136. package/dist/commands/submodule-update-command.d.ts +8 -0
  137. package/dist/commands/submodule-update-command.d.ts.map +1 -1
  138. package/dist/commands/subtree-shift.d.ts +27 -0
  139. package/dist/commands/subtree-shift.d.ts.map +1 -0
  140. package/dist/commands/switch-command.d.ts +3 -0
  141. package/dist/commands/switch-command.d.ts.map +1 -1
  142. package/dist/commands/tree-restore.d.ts.map +1 -1
  143. package/dist/commands/worktree-overwrite-checks.d.ts +2 -0
  144. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -1
  145. package/dist/{commands-ISM52N0n.js → commands-CNvli5bl.js} +39426 -61169
  146. package/dist/errors/command-errors.d.ts +25 -0
  147. package/dist/errors/command-errors.d.ts.map +1 -1
  148. package/dist/errors/index.js +29 -1
  149. package/dist/fsck-CPeDh9fh.js +5138 -0
  150. package/dist/git-command.d.ts +31 -1
  151. package/dist/git-command.d.ts.map +1 -1
  152. package/dist/git.d.ts +97 -1
  153. package/dist/git.d.ts.map +1 -1
  154. package/dist/guarded-transport-command.d.ts +82 -0
  155. package/dist/guarded-transport-command.d.ts.map +1 -0
  156. package/dist/index.d.ts +1 -0
  157. package/dist/index.d.ts.map +1 -1
  158. package/dist/index.js +6 -5
  159. package/dist/remote-transport-CCmBadm-.js +1606 -0
  160. package/dist/rename/detect-renames.d.ts +20 -0
  161. package/dist/rename/detect-renames.d.ts.map +1 -1
  162. package/dist/rename/diffcore-break.d.ts +51 -0
  163. package/dist/rename/diffcore-break.d.ts.map +1 -0
  164. package/dist/rename/index.d.ts +1 -0
  165. package/dist/rename/index.d.ts.map +1 -1
  166. package/dist/results/blame-format.d.ts +62 -1
  167. package/dist/results/blame-format.d.ts.map +1 -1
  168. package/dist/results/clone-result.d.ts +9 -0
  169. package/dist/results/clone-result.d.ts.map +1 -1
  170. package/dist/results/diff-dirstat.d.ts +36 -0
  171. package/dist/results/diff-dirstat.d.ts.map +1 -0
  172. package/dist/results/diff-entry.d.ts +10 -0
  173. package/dist/results/diff-entry.d.ts.map +1 -1
  174. package/dist/results/diff-formatter.d.ts.map +1 -1
  175. package/dist/results/diff-output.d.ts +18 -0
  176. package/dist/results/diff-output.d.ts.map +1 -1
  177. package/dist/results/fetch-result.d.ts +12 -1
  178. package/dist/results/fetch-result.d.ts.map +1 -1
  179. package/dist/results/index.d.ts +2 -0
  180. package/dist/results/index.d.ts.map +1 -1
  181. package/dist/results/index.js +2 -2
  182. package/dist/results/init-result.d.ts +8 -1
  183. package/dist/results/init-result.d.ts.map +1 -1
  184. package/dist/results/line-range-hunks.d.ts +27 -0
  185. package/dist/results/line-range-hunks.d.ts.map +1 -0
  186. package/dist/results/merge-result.d.ts +8 -1
  187. package/dist/results/merge-result.d.ts.map +1 -1
  188. package/dist/results/pull-result.d.ts +11 -0
  189. package/dist/results/pull-result.d.ts.map +1 -1
  190. package/dist/results/push-result.d.ts +5 -0
  191. package/dist/results/push-result.d.ts.map +1 -1
  192. package/dist/results/status-result.d.ts +1 -1
  193. package/dist/results/status-result.d.ts.map +1 -1
  194. package/dist/results-BDuEgdLU.js +46847 -0
  195. package/dist/transport-command.d.ts +14 -0
  196. package/dist/transport-command.d.ts.map +1 -1
  197. package/package.json +12 -12
  198. package/src/commands/add-command.ts +115 -0
  199. package/src/commands/add-patch/add-patch.ts +8 -0
  200. package/src/commands/add-patch/patch-backend.ts +20 -2
  201. package/src/commands/am/am-command.ts +138 -4
  202. package/src/commands/apply/apply-command.ts +52 -9
  203. package/src/commands/apply/apply-parse.ts +10 -0
  204. package/src/commands/apply/index.ts +8 -1
  205. package/src/commands/blame-command.ts +1450 -51
  206. package/src/commands/blame-ignore.ts +307 -0
  207. package/src/commands/check-mailmap-command.ts +129 -0
  208. package/src/commands/checkout-command.ts +97 -12
  209. package/src/commands/checkout-paths.ts +28 -0
  210. package/src/commands/cherry-command.ts +187 -0
  211. package/src/commands/cherry-pick-command.ts +42 -1
  212. package/src/commands/clean-command.ts +92 -12
  213. package/src/commands/clean-interactive.ts +522 -0
  214. package/src/commands/clone-command.ts +596 -44
  215. package/src/commands/commit-command.ts +180 -47
  216. package/src/commands/describe-command.ts +341 -254
  217. package/src/commands/diff-command.ts +616 -56
  218. package/src/commands/fetch-command.ts +353 -6
  219. package/src/commands/fetch-multiple-command.ts +665 -0
  220. package/src/commands/format-patch-command.ts +189 -77
  221. package/src/commands/git-describe.ts +456 -217
  222. package/src/commands/git-hooks.ts +42 -3
  223. package/src/commands/index.ts +17 -0
  224. package/src/commands/init-command.ts +603 -49
  225. package/src/commands/line-log.ts +931 -0
  226. package/src/commands/log-command.ts +1414 -177
  227. package/src/commands/log-graph.ts +6 -3
  228. package/src/commands/log-output.ts +173 -10
  229. package/src/commands/mailmap.ts +41 -5
  230. package/src/commands/merge-command.ts +274 -16
  231. package/src/commands/merge-drivers.ts +3 -0
  232. package/src/commands/merge-strategy-options.ts +224 -0
  233. package/src/commands/merge-support.ts +101 -21
  234. package/src/commands/message-cleanup.ts +1 -1
  235. package/src/commands/name-rev-command.ts +184 -0
  236. package/src/commands/name-rev.ts +700 -109
  237. package/src/commands/octopus-merge.ts +35 -11
  238. package/src/commands/ort-merge.ts +41 -7
  239. package/src/commands/ort-recursive.ts +40 -2
  240. package/src/commands/patch-id.ts +109 -0
  241. package/src/commands/pull-command.ts +718 -224
  242. package/src/commands/push-command.ts +353 -3
  243. package/src/commands/range-diff/index.ts +3 -0
  244. package/src/commands/range-diff/linear-assignment.ts +203 -0
  245. package/src/commands/range-diff/range-diff-command.ts +433 -0
  246. package/src/commands/range-diff/range-diff.ts +617 -0
  247. package/src/commands/read-tree-command.ts +74 -3
  248. package/src/commands/rebase-command.ts +141 -65
  249. package/src/commands/remerge-diff.ts +241 -0
  250. package/src/commands/remote-command.ts +98 -10
  251. package/src/commands/remote-show-command.ts +836 -0
  252. package/src/commands/reset-command.ts +78 -3
  253. package/src/commands/restore-command.ts +15 -0
  254. package/src/commands/rev-list-command.ts +187 -11
  255. package/src/commands/revert-command.ts +41 -1
  256. package/src/commands/revision-range.ts +3 -1
  257. package/src/commands/sequencer-pick.ts +323 -29
  258. package/src/commands/sequencer-support.ts +164 -2
  259. package/src/commands/shortlog-command.ts +354 -0
  260. package/src/commands/shortlog.ts +361 -0
  261. package/src/commands/show-command.ts +2 -1
  262. package/src/commands/status-command.ts +115 -25
  263. package/src/commands/status-format.ts +1 -1
  264. package/src/commands/submodule-commands.ts +321 -3
  265. package/src/commands/submodule-fetch.ts +789 -0
  266. package/src/commands/submodule-model.ts +9 -1
  267. package/src/commands/submodule-unpack.ts +265 -0
  268. package/src/commands/submodule-update-command.ts +39 -5
  269. package/src/commands/subtree-shift.ts +215 -0
  270. package/src/commands/switch-command.ts +9 -0
  271. package/src/commands/tree-restore.ts +6 -1
  272. package/src/commands/worktree-overwrite-checks.ts +5 -0
  273. package/src/errors/command-errors.ts +35 -0
  274. package/src/git-command.ts +87 -1
  275. package/src/git.ts +146 -0
  276. package/src/guarded-transport-command.ts +171 -0
  277. package/src/index.ts +1 -0
  278. package/src/rename/detect-renames.ts +42 -8
  279. package/src/rename/diffcore-break.ts +166 -0
  280. package/src/rename/index.ts +1 -0
  281. package/src/results/blame-format.ts +268 -43
  282. package/src/results/clone-result.ts +6 -0
  283. package/src/results/diff-dirstat.ts +117 -0
  284. package/src/results/diff-entry.ts +12 -0
  285. package/src/results/diff-formatter.ts +1 -0
  286. package/src/results/diff-output.ts +127 -2
  287. package/src/results/fetch-result.ts +12 -1
  288. package/src/results/index.ts +2 -0
  289. package/src/results/init-result.ts +10 -1
  290. package/src/results/line-range-hunks.ts +126 -0
  291. package/src/results/merge-result.ts +9 -0
  292. package/src/results/pull-result.ts +7 -0
  293. package/src/results/push-result.ts +5 -0
  294. package/src/results/status-result.ts +2 -2
  295. package/src/transport-command.ts +34 -3
  296. package/dist/fsck-DLRpbwTj.js +0 -13405
  297. package/dist/results-TB2IJ64h.js +0 -4700
@@ -0,0 +1,836 @@
1
+ import { isSymbolicRef, isValidRefName } from "@statewalker/vcs-core";
2
+ import {
3
+ expandFromDestination,
4
+ expandFromSource,
5
+ lsRefs,
6
+ type MatchedPushRef,
7
+ matchDestination,
8
+ matchPushRefs,
9
+ matchSource,
10
+ PushRefspecError,
11
+ parseRefSpec,
12
+ type RefSpec,
13
+ type RemoteRef as TransportRemoteRef,
14
+ } from "@statewalker/vcs-transport";
15
+ import { parseGitBool } from "@statewalker/vcs-utils";
16
+
17
+ import { GitApiError, MissingArgumentError } from "../errors/index.js";
18
+ import { GuardedTransportCommand } from "../guarded-transport-command.js";
19
+ import { deleteRefs, RemoteConfigStore } from "../remote-config/index.js";
20
+ import { RemoteListCommand } from "./remote-command.js";
21
+ import { withRemoteUploadPack } from "./remote-transport.js";
22
+
23
+ /** What `git remote show` says of one ref a push would update (builtin/remote.c `push_info`). */
24
+ export interface RemotePushInfo {
25
+ /** The local ref, short (`main`), `(delete)` for a deleting refspec, `(matching)` */
26
+ source: string;
27
+ /** The remote ref, short (`main`), or `(matching)` */
28
+ destination: string;
29
+ /** Whether the refspec forces the update (`+`) */
30
+ forced: boolean;
31
+ /**
32
+ * What the push would do (with the remote queried): `create`, `delete`, `up to date`,
33
+ * `fast-forwardable`, `local out of date`; undefined when the remote was not queried
34
+ */
35
+ status?: "create" | "delete" | "up to date" | "fast-forwardable" | "local out of date";
36
+ }
37
+
38
+ /** A local branch that `git pull` merges from the remote (builtin/remote.c `branch_info`). */
39
+ export interface RemotePullInfo {
40
+ branch: string;
41
+ /** The remote branches it merges, short names (`branch.<name>.merge`) */
42
+ merges: string[];
43
+ /** `branch.<name>.rebase`: none, `true`, `merges` or `interactive` */
44
+ rebase?: "true" | "merges" | "interactive";
45
+ }
46
+
47
+ /** What `git remote show <name>` knows of a remote (builtin/remote.c `ref_states`). */
48
+ export interface RemoteShowInfo {
49
+ name: string;
50
+ fetchUrl: string;
51
+ pushUrls: string[];
52
+ /** Whether the remote was asked for its refs (no `-n`) */
53
+ queried: boolean;
54
+ /**
55
+ * The remote's HEAD branch: one name, several when HEAD's commit is at several branches
56
+ * and the remote names none, empty when unknown; undefined when not queried
57
+ */
58
+ heads?: string[];
59
+ /** The remote's refs the fetch refspecs take that have no tracking ref yet (short names) */
60
+ newRefs: string[];
61
+ /** The remote's refs the fetch refspecs take whose tracking refs exist (short names) */
62
+ tracked: string[];
63
+ /** The remote's refs a negative refspec excludes */
64
+ skipped: string[];
65
+ /** The tracking refs whose remote ref is gone (outside `refs/heads/`: full names) */
66
+ stale: string[];
67
+ /** The local branches `git pull` merges from this remote */
68
+ pull: RemotePullInfo[];
69
+ /** Whether `remote.<name>.mirror` makes `git push` mirror every ref */
70
+ mirror: boolean;
71
+ /** What `git push` does, sorted as git prints it */
72
+ push: RemotePushInfo[];
73
+ }
74
+
75
+ /** One remote of {@link RemotePruneCommand}: what was (or would be) pruned. */
76
+ export interface RemotePruneResult {
77
+ name: string;
78
+ url: string;
79
+ /** The tracking refs pruned, full names, in git's order */
80
+ pruned: string[];
81
+ }
82
+
83
+ /**
84
+ * The commands that read a remote's refs as builtin/remote.c's `get_remote_ref_states`:
85
+ * `git remote show` and `git remote prune`.
86
+ */
87
+ abstract class RemoteStatesCommand<T> extends GuardedTransportCommand<T> {
88
+ /** git's command reads no core settings: an unparsable `core.whitespace` does not stop it */
89
+ protected override readsCoreConfig(): boolean {
90
+ return false;
91
+ }
92
+
93
+ protected messages: string[] = [];
94
+
95
+ /**
96
+ * What git prints on stderr besides the output: legacy-remote warnings (2.5x), `more than
97
+ * one branch.<name>.remote`, `invalid branch.<name>.merge`. Empty before the call.
98
+ */
99
+ getMessages(): string[] {
100
+ return [...this.messages];
101
+ }
102
+
103
+ /**
104
+ * Reads the legacy remotes of `names` (git's remote_get) and decides who gets the static
105
+ * credentials and headers from the URLs of every remote this call asks (see
106
+ * `GuardedTransportCommand`), before the first connection.
107
+ */
108
+ protected async prepareRemotes(names: readonly string[]): Promise<void> {
109
+ for (const name of names) this.messages.push(...(await this.loadLegacyRemote(name)));
110
+ const store = RemoteConfigStore.from(this.workingCopy);
111
+ const head = await this.refsStore.get("HEAD");
112
+ const branch =
113
+ head && isSymbolicRef(head) && head.target.startsWith("refs/heads/")
114
+ ? head.target.slice("refs/heads/".length)
115
+ : undefined;
116
+ this.resolveAuth(
117
+ names.map((name) => this.urlsOf(store, name).fetch),
118
+ store.urlFor(store.remoteForBranch(branch)),
119
+ );
120
+ }
121
+
122
+ /** The remote as `remote_get` gives it: its first URL and its push URLs. */
123
+ protected urlsOf(store: RemoteConfigStore, name: string): { fetch: string; push: string[] } {
124
+ const fetch = store.remoteUrlOf(name);
125
+ const push = store.isConfigured(name) ? store.remotePushUrls(name) : [];
126
+ return { fetch, push: push.length > 0 ? push : [store.remoteUrlOf(name, { push: true })] };
127
+ }
128
+
129
+ /** Every ref the remote advertises (transport_get_remote_refs without prefixes). */
130
+ protected async remoteRefs(name: string, url: string): Promise<readonly TransportRemoteRef[]> {
131
+ const program = this.remoteProgram(name, "uploadpack");
132
+ return withRemoteUploadPack(
133
+ await this.prepareRemote(url),
134
+ { ...this.remoteSessionOptions(), ...(program !== undefined ? { program } : {}) },
135
+ async (connection) =>
136
+ connection.version === 2 ? lsRefs(connection, []) : (connection.advertisedRefs ?? []),
137
+ );
138
+ }
139
+
140
+ /**
141
+ * git's get_ref_states: the remote refs the fetch refspecs map (new, tracked, or skipped
142
+ * by a negative refspec) and the tracking refs whose remote ref is gone (get_stale_heads).
143
+ */
144
+ protected async refStates(
145
+ specs: RefSpec[],
146
+ remoteRefs: readonly TransportRemoteRef[],
147
+ ): Promise<{
148
+ newRefs: string[];
149
+ tracked: string[];
150
+ skipped: string[];
151
+ /** The stale tracking refs: `short` as git shows them, `ref` in full; by `short` */
152
+ stale: { short: string; ref: string }[];
153
+ }> {
154
+ const fetchMap: { name: string; peer?: string }[] = [];
155
+ for (const spec of specs) {
156
+ if (spec.negative) continue;
157
+ if (spec.wildcard) {
158
+ // get_expanded_map: a local symbolic ref is never updated
159
+ for (const ref of remoteRefs) {
160
+ if (ref.name.includes("^") || !spec.source || !matchSource(spec, ref.name)) continue;
161
+ const peer = spec.destination
162
+ ? (expandFromSource(spec, ref.name).destination ?? undefined)
163
+ : undefined;
164
+ if (peer !== undefined) {
165
+ const local = await this.refsStore.get(peer);
166
+ if (local && isSymbolicRef(local)) continue;
167
+ }
168
+ if (peer !== undefined && !funnyRef(peer)) fetchMap.push({ name: ref.name, peer });
169
+ else if (peer === undefined) fetchMap.push({ name: ref.name });
170
+ }
171
+ } else {
172
+ const wanted = spec.source ? spec.source : "HEAD";
173
+ const ref = findRefByNameAbbrev(remoteRefs, wanted);
174
+ if (!ref) continue;
175
+ const peer = localRefName(spec.destination);
176
+ if (peer !== undefined && funnyRef(peer)) continue;
177
+ fetchMap.push({ name: ref.name, ...(peer !== undefined ? { peer } : {}) });
178
+ }
179
+ }
180
+ const negative = specs.filter((s) => s.negative && s.source);
181
+ const newRefs = new Set<string>();
182
+ const tracked = new Set<string>();
183
+ const skipped = new Set<string>();
184
+ for (const ref of fetchMap) {
185
+ if (negative.some((n) => matchSource(n, ref.name))) skipped.add(abbrevBranch(ref.name));
186
+ else if (!ref.peer || !(await this.refExists(ref.peer))) newRefs.add(abbrevBranch(ref.name));
187
+ else tracked.add(abbrevBranch(ref.name));
188
+ }
189
+ const names = new Set(fetchMap.map((r) => r.name));
190
+ const stale: string[] = [];
191
+ for await (const ref of this.refsStore.list("refs/")) {
192
+ const sources = trackingSources(specs, ref.name);
193
+ if (!sources || sources.length === 0 || isSymbolicRef(ref)) continue;
194
+ if (!sources.some((s) => names.has(s))) stale.push(ref.name);
195
+ }
196
+ return {
197
+ newRefs: sortBytes([...newRefs]),
198
+ tracked: sortBytes([...tracked]),
199
+ skipped: sortBytes([...skipped]),
200
+ stale: stale
201
+ .map((ref) => ({ short: abbrevBranch(ref), ref }))
202
+ .sort((a, b) => compareBytes(a.short, b.short)),
203
+ };
204
+ }
205
+
206
+ /** git's refs_ref_exists: the ref resolves to an object. */
207
+ private async refExists(name: string): Promise<boolean> {
208
+ return !!(await this.refsStore.resolve(name))?.objectId;
209
+ }
210
+
211
+ /**
212
+ * The symbolic refs whose target is one of `names` (refs_warn_dangling_symrefs), sorted:
213
+ * `[name, target]`.
214
+ */
215
+ protected async danglingSymrefs(names: Set<string>): Promise<[string, string][]> {
216
+ const found: [string, string][] = [];
217
+ for await (const ref of this.refsStore.list("refs/")) {
218
+ if (!isSymbolicRef(ref)) continue;
219
+ let target = ref.target;
220
+ for (let i = 0; i < 5; i++) {
221
+ const next = await this.refsStore.get(target);
222
+ if (!next || !isSymbolicRef(next)) break;
223
+ target = next.target;
224
+ }
225
+ if (names.has(target)) found.push([ref.name, target]);
226
+ }
227
+ return found.sort((a, b) => compareBytes(a[0], b[0]));
228
+ }
229
+ }
230
+
231
+ /**
232
+ * What git knows of a remote: `git remote show [-n] <name>...`.
233
+ *
234
+ * As builtin/remote.c `show`: the remote's URLs; unless {@link setNoQuery} (`-n`), the
235
+ * remote is asked for its refs through the command's transports (as `git fetch` reaches it),
236
+ * which gives its HEAD branch (the branch HEAD's symref names, else every branch at HEAD's
237
+ * commit), the state of each branch the fetch refspecs take (`tracked`, `new (next fetch will
238
+ * store in remotes/<name>)`, `skipped` by a negative refspec, and the tracking refs whose
239
+ * branch is gone, `stale`) and what `git push` would do to each remote ref (`create`, `up to
240
+ * date`, `fast-forwardable`, `local out of date`, `delete`); with `-n` nothing is asked and
241
+ * the tracking refs are listed from the refspecs alone. The local branches `git pull` merges
242
+ * from the remote (`branch.<name>.remote`, `.merge`, `.rebase`) are listed either way. Without
243
+ * a remote name it is `git remote` ({@link RemoteListCommand}).
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * const text = await git.remoteShow().setRemoteNames("origin").callText();
248
+ * // "* remote origin\n Fetch URL: ...\n HEAD branch: main\n Remote branches:\n ..."
249
+ * ```
250
+ */
251
+ export class RemoteShowCommand extends RemoteStatesCommand<RemoteShowInfo[]> {
252
+ private names: string[] = [];
253
+ private noQuery = false;
254
+
255
+ /** The remotes to show, in order. */
256
+ setRemoteNames(...names: string[]): this {
257
+ this.checkCallable();
258
+ this.names = [...names];
259
+ return this;
260
+ }
261
+
262
+ /** Do not ask the remotes for their refs (`-n`). */
263
+ setNoQuery(noQuery: boolean): this {
264
+ this.checkCallable();
265
+ this.noQuery = noQuery;
266
+ return this;
267
+ }
268
+
269
+ /**
270
+ * @returns what git knows of each remote
271
+ * @throws the transport's error when a remote cannot be reached (git dies, exit 128)
272
+ */
273
+ async call(): Promise<RemoteShowInfo[]> {
274
+ this.checkCallable();
275
+ this.setCallable(false);
276
+ const infos: RemoteShowInfo[] = [];
277
+ if (!this.noQuery) await this.prepareRemotes(this.names);
278
+ else for (const name of this.names) this.messages.push(...(await this.loadLegacyRemote(name)));
279
+ for (const name of this.names) infos.push(await this.collect(name));
280
+ return infos;
281
+ }
282
+
283
+ /**
284
+ * What `git remote show` prints on stdout: per remote, `* remote <name>`, ` Fetch URL:`,
285
+ * ` Push URL:` lines, ` HEAD branch:`, ` Remote branches:` with each branch's state,
286
+ * ` Local branches configured for 'git pull':` and ` Local refs configured for 'git
287
+ * push':`, columns as wide as git makes them. Without remote names, `git remote`'s list.
288
+ *
289
+ * @throws the transport's error when a remote cannot be reached (git dies, exit 128); the
290
+ * text of the remotes shown before it is on the error as `stdout`
291
+ */
292
+ async callText(): Promise<string> {
293
+ this.checkCallable();
294
+ if (this.names.length === 0) {
295
+ this.setCallable(false);
296
+ return new RemoteListCommand(this._workingCopy).callText();
297
+ }
298
+ this.setCallable(false);
299
+ if (!this.noQuery) await this.prepareRemotes(this.names);
300
+ else for (const name of this.names) this.messages.push(...(await this.loadLegacyRemote(name)));
301
+ let out = "";
302
+ for (const name of this.names) {
303
+ let info: RemoteShowInfo;
304
+ try {
305
+ info = await this.collect(name);
306
+ } catch (error) {
307
+ if (error instanceof Error) Object.assign(error, { stdout: out });
308
+ throw error;
309
+ }
310
+ out += formatShow(info, this.noQuery);
311
+ }
312
+ return out;
313
+ }
314
+
315
+ private async collect(name: string): Promise<RemoteShowInfo> {
316
+ const store = RemoteConfigStore.from(this.workingCopy);
317
+ const specs = store.configuredFetchRefspecs(name).map((s) => parseRefSpec(s));
318
+ const urls = this.urlsOf(store, name);
319
+ const mirror = parseGitBool(store.value(`remote.${name}.mirror`)) === true;
320
+ const pushSpecs = store.pushRefspecs(name);
321
+ const info: RemoteShowInfo = {
322
+ name,
323
+ fetchUrl: urls.fetch,
324
+ pushUrls: urls.push,
325
+ queried: !this.noQuery,
326
+ newRefs: [],
327
+ tracked: [],
328
+ skipped: [],
329
+ stale: [],
330
+ pull: [],
331
+ mirror,
332
+ push: [],
333
+ };
334
+ // read_branches comes before the query
335
+ const branches = readBranches(store, this.messages);
336
+ if (!this.noQuery) {
337
+ const refs = await this.remoteRefs(name, urls.fetch);
338
+ const states = await this.refStates(specs, refs);
339
+ info.newRefs = states.newRefs;
340
+ info.tracked = states.tracked;
341
+ info.skipped = states.skipped;
342
+ info.stale = states.stale.map((s) => s.short);
343
+ info.heads = headNames(refs);
344
+ if (!mirror) info.push = await this.pushStates(pushSpecs, refs);
345
+ } else {
346
+ // append_ref_to_tracked_list: every ref the fetch refspecs map back to a remote ref
347
+ const tracked: string[] = [];
348
+ for await (const ref of this.refsStore.list("refs/")) {
349
+ if (isSymbolicRef(ref)) continue;
350
+ const source = trackingSources(specs, ref.name)?.[0];
351
+ if (source !== undefined) tracked.push(abbrevBranch(source));
352
+ }
353
+ info.tracked = sortBytes(tracked);
354
+ if (!mirror) info.push = pushNoQuery(pushSpecs);
355
+ }
356
+ for (const branch of branches) {
357
+ if (branch.merges.length === 0 || branch.remote !== name) continue;
358
+ info.pull.push({
359
+ branch: branch.name,
360
+ merges: branch.merges,
361
+ ...(branch.rebase ? { rebase: branch.rebase } : {}),
362
+ });
363
+ }
364
+ info.push.sort(
365
+ (a, b) => compareBytes(a.source, b.source) || compareBytes(a.destination, b.destination),
366
+ );
367
+ // show_local_info_item: a rebase onto several branches is refused
368
+ for (const pull of info.pull) {
369
+ if (pull.rebase && pull.merges.length > 1) {
370
+ this.messages.push(
371
+ `error: invalid branch.${pull.branch}.merge; cannot rebase onto > 1 branch`,
372
+ );
373
+ }
374
+ }
375
+ return info;
376
+ }
377
+
378
+ /** get_push_ref_states: match_push_refs over the local refs and the remote's. */
379
+ private async pushStates(
380
+ pushSpecs: string[],
381
+ remoteRefs: readonly TransportRemoteRef[],
382
+ ): Promise<RemotePushInfo[]> {
383
+ const local = new Map<string, string>();
384
+ for await (const ref of this.refsStore.list("refs/")) {
385
+ if (!isValidRefName(ref.name)) continue;
386
+ const id = isSymbolicRef(ref)
387
+ ? (await this.refsStore.resolve(ref.name))?.objectId
388
+ : ref.objectId;
389
+ if (id) local.set(ref.name, id);
390
+ }
391
+ const head = await this.refsStore.get("HEAD");
392
+ const headId = (await this.refsStore.resolve("HEAD"))?.objectId;
393
+ const localState = {
394
+ refs: local,
395
+ head: {
396
+ ...(head && isSymbolicRef(head) ? { target: head.target } : {}),
397
+ ...(headId ? { oid: headId } : {}),
398
+ },
399
+ hasObject: async (id: string) => this.objectExists(id),
400
+ };
401
+ const match = (specs: string[]) =>
402
+ matchPushRefs(specs, localState, remoteRefs, { objectFormat: this.objectFormat });
403
+ // match_explicit_refs reports a refspec that matches nothing (or too much) and matches
404
+ // the others: such refspecs are left out here
405
+ const specs = pushSpecs.length > 0 ? pushSpecs : [":"];
406
+ const usable: string[] = [];
407
+ for (const spec of specs) {
408
+ try {
409
+ await match([spec]);
410
+ usable.push(spec);
411
+ } catch (error) {
412
+ if (!(error instanceof PushRefspecError)) throw error;
413
+ this.messages.push(`error: ${error.message}`);
414
+ }
415
+ }
416
+ if (usable.length === 0) return [];
417
+ let matched: MatchedPushRef[];
418
+ try {
419
+ matched = await match(usable);
420
+ } catch (error) {
421
+ if (error instanceof PushRefspecError) return [];
422
+ throw error;
423
+ }
424
+ const nullId = this.objectFormat.nullId;
425
+ const infos: RemotePushInfo[] = [];
426
+ for (const ref of matched) {
427
+ const deleting = ref.newOid === nullId;
428
+ const source = deleting ? "(delete)" : abbrevBranch(ref.localRef ?? ref.source ?? "");
429
+ let status: RemotePushInfo["status"];
430
+ if (deleting) status = "delete";
431
+ else if (ref.oldOid === ref.newOid) status = "up to date";
432
+ else if (ref.oldOid === nullId) status = "create";
433
+ else if (
434
+ (await this.objectExists(ref.oldOid)) &&
435
+ (await this.isNewer(ref.newOid, ref.oldOid))
436
+ )
437
+ status = "fast-forwardable";
438
+ else status = "local out of date";
439
+ infos.push({ source, destination: abbrevBranch(ref.remoteRef), forced: ref.force, status });
440
+ }
441
+ return infos;
442
+ }
443
+
444
+ /** odb_has_object; a store without its object kernel asks the typed stores. */
445
+ private async objectExists(id: string): Promise<boolean> {
446
+ const objects = this.workingCopy.history.objects;
447
+ if (objects) return objects.has(id).catch(() => false);
448
+ for (const s of [this.commits, this.trees, this.blobs, this.tagsStore]) {
449
+ if (s && (await s.has(id).catch(() => false))) return true;
450
+ }
451
+ return false;
452
+ }
453
+
454
+ /** git's ref_newer: both peel to commits, and `old` is an ancestor of `next`. */
455
+ private async isNewer(next: string, old: string): Promise<boolean> {
456
+ const a = await this.peelToCommit(next);
457
+ const b = await this.peelToCommit(old);
458
+ if (!a || !b) return false;
459
+ return this.commits.isAncestor(b, a);
460
+ }
461
+
462
+ private async peelToCommit(id: string): Promise<string | undefined> {
463
+ const tags = this.tagsStore;
464
+ let current: string | undefined = id;
465
+ for (let i = 0; current && i < 16; i++) {
466
+ if (await this.commits.has(current)) return current;
467
+ if (!tags || !(await tags.has(current))) return undefined;
468
+ current = await tags.getTarget(current);
469
+ }
470
+ return undefined;
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Delete the tracking refs whose remote branch is gone: `git remote prune [--dry-run]
476
+ * <name>...`.
477
+ *
478
+ * As builtin/remote.c `prune_remote`: the remote is asked for its refs through the command's
479
+ * transports, and every ref its fetch refspecs map from a remote ref the remote no longer has
480
+ * (git's get_stale_heads: not a symbolic ref, not excluded by a negative refspec) is deleted
481
+ * with its reflog in one batch (`remote: prune`). git's output is {@link getOutput}:
482
+ * `Pruning <name>`, `URL: <url>`, ` * [pruned] <name>/<branch>` (` * [would prune] ...` for
483
+ * a dry run), then the symbolic refs left dangling; nothing for a remote with nothing stale.
484
+ *
485
+ * @example
486
+ * ```typescript
487
+ * await git.remotePrune().setRemoteNames("origin").call();
488
+ * const preview = git.remotePrune().setRemoteNames("origin").setDryRun(true);
489
+ * await preview.call();
490
+ * console.log(preview.getOutput());
491
+ * ```
492
+ */
493
+ export class RemotePruneCommand extends RemoteStatesCommand<RemotePruneResult[]> {
494
+ private names: string[] = [];
495
+ private dryRun = false;
496
+ private output = "";
497
+
498
+ /** The remotes to prune, in order. */
499
+ setRemoteNames(...names: string[]): this {
500
+ this.checkCallable();
501
+ this.names = [...names];
502
+ return this;
503
+ }
504
+
505
+ /** Report what would be pruned, delete nothing (`--dry-run`). */
506
+ setDryRun(dryRun: boolean): this {
507
+ this.checkCallable();
508
+ this.dryRun = dryRun;
509
+ return this;
510
+ }
511
+
512
+ /** What git prints on stdout. Empty before {@link call}. */
513
+ getOutput(): string {
514
+ return this.output;
515
+ }
516
+
517
+ /**
518
+ * @returns each remote's pruned refs (empty for one with nothing stale)
519
+ * @throws MissingArgumentError (git: its usage, exit 129) without a remote
520
+ * @throws the transport's error when a remote cannot be reached (git dies, exit 128); what
521
+ * was printed before it is in {@link getOutput}
522
+ * @throws GitApiError (exit 1) when the ref store refused the deletion
523
+ */
524
+ async call(): Promise<RemotePruneResult[]> {
525
+ this.checkCallable();
526
+ this.setCallable(false);
527
+ if (this.names.length === 0) {
528
+ throw new MissingArgumentError("remoteNames", "usage: git remote prune [<options>] <name>");
529
+ }
530
+ const results: RemotePruneResult[] = [];
531
+ let failure: string | undefined;
532
+ await this.prepareRemotes(this.names);
533
+ for (const name of this.names) {
534
+ const store = RemoteConfigStore.from(this.workingCopy);
535
+ const specs = store.configuredFetchRefspecs(name).map((s) => parseRefSpec(s));
536
+ const url = this.urlsOf(store, name).fetch;
537
+ const states = await this.refStates(specs, await this.remoteRefs(name, url));
538
+ const stale = states.stale.map((s) => s.ref);
539
+ results.push({ name, url, pruned: stale });
540
+ if (stale.length === 0) continue;
541
+ this.output += `Pruning ${name}\nURL: ${url}\n`;
542
+ const toPrune = sortBytes([...stale]);
543
+ if (!this.dryRun) {
544
+ try {
545
+ await deleteRefs(this.refsStore, toPrune, "remote: prune", {
546
+ legacy: this.hooks.compatibility === "2.43",
547
+ });
548
+ } catch (error) {
549
+ failure = error instanceof Error ? error.message : String(error);
550
+ }
551
+ }
552
+ for (const ref of stale) {
553
+ const short = ref.startsWith("refs/remotes/") ? ref.slice("refs/remotes/".length) : ref;
554
+ this.output += ` * [${this.dryRun ? "would prune" : "pruned"}] ${short}\n`;
555
+ }
556
+ // git 2.43 names the symbolic ref alone
557
+ const legacy = this.hooks.compatibility === "2.43";
558
+ for (const [symref, target] of await this.danglingSymrefs(new Set(toPrune))) {
559
+ if (legacy) {
560
+ this.output += ` ${symref} ${this.dryRun ? "will become" : "has become"} dangling!\n`;
561
+ } else {
562
+ this.output += this.dryRun
563
+ ? ` ${symref} will become dangling after ${target} is deleted\n`
564
+ : ` ${symref} has become dangling after ${target} was deleted\n`;
565
+ }
566
+ }
567
+ }
568
+ if (failure !== undefined) throw new GitApiError(failure, { exitCode: 1 });
569
+ return results;
570
+ }
571
+ }
572
+
573
+ /** The text of one remote of `git remote show` (builtin/remote.c `show`). */
574
+ function formatShow(info: RemoteShowInfo, noQuery: boolean): string {
575
+ const lines: string[] = [`* remote ${info.name}`, ` Fetch URL: ${info.fetchUrl}`];
576
+ for (const url of info.pushUrls) lines.push(` Push URL: ${url}`);
577
+ if (info.pushUrls.length === 0) lines.push(" Push URL: (no URL)");
578
+ const heads = info.heads ?? [];
579
+ if (noQuery) lines.push(" HEAD branch: (not queried)");
580
+ else if (heads.length === 0) lines.push(" HEAD branch: (unknown)");
581
+ else if (heads.length === 1) lines.push(` HEAD branch: ${heads[0]}`);
582
+ else {
583
+ lines.push(" HEAD branch (remote HEAD is ambiguous, may be one of the following):");
584
+ for (const head of heads) lines.push(` ${head}`);
585
+ }
586
+
587
+ // remote branch info: a sorted set of every name
588
+ const all = sortBytes([
589
+ ...new Set([...info.newRefs, ...info.skipped, ...info.tracked, ...info.stale]),
590
+ ]);
591
+ const width = Math.max(0, ...all.map((n) => n.length));
592
+ if (all.length > 0) {
593
+ lines.push(
594
+ ` Remote branch${all.length === 1 ? "" : "es"}:${noQuery ? " (status not queried)" : ""}`,
595
+ );
596
+ }
597
+ for (const name of all) {
598
+ if (!info.queried) {
599
+ lines.push(` ${name}`);
600
+ continue;
601
+ }
602
+ let state: string;
603
+ if (info.newRefs.includes(name)) state = ` new (next fetch will store in remotes/${info.name})`;
604
+ else if (info.tracked.includes(name)) state = " tracked";
605
+ else if (info.skipped.includes(name)) state = " skipped";
606
+ else if (info.stale.includes(name)) state = " stale (use 'git remote prune' to remove)";
607
+ else state = " ???";
608
+ lines.push(` ${name.padEnd(width)}${state}`);
609
+ }
610
+
611
+ // git pull info
612
+ const pullWidth = Math.max(0, ...info.pull.map((p) => p.branch.length));
613
+ const anyRebase = info.pull.some((p) => p.rebase);
614
+ if (info.pull.length > 0) {
615
+ lines.push(
616
+ info.pull.length === 1
617
+ ? " Local branch configured for 'git pull':"
618
+ : " Local branches configured for 'git pull':",
619
+ );
620
+ }
621
+ for (const pull of info.pull) {
622
+ if (pull.rebase && pull.merges.length > 1) continue;
623
+ const head = ` ${pull.branch.padEnd(pullWidth)} `;
624
+ let width = pullWidth + 4;
625
+ if (pull.rebase) {
626
+ const what =
627
+ pull.rebase === "interactive"
628
+ ? "rebases interactively onto remote"
629
+ : pull.rebase === "merges"
630
+ ? "rebases interactively (with merges) onto remote"
631
+ : "rebases onto remote";
632
+ lines.push(`${head}${what} ${pull.merges[0]}`);
633
+ continue;
634
+ }
635
+ if (anyRebase) {
636
+ lines.push(`${head} merges with remote ${pull.merges[0]}`);
637
+ width++;
638
+ } else lines.push(`${head}merges with remote ${pull.merges[0]}`);
639
+ for (const merge of pull.merges.slice(1)) {
640
+ lines.push(`${"".padEnd(width)} and with remote ${merge}`);
641
+ }
642
+ }
643
+
644
+ // git push info
645
+ if (info.mirror) lines.push(" Local refs will be mirrored by 'git push'");
646
+ const width1 = Math.max(0, ...info.push.map((p) => p.source.length));
647
+ const width2 = Math.max(0, ...info.push.map((p) => p.destination.length));
648
+ if (info.push.length > 0) {
649
+ lines.push(
650
+ ` Local ref${info.push.length === 1 ? "" : "s"} configured for 'git push'${noQuery ? " (status not queried)" : ""}:`,
651
+ );
652
+ }
653
+ for (const push of info.push) {
654
+ const verb = push.forced ? "forces to" : "pushes to";
655
+ const source = push.status === "delete" ? "(none)" : push.source;
656
+ if (push.status) {
657
+ lines.push(
658
+ ` ${source.padEnd(width1)} ${verb} ${push.destination.padEnd(width2)} (${push.status})`,
659
+ );
660
+ } else lines.push(` ${source.padEnd(width1)} ${verb} ${push.destination}`);
661
+ }
662
+ return `${lines.join("\n")}\n`;
663
+ }
664
+
665
+ /** get_push_ref_states_noquery: the push refspecs as written. */
666
+ function pushNoQuery(pushSpecs: string[]): RemotePushInfo[] {
667
+ if (pushSpecs.length === 0) {
668
+ return [{ source: "(matching)", destination: "(matching)", forced: false }];
669
+ }
670
+ return pushSpecs.map((raw) => {
671
+ let spec = raw;
672
+ const forced = spec.startsWith("+");
673
+ if (forced) spec = spec.slice(1);
674
+ const negative = spec.startsWith("^");
675
+ if (negative) spec = spec.slice(1);
676
+ const colon = spec.indexOf(":");
677
+ const src = colon < 0 ? spec : spec.slice(0, colon);
678
+ const dst = colon < 0 ? undefined : spec.slice(colon + 1);
679
+ // ":" (and "+:") is the matching refspec
680
+ const source = spec === ":" ? "(matching)" : src.length > 0 ? src : "(delete)";
681
+ return { source, destination: dst ? dst : source, forced };
682
+ });
683
+ }
684
+
685
+ /** The branch settings `git remote show` reads (read_branches), sorted by branch name. */
686
+ function readBranches(
687
+ store: RemoteConfigStore,
688
+ messages: string[],
689
+ ): { name: string; remote?: string; merges: string[]; rebase?: RemotePullInfo["rebase"] }[] {
690
+ const byName = new Map<
691
+ string,
692
+ {
693
+ name: string;
694
+ remote?: string;
695
+ merges: string[];
696
+ rebase?: RemotePullInfo["rebase"];
697
+ pushRemote?: string;
698
+ }
699
+ >();
700
+ const entries =
701
+ store.entriesWithPrefix("branch.") ??
702
+ store
703
+ .subsections("branch")
704
+ .flatMap((branch) =>
705
+ ["remote", "merge", "rebase", "pushremote"].flatMap((v) =>
706
+ store
707
+ .values(`branch.${branch}.${v}`)
708
+ .map((value) => ({ key: `branch.${branch}.${v}`, value })),
709
+ ),
710
+ );
711
+ for (const { key, value } of entries) {
712
+ const rest = key.slice("branch.".length);
713
+ const dot = rest.lastIndexOf(".");
714
+ if (dot < 0) continue;
715
+ const name = rest.slice(0, dot);
716
+ const variable = rest.slice(dot + 1).toLowerCase();
717
+ if (!["remote", "merge", "rebase", "pushremote"].includes(variable)) continue;
718
+ let info = byName.get(name);
719
+ if (!info) {
720
+ info = { name, merges: [] };
721
+ byName.set(name, info);
722
+ }
723
+ if (value === undefined) continue;
724
+ if (variable === "remote") {
725
+ if (info.remote !== undefined) messages.push(`warning: more than one ${key}`);
726
+ info.remote = value;
727
+ } else if (variable === "pushremote") {
728
+ if (info.pushRemote !== undefined) messages.push(`warning: more than one ${key}`);
729
+ info.pushRemote = value;
730
+ } else if (variable === "merge") {
731
+ // several branches on one line, separated by spaces
732
+ for (const part of value.split(" ")) info.merges.push(abbrevBranch(part));
733
+ } else {
734
+ const bool = parseGitBool(value);
735
+ if (bool === true) info.rebase = "true";
736
+ else if (bool === false) info.rebase = undefined;
737
+ else if (value === "merges" || value === "m") info.rebase = "merges";
738
+ else if (value === "interactive" || value === "i") info.rebase = "interactive";
739
+ else {
740
+ if (value === "preserve" || value === "p") {
741
+ messages.push(`error: ${value}: 'preserve' superseded by 'merges'`);
742
+ }
743
+ messages.push(`warning: unhandled branch.${name}.rebase=${value}; assuming 'true'`);
744
+ info.rebase = undefined;
745
+ }
746
+ }
747
+ }
748
+ return [...byName.values()].sort((a, b) => compareBytes(a.name, b.name));
749
+ }
750
+
751
+ /**
752
+ * get_head_names: the branch HEAD's symref names, else every branch at HEAD's commit
753
+ * (guess_remote_head with REMOTE_GUESS_HEAD_ALL), short names.
754
+ */
755
+ function headNames(refs: readonly TransportRemoteRef[]): string[] {
756
+ const head = refs.find((r) => r.name === "HEAD");
757
+ if (!head) return [];
758
+ const branches = refs.filter((r) => r.name.startsWith("refs/heads/") && !r.name.includes("^"));
759
+ const matches = head.symref
760
+ ? branches.filter((r) => r.name === head.symref)
761
+ : branches.filter((r) => r.oid !== undefined && r.oid === head.oid);
762
+ return matches.map((r) => abbrevBranch(r.name));
763
+ }
764
+
765
+ /**
766
+ * The remote refs a local ref is the tracking ref of (remote_find_tracking /
767
+ * refspec_find_all_matches over the fetch refspecs); undefined when a negative refspec
768
+ * excludes one of them.
769
+ */
770
+ export function trackingSources(specs: RefSpec[], refName: string): string[] | undefined {
771
+ const sources: string[] = [];
772
+ for (const spec of specs) {
773
+ if (spec.negative || !spec.source || !spec.destination) continue;
774
+ if (spec.wildcard) {
775
+ if (!matchDestination(spec, refName)) continue;
776
+ const source = expandFromDestination(spec, refName).source;
777
+ if (source) sources.push(source);
778
+ } else if (spec.destination === refName) sources.push(spec.source);
779
+ }
780
+ const negative = specs.filter((s) => s.negative && s.source);
781
+ if (sources.some((src) => negative.some((n) => matchSource(n, src)))) return undefined;
782
+ return sources;
783
+ }
784
+
785
+ /** git's find_ref_by_name_abbrev: the ref `name` names by refname_match's rules, best first. */
786
+ function findRefByNameAbbrev(
787
+ refs: readonly TransportRemoteRef[],
788
+ name: string,
789
+ ): TransportRemoteRef | undefined {
790
+ const rules = [
791
+ name,
792
+ `refs/${name}`,
793
+ `refs/tags/${name}`,
794
+ `refs/heads/${name}`,
795
+ `refs/remotes/${name}`,
796
+ `refs/remotes/${name}/HEAD`,
797
+ ];
798
+ let best: TransportRemoteRef | undefined;
799
+ let bestRule = rules.length;
800
+ for (const ref of refs) {
801
+ const rule = rules.indexOf(ref.name);
802
+ if (rule >= 0 && rule < bestRule) {
803
+ best = ref;
804
+ bestRule = rule;
805
+ }
806
+ }
807
+ return best;
808
+ }
809
+
810
+ /** git's get_local_ref: the local ref a refspec's destination names. */
811
+ function localRefName(dst: string | null): string | undefined {
812
+ if (!dst) return undefined;
813
+ if (dst.startsWith("refs/")) return dst;
814
+ if (dst.startsWith("heads/") || dst.startsWith("tags/") || dst.startsWith("remotes/")) {
815
+ return `refs/${dst}`;
816
+ }
817
+ return `refs/heads/${dst}`;
818
+ }
819
+
820
+ /** get_fetch_map's "funny ref": a local ref outside `refs/` or of an invalid name. */
821
+ function funnyRef(name: string): boolean {
822
+ return !name.startsWith("refs/") || !isValidRefName(name);
823
+ }
824
+
825
+ /** git's abbrev_branch: `refs/heads/` dropped. */
826
+ function abbrevBranch(name: string): string {
827
+ return name.startsWith("refs/heads/") ? name.slice("refs/heads/".length) : name;
828
+ }
829
+
830
+ function compareBytes(a: string, b: string): number {
831
+ return a < b ? -1 : a > b ? 1 : 0;
832
+ }
833
+
834
+ function sortBytes(names: string[]): string[] {
835
+ return names.sort(compareBytes);
836
+ }