@statewalker/vcs-commands 0.6.0 → 0.7.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 (166) hide show
  1. package/dist/commands/apply/apply-command.d.ts.map +1 -1
  2. package/dist/commands/apply/apply-engine.d.ts.map +1 -1
  3. package/dist/commands/apply/apply-parse.d.ts.map +1 -1
  4. package/dist/commands/bisect/bisect-engine.d.ts.map +1 -1
  5. package/dist/commands/clone-command.d.ts +17 -0
  6. package/dist/commands/clone-command.d.ts.map +1 -1
  7. package/dist/commands/comment-char-config.d.ts +35 -0
  8. package/dist/commands/comment-char-config.d.ts.map +1 -0
  9. package/dist/commands/commit-command.d.ts.map +1 -1
  10. package/dist/commands/core-config.d.ts.map +1 -1
  11. package/dist/commands/default-branch.d.ts +70 -0
  12. package/dist/commands/default-branch.d.ts.map +1 -0
  13. package/dist/commands/diff-command.d.ts.map +1 -1
  14. package/dist/commands/fetch-command.d.ts.map +1 -1
  15. package/dist/commands/format-patch-command.d.ts.map +1 -1
  16. package/dist/commands/fsck/fsck-command.d.ts +2 -0
  17. package/dist/commands/fsck/fsck-command.d.ts.map +1 -1
  18. package/dist/commands/fsck/fsck-loose.d.ts +3 -0
  19. package/dist/commands/fsck/fsck-loose.d.ts.map +1 -1
  20. package/dist/commands/fsck/fsck-object-checks.d.ts +25 -14
  21. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -1
  22. package/dist/commands/fsck/fsck-object-table.d.ts +15 -7
  23. package/dist/commands/fsck/fsck-object-table.d.ts.map +1 -1
  24. package/dist/commands/fsck/fsck-pack.d.ts +11 -4
  25. package/dist/commands/fsck/fsck-pack.d.ts.map +1 -1
  26. package/dist/commands/fsck/verify-pack-command.d.ts.map +1 -1
  27. package/dist/commands/gc-command.d.ts +72 -48
  28. package/dist/commands/gc-command.d.ts.map +1 -1
  29. package/dist/commands/git-date.d.ts +1 -65
  30. package/dist/commands/git-date.d.ts.map +1 -1
  31. package/dist/commands/git-hooks.d.ts +8 -0
  32. package/dist/commands/git-hooks.d.ts.map +1 -1
  33. package/dist/commands/index-adder.d.ts +2 -0
  34. package/dist/commands/index-adder.d.ts.map +1 -1
  35. package/dist/commands/index.d.ts +2 -0
  36. package/dist/commands/index.d.ts.map +1 -1
  37. package/dist/commands/index.js +3 -3
  38. package/dist/commands/init-command.d.ts +50 -3
  39. package/dist/commands/init-command.d.ts.map +1 -1
  40. package/dist/commands/legacy-remotes.d.ts +55 -0
  41. package/dist/commands/legacy-remotes.d.ts.map +1 -0
  42. package/dist/commands/log-command.d.ts.map +1 -1
  43. package/dist/commands/ls-remote-command.d.ts.map +1 -1
  44. package/dist/commands/merge-command.d.ts +12 -0
  45. package/dist/commands/merge-command.d.ts.map +1 -1
  46. package/dist/commands/merge-support.d.ts +11 -3
  47. package/dist/commands/merge-support.d.ts.map +1 -1
  48. package/dist/commands/notes-merge-command.d.ts.map +1 -1
  49. package/dist/commands/notes-tree.d.ts +11 -1
  50. package/dist/commands/notes-tree.d.ts.map +1 -1
  51. package/dist/commands/patch-id.d.ts +3 -0
  52. package/dist/commands/patch-id.d.ts.map +1 -1
  53. package/dist/commands/pretty-format.d.ts.map +1 -1
  54. package/dist/commands/pull-command.d.ts +18 -0
  55. package/dist/commands/pull-command.d.ts.map +1 -1
  56. package/dist/commands/push-command.d.ts.map +1 -1
  57. package/dist/commands/read-tree-command.d.ts.map +1 -1
  58. package/dist/commands/rebase-command.d.ts.map +1 -1
  59. package/dist/commands/remote-command.d.ts.map +1 -1
  60. package/dist/commands/reset-command.d.ts.map +1 -1
  61. package/dist/commands/rev-parse-command.d.ts +9 -0
  62. package/dist/commands/rev-parse-command.d.ts.map +1 -1
  63. package/dist/commands/revision-resolver.d.ts +6 -2
  64. package/dist/commands/revision-resolver.d.ts.map +1 -1
  65. package/dist/commands/sequencer-pick.d.ts +1 -1
  66. package/dist/commands/sequencer-pick.d.ts.map +1 -1
  67. package/dist/commands/sequencer-support.d.ts.map +1 -1
  68. package/dist/commands/stash-create-command.d.ts +1 -1
  69. package/dist/commands/stash-create-command.d.ts.map +1 -1
  70. package/dist/commands/status-command.d.ts.map +1 -1
  71. package/dist/commands/submodule-summary-command.d.ts.map +1 -1
  72. package/dist/commands/untracked-cache-support.d.ts +2 -1
  73. package/dist/commands/untracked-cache-support.d.ts.map +1 -1
  74. package/dist/commands/worktree-list-command.d.ts.map +1 -1
  75. package/dist/{commands-DnmlfwGV.js → commands-DIJ91NnD.js} +1111 -506
  76. package/dist/{git-command-DxvwPrPB.js → git-command-BGiOJ8Zk.js} +630 -996
  77. package/dist/git-command.d.ts +16 -1
  78. package/dist/git-command.d.ts.map +1 -1
  79. package/dist/git.d.ts +9 -2
  80. package/dist/git.d.ts.map +1 -1
  81. package/dist/index.js +4 -4
  82. package/dist/remote-config/index.d.ts +1 -1
  83. package/dist/remote-config/index.d.ts.map +1 -1
  84. package/dist/remote-config/remote-config-store.d.ts +62 -3
  85. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  86. package/dist/rename/detect-renames.d.ts.map +1 -1
  87. package/dist/results/clone-result.d.ts +8 -0
  88. package/dist/results/clone-result.d.ts.map +1 -1
  89. package/dist/results/diff-output.d.ts.map +1 -1
  90. package/dist/results/index.js +1 -1
  91. package/dist/results/init-result.d.ts +7 -0
  92. package/dist/results/init-result.d.ts.map +1 -1
  93. package/dist/results/pull-result.d.ts +5 -0
  94. package/dist/results/pull-result.d.ts.map +1 -1
  95. package/dist/results/push-result.d.ts +5 -0
  96. package/dist/results/push-result.d.ts.map +1 -1
  97. package/dist/results/status-result.d.ts.map +1 -1
  98. package/dist/{results-BZGa2Z3I.js → results-WVlBhVb1.js} +11 -10
  99. package/package.json +12 -12
  100. package/src/commands/add-patch/add-interactive.ts +3 -3
  101. package/src/commands/am/am-command.ts +1 -1
  102. package/src/commands/apply/apply-command.ts +12 -2
  103. package/src/commands/apply/apply-engine.ts +5 -6
  104. package/src/commands/apply/apply-parse.ts +3 -2
  105. package/src/commands/attributes-source.ts +1 -1
  106. package/src/commands/bisect/bisect-engine.ts +2 -1
  107. package/src/commands/checkout-command.ts +1 -1
  108. package/src/commands/clone-command.ts +116 -4
  109. package/src/commands/comment-char-config.ts +160 -0
  110. package/src/commands/commit-command.ts +8 -7
  111. package/src/commands/core-config.ts +7 -2
  112. package/src/commands/default-branch.ts +196 -0
  113. package/src/commands/diff-command.ts +45 -27
  114. package/src/commands/fetch-command.ts +19 -5
  115. package/src/commands/format-patch-command.ts +7 -2
  116. package/src/commands/fsck/fsck-command.ts +183 -66
  117. package/src/commands/fsck/fsck-loose.ts +14 -4
  118. package/src/commands/fsck/fsck-object-checks.ts +87 -46
  119. package/src/commands/fsck/fsck-object-table.ts +52 -42
  120. package/src/commands/fsck/fsck-pack.ts +64 -34
  121. package/src/commands/fsck/verify-pack-command.ts +5 -2
  122. package/src/commands/gc-command.ts +208 -107
  123. package/src/commands/git-date.ts +9 -895
  124. package/src/commands/git-hooks.ts +11 -0
  125. package/src/commands/index-adder.ts +8 -3
  126. package/src/commands/index.ts +2 -0
  127. package/src/commands/init-command.ts +167 -11
  128. package/src/commands/legacy-remotes.ts +224 -0
  129. package/src/commands/log-command.ts +37 -22
  130. package/src/commands/ls-remote-command.ts +4 -0
  131. package/src/commands/merge-command.ts +31 -1
  132. package/src/commands/merge-support.ts +29 -8
  133. package/src/commands/notes-merge-command.ts +23 -14
  134. package/src/commands/notes-tree.ts +28 -13
  135. package/src/commands/octopus-merge.ts +3 -2
  136. package/src/commands/patch-id.ts +16 -8
  137. package/src/commands/pretty-format.ts +2 -1
  138. package/src/commands/pull-command.ts +128 -20
  139. package/src/commands/push-command.ts +23 -8
  140. package/src/commands/read-tree-command.ts +6 -2
  141. package/src/commands/rebase-command.ts +24 -13
  142. package/src/commands/remote-command.ts +35 -5
  143. package/src/commands/reset-command.ts +4 -11
  144. package/src/commands/rev-parse-command.ts +22 -0
  145. package/src/commands/revision-resolver.ts +32 -14
  146. package/src/commands/sequencer-pick.ts +7 -2
  147. package/src/commands/sequencer-support.ts +10 -3
  148. package/src/commands/stash-apply-command.ts +1 -1
  149. package/src/commands/stash-create-command.ts +2 -2
  150. package/src/commands/status-command.ts +2 -4
  151. package/src/commands/status-header.ts +3 -1
  152. package/src/commands/submodule-summary-command.ts +6 -7
  153. package/src/commands/untracked-cache-support.ts +16 -12
  154. package/src/commands/worktree-list-command.ts +3 -5
  155. package/src/core-commands/add.command.impl.ts +1 -1
  156. package/src/git-command.ts +32 -2
  157. package/src/git.ts +16 -3
  158. package/src/remote-config/index.ts +2 -0
  159. package/src/remote-config/remote-config-store.ts +137 -11
  160. package/src/rename/detect-renames.ts +5 -1
  161. package/src/results/clone-result.ts +9 -0
  162. package/src/results/diff-output.ts +9 -7
  163. package/src/results/init-result.ts +9 -0
  164. package/src/results/pull-result.ts +5 -0
  165. package/src/results/push-result.ts +5 -0
  166. package/src/results/status-result.ts +5 -2
@@ -7,7 +7,13 @@
7
7
  */
8
8
 
9
9
  import { type Blobs, compareTreeEntries, FileMode, type ObjectId } from "@statewalker/vcs-core";
10
- import { bytesToHex, createSha1, type Hasher, unifiedDiffHunks } from "@statewalker/vcs-utils";
10
+ import {
11
+ bytesToHex,
12
+ type Hasher,
13
+ type ObjectFormat,
14
+ SHA1_OBJECT_FORMAT,
15
+ unifiedDiffHunks,
16
+ } from "@statewalker/vcs-utils";
11
17
  import { encodeGitPath } from "@statewalker/vcs-utils/encoding";
12
18
 
13
19
  import type { CommandTrees } from "../git-command.js";
@@ -102,7 +108,7 @@ export async function patchId(
102
108
  blobs: Blobs,
103
109
  parentTree: ObjectId | undefined,
104
110
  tree: ObjectId,
105
- options: { headerOnly?: boolean } = {},
111
+ options: { headerOnly?: boolean; objectFormat?: ObjectFormat } = {},
106
112
  ): Promise<string | undefined> {
107
113
  const changes = await treeChanges(trees, parentTree, tree);
108
114
  if (changes.length === 0) return undefined;
@@ -124,11 +130,13 @@ export interface PatchIdChange {
124
130
  export async function patchIdOfChanges(
125
131
  blobs: Blobs,
126
132
  changes: PatchIdChange[],
127
- options: { headerOnly?: boolean } = {},
133
+ options: { headerOnly?: boolean; objectFormat?: ObjectFormat } = {},
128
134
  ): Promise<string> {
129
- const sum = new Uint8Array(20);
135
+ // the repository's hash (git's the_hash_algo): a SHA-256 repository's patch-ids are 64-hex
136
+ const format = options.objectFormat ?? blobs.objectFormat ?? SHA1_OBJECT_FORMAT;
137
+ const sum = new Uint8Array(format.rawLength);
130
138
  for (const change of changes) {
131
- const h = createSha1();
139
+ const h = format.createHasher();
132
140
  const newPath = removeSpace(encodeGitPath(change.path));
133
141
  const oldPath =
134
142
  change.oldPath !== undefined ? removeSpace(encodeGitPath(change.oldPath)) : newPath;
@@ -156,8 +164,8 @@ export async function patchIdOfChanges(
156
164
  if (options.headerOnly) {
157
165
  // only the header
158
166
  } else if (isBinary(a) || isBinary(b)) {
159
- str(h, change.old?.id ?? "0".repeat(40));
160
- str(h, change.new?.id ?? "0".repeat(40));
167
+ str(h, change.old?.id ?? format.nullId);
168
+ str(h, change.new?.id ?? format.nullId);
161
169
  } else {
162
170
  if (!change.old) {
163
171
  str(h, "---/dev/null");
@@ -186,7 +194,7 @@ export async function patchIdOfChanges(
186
194
  // flush_one_hunk: the file's hash added to the sum, bytewise with carry
187
195
  const digest = h.digest();
188
196
  let carry = 0;
189
- for (let i = 0; i < 20; i++) {
197
+ for (let i = 0; i < sum.length; i++) {
190
198
  carry += sum[i] + digest[i];
191
199
  sum[i] = carry & 0xff;
192
200
  carry >>= 8;
@@ -198,12 +198,13 @@ export async function loadRefDecorations(
198
198
  if (name.startsWith(replaceBase)) {
199
199
  if (options.useReplaceRefs === false) return;
200
200
  const hex = name.slice(replaceBase.length);
201
+ const hexLength = /^[0-9a-fA-F]{64}/.test(hex) ? 64 : 40;
201
202
  if (!/^[0-9a-fA-F]{40}/.test(hex)) {
202
203
  // add_ref_decoration: get_oid_hex of what follows the base
203
204
  options.onWarning?.(`warning: invalid replace ref ${name}`);
204
205
  return;
205
206
  }
206
- const original = hex.slice(0, 40).toLowerCase();
207
+ const original = hex.slice(0, hexLength).toLowerCase();
207
208
  if (options.hasObject && !(await options.hasObject(original))) return;
208
209
  add(original, { type: "grafted", name: "replaced" });
209
210
  return;
@@ -1,8 +1,9 @@
1
- import type { FilesApi } from "@statewalker/vcs-core";
1
+ import type { FilesApi, ObjectId } from "@statewalker/vcs-core";
2
2
  import { parseGitBool } from "@statewalker/vcs-utils";
3
- import { isIndexUnborn } from "@statewalker/vcs-working-tree";
3
+ import { type Checkout, isIndexUnborn } from "@statewalker/vcs-working-tree";
4
4
 
5
- import { NoHeadError } from "../errors/index.js";
5
+ import { GitApiError, NoHeadError } from "../errors/index.js";
6
+ import { RemoteConfigStore } from "../remote-config/index.js";
6
7
  import { FastForwardMode, isMergeSuccessful, type MergeStrategy } from "../results/merge-result.js";
7
8
  import type { PullResult } from "../results/pull-result.js";
8
9
  import { isRebaseSuccessful, RebaseStatus } from "../results/rebase-result.js";
@@ -212,8 +213,20 @@ export class PullCommand extends TransportCommand<PullResult> {
212
213
  // Determine remote branch
213
214
  const remoteBranch = this.remoteBranchName || localBranchName;
214
215
 
216
+ // a remote read from .git/remotes/ or .git/branches/ (git 2.x) is pulled as pull.c does:
217
+ // `git fetch <remote> [<branch>]` with the remote's own refspecs, then the FETCH_HEAD
218
+ // entries marked for merge
219
+ await this.loadLegacyRemote(this.remote);
220
+ const store = RemoteConfigStore.from(this._workingCopy);
221
+ const legacy = store.legacyOrigin(this.remote) !== undefined;
222
+ const trackingRef = `refs/remotes/${this.remote}/${remoteBranch}`;
223
+
215
224
  // Build refspec
216
- const refspec = `refs/heads/${remoteBranch}:refs/remotes/${this.remote}/${remoteBranch}`;
225
+ const refspecs = legacy
226
+ ? this.remoteBranchName
227
+ ? [this.remoteBranchName]
228
+ : []
229
+ : [`refs/heads/${remoteBranch}:${trackingRef}`];
217
230
 
218
231
  // git's GIT_REFLOG_ACTION for everything the pull writes: "pull" and its command-line
219
232
  // arguments (a rebase or autostash the configuration asks for is not among them)
@@ -274,7 +287,7 @@ export class PullCommand extends TransportCommand<PullResult> {
274
287
  const fetchCommand = new FetchCommand(this._workingCopy);
275
288
  fetchCommand.setTransports(this.getTransports());
276
289
  fetchCommand.setRemote(this.remote);
277
- fetchCommand.setRefSpecs(refspec);
290
+ fetchCommand.setRefSpecs(...refspecs);
278
291
  // git pull fetches with --update-head-ok
279
292
  fetchCommand.setUpdateHeadOk(true);
280
293
  fetchCommand.setReflogAction(action);
@@ -303,21 +316,30 @@ export class PullCommand extends TransportCommand<PullResult> {
303
316
 
304
317
  const fetchResult = await fetchCommand.call();
305
318
 
306
- // If repository is empty or nothing fetched, we're done
307
- if (fetchResult.isEmpty || fetchResult.trackingRefUpdates.length === 0) {
308
- return {
309
- fetchResult,
310
- successful: true,
311
- rebaseUsed: false,
312
- fetchedFrom: this.remote,
313
- };
319
+ let warnings: string[] = [];
320
+ let mergeTarget: { objectId: ObjectId; description?: string } | undefined;
321
+ if (legacy) {
322
+ if (fetchResult.isEmpty) {
323
+ return { fetchResult, successful: true, rebaseUsed: false, fetchedFrom: this.remote };
324
+ }
325
+ warnings = await this.fastForwardMovedHead(origHead);
326
+ mergeTarget = await this.mergeHeadFromFetchHead(localBranchName);
327
+ } else {
328
+ // If repository is empty or nothing fetched, we're done
329
+ if (fetchResult.isEmpty || fetchResult.trackingRefUpdates.length === 0) {
330
+ return {
331
+ fetchResult,
332
+ successful: true,
333
+ rebaseUsed: false,
334
+ fetchedFrom: this.remote,
335
+ };
336
+ }
337
+ // Get the remote tracking ref to merge
338
+ const resolved = await this.refsStore.resolve(trackingRef);
339
+ if (resolved?.objectId) mergeTarget = { objectId: resolved.objectId };
314
340
  }
315
341
 
316
- // Get the remote tracking ref to merge
317
- const trackingRef = `refs/remotes/${this.remote}/${remoteBranch}`;
318
- const trackingRefResolved = await this.refsStore.resolve(trackingRef);
319
-
320
- if (!trackingRefResolved?.objectId) {
342
+ if (!mergeTarget) {
321
343
  // Nothing to merge
322
344
  return {
323
345
  fetchResult,
@@ -326,6 +348,9 @@ export class PullCommand extends TransportCommand<PullResult> {
326
348
  fetchedFrom: this.remote,
327
349
  };
328
350
  }
351
+ const trackingRefResolved = mergeTarget;
352
+ // pull.c's warning() when the fetch moved the checked-out branch
353
+ const shown = warnings.length > 0 ? { warnings } : {};
329
354
 
330
355
  // pull_into_void: an unborn branch (rebasing or not) branches off what was fetched, a
331
356
  // two-way switch from the empty tree keeping the staged changes it does not overwrite
@@ -340,6 +365,7 @@ export class PullCommand extends TransportCommand<PullResult> {
340
365
  successful: isMergeSuccessful(mergeResult.status),
341
366
  rebaseUsed: false,
342
367
  fetchedFrom: this.remote,
368
+ ...shown,
343
369
  };
344
370
  }
345
371
 
@@ -363,6 +389,7 @@ export class PullCommand extends TransportCommand<PullResult> {
363
389
  successful: isRebaseSuccessful(rebaseResult.status),
364
390
  rebaseUsed: true,
365
391
  fetchedFrom: this.remote,
392
+ ...shown,
366
393
  };
367
394
  }
368
395
 
@@ -370,12 +397,20 @@ export class PullCommand extends TransportCommand<PullResult> {
370
397
  const mergeCommand = new MergeCommand(this._workingCopy).shareHooksOf(this);
371
398
  mergeCommand.include(trackingRefResolved.objectId);
372
399
  // git's fmt-merge-msg shortens the URL: no trailing slash, no `.git`
373
- const url = (configValue(this._workingCopy, `remote.${this.remote}.url`) ?? this.remote)
400
+ const url = (
401
+ configValue(this._workingCopy, `remote.${this.remote}.url`) ??
402
+ store.remoteUrls(this.remote)[0] ??
403
+ this.remote
404
+ )
374
405
  .replace(/\/+$/, "")
375
406
  .replace(/\.git$/, "");
376
407
  const into =
377
408
  localBranchName === "main" || localBranchName === "master" ? "" : ` into ${localBranchName}`;
378
- mergeCommand.setMessage(`Merge branch '${remoteBranch}' of ${url}${into}`);
409
+ mergeCommand.setMessage(
410
+ mergeTarget.description
411
+ ? `Merge ${mergeTarget.description}${into}`
412
+ : `Merge branch '${remoteBranch}' of ${url}${into}`,
413
+ );
379
414
  mergeCommand.setReflogAction(action);
380
415
  if (canFastForward) mergeCommand.setFastForwardMode(FastForwardMode.FF_ONLY);
381
416
  // run_merge passes --autostash / --no-autostash only when pull has one to give
@@ -402,6 +437,7 @@ export class PullCommand extends TransportCommand<PullResult> {
402
437
  successful,
403
438
  rebaseUsed: true,
404
439
  fetchedFrom: this.remote,
440
+ ...shown,
405
441
  };
406
442
  }
407
443
  return {
@@ -410,9 +446,81 @@ export class PullCommand extends TransportCommand<PullResult> {
410
446
  successful,
411
447
  rebaseUsed: false,
412
448
  fetchedFrom: this.remote,
449
+ ...shown,
413
450
  };
414
451
  }
415
452
 
453
+ /**
454
+ * pull.c after its fetch: when the fetch moved the checked-out branch itself
455
+ * (`--update-head-ok`, a branches remote named after it), the index and worktree still at
456
+ * `origHead` are fast-forwarded to the new HEAD (merge.c `checkout_fast_forward`), with
457
+ * git's warning; local changes in the way are git's death.
458
+ *
459
+ * @returns the warning git printed, if any
460
+ * @throws GitApiError with git's stderr: the warning, unpack-trees' refusal and pull.c's
461
+ * `Cannot fast-forward your working tree.` lines (exit 128)
462
+ */
463
+ private async fastForwardMovedHead(origHead: ObjectId | undefined): Promise<string[]> {
464
+ const currHead = (await this.refsStore.resolve("HEAD").catch(() => undefined))?.objectId;
465
+ if (origHead === undefined || currHead === undefined || origHead === currHead) return [];
466
+ const warning =
467
+ "warning: fetch updated the current branch head.\n" +
468
+ "fast-forwarding your working tree from\n" +
469
+ `commit ${origHead}.`;
470
+ const refused = await new MergeCommand(this._workingCopy)
471
+ .shareHooksOf(this)
472
+ .callCheckoutFastForward(origHead, currHead);
473
+ if (refused) {
474
+ throw new GitApiError(
475
+ `${warning}\n${refused.message}\n` +
476
+ "fatal: Cannot fast-forward your working tree.\n" +
477
+ "After making sure that you saved anything precious from\n" +
478
+ `$ git diff ${origHead}\n` +
479
+ "output, run\n" +
480
+ "$ git reset --hard\n" +
481
+ "to recover.",
482
+ { exitCode: 128 },
483
+ );
484
+ }
485
+ return [warning];
486
+ }
487
+
488
+ /**
489
+ * pull.c's `get_merge_heads`: the first FETCH_HEAD entry not marked `not-for-merge`, with
490
+ * its description (`branch 'x' of <url>`, as fmt-merge-msg titles the merge).
491
+ *
492
+ * @throws GitApiError with `die_no_merge_candidates`' lines (exit 1) when there is none
493
+ */
494
+ private async mergeHeadFromFetchHead(
495
+ branch: string,
496
+ ): Promise<{ objectId: ObjectId; description?: string }> {
497
+ const checkout = (this._workingCopy as { checkout?: Checkout }).checkout;
498
+ const text = (await checkout?.readFetchHead?.()) ?? "";
499
+ for (const line of text.split("\n")) {
500
+ const m = /^([0-9a-f]{40,64})\t([^\t]*)\t(.*)$/.exec(line);
501
+ if (!m || m[2] === "not-for-merge") continue;
502
+ return { objectId: m[1] as ObjectId, description: m[3] };
503
+ }
504
+ const store = RemoteConfigStore.from(this._workingCopy);
505
+ let message: string;
506
+ if (this.remoteBranchName) {
507
+ message =
508
+ "There are no candidates for merging among the refs that you just fetched.\n" +
509
+ "Generally this means that you provided a wildcard refspec which had no\n" +
510
+ "matches on the remote end.";
511
+ } else if (store.value(`branch.${branch}.remote`) !== this.remote) {
512
+ message =
513
+ `You asked to pull from the remote '${this.remote}', but did not specify\n` +
514
+ "a branch. Because this is not the default configured remote\n" +
515
+ "for your current branch, you must specify a branch on the command line.";
516
+ } else {
517
+ message =
518
+ `Your configuration specifies to merge with the ref '${store.value(`branch.${branch}.merge`) ?? ""}'\n` +
519
+ "from the remote, but no such ref was fetched.";
520
+ }
521
+ throw new GitApiError(message, { exitCode: 1 });
522
+ }
523
+
416
524
  private config(key: string): string | undefined {
417
525
  return configValue(this._workingCopy, key);
418
526
  }
@@ -7,6 +7,7 @@ import {
7
7
  formatPushStatus,
8
8
  mapRejectReason,
9
9
  matchSource,
10
+ ObjectFormatMismatchError,
10
11
  type PushClientResult,
11
12
  type PushCommandResult,
12
13
  type PushRefUpdate,
@@ -16,6 +17,7 @@ import {
16
17
  type PushOptions as TransportPushOptions,
17
18
  } from "@statewalker/vcs-transport";
18
19
  import { parseGitBool, parseGitInt } from "@statewalker/vcs-utils/encoding";
20
+ import { isNullObjectId } from "@statewalker/vcs-utils/hash";
19
21
 
20
22
  import {
21
23
  HookFailedError,
@@ -31,9 +33,6 @@ import { TransportCommand } from "../transport-command.js";
31
33
  import { remoteHookSession } from "./local-transport.js";
32
34
  import { withRemoteReceivePack } from "./remote-transport.js";
33
35
 
34
- /** All-zero object id — Git's "no object", used to express a ref delete. */
35
- const ZERO_OBJECT_ID = "0".repeat(40);
36
-
37
36
  /**
38
37
  * How a server's rejection reason (`ng <ref> <reason>`) lands on the statuses this package
39
38
  * reports. PushStatus, following JGit's RemoteRefUpdate, keeps only the non-fast-forward case
@@ -430,6 +429,10 @@ export class PushCommand extends TransportCommand<PushResult> {
430
429
  this.checkCallable();
431
430
  this.setCallable(false);
432
431
 
432
+ // pushremote_get: a remote the configuration gives no URL may come from .git/remotes/ or
433
+ // .git/branches/ (git 2.x)
434
+ const legacyWarnings = await this.loadLegacyRemote(this.remote);
435
+ const warnings = legacyWarnings.length > 0 ? { warnings: legacyWarnings } : {};
433
436
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
434
437
  if (!remoteUrl) {
435
438
  throw new InvalidRemoteError(this.remote);
@@ -440,7 +443,14 @@ export class PushCommand extends TransportCommand<PushResult> {
440
443
  const resolved = this.resolveRemote(remoteUrl);
441
444
  const refspecs = await this.buildRefSpecs();
442
445
  if (refspecs.length === 0) {
443
- return { uri: remoteUrl, remoteUpdates: [], bytesSent: 0, objectCount: 0, messages: [] };
446
+ return {
447
+ uri: remoteUrl,
448
+ remoteUpdates: [],
449
+ bytesSent: 0,
450
+ objectCount: 0,
451
+ messages: [],
452
+ ...warnings,
453
+ };
444
454
  }
445
455
 
446
456
  const remote = await this.openRemote(resolved);
@@ -513,6 +523,10 @@ export class PushCommand extends TransportCommand<PushResult> {
513
523
  transactionHooks,
514
524
  );
515
525
  } catch (error) {
526
+ // send_pack dies: the remote's repository names objects with another hash
527
+ if (error instanceof ObjectFormatMismatchError) {
528
+ throw new TransportError(`fatal: ${error.message}`, undefined, { cause: error });
529
+ }
516
530
  if (error instanceof PushRefusedByHookError) {
517
531
  throw new HookFailedError(
518
532
  "pre-push",
@@ -557,7 +571,7 @@ export class PushCommand extends TransportCommand<PushResult> {
557
571
  // error lines (the push is done: git exits 0). The names and ids come from the
558
572
  // server (a proc-receive hook's `option refname` / `new-oid`): a bad name or an
559
573
  // object we lack is refused, as refs.c's transaction refuses it
560
- if (target.oid === ZERO_OBJECT_ID) {
574
+ if (isNullObjectId(target.oid)) {
561
575
  if (!refNameIsSafe(local)) {
562
576
  trackingErrors.push(`error: refusing to update ref with bad name '${local}'`);
563
577
  continue;
@@ -607,7 +621,7 @@ export class PushCommand extends TransportCommand<PushResult> {
607
621
  message: update.message ?? (update.status === "ok" ? undefined : update.summary),
608
622
  summary: update.summary,
609
623
  forceUpdate: update.force,
610
- delete: update.newOid === ZERO_OBJECT_ID,
624
+ delete: isNullObjectId(update.newOid),
611
625
  ...(update.reports?.length
612
626
  ? {
613
627
  reports: update.reports.map((r) => ({
@@ -626,6 +640,7 @@ export class PushCommand extends TransportCommand<PushResult> {
626
640
  bytesSent: result.bytesSent,
627
641
  objectCount: result.packObjects,
628
642
  messages,
643
+ ...warnings,
629
644
  display: formatPushStatus(result, { dest: remoteUrl }),
630
645
  porcelain: formatPushStatus(result, { dest: remoteUrl, porcelain: true }),
631
646
  ...(trackingErrors.length ? { errors: trackingErrors } : {}),
@@ -645,7 +660,7 @@ export class PushCommand extends TransportCommand<PushResult> {
645
660
  exit: (code: number) => void,
646
661
  ): Promise<boolean> {
647
662
  const skipped = new Set(["rejected-nonfastforward", "rejected-stale", "up-to-date"]);
648
- const zero = "0".repeat(40);
663
+ const zero = this.objectFormat.nullId;
649
664
  const stdin = updates
650
665
  .filter((u) => !skipped.has(u.status))
651
666
  .map((u) => {
@@ -726,7 +741,7 @@ export class PushCommand extends TransportCommand<PushResult> {
726
741
 
727
742
  const store = RemoteConfigStore.from(this.workingCopy);
728
743
  if (store.isConfigured(this.remote)) {
729
- const configured = store.read(this.remote).pushRefspecs;
744
+ const configured = store.pushRefspecs(this.remote);
730
745
  if (configured.length > 0) return configured;
731
746
  }
732
747
  const mode = (store.value("push.default") ?? "simple").toLowerCase();
@@ -2,7 +2,7 @@
2
2
  * `git read-tree` (builtin/read-tree.c over unpack-trees.c): read trees into the index,
3
3
  * merging them with it (`-m`: one-, two- and three-way), optionally updating the worktree.
4
4
  */
5
- import { EMPTY_TREE_ID, FileMode, type ObjectId } from "@statewalker/vcs-core";
5
+ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
6
6
  import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
7
7
  import {
8
8
  attributesIndexOf,
@@ -294,8 +294,12 @@ export class ReadTreeCommand extends GitCommand<ReadTreeResult> {
294
294
  const entries = await this.entryList();
295
295
  const trees = this.trees;
296
296
  return repairCacheTree(
297
- { has: async (id: ObjectId) => id === EMPTY_TREE_ID || (await trees.has(id)) },
297
+ {
298
+ has: async (id: ObjectId) => id === this.objectFormat.emptyTreeId || (await trees.has(id)),
299
+ },
298
300
  entries,
301
+ // the repository's format: an empty index has no id to tell it (read-tree --empty)
302
+ this.objectFormat,
299
303
  );
300
304
  }
301
305
 
@@ -1,6 +1,5 @@
1
1
  import {
2
2
  type Commit,
3
- EMPTY_TREE_ID,
4
3
  isSymbolicRef,
5
4
  listObjectsWithPrefix,
6
5
  type ObjectId,
@@ -183,8 +182,6 @@ type PickOutcome =
183
182
  }
184
183
  | { kind: "reschedule"; result: RebaseResult & { reschedule?: boolean } };
185
184
 
186
- const ZERO_ID = "0000000000000000000000000000000000000000";
187
-
188
185
  /**
189
186
  * What a todo command came to: nothing (go on), `checkTodo` (go on, the list read again if
190
187
  * it changed), or a result that stops the rebase (`reschedule`: the command goes back).
@@ -1511,7 +1508,7 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
1511
1508
  // dropped (drop_redundant_commits), kept (keep_redundant_commits) or stops the rebase
1512
1509
  let allowEmpty = false;
1513
1510
  if (treeId === headTreeId) {
1514
- if (commit.tree === (parentTreeId ?? EMPTY_TREE_ID)) allowEmpty = true;
1511
+ if (commit.tree === (parentTreeId ?? this.objectFormat.emptyTreeId)) allowEmpty = true;
1515
1512
  else if (await state.exists(`${DIR}/keep_redundant_commits`)) allowEmpty = true;
1516
1513
  else if (await state.exists(`${DIR}/drop_redundant_commits`)) {
1517
1514
  await state.removeRef("AUTO_MERGE");
@@ -1533,7 +1530,7 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
1533
1530
  if (!allowEmpty && head.parents.length <= 1) {
1534
1531
  const parentTree = head.parents[0]
1535
1532
  ? await this.commits.getTree(head.parents[0])
1536
- : EMPTY_TREE_ID;
1533
+ : this.objectFormat.emptyTreeId;
1537
1534
  if (parentTree === treeId) {
1538
1535
  // do_commit: REBASE_HEAD written before git commit runs
1539
1536
  await state.setRef("REBASE_HEAD", item.id);
@@ -2404,7 +2401,7 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
2404
2401
  }
2405
2402
  if (buf === "") buf = `rev-${await this.abbreviateObjectId(oid)}`;
2406
2403
  if (
2407
- (buf.length === 40 && /^[0-9a-fA-F]{40}$/.test(buf)) ||
2404
+ (buf.length === this.objectFormat.hexLength && /^[0-9a-fA-F]+$/.test(buf)) ||
2408
2405
  buf === "#" ||
2409
2406
  labels.has(buf)
2410
2407
  ) {
@@ -2443,7 +2440,7 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
2443
2440
  if (!commit) throw new CommitNotFoundError(id);
2444
2441
  const parentTree = commit.parents[0]
2445
2442
  ? (await this.loadCommit(commit.parents[0]))?.tree
2446
- : EMPTY_TREE_ID;
2443
+ : this.objectFormat.emptyTreeId;
2447
2444
  const empty = commit.tree === parentTree;
2448
2445
  if (!empty && skipped.has(id)) continue;
2449
2446
  if (empty && !keepEmpty) continue;
@@ -3326,7 +3323,7 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
3326
3323
  if (!commit) return false;
3327
3324
  const parentTree = commit.parents[0]
3328
3325
  ? (await this.loadCommit(commit.parents[0]))?.tree
3329
- : EMPTY_TREE_ID;
3326
+ : this.objectFormat.emptyTreeId;
3330
3327
  return commit.tree === parentTree;
3331
3328
  }
3332
3329
 
@@ -3606,7 +3603,11 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
3606
3603
  } else {
3607
3604
  out.push({ action: RebaseAction.UPDATE_REF, id: "", rest: name, blankAfter: true });
3608
3605
  if (!records.some((r) => r.ref === name)) {
3609
- records.push({ ref: name, before: values.get(name) ?? ZERO_ID, after: ZERO_ID });
3606
+ records.push({
3607
+ ref: name,
3608
+ before: values.get(name) ?? this.objectFormat.nullId,
3609
+ after: this.objectFormat.nullId,
3610
+ });
3610
3611
  }
3611
3612
  }
3612
3613
  }
@@ -3626,14 +3627,18 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
3626
3627
  .map((item) => item.rest ?? "");
3627
3628
  let updated = false;
3628
3629
  const kept = records.filter((r) => {
3629
- const keep = r.after !== ZERO_ID || named.includes(r.ref);
3630
+ const keep = r.after !== this.objectFormat.nullId || named.includes(r.ref);
3630
3631
  if (!keep) updated = true;
3631
3632
  return keep;
3632
3633
  });
3633
3634
  for (const ref of named) {
3634
3635
  if (!kept.some((r) => r.ref === ref)) {
3635
3636
  const value = (await this.refsStore.resolve(ref).catch(() => undefined))?.objectId;
3636
- kept.push({ ref, before: value ?? ZERO_ID, after: ZERO_ID });
3637
+ kept.push({
3638
+ ref,
3639
+ before: value ?? this.objectFormat.nullId,
3640
+ after: this.objectFormat.nullId,
3641
+ });
3637
3642
  updated = true;
3638
3643
  }
3639
3644
  }
@@ -3663,7 +3668,10 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
3663
3668
  const failed: string[] = [];
3664
3669
  for (const record of records) {
3665
3670
  const value = (await this.refsStore.resolve(record.ref).catch(() => undefined))?.objectId;
3666
- if ((value ?? ZERO_ID) !== record.before || record.after === ZERO_ID) {
3671
+ if (
3672
+ (value ?? this.objectFormat.nullId) !== record.before ||
3673
+ record.after === this.objectFormat.nullId
3674
+ ) {
3667
3675
  failed.push(record.ref);
3668
3676
  continue;
3669
3677
  }
@@ -3849,7 +3857,10 @@ export class RebaseCommand extends GitCommand<RebaseResult> {
3849
3857
  const parentTree = commit.parents[0]
3850
3858
  ? (await this.loadCommit(commit.parents[0]))?.tree
3851
3859
  : undefined;
3852
- return patchId(trees, this.blobs, parentTree, commit.tree, { headerOnly });
3860
+ return patchId(trees, this.blobs, parentTree, commit.tree, {
3861
+ headerOnly,
3862
+ objectFormat: this.objectFormat,
3863
+ });
3853
3864
  };
3854
3865
  const full = new Map<ObjectId, string | undefined>();
3855
3866
  const fullOf = async (id: ObjectId) => {
@@ -9,6 +9,7 @@ import {
9
9
  } from "@statewalker/vcs-transport";
10
10
 
11
11
  import {
12
+ GitApiError,
12
13
  InvalidArgumentError,
13
14
  InvalidRemoteError,
14
15
  MissingArgumentError,
@@ -26,10 +27,9 @@ import {
26
27
  RemoteConfigStore,
27
28
  } from "../remote-config/index.js";
28
29
  import { TransportCommand } from "../transport-command.js";
30
+ import { removeLegacyRemoteFile } from "./legacy-remotes.js";
29
31
  import { withRemoteUploadPack } from "./remote-transport.js";
30
32
 
31
- const ZERO_ID = "0".repeat(40);
32
-
33
33
  export type { RemoteConfig };
34
34
 
35
35
  /**
@@ -349,15 +349,46 @@ export class RemoteRenameCommand extends GitCommand<RemoteRenameResult> {
349
349
  if (!newName) throw new MissingArgumentError("newName", "New remote name must be specified");
350
350
 
351
351
  const store = RemoteConfigStore.from(this.workingCopy);
352
+ // remote_get: a remote missing from the configuration may be read from .git/remotes/ or
353
+ // .git/branches/ (git 2.x; 2.5x warns), and counts as configured
354
+ const warnings: string[] = (await this.loadLegacyRemote(oldName))
355
+ .filter((m) => m.startsWith("warning: "))
356
+ .map((m) => m.slice("warning: ".length));
352
357
  if (!store.isConfigured(oldName)) {
353
358
  throw new RemoteNotFoundError(oldName, `No such remote: '${oldName}'`);
354
359
  }
360
+ const legacyOrigin = store.legacyOrigin(oldName);
361
+ if (oldName === newName && legacyOrigin) {
362
+ // migrate_file: the remote as read goes into the configuration, the file goes away
363
+ // read whole before writing: once it has a URL, the configuration hides the file
364
+ const urls = store.remoteUrls(oldName);
365
+ const push = store.pushRefspecs(oldName);
366
+ const fetch = store.configuredFetchRefspecs(oldName);
367
+ for (const url of urls) store.addValue(`remote.${oldName}.url`, url);
368
+ for (const spec of push) store.addValue(`remote.${oldName}.push`, spec);
369
+ for (const spec of fetch) store.addValue(`remote.${oldName}.fetch`, spec);
370
+ await store.save();
371
+ await removeLegacyRemoteFile(this.workingCopy, legacyOrigin, oldName);
372
+ return { remote: store.read(oldName), warnings };
373
+ }
374
+ if (oldName !== newName) {
375
+ for (const m of await this.loadLegacyRemote(newName)) {
376
+ if (m.startsWith("warning: ")) warnings.push(m.slice("warning: ".length));
377
+ }
378
+ }
355
379
  if (store.isConfigured(newName)) {
356
380
  throw new RemoteAlreadyExistsError(newName, `remote ${newName} already exists.`);
357
381
  }
358
382
  if (!isValidRemoteName(newName)) {
359
383
  throw new InvalidArgumentError("newName", newName, `'${newName}' is not a valid remote name`);
360
384
  }
385
+ // git_config_rename_section finds no section to rename for a remote read from a file
386
+ if (!store.hasSection(oldName)) {
387
+ throw new GitApiError(
388
+ `Could not rename config section 'remote.${oldName}' to 'remote.${newName}'`,
389
+ { exitCode: 1 },
390
+ );
391
+ }
361
392
 
362
393
  const fetch = store.configuredFetchRefspecs(oldName);
363
394
  const oldContext = `:refs/remotes/${oldName}/`;
@@ -387,8 +418,8 @@ export class RemoteRenameCommand extends GitCommand<RemoteRenameResult> {
387
418
  });
388
419
  }
389
420
  reflog.push({
390
- oldId: id ?? ZERO_ID,
391
- newId: id ?? ZERO_ID,
421
+ oldId: id ?? this.objectFormat.nullId,
422
+ newId: id ?? this.objectFormat.nullId,
392
423
  ...(renameLine.ident !== undefined ? { ident: renameLine.ident } : {}),
393
424
  message: `remote: renamed ${ref.name} to ${to}`,
394
425
  });
@@ -401,7 +432,6 @@ export class RemoteRenameCommand extends GitCommand<RemoteRenameResult> {
401
432
  }
402
433
 
403
434
  store.rename(oldName, newName);
404
- const warnings: string[] = [];
405
435
  if (fetch.length > 0) {
406
436
  const rewritten = fetch.map((spec) => {
407
437
  const at = spec.indexOf(oldContext);
@@ -1,11 +1,4 @@
1
- import {
2
- type Blobs,
3
- EMPTY_BLOB_ID,
4
- EMPTY_TREE_ID,
5
- FileMode,
6
- type ObjectId,
7
- type Ref,
8
- } from "@statewalker/vcs-core";
1
+ import { type Blobs, FileMode, type ObjectId, type Ref } from "@statewalker/vcs-core";
9
2
  import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
10
3
  import {
11
4
  applyStatUpdate,
@@ -184,8 +177,8 @@ export class ResetCommand extends GitCommand<Ref> {
184
177
  }
185
178
  const rev = this.ref === undefined || this.ref === "@" ? "HEAD" : this.ref;
186
179
  const head = await this.refsStore.resolve("HEAD");
187
- const diffRevision = rev === "HEAD" && !head?.objectId ? EMPTY_TREE_ID : rev;
188
- if (diffRevision !== EMPTY_TREE_ID) await this.resolveRef(rev);
180
+ const diffRevision = rev === "HEAD" && !head?.objectId ? this.objectFormat.emptyTreeId : rev;
181
+ if (diffRevision !== this.objectFormat.emptyTreeId) await this.resolveRef(rev);
189
182
  this.patchResult = await runPatchSelection(this.workingCopy, {
190
183
  hookSource: this,
191
184
  ...this.patchOptions,
@@ -729,7 +722,7 @@ export class ResetCommand extends GitCommand<Ref> {
729
722
  path,
730
723
  // make_cache_entry of a path the tree lacks: create_ce_mode(0), a regular file
731
724
  mode: t ? t.mode : FileMode.REGULAR_FILE,
732
- objectId: t ? t.objectId : EMPTY_BLOB_ID,
725
+ objectId: t ? t.objectId : this.objectFormat.emptyBlobId,
733
726
  stage: 0,
734
727
  size: 0,
735
728
  mtime: 0,