@statewalker/vcs-commands 0.3.2 → 0.5.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 (133) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts +7 -24
  8. package/dist/commands/checkout-command.d.ts.map +1 -1
  9. package/dist/commands/clean-command.d.ts +34 -4
  10. package/dist/commands/clean-command.d.ts.map +1 -1
  11. package/dist/commands/clone-command.d.ts +61 -21
  12. package/dist/commands/clone-command.d.ts.map +1 -1
  13. package/dist/commands/core-config.d.ts +16 -0
  14. package/dist/commands/core-config.d.ts.map +1 -0
  15. package/dist/commands/fetch-command.d.ts +104 -37
  16. package/dist/commands/fetch-command.d.ts.map +1 -1
  17. package/dist/commands/index.d.ts +1 -0
  18. package/dist/commands/index.d.ts.map +1 -1
  19. package/dist/commands/index.js +2 -2
  20. package/dist/commands/init-command.d.ts.map +1 -1
  21. package/dist/commands/merge-command.d.ts +15 -2
  22. package/dist/commands/merge-command.d.ts.map +1 -1
  23. package/dist/commands/push-command.d.ts +58 -25
  24. package/dist/commands/push-command.d.ts.map +1 -1
  25. package/dist/commands/remote-command.d.ts +115 -6
  26. package/dist/commands/remote-command.d.ts.map +1 -1
  27. package/dist/commands/reset-command.d.ts.map +1 -1
  28. package/dist/commands/stash-apply-command.d.ts +35 -13
  29. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  30. package/dist/commands/stash-create-command.d.ts +59 -25
  31. package/dist/commands/stash-create-command.d.ts.map +1 -1
  32. package/dist/commands/stash-drop-command.d.ts +8 -2
  33. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  34. package/dist/commands/stash-list-command.d.ts +2 -4
  35. package/dist/commands/stash-list-command.d.ts.map +1 -1
  36. package/dist/commands/stash-working-tree.d.ts +72 -0
  37. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  38. package/dist/commands/status-command.d.ts +29 -22
  39. package/dist/commands/status-command.d.ts.map +1 -1
  40. package/dist/commands/tag-command.d.ts.map +1 -1
  41. package/dist/commands/tree-restore.d.ts +52 -5
  42. package/dist/commands/tree-restore.d.ts.map +1 -1
  43. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  44. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  45. package/dist/{commands-COO4tJhv.js → commands-CsLNyvZ1.js} +3370 -1057
  46. package/dist/core-commands/add.command.impl.d.ts +0 -4
  47. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  48. package/dist/core-commands/index.d.ts +1 -3
  49. package/dist/core-commands/index.d.ts.map +1 -1
  50. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  51. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  52. package/dist/errors/checkout-errors.d.ts +13 -0
  53. package/dist/errors/checkout-errors.d.ts.map +1 -1
  54. package/dist/errors/index.js +18 -1
  55. package/dist/git-command.d.ts +10 -1
  56. package/dist/git-command.d.ts.map +1 -1
  57. package/dist/git.d.ts +21 -3
  58. package/dist/git.d.ts.map +1 -1
  59. package/dist/index.js +4 -4
  60. package/dist/remote-config/index.d.ts +1 -0
  61. package/dist/remote-config/index.d.ts.map +1 -1
  62. package/dist/remote-config/remote-config-store.d.ts +22 -0
  63. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  64. package/dist/remote-config/remote-refs.d.ts +37 -0
  65. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  66. package/dist/results/clone-result.d.ts +6 -0
  67. package/dist/results/clone-result.d.ts.map +1 -1
  68. package/dist/results/diff-formatter.d.ts +14 -7
  69. package/dist/results/diff-formatter.d.ts.map +1 -1
  70. package/dist/results/fetch-result.d.ts +16 -1
  71. package/dist/results/fetch-result.d.ts.map +1 -1
  72. package/dist/results/index.js +28 -23
  73. package/dist/results/push-result.d.ts +9 -2
  74. package/dist/results/push-result.d.ts.map +1 -1
  75. package/dist/results/status-result.d.ts +91 -20
  76. package/dist/results/status-result.d.ts.map +1 -1
  77. package/dist/{status-result-BwAyxq6R.js → status-result-BpyUK1Sg.js} +115 -5
  78. package/dist/transport-command.d.ts +12 -0
  79. package/dist/transport-command.d.ts.map +1 -1
  80. package/package.json +14 -12
  81. package/src/commands/add-command.ts +23 -30
  82. package/src/commands/blame-command.ts +41 -0
  83. package/src/commands/branch-command.ts +2 -53
  84. package/src/commands/checkout-command.ts +205 -127
  85. package/src/commands/clean-command.ts +187 -81
  86. package/src/commands/clone-command.ts +334 -137
  87. package/src/commands/core-config.ts +41 -0
  88. package/src/commands/fetch-command.ts +536 -211
  89. package/src/commands/gc-command.ts +1 -1
  90. package/src/commands/index.ts +1 -0
  91. package/src/commands/init-command.ts +108 -11
  92. package/src/commands/merge-command.ts +60 -27
  93. package/src/commands/pack-refs-command.ts +2 -2
  94. package/src/commands/push-command.ts +242 -308
  95. package/src/commands/reflog-command.ts +2 -2
  96. package/src/commands/remote-command.ts +429 -19
  97. package/src/commands/reset-command.ts +18 -5
  98. package/src/commands/stash-apply-command.ts +632 -97
  99. package/src/commands/stash-create-command.ts +142 -62
  100. package/src/commands/stash-drop-command.ts +53 -5
  101. package/src/commands/stash-list-command.ts +10 -4
  102. package/src/commands/stash-working-tree.ts +243 -0
  103. package/src/commands/status-command.ts +197 -91
  104. package/src/commands/tag-command.ts +2 -53
  105. package/src/commands/tree-restore.ts +143 -18
  106. package/src/commands/worktree-overwrite-checks.ts +215 -0
  107. package/src/core-commands/add.command.impl.ts +15 -20
  108. package/src/core-commands/index.ts +1 -8
  109. package/src/core-commands/store-worktree-file.ts +5 -0
  110. package/src/errors/checkout-errors.ts +20 -0
  111. package/src/git-command.ts +42 -1
  112. package/src/git.ts +30 -2
  113. package/src/remote-config/index.ts +1 -0
  114. package/src/remote-config/remote-config-store.ts +95 -8
  115. package/src/remote-config/remote-refs.ts +103 -0
  116. package/src/results/clone-result.ts +6 -0
  117. package/src/results/diff-formatter.ts +31 -38
  118. package/src/results/fetch-result.ts +16 -1
  119. package/src/results/push-result.ts +9 -2
  120. package/src/results/status-result.ts +212 -29
  121. package/src/transport-command.ts +18 -0
  122. package/dist/core-commands/checkout.command.d.ts +0 -103
  123. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  124. package/dist/core-commands/checkout.command.impl.d.ts +0 -114
  125. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  126. package/dist/pack-import/index.d.ts +0 -8
  127. package/dist/pack-import/index.d.ts.map +0 -1
  128. package/dist/pack-import/pack-import.d.ts +0 -11
  129. package/dist/pack-import/pack-import.d.ts.map +0 -1
  130. package/src/core-commands/checkout.command.impl.ts +0 -586
  131. package/src/core-commands/checkout.command.ts +0 -125
  132. package/src/pack-import/index.ts +0 -8
  133. package/src/pack-import/pack-import.ts +0 -24
@@ -1,12 +1,22 @@
1
- import { serializeCommit, serializeTree, type TreeEntry } from "@statewalker/vcs-core";
2
1
  import {
2
+ createRepositoryFacade,
3
+ createTransportRefStore,
4
+ expandFromSource,
5
+ type ForceWithLease,
3
6
  mapRejectReason,
7
+ matchSource,
4
8
  type PushCommandResult,
5
- type PushObject,
9
+ type PushRefUpdate,
10
+ parseRefSpec,
6
11
  push as transportPush,
7
12
  } from "@statewalker/vcs-transport";
8
13
 
9
- import { InvalidRemoteError, NonFastForwardError, PushRejectedException } from "../errors/index.js";
14
+ import {
15
+ InvalidArgumentError,
16
+ InvalidRemoteError,
17
+ NonFastForwardError,
18
+ PushRejectedException,
19
+ } from "../errors/index.js";
10
20
  import { RemoteConfigStore } from "../remote-config/index.js";
11
21
  import { type PushResult, PushStatus, type RemoteRefUpdate } from "../results/push-result.js";
12
22
  import { TransportCommand } from "../transport-command.js";
@@ -15,16 +25,11 @@ import { TransportCommand } from "../transport-command.js";
15
25
  const ZERO_OBJECT_ID = "0".repeat(40);
16
26
 
17
27
  /**
18
- * How the transport's rejection reasons land on the statuses this package
19
- * reports.
20
- *
21
- * The two vocabularies are not the same: the transport tells seven kinds of
22
- * rejection apart, while PushStatus — following JGit's RemoteRefUpdate — keeps
23
- * only the non-fast-forward case separate, because that is the one callers act
24
- * on (callOrThrow raises NonFastForwardError for it). Everything else is a
25
- * rejection whose detail lives in the server's message, so it collapses to
26
- * REJECTED_OTHER. Spelled out per reason rather than defaulted, so that a new
27
- * transport reason is a compile error here instead of a silent REJECTED_OTHER.
28
+ * How a server's rejection reason (`ng <ref> <reason>`) lands on the statuses this package
29
+ * reports. PushStatus, following JGit's RemoteRefUpdate, keeps only the non-fast-forward case
30
+ * separate (callOrThrow raises NonFastForwardError for it); every other refusal is
31
+ * REJECTED_OTHER with the server's message. Spelled out per reason so that a new transport
32
+ * reason is a compile error here.
28
33
  */
29
34
  const REJECT_REASON_STATUS: Record<PushCommandResult, PushStatus> = {
30
35
  NOT_ATTEMPTED: PushStatus.NOT_ATTEMPTED,
@@ -40,28 +45,28 @@ const REJECT_REASON_STATUS: Record<PushCommandResult, PushStatus> = {
40
45
  };
41
46
 
42
47
  /**
43
- * Classify a server's rejection message.
44
- *
45
- * Reuses the transport's `mapRejectReason` so both sides read the same wire
46
- * text the same way; a message the transport cannot place — or none at all —
47
- * ends up as REJECTED_OTHER.
48
+ * The status of a transport update. git's local refusals map as JGit's: "fetch first" (the
49
+ * remote has a commit we lack) and "non-fast-forward" are both REJECTED_NONFASTFORWARD, a
50
+ * stale lease is REJECTED_REMOTE_CHANGED, a remote ref the server did not report is FAILED.
48
51
  */
49
- function classifyRejection(message: string | undefined): PushStatus {
50
- return REJECT_REASON_STATUS[mapRejectReason(message ?? "")];
51
- }
52
-
53
- /**
54
- * Split a refspec into its source and destination ref names.
55
- *
56
- * Mirrors the parsing the transport performs so that the destination keys we
57
- * derive here line up exactly with the ones it reports back:
58
- * an optional leading `+` (force) is stripped, and a refspec with no `:` pushes
59
- * a ref to its own name.
60
- */
61
- function parseRefSpec(refSpec: string): { source: string; dest: string } {
62
- const normalized = refSpec.startsWith("+") ? refSpec.slice(1) : refSpec;
63
- const [source = "", dest] = normalized.split(":");
64
- return { source, dest: dest || source };
52
+ function toPushStatus(update: PushRefUpdate): PushStatus {
53
+ switch (update.status) {
54
+ case "ok":
55
+ return PushStatus.OK;
56
+ case "up-to-date":
57
+ return PushStatus.UP_TO_DATE;
58
+ case "rejected-nonfastforward":
59
+ case "rejected-fetch-first":
60
+ return PushStatus.REJECTED_NONFASTFORWARD;
61
+ case "rejected-stale":
62
+ return PushStatus.REJECTED_REMOTE_CHANGED;
63
+ case "remote-rejected":
64
+ return REJECT_REASON_STATUS[mapRejectReason(update.message ?? "")];
65
+ case "remote-failure":
66
+ return PushStatus.FAILED;
67
+ default:
68
+ return PushStatus.REJECTED_OTHER;
69
+ }
65
70
  }
66
71
 
67
72
  /**
@@ -115,6 +120,10 @@ export class PushCommand extends TransportCommand<PushResult> {
115
120
  private useBitmaps = true;
116
121
  private pushOptions: string[] = [];
117
122
  private receivePack?: string;
123
+ private prune = false;
124
+ private streamRequestBody?: boolean;
125
+ /** Leases (an entry without a ref: every other pushed ref at its tracking value) */
126
+ private leases?: ForceWithLease[];
118
127
 
119
128
  /**
120
129
  * Set the remote to push to.
@@ -179,6 +188,52 @@ export class PushCommand extends TransportCommand<PushResult> {
179
188
  return this.force;
180
189
  }
181
190
 
191
+ /**
192
+ * `--force-with-lease`: allow a non-fast-forward of `ref` only while the remote ref still
193
+ * has `expect` (`""` or the zero id: it must not exist). Without `expect` the remote ref's
194
+ * remote-tracking value is expected (`refs/remotes/<remote>/...`). Without `ref` every pushed
195
+ * ref (that no explicit lease names) is leased at its remote-tracking value; `expect` may be
196
+ * a revision or an abbreviated id. A lease that does not hold is
197
+ * REJECTED_REMOTE_CHANGED; {@link setForce} overrides it, as in git.
198
+ *
199
+ * @param ref The remote ref (full or short name)
200
+ * @param expect The value it must have
201
+ */
202
+ setForceWithLease(ref?: string, expect?: string): this {
203
+ this.checkCallable();
204
+ this.leases ??= [];
205
+ // without a ref: every other pushed ref at its remote-tracking value (git's bare
206
+ // --force-with-lease, which explicit ones combine with)
207
+ this.leases.push(ref === undefined ? {} : { ref, ...(expect !== undefined ? { expect } : {}) });
208
+ return this;
209
+ }
210
+
211
+ /**
212
+ * Stream the smart-HTTP request body (default: outside browsers, where supported); `false`
213
+ * collects it first, so the request has a `Content-Length` (servers or proxies that refuse
214
+ * chunked requests).
215
+ */
216
+ setStreamRequestBody(stream: boolean): this {
217
+ this.checkCallable();
218
+ this.streamRequestBody = stream;
219
+ return this;
220
+ }
221
+
222
+ /** Whether the request body streams (undefined: the transport decides). */
223
+ isStreamRequestBody(): boolean | undefined {
224
+ return this.streamRequestBody;
225
+ }
226
+
227
+ /**
228
+ * `--prune`: delete remote refs a pattern refspec's destination covers whose local source is
229
+ * gone (with `+refs/*:refs/*`, `--mirror`).
230
+ */
231
+ setPrune(prune: boolean): this {
232
+ this.checkCallable();
233
+ this.prune = prune;
234
+ return this;
235
+ }
236
+
182
237
  /**
183
238
  * Set atomic push mode.
184
239
  *
@@ -319,123 +374,96 @@ export class PushCommand extends TransportCommand<PushResult> {
319
374
  }
320
375
 
321
376
  /**
322
- * Execute the push operation.
377
+ * Execute the push.
378
+ *
379
+ * Runs the transport's push client (git's send-pack): the refspecs are mapped onto the
380
+ * remote refs as `git push` does (short names, `HEAD`, patterns, `:dst` deletes); each ref
381
+ * is checked first (fast-forward, "fetch first", tags, `--force-with-lease`) and refused
382
+ * refs are not sent; the pack is thin against the remote refs here. Once the server accepts
383
+ * a ref, the remote-tracking ref of a named remote follows it (`refs/remotes/<remote>/…`).
323
384
  *
324
- * @returns Push result with updated refs
385
+ * Without refspecs (nor `setPushAll`/`setPushTags`), the configured `remote.<name>.push`
386
+ * refspecs are used, else `push.default` decides (default `simple`: the current branch to
387
+ * its upstream of the same name on its own remote, to the same name elsewhere; see
388
+ * `buildRefSpecs`). A detached HEAD is refused.
389
+ *
390
+ * @returns Push result with each remote ref's status
325
391
  * @throws InvalidRemoteError if remote cannot be resolved
326
- * @throws PushRejectedException if push is rejected
327
392
  */
328
393
  async call(): Promise<PushResult> {
329
394
  this.checkCallable();
330
395
  this.setCallable(false);
331
396
 
332
- // Resolve remote URL
333
397
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
334
398
  if (!remoteUrl) {
335
399
  throw new InvalidRemoteError(this.remote);
336
400
  }
337
401
 
338
- // Build refspecs
339
402
  const refspecs = await this.buildRefSpecs();
340
-
341
- // Map each destination ref back to the local ref it came from. The transport
342
- // keys its update results by the destination ref, and carries no object ids,
343
- // so this is what lets us report srcRef/newObjectId per update below.
344
- const sourceByDest = new Map<string, string>();
345
- for (const spec of refspecs) {
346
- const { source, dest } = parseRefSpec(spec);
347
- sourceByDest.set(dest, source);
348
- }
349
-
350
403
  if (refspecs.length === 0) {
351
- // Nothing to push
352
- return {
353
- uri: remoteUrl,
354
- remoteUpdates: [],
355
- bytesSent: 0,
356
- objectCount: 0,
357
- messages: [],
358
- };
404
+ return { uri: remoteUrl, remoteUpdates: [], bytesSent: 0, objectCount: 0, messages: [] };
359
405
  }
360
406
 
361
- // Build exportPack if history supports serialization (HistoryWithOperations)
362
407
  const history = this._workingCopy.history;
363
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
364
- const serialization = (history as any).serialization as
365
- | { createPack(objectIds: AsyncIterable<string>): AsyncIterable<Uint8Array> }
366
- | undefined;
367
-
368
- const exportPack = serialization
369
- ? async function* (wants: Set<string>, exclude: Set<string>): AsyncIterable<Uint8Array> {
370
- const objectIds = history.collectReachableObjects(wants, exclude);
371
- yield* serialization.createPack(objectIds);
372
- }
373
- : undefined;
374
-
375
- // Object ids resolved for each source ref, captured as the transport asks
376
- // for them, so we report the value that was really sent on the wire.
377
- const resolvedLocalOids = new Map<string, string>();
378
-
379
- // Execute push using high-level push API
380
- const transportResult = await transportPush({
408
+ const tracking = this.trackingRefMapper();
409
+ const messages: string[] = [];
410
+ const leases = this.leases;
411
+ const result = await transportPush({
381
412
  url: remoteUrl,
382
- refspecs,
383
413
  auth: this.credentials,
384
414
  headers: this.headers,
385
415
  timeout: this.timeout,
416
+ repository: createRepositoryFacade({ history }),
417
+ refStore: createTransportRefStore(history.refs),
418
+ refspecs,
386
419
  force: this.force,
387
420
  atomic: this.atomic,
388
- onProgressMessage: this.progressMessageCallback,
389
- exportPack,
390
- getLocalRef: async (refName: string) => {
391
- // A refspec with an empty source (":refs/heads/x") is a delete request:
392
- // Git expresses it as an update to the all-zero object id.
393
- if (refName === "") {
394
- resolvedLocalOids.set(refName, ZERO_OBJECT_ID);
395
- return ZERO_OBJECT_ID;
396
- }
397
- const ref = await this.refsStore.resolve(refName);
398
- // Memoise exactly the object id the transport used for this source ref,
399
- // so the reported newObjectId is the value that was actually pushed.
400
- if (ref?.objectId !== undefined) {
401
- resolvedLocalOids.set(refName, ref.objectId);
402
- }
403
- return ref?.objectId;
421
+ thin: this.thin,
422
+ dryRun: this.dryRun,
423
+ prune: this.prune,
424
+ streamRequestBody: this.streamRequestBody,
425
+ pushOptions: this.pushOptions.length > 0 ? this.pushOptions : undefined,
426
+ forceWithLease: leases,
427
+ trackingValue: async (remoteRef) => {
428
+ const local = tracking(remoteRef);
429
+ return local ? (await history.refs.resolve(local))?.objectId : undefined;
430
+ },
431
+ onProgress: (message) => {
432
+ messages.push(message);
433
+ this.progressMessageCallback?.(message);
404
434
  },
405
- getObjectsToPush: (newIds: string[], oldIds: string[]) =>
406
- this.getObjectsToPush(newIds, oldIds),
407
435
  });
408
436
 
409
- // Convert to PushResult.
410
- //
411
- // `transportResult.updates` is keyed by the DESTINATION ref name and carries
412
- // {ok, message, oldOid}: the new object ids come from the refspecs we built
413
- // and the source-ref lookups the transport performed through `getLocalRef`
414
- // above, while `oldOid` is the remote's pre-push value — the expectation the
415
- // server compared its ref against — as read from its advertisement.
416
- const remoteUpdates: RemoteRefUpdate[] = [];
417
- for (const [refName, updateResult] of transportResult.updates) {
418
- const srcRef = sourceByDest.get(refName);
419
- const newObjectId = srcRef !== undefined ? resolvedLocalOids.get(srcRef) : undefined;
420
- remoteUpdates.push({
421
- // Omit srcRef for a delete: there is no local ref behind it.
422
- ...(srcRef ? { srcRef } : {}),
423
- remoteName: refName,
424
- expectedOldObjectId: updateResult.oldOid,
425
- newObjectId: newObjectId ?? "",
426
- status: updateResult.ok ? PushStatus.OK : classifyRejection(updateResult.message),
427
- message: updateResult.message,
428
- forceUpdate: this.force,
429
- delete: newObjectId === ZERO_OBJECT_ID,
430
- });
437
+ // git updates the remote-tracking refs of what the server accepted, and of what it had
438
+ // already (transport.c: update_tracking_ref for ok and up-to-date refs)
439
+ if (!this.dryRun) {
440
+ for (const update of result.updates) {
441
+ if (update.status !== "ok" && update.status !== "up-to-date") continue;
442
+ const local = tracking(update.remoteRef);
443
+ if (!local) continue;
444
+ if (update.newOid === ZERO_OBJECT_ID) await history.refs.remove(local);
445
+ else await history.refs.set(local, update.newOid);
446
+ }
431
447
  }
432
448
 
449
+ const remoteUpdates: RemoteRefUpdate[] = result.updates.map((update) => ({
450
+ ...(update.localRef ? { srcRef: update.localRef } : {}),
451
+ remoteName: update.remoteRef,
452
+ expectedOldObjectId: update.expectedOid ?? update.oldOid,
453
+ newObjectId: update.newOid,
454
+ status: toPushStatus(update),
455
+ message: update.message ?? (update.status === "ok" ? undefined : update.summary),
456
+ summary: update.summary,
457
+ forceUpdate: update.force,
458
+ delete: update.newOid === ZERO_OBJECT_ID,
459
+ }));
460
+
433
461
  return {
434
462
  uri: remoteUrl,
435
463
  remoteUpdates,
436
- bytesSent: transportResult.bytesSent,
437
- objectCount: transportResult.objectCount,
438
- messages: [],
464
+ bytesSent: result.bytesSent,
465
+ objectCount: result.packObjects,
466
+ messages,
439
467
  };
440
468
  }
441
469
 
@@ -449,7 +477,11 @@ export class PushCommand extends TransportCommand<PushResult> {
449
477
  if (update.status === PushStatus.REJECTED_NONFASTFORWARD) {
450
478
  throw new NonFastForwardError(update.remoteName, result.uri);
451
479
  }
452
- if (update.status === PushStatus.REJECTED_OTHER || update.status === PushStatus.FAILED) {
480
+ if (
481
+ update.status === PushStatus.REJECTED_OTHER ||
482
+ update.status === PushStatus.REJECTED_REMOTE_CHANGED ||
483
+ update.status === PushStatus.FAILED
484
+ ) {
453
485
  throw new PushRejectedException(
454
486
  update.remoteName,
455
487
  update.message || "rejected",
@@ -478,205 +510,107 @@ export class PushCommand extends TransportCommand<PushResult> {
478
510
  }
479
511
 
480
512
  /**
481
- * Build refspecs for the push.
513
+ * The refspecs to push: the explicit ones, `--all` (every branch), `--tags` (every tag);
514
+ * else the remote's configured push refspecs; else what `push.default` says (git's
515
+ * builtin/push.c `setup_default_push_refspecs`, default `simple`):
516
+ *
517
+ * - `simple`: the current branch to its upstream of the same name when pushing to the
518
+ * branch's own remote (refused without an upstream, or with one of another name); to the
519
+ * same name when pushing elsewhere (a URL, another remote)
520
+ * - `current`: the current branch to the same name
521
+ * - `upstream` (`tracking`): the current branch to its upstream, on its remote only
522
+ * - `matching`: `:` (the branches both sides have)
523
+ * - `nothing`: refused
524
+ *
525
+ * A detached HEAD is refused, except with `matching`.
482
526
  */
483
527
  private async buildRefSpecs(): Promise<string[]> {
484
- const specs: string[] = [];
485
-
486
- // Add explicit refspecs
487
- for (const spec of this.refSpecs) {
488
- if (this.force && !spec.startsWith("+")) {
489
- specs.push(`+${spec}`);
490
- } else {
491
- specs.push(spec);
492
- }
493
- }
494
-
495
- // Push all branches
496
- if (this.pushAll) {
497
- for await (const ref of this.refsStore.list("refs/heads/")) {
498
- const spec = `${ref.name}:${ref.name}`;
499
- specs.push(this.force ? `+${spec}` : spec);
500
- }
501
- }
502
-
503
- // Push all tags
504
- if (this.pushTags) {
505
- for await (const ref of this.refsStore.list("refs/tags/")) {
506
- const spec = `${ref.name}:${ref.name}`;
507
- specs.push(this.force ? `+${spec}` : spec);
508
- }
528
+ const specs = [...this.refSpecs];
529
+ if (this.pushAll) specs.push("refs/heads/*:refs/heads/*");
530
+ if (this.pushTags) specs.push("refs/tags/*:refs/tags/*");
531
+ if (specs.length > 0) return specs;
532
+
533
+ const store = RemoteConfigStore.from(this.workingCopy);
534
+ if (store.isConfigured(this.remote)) {
535
+ const configured = store.read(this.remote).pushRefspecs;
536
+ if (configured.length > 0) return configured;
509
537
  }
510
-
511
- // Default: push current branch
512
- if (specs.length === 0) {
513
- const currentBranch = await this.getCurrentBranch();
514
- if (currentBranch) {
515
- const spec = `${currentBranch}:${currentBranch}`;
516
- specs.push(this.force ? `+${spec}` : spec);
517
- }
518
- }
519
-
520
- return specs;
521
- }
522
-
523
- /**
524
- * Get objects to push.
525
- *
526
- * Returns objects reachable from newIds but not from oldIds.
527
- */
528
- private async *getObjectsToPush(newIds: string[], oldIds: string[]): AsyncIterable<PushObject> {
529
- // Build set of commits to exclude (already on remote)
530
- const excludeCommits = new Set<string>();
531
- for (const oldId of oldIds) {
532
- if (oldId !== "0".repeat(40)) {
533
- await this.collectReachableCommits(oldId, excludeCommits);
534
- }
538
+ const mode = (store.value("push.default") ?? "simple").toLowerCase();
539
+ if (mode === "matching") return [":"];
540
+ if (mode === "nothing") {
541
+ throw new InvalidArgumentError(
542
+ "refspecs",
543
+ undefined,
544
+ 'You didn\'t specify any refspecs to push, and push.default is "nothing".',
545
+ );
535
546
  }
536
-
537
- // Walk from new commits and yield objects not in exclude set
538
- const visitedObjects = new Set<string>();
539
- const commitQueue: string[] = [...newIds.filter((id) => id !== "0".repeat(40))];
540
-
541
- while (commitQueue.length > 0) {
542
- const commitId = commitQueue.shift();
543
- if (commitId === undefined) break;
544
-
545
- if (excludeCommits.has(commitId) || visitedObjects.has(commitId)) {
546
- continue;
547
- }
548
- visitedObjects.add(commitId);
549
-
550
- try {
551
- const commit = await this.commits.load(commitId);
552
- if (!commit) continue;
553
-
554
- // Yield commit object
555
- yield await this.loadObjectForPush(commitId, 1);
556
-
557
- // Yield tree and its contents
558
- yield* this.yieldTreeObjects(commit.tree, visitedObjects);
559
-
560
- // Queue parent commits
561
- for (const parent of commit.parents) {
562
- if (!excludeCommits.has(parent) && !visitedObjects.has(parent)) {
563
- commitQueue.push(parent);
564
- }
565
- }
566
- } catch {
567
- // Commit not found, skip
568
- }
547
+ const ref = await this.getCurrentBranch();
548
+ // a repository without HEAD (nothing committed, nothing checked out) has nothing to push
549
+ if (!ref && !(await this.refsStore.get("HEAD"))) return [];
550
+ if (!ref?.startsWith("refs/heads/")) {
551
+ throw new InvalidArgumentError(
552
+ "refspecs",
553
+ undefined,
554
+ "You are not currently on a branch. To push the history leading to the current " +
555
+ "(detached HEAD) state now, use git push <remote> HEAD:<name-of-remote-branch>",
556
+ );
569
557
  }
570
- }
571
-
572
- /**
573
- * Collect all commits reachable from a given commit.
574
- */
575
- private async collectReachableCommits(
576
- commitId: string,
577
- result: Set<string>,
578
- maxDepth = 1000,
579
- ): Promise<void> {
580
- const queue: string[] = [commitId];
581
- let depth = 0;
582
-
583
- while (queue.length > 0 && depth < maxDepth) {
584
- const id = queue.shift();
585
- if (id === undefined) break;
586
- if (result.has(id)) {
587
- continue;
588
- }
589
- result.add(id);
590
- depth++;
591
-
592
- try {
593
- const commit = await this.commits.load(id);
594
- if (commit) queue.push(...commit.parents);
595
- } catch {
596
- // Commit not found, skip
558
+ const branch = ref.slice("refs/heads/".length);
559
+ if (mode === "current") return [`${ref}:${ref}`];
560
+
561
+ // the branch's remote (git: branch.<name>.remote, else "origin") and upstream
562
+ const branchRemote = store.value(`branch.${branch}.remote`) ?? "origin";
563
+ const merge = store.value(`branch.${branch}.merge`);
564
+ const triangular = this.remote !== branchRemote;
565
+ const noUpstream = () =>
566
+ new InvalidArgumentError(
567
+ "refspecs",
568
+ undefined,
569
+ `The current branch ${branch} has no upstream branch. To push the current branch and ` +
570
+ `set the remote as upstream, use git push --set-upstream ${this.remote} ${branch}`,
571
+ );
572
+ if (mode === "upstream" || mode === "tracking") {
573
+ if (triangular) {
574
+ throw new InvalidArgumentError(
575
+ "refspecs",
576
+ undefined,
577
+ `You are pushing to remote '${this.remote}', which is not the upstream of your ` +
578
+ `current branch '${branch}', without telling me what to push to update which ` +
579
+ "remote branch.",
580
+ );
597
581
  }
582
+ if (!merge) throw noUpstream();
583
+ return [`${ref}:${merge}`];
598
584
  }
599
- }
600
-
601
- /**
602
- * Yield tree and blob objects recursively.
603
- */
604
- private async *yieldTreeObjects(
605
- treeId: string,
606
- visited: Set<string>,
607
- ): AsyncGenerator<PushObject> {
608
- if (visited.has(treeId)) {
609
- return;
610
- }
611
- visited.add(treeId);
612
-
613
- // Yield tree object
614
- yield await this.loadObjectForPush(treeId, 2);
615
-
616
- // Recursively process tree entries
617
- for await (const entry of this.trees.loadTree(treeId)) {
618
- if (visited.has(entry.id)) {
619
- continue;
620
- }
621
-
622
- const isTree = (entry.mode & 0o170000) === 0o040000;
623
- if (isTree) {
624
- yield* this.yieldTreeObjects(entry.id, visited);
625
- } else {
626
- // Blob
627
- visited.add(entry.id);
628
- yield await this.loadObjectForPush(entry.id, 3);
629
- }
585
+ // simple (and anything unknown, as git's default)
586
+ if (triangular) return [`${ref}:${ref}`];
587
+ if (!merge) throw noUpstream();
588
+ if (merge !== ref) {
589
+ throw new InvalidArgumentError(
590
+ "refspecs",
591
+ undefined,
592
+ "The upstream branch of your current branch does not match\n" +
593
+ `the name of your current branch. To push to the upstream branch on the remote, use\n` +
594
+ ` git push ${this.remote} HEAD:${merge.replace(/^refs\/heads\//, "")}`,
595
+ );
630
596
  }
597
+ return [`${ref}:${ref}`];
631
598
  }
632
599
 
633
600
  /**
634
- * Load an object for pushing.
635
- *
636
- * Serializes objects to raw Git format based on type:
637
- * - type 1 (commit): serialize via serializeCommit()
638
- * - type 2 (tree): serialize via serializeTree()
639
- * - type 3 (blob): load raw content from blob store
601
+ * The remote-tracking ref of a remote ref (`refs/heads/main` → `refs/remotes/origin/main`)
602
+ * through the named remote's fetch refspecs; none for a URL.
640
603
  */
641
- private async loadObjectForPush(objectId: string, type: number): Promise<PushObject> {
642
- let content: Uint8Array;
643
-
644
- if (type === 1) {
645
- // Commit
646
- const commit = await this.commits.load(objectId);
647
- if (!commit) {
648
- throw new Error(`Commit not found: ${objectId}`);
649
- }
650
- content = serializeCommit(commit);
651
- } else if (type === 2) {
652
- // Tree
653
- const entries: TreeEntry[] = [];
654
- for await (const entry of this.trees.loadTree(objectId)) {
655
- entries.push(entry);
656
- }
657
- content = serializeTree(entries);
658
- } else {
659
- // Blob (type 3) or other
660
- const chunks: Uint8Array[] = [];
661
- const blobContent = await this.blobs.load(objectId);
662
- if (blobContent) {
663
- for await (const chunk of blobContent) {
664
- chunks.push(chunk);
665
- }
666
- }
667
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
668
- content = new Uint8Array(totalLength);
669
- let offset = 0;
670
- for (const chunk of chunks) {
671
- content.set(chunk, offset);
672
- offset += chunk.length;
673
- }
674
- }
675
-
676
- return {
677
- id: objectId,
678
- type,
679
- content,
604
+ private trackingRefMapper(): (remoteRef: string) => string | undefined {
605
+ const store = RemoteConfigStore.from(this.workingCopy);
606
+ if (!store.isConfigured(this.remote)) return () => undefined;
607
+ const specs = store
608
+ .read(this.remote)
609
+ .fetchRefspecs.map((spec) => parseRefSpec(spec))
610
+ .filter((spec) => !spec.negative && spec.source && spec.destination);
611
+ return (remoteRef) => {
612
+ const spec = specs.find((s) => matchSource(s, remoteRef));
613
+ return spec ? (expandFromSource(spec, remoteRef).destination ?? undefined) : undefined;
680
614
  };
681
615
  }
682
616
  }
@@ -52,9 +52,9 @@ export class ReflogCommand extends GitCommand<ReflogEntry[]> {
52
52
  this.checkCallable();
53
53
  this.setCallable(false);
54
54
 
55
- // Check if the RefStore supports reflog
55
+ // Check if the ref store supports reflog
56
56
  if (!this.refsStore.getReflog) {
57
- throw new Error("RefStore does not support reflog");
57
+ throw new Error("This ref store does not support reflog");
58
58
  }
59
59
 
60
60
  const reader = await this.refsStore.getReflog(this.ref);