@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
@@ -12,6 +12,10 @@
12
12
  * // without --verify: ranges and set notation, one line per object as git prints them
13
13
  * const { lines } = await git.revParse().addArgument("main..feat").addArgument("v1^!").call();
14
14
  * // lines: ["<feat>", "^<main>", "<v1's commit>", "^<its parent>"]
15
+ *
16
+ * // the repository's hash
17
+ * const { lines: [format] } = await git.revParse().addArgument("--show-object-format").call();
18
+ * // format: "sha1", or "sha256"
15
19
  * ```
16
20
  */
17
21
 
@@ -70,6 +74,14 @@ export class RevParseCommand extends GitCommand<RevParseResult> {
70
74
  return this;
71
75
  }
72
76
 
77
+ /**
78
+ * `git rev-parse --show-object-format`: the repository's object format (`sha1`, `sha256`),
79
+ * as the result's `lines` give it with `addArgument("--show-object-format")`.
80
+ */
81
+ showObjectFormat(): string {
82
+ return this.objectFormat.name;
83
+ }
84
+
73
85
  /** The revision to resolve (`HEAD~2`, `@{u}`, `main@{yesterday}`, `:/fix`, `HEAD:a.txt`). */
74
86
  setRevision(revision: string): this {
75
87
  this.checkCallable();
@@ -142,6 +154,16 @@ export class RevParseCommand extends GitCommand<RevParseResult> {
142
154
  lines.push(arg);
143
155
  continue;
144
156
  }
157
+ // --show-object-format[=storage|input|output]: the repository's hash (all three agree
158
+ // without a compatibility format)
159
+ if (arg === "--show-object-format" || arg.startsWith("--show-object-format=")) {
160
+ const mode = arg.slice("--show-object-format=".length);
161
+ if (arg.includes("=") && mode !== "storage" && mode !== "input" && mode !== "output") {
162
+ throw new RevisionError(arg, `fatal: unknown mode for --show-object-format: ${mode}`);
163
+ }
164
+ lines.push(this.objectFormat.name);
165
+ continue;
166
+ }
145
167
  if (await this.tryDifference(resolver, arg, lines)) continue;
146
168
  if (await this.tryParentShorthands(resolver, arg, lines)) continue;
147
169
  const reversed = arg.startsWith("^");
@@ -37,8 +37,9 @@ import {
37
37
  isValidRefName,
38
38
  listObjectsWithPrefix,
39
39
  MINIMUM_ABBREV_LENGTH,
40
+ objectFormatOf,
40
41
  } from "@statewalker/vcs-core";
41
- import { compilePosixRegex, parseGitBool } from "@statewalker/vcs-utils";
42
+ import { compilePosixRegex, isNullObjectId, parseGitBool } from "@statewalker/vcs-utils";
42
43
  import type { Staging, WorkingCopy } from "@statewalker/vcs-working-tree";
43
44
 
44
45
  import { RevisionError } from "../errors/index.js";
@@ -46,6 +47,7 @@ import { RemoteConfigStore } from "../remote-config/index.js";
46
47
  import { applyRefspecs } from "./branch-tracking.js";
47
48
  import { configLoadError } from "./core-config.js";
48
49
  import { approxidateCareful, formatRfc2822Date } from "./git-date.js";
50
+ import { loadLegacyRemote } from "./legacy-remotes.js";
49
51
 
50
52
  /** The stores a revision is read from. */
51
53
  export interface RevisionSources {
@@ -69,7 +71,7 @@ export interface RevisionSources {
69
71
  * The object store, for abbreviated ids (its `listPrefix`, else `list`); without it the
70
72
  * typed stores' `keys()` are listed
71
73
  */
72
- objects?: Pick<GitObjects, "list" | "listPrefix">;
74
+ objects?: Pick<GitObjects, "list" | "listPrefix" | "objectFormat">;
73
75
  /**
74
76
  * The lengths git abbreviates ids to (`repo_find_unique_abbrev` with `core.abbrev`), for
75
77
  * the candidates of an ambiguous short id; 7 digits without it
@@ -123,8 +125,7 @@ type ShortOid =
123
125
  const HEX_DIGIT = /^[0-9a-fA-F]$/;
124
126
  const isHexDigit = (c: string | undefined) => c !== undefined && HEX_DIGIT.test(c);
125
127
 
126
- const ZERO_ID = "0000000000000000000000000000000000000000";
127
- const HEX_ID = /^[0-9a-fA-F]{40}$/;
128
+ const HEX_DIGITS = /^[0-9a-fA-F]+$/;
128
129
 
129
130
  /** git's `object_name_msg` advice after a 40-hex name that is also a ref. */
130
131
  const OBJECT_NAME_ADVICE = [
@@ -193,7 +194,17 @@ export class RevisionResolver {
193
194
  constructor(
194
195
  private readonly sources: RevisionSources,
195
196
  private readonly now: () => number = () => Math.floor(Date.now() / 1000),
196
- ) {}
197
+ ) {
198
+ this.hexLength = objectFormatOf(sources.objects).hexLength;
199
+ }
200
+
201
+ /** The repository's full hex id length: 40, or 64 in a SHA-256 repository (git's hexsz) */
202
+ private readonly hexLength: number;
203
+
204
+ /** Whether `str` is a full hex object id of the repository's format, in any case */
205
+ private isFullHex(str: string): boolean {
206
+ return str.length === this.hexLength && HEX_DIGITS.test(str);
207
+ }
197
208
 
198
209
  /**
199
210
  * The object `name` names, or undefined when it names none (git's `unknown revision`).
@@ -280,6 +291,8 @@ export class RevisionResolver {
280
291
  throw this.fatal(revision, `no upstream configured for branch '${name}'`);
281
292
  }
282
293
  const src = merges[0] ?? "";
294
+ // set_merge: remote_get reads a legacy remote (.git/remotes/, .git/branches/: git 2.x)
295
+ await loadLegacyRemote(this.sources.workingCopy, remote);
283
296
  let dst = applyRefspecs(config.configuredFetchRefspecs(remote), src);
284
297
  if (dst === undefined && remote === ".") {
285
298
  const found = await this.dwimRefAll(src, false);
@@ -319,6 +332,7 @@ export class RevisionResolver {
319
332
  const config = this.remoteConfig();
320
333
  const refname = `refs/heads/${name}`;
321
334
  const remote = this.pushRemoteOf(name);
335
+ await loadLegacyRemote(this.sources.workingCopy, remote);
322
336
  const trackingFor = (dst: string) => {
323
337
  const tracking = applyRefspecs(config.configuredFetchRefspecs(remote), dst);
324
338
  if (tracking === undefined) {
@@ -329,7 +343,7 @@ export class RevisionResolver {
329
343
  }
330
344
  return tracking;
331
345
  };
332
- const pushSpecs = config.values(`remote.${remote}.push`);
346
+ const pushSpecs = config.pushRefspecs(remote);
333
347
  if (pushSpecs.length > 0) {
334
348
  const dst = applyRefspecs(pushSpecs, refname);
335
349
  if (dst === undefined) {
@@ -456,7 +470,7 @@ export class RevisionResolver {
456
470
  * object or not), a ref, `<ref>@{<n>|<date>}`, `@{-N}`.
457
471
  */
458
472
  private async basic(str: string, flags: ResolveOptions = {}): Promise<ObjectId | undefined> {
459
- if (HEX_ID.test(str)) {
473
+ if (this.isFullHex(str)) {
460
474
  // warn_on_object_refname_ambiguity: a ref spelled as the 40-hex
461
475
  if (this.warnAmbiguousRefs() && (await this.dwimRefAll(str)).length > 0) {
462
476
  this.warnings.push(`warning: refname '${str}' is ambiguous.`);
@@ -492,7 +506,7 @@ export class RevisionResolver {
492
506
 
493
507
  if (nthPrior) {
494
508
  const prior = await this.nthPriorCheckout(base);
495
- if (typeof prior === "object" && HEX_ID.test(prior.value)) {
509
+ if (typeof prior === "object" && this.isFullHex(prior.value)) {
496
510
  return (await this.objectType(prior.value.toLowerCase()))
497
511
  ? prior.value.toLowerCase()
498
512
  : undefined;
@@ -539,7 +553,7 @@ export class RevisionResolver {
539
553
  `warning: log for '${shown}' only goes back to ${formatRfc2822Date(read.cutoffTime, read.cutoffTz)}`,
540
554
  );
541
555
  }
542
- } else if (!(nth === read.cutoffCount && read.id !== ZERO_ID)) {
556
+ } else if (!(nth === read.cutoffCount && !isNullObjectId(read.id))) {
543
557
  throw this.fatal(str, `log for '${shown}' only has ${read.cutoffCount} entries`);
544
558
  }
545
559
  }
@@ -565,14 +579,14 @@ export class RevisionResolver {
565
579
  const log = await this.sources.refs.getReflog?.(ref);
566
580
  const entries = log ? await log.getReverseEntries() : [];
567
581
  let cnt = nth;
568
- let ooid = ZERO_ID;
582
+ let ooid: ObjectId | undefined;
569
583
  let reccnt = 0;
570
584
  let id = current;
571
585
  for (const entry of entries) {
572
586
  const timestamp = entry.who.timestamp;
573
587
  if (timestamp <= atTime || cnt === 0) {
574
588
  const date = formatRfc2822Date(timestamp, entry.who.tzOffset);
575
- if (ooid !== ZERO_ID) {
589
+ if (ooid !== undefined && !isNullObjectId(ooid)) {
576
590
  id = entry.newId;
577
591
  if (ooid !== entry.newId) {
578
592
  this.warnings.push(`warning: log for ref ${ref} has gap after ${date}`);
@@ -603,7 +617,7 @@ export class RevisionResolver {
603
617
  const oldest = entries[entries.length - 1];
604
618
  if (!oldest) throw this.fatal(ref, `log for ${ref} is empty`);
605
619
  id = oldest.oldId;
606
- if (atTime && id === ZERO_ID) id = oldest.newId;
620
+ if (atTime && isNullObjectId(id)) id = oldest.newId;
607
621
  return {
608
622
  id,
609
623
  missing: true,
@@ -998,7 +1012,7 @@ export class RevisionResolver {
998
1012
  // ------------------------------------------------------------------ short ids
999
1013
 
1000
1014
  /**
1001
- * git's `get_short_oid`: the one stored object whose id starts with `name` (4 to 40 hex
1015
+ * git's `get_short_oid`: the one stored object whose id starts with `name` (4 to 40 hex, 64 in a SHA-256 repository,
1002
1016
  * digits, any case). Of several, the one the hint (`flags.hint`, else `core.disambiguate`)
1003
1017
  * accepts, when it accepts exactly one. An ambiguity is reported, unless quiet, as git
1004
1018
  * reports it: `error: short object ID <prefix> is ambiguous` and `hint:` lines listing the
@@ -1006,7 +1020,11 @@ export class RevisionResolver {
1006
1020
  * when it accepts several.
1007
1021
  */
1008
1022
  private async shortOid(name: string, flags: ResolveOptions = {}): Promise<ShortOid> {
1009
- if (name.length < MINIMUM_ABBREV_LENGTH || name.length > 40 || !/^[0-9a-fA-F]+$/.test(name)) {
1023
+ if (
1024
+ name.length < MINIMUM_ABBREV_LENGTH ||
1025
+ name.length > this.hexLength ||
1026
+ !HEX_DIGITS.test(name)
1027
+ ) {
1010
1028
  return { status: "invalid" };
1011
1029
  }
1012
1030
  const prefix = name.toLowerCase();
@@ -6,7 +6,12 @@
6
6
  * `--continue`, `--skip` or `--abort` what we started and the other way round.
7
7
  */
8
8
 
9
- import type { Commit, ObjectId, PersonIdent } from "@statewalker/vcs-core";
9
+ import {
10
+ type Commit,
11
+ type ObjectId,
12
+ objectFormatOf,
13
+ type PersonIdent,
14
+ } from "@statewalker/vcs-core";
10
15
  import { compareGitPaths, parseGitBool } from "@statewalker/vcs-utils/encoding";
11
16
  import type { Worktree } from "@statewalker/vcs-working-tree";
12
17
  import { GitApiError } from "../errors/git-api-error.js";
@@ -255,7 +260,7 @@ export class PickSequencer {
255
260
  // with --no-commit the change is merged into the index as it is (git's
256
261
  // write_index_as_tree): each commit's change on top of the previous one's
257
262
  const headTreeId = this.options.noCommit
258
- ? await writeIndexAsTree(deps.staging, deps.trees)
263
+ ? await writeIndexAsTree(deps.staging, deps.trees, objectFormatOf(deps.workingCopy.history))
259
264
  : headCommit.tree;
260
265
  // a commit is never made on top of staged changes (error_dirty_index)
261
266
  const { index } = await readIndex(deps.staging);
@@ -8,6 +8,7 @@ import {
8
8
  FileMode,
9
9
  formatPersonIdent,
10
10
  type ObjectId,
11
+ objectFormatOf,
11
12
  type PersonIdent,
12
13
  type RefLogOptions,
13
14
  } from "@statewalker/vcs-core";
@@ -297,7 +298,9 @@ async function resetMergeWith(
297
298
  }
298
299
  // unpack-trees writes a new index: no resolve-undo record survives the reset
299
300
  ctx.staging.clearResolveUndo?.();
300
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
301
+ await rewriteIndex(ctx.staging, edits, {
302
+ updateCacheTreeWith: { trees: ctx.trees, format: objectFormatOf(ctx.workingCopy.history) },
303
+ });
301
304
  return { written: worktree ? writing : new Set() };
302
305
  }
303
306
 
@@ -360,7 +363,9 @@ export async function resetUnmergedToHead(
360
363
  ]);
361
364
  }
362
365
  ctx.staging.clearResolveUndo?.();
363
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
366
+ await rewriteIndex(ctx.staging, edits, {
367
+ updateCacheTreeWith: { trees: ctx.trees, format: objectFormatOf(ctx.workingCopy.history) },
368
+ });
364
369
  }
365
370
 
366
371
  /**
@@ -519,7 +524,9 @@ async function resetKeepWith(
519
524
  ]);
520
525
  }
521
526
  ctx.staging.clearResolveUndo?.();
522
- await rewriteIndex(ctx.staging, edits, { updateCacheTreeWith: ctx.trees });
527
+ await rewriteIndex(ctx.staging, edits, {
528
+ updateCacheTreeWith: { trees: ctx.trees, format: objectFormatOf(ctx.workingCopy.history) },
529
+ });
523
530
  return { written: worktree ? writing : new Set() };
524
531
  }
525
532
 
@@ -605,7 +605,7 @@ export class StashApplyCommand extends GitCommand<StashApplyResult> {
605
605
  await editor.finish();
606
606
  // reset_tree's unpack-trees ends with cache_tree_update: the invalid directories
607
607
  // computed from the index (fully valid)
608
- await updateIndexCacheTree(this.staging, this.trees);
608
+ await updateIndexCacheTree(this.staging, this.trees, this.objectFormat);
609
609
  } else {
610
610
  // the index keeps its entries, plus the files the stash adds (git stages them)
611
611
  const added = new Set<string>();
@@ -1,4 +1,4 @@
1
- import { EMPTY_TREE_ID, type ObjectId, type PersonIdent } from "@statewalker/vcs-core";
1
+ import type { ObjectId, PersonIdent } from "@statewalker/vcs-core";
2
2
  import { flattenTree, type Staging } from "@statewalker/vcs-working-tree";
3
3
 
4
4
  import {
@@ -860,7 +860,7 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
860
860
  // of the reset index or of the index tree, else nothing is checked out
861
861
  let keepIndex = this.keepIndex;
862
862
  let checkoutErrors: string[] = [];
863
- if (keepIndex && indexTree !== EMPTY_TREE_ID) {
863
+ if (keepIndex && indexTree !== this.objectFormat.emptyTreeId) {
864
864
  const seen = items.map(() => 0);
865
865
  const mark = (path: string, mode: number) =>
866
866
  matchPathspecSeen(items, path, mode === 0o160000 ? DO_MATCH_DIRECTORY : 0, seen);
@@ -711,7 +711,7 @@ export class StatusCommand extends GitCommand<Status> {
711
711
  }
712
712
  const cached = new DiffCommand(this.workingCopy)
713
713
  .setCached(true)
714
- .setOldTree(o.referenceId ?? EMPTY_TREE)
714
+ .setOldTree(o.referenceId ?? this.objectFormat.emptyTreeId)
715
715
  .setOptions({ ...(cachedPrefixes ?? {}) });
716
716
  if (this.renames !== undefined) cached.setRenames(this.renames);
717
717
  out += await cached.callText("patch");
@@ -998,6 +998,7 @@ export class StatusCommand extends GitCommand<Status> {
998
998
  this.config,
999
999
  hostEnvironmentOf(this.workingCopy),
1000
1000
  host,
1001
+ this.objectFormat,
1001
1002
  );
1002
1003
  if (worktree && this.resolvedUntracked !== "no") {
1003
1004
  // git's wt_status_collect_untracked: the dir flags of the modes
@@ -1454,9 +1455,6 @@ function cfgBool(config: RemoteConfigStore, key: string, fallback: boolean): boo
1454
1455
  return value === undefined ? fallback : (parseGitBool(value) ?? fallback);
1455
1456
  }
1456
1457
 
1457
- /** git's empty tree, the side compared with before the first commit. */
1458
- const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
1459
-
1460
1458
  /** The comment-line string of status's commented lines. */
1461
1459
  function commentLineString(workingCopy: WorkingCopy): string {
1462
1460
  return commentPrefixOf(workingCopy);
@@ -112,7 +112,9 @@ async function getBranch(source: StatusHeaderSource, name: string): Promise<stri
112
112
  if (!value) return undefined;
113
113
  if (value.startsWith("refs/heads/")) return value.slice("refs/heads/".length);
114
114
  if (value.startsWith("refs/")) return value;
115
- if (/^[0-9a-fA-F]{40}/.test(value)) return source.abbreviate(value.slice(0, 40).toLowerCase());
115
+ // a SHA-256 id (64 hex digits), else a SHA-1 one
116
+ const hex = /^[0-9a-fA-F]{64}/.test(value) ? 64 : /^[0-9a-fA-F]{40}/.test(value) ? 40 : 0;
117
+ if (hex) return source.abbreviate(value.slice(0, hex).toLowerCase());
116
118
  if (value === "detached HEAD") return undefined;
117
119
  return value;
118
120
  }
@@ -1,4 +1,4 @@
1
- import { EMPTY_TREE_ID, type ObjectId } from "@statewalker/vcs-core";
1
+ import type { ObjectId } from "@statewalker/vcs-core";
2
2
 
3
3
  import { IncompatibleOptionsError, RevisionError } from "../errors/index.js";
4
4
  import { GitCommand } from "../git-command.js";
@@ -6,7 +6,6 @@ import { RemoteConfigStore } from "../remote-config/index.js";
6
6
  import { ChangeType, type DiffEntry } from "../results/diff-entry.js";
7
7
  import { DiffCommand } from "./diff-command.js";
8
8
  import {
9
- NULL_OBJECT_ID,
10
9
  openSubmoduleRepository,
11
10
  readGitmodulesEntries,
12
11
  type SubmoduleRepository,
@@ -117,7 +116,7 @@ export class SubmoduleSummaryCommand extends GitCommand<string> {
117
116
  if (resolved !== undefined) head = resolved;
118
117
  else if (first === "HEAD") {
119
118
  // before the first commit: compare with an empty tree
120
- head = EMPTY_TREE_ID;
119
+ head = this.objectFormat.emptyTreeId;
121
120
  } else {
122
121
  paths.unshift(first);
123
122
  const fallback = await this.resolveTree("HEAD");
@@ -194,8 +193,8 @@ export class SubmoduleSummaryCommand extends GitCommand<string> {
194
193
  out.push({
195
194
  modSrc,
196
195
  modDst,
197
- oidSrc: modSrc ? (e.oldId ?? NULL_OBJECT_ID) : NULL_OBJECT_ID,
198
- oidDst: modDst ? (e.newId ?? NULL_OBJECT_ID) : NULL_OBJECT_ID,
196
+ oidSrc: modSrc ? (e.oldId ?? this.objectFormat.nullId) : this.objectFormat.nullId,
197
+ oidDst: modDst ? (e.newId ?? this.objectFormat.nullId) : this.objectFormat.nullId,
199
198
  status,
200
199
  path: (e.oldPath ?? e.newPath) as string,
201
200
  });
@@ -254,9 +253,9 @@ export class SubmoduleSummaryCommand extends GitCommand<string> {
254
253
  /** generate_submodule_summary and print_submodule_summary for one submodule. */
255
254
  private async generate(p: ModuleChange): Promise<string> {
256
255
  const worktree = this.worktreeAccess;
257
- if (!this.cached && p.oidDst === NULL_OBJECT_ID && isGitlink(p.modDst)) {
256
+ if (!this.cached && p.oidDst === this.objectFormat.nullId && isGitlink(p.modDst)) {
258
257
  const sub = await openSubmoduleRepository(this.workingCopy, p.path);
259
- if (sub?.populated) p.oidDst = (await sub.head()) ?? NULL_OBJECT_ID;
258
+ if (sub?.populated) p.oidDst = (await sub.head()) ?? this.objectFormat.nullId;
260
259
  }
261
260
  const repo = worktree ? await this.repositoryAt(p.path) : undefined;
262
261
  let missingSrc = false;
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { parseGitBool } from "@statewalker/vcs-utils";
16
+ import { type ObjectFormat, SHA1_OBJECT_FORMAT } from "@statewalker/vcs-utils/hash";
16
17
  import {
17
18
  DIR_HIDE_EMPTY_DIRECTORIES,
18
19
  DIR_SHOW_OTHER_DIRECTORIES,
@@ -20,7 +21,6 @@ import {
20
21
  expandUserPath,
21
22
  type GitHostEnvironment,
22
23
  invalidateGitignore,
23
- NULL_OID,
24
24
  newUntrackedCache,
25
25
  newUntrackedCacheDir,
26
26
  type OidStat,
@@ -93,6 +93,7 @@ export function openUntrackedCache(
93
93
  config: UntrackedCacheConfig,
94
94
  environment: GitHostEnvironment | undefined,
95
95
  host: UntrackedScanHost | undefined,
96
+ objectFormat: ObjectFormat = SHA1_OBJECT_FORMAT,
96
97
  ): UntrackedCacheState {
97
98
  const supported = typeof staging.getUntrackedCache === "function";
98
99
  let cache = supported ? staging.getUntrackedCache?.() : undefined;
@@ -108,7 +109,7 @@ export function openUntrackedCache(
108
109
  changed = true;
109
110
  } else if (supported && setting === "write" && ident) {
110
111
  if (!cache || !untrackedCacheIdentIs(cache, ident)) {
111
- cache = newUntrackedCache(ident, newUntrackedCacheFlags(config));
112
+ cache = newUntrackedCache(ident, newUntrackedCacheFlags(config), objectFormat);
112
113
  changed = true;
113
114
  }
114
115
  }
@@ -127,17 +128,17 @@ export function openUntrackedCache(
127
128
  // configured mode's, else kept for the scans of that mode and not used here
128
129
  if (cache.dirFlags !== flags) {
129
130
  if (cache.dirFlags === newUntrackedCacheFlags(config)) return undefined;
130
- cache = newUntrackedCache(ident, flags);
131
+ cache = newUntrackedCache(ident, flags, objectFormat);
131
132
  changed = true;
132
133
  }
133
134
  if (!cache.root) {
134
135
  // a cache not yet initialized gets its root
135
- cache.root = newUntrackedCacheDir("");
136
+ cache.root = newUntrackedCacheDir("", objectFormat.nullId);
136
137
  changed = true;
137
138
  }
138
139
  // $GIT_DIR/info/exclude and core.excludesFile: another id invalidates everything
139
- const info = await readExcludeFile(await host.readInfoExclude?.());
140
- const excludes = await readExcludesFile(config, environment);
140
+ const info = await readExcludeFile(await host.readInfoExclude?.(), objectFormat);
141
+ const excludes = await readExcludesFile(config, environment, objectFormat);
141
142
  if (info.oid !== cache.infoExclude.oid) {
142
143
  invalidateGitignore(cache, cache.root);
143
144
  cache.infoExclude = info;
@@ -164,9 +165,10 @@ export function openUntrackedCache(
164
165
  /** An exclude file's id and stat as git's `add_patterns` records them (no istate). */
165
166
  async function readExcludeFile(
166
167
  read: { bytes: Uint8Array; stat: import("@statewalker/vcs-utils/files").LinkStats } | undefined,
168
+ objectFormat: ObjectFormat,
167
169
  ): Promise<OidStat> {
168
- if (!read) return { stat: zeroStatData(), oid: NULL_OID };
169
- return { stat: statDataOf(read.stat), oid: await excludeFileOid(read.bytes) };
170
+ if (!read) return { stat: zeroStatData(), oid: objectFormat.nullId };
171
+ return { stat: statDataOf(read.stat), oid: await excludeFileOid(read.bytes, objectFormat) };
170
172
  }
171
173
 
172
174
  /**
@@ -176,19 +178,21 @@ async function readExcludeFile(
176
178
  async function readExcludesFile(
177
179
  config: UntrackedCacheConfig,
178
180
  environment: GitHostEnvironment | undefined,
181
+ objectFormat: ObjectFormat,
179
182
  ): Promise<OidStat> {
180
- if (!environment) return { stat: zeroStatData(), oid: NULL_OID };
183
+ const none = { stat: zeroStatData(), oid: objectFormat.nullId };
184
+ if (!environment) return none;
181
185
  const configured = config.value("core.excludesFile");
182
186
  const path =
183
187
  configured !== undefined && configured !== ""
184
188
  ? expandUserPath(configured, environment)
185
189
  : xdgConfigPath(environment, "ignore");
186
- if (!path) return { stat: zeroStatData(), oid: NULL_OID };
190
+ if (!path) return none;
187
191
  const bytes = await environment.readFile(path).catch(() => undefined);
188
- if (!bytes) return { stat: zeroStatData(), oid: NULL_OID };
192
+ if (!bytes) return none;
189
193
  const stat = await environment.statFile?.(path).catch(() => undefined);
190
194
  return {
191
195
  stat: stat ? statDataOf(stat) : zeroStatData(),
192
- oid: await excludeFileOid(bytes),
196
+ oid: await excludeFileOid(bytes, objectFormat),
193
197
  };
194
198
  }
@@ -9,8 +9,6 @@ import { quotePath } from "../results/quote-path.js";
9
9
  import { abbrevLengths } from "./core-config.js";
10
10
  import { parseExpiry, requireWorktrees, type WorktreeExpiry } from "./worktree-support.js";
11
11
 
12
- const ZERO_ID = "0000000000000000000000000000000000000000";
13
-
14
12
  /** A worktree as `git worktree list` shows it. */
15
13
  export interface WorktreeListEntry extends WorktreeInfo {
16
14
  /** Why it can be pruned (`should_prune_worktree` with `--expire`), when it can. */
@@ -126,7 +124,7 @@ export class WorktreeListCommand extends GitCommand<WorktreeListResult> {
126
124
  let out = `worktree ${wt.path}${lt}`;
127
125
  if (wt.bare) out += `bare${lt}`;
128
126
  else {
129
- out += `HEAD ${wt.head ?? ZERO_ID}${lt}`;
127
+ out += `HEAD ${wt.head ?? this.objectFormat.nullId}${lt}`;
130
128
  if (wt.detached) out += `detached${lt}`;
131
129
  else if (wt.headRef) out += `branch ${wt.headRef}${lt}`;
132
130
  }
@@ -146,7 +144,7 @@ export class WorktreeListCommand extends GitCommand<WorktreeListResult> {
146
144
  /** git's `measure_widths` and `show_worktree`. */
147
145
  private async lines(entries: WorktreeListEntry[]): Promise<string> {
148
146
  const verbose = this.format === "verbose";
149
- const ids = entries.map((wt) => wt.head ?? ZERO_ID);
147
+ const ids = entries.map((wt) => wt.head ?? this.objectFormat.nullId);
150
148
  const lengths = await abbrevLengths(this.workingCopy, ids);
151
149
  const abbrevLen = Math.max(...ids.map((id) => lengths.get(id) ?? 7));
152
150
  const fully = this.quotePathFully();
@@ -161,7 +159,7 @@ export class WorktreeListCommand extends GitCommand<WorktreeListResult> {
161
159
  let line = `${display[i]}${" ".repeat(pad + maxWidth - width(display[i]))}`;
162
160
  if (wt.bare) line += "(bare)";
163
161
  else {
164
- const id = wt.head ?? ZERO_ID;
162
+ const id = wt.head ?? this.objectFormat.nullId;
165
163
  line += `${id.slice(0, lengths.get(id) ?? 7).padEnd(abbrevLen)} `;
166
164
  if (wt.detached) line += "(detached HEAD)";
167
165
  else if (wt.headRef) line += `[${await shortenUnambiguousRef(this.refsStore, wt.headRef)}]`;
@@ -217,7 +217,7 @@ export class AddCommand implements Add {
217
217
  // or all-zero id, which a worktree hash could be compared against)
218
218
  new UpdateStagingEntry(
219
219
  file.path,
220
- EMPTY_BLOB_ID,
220
+ this.blobs.objectFormat?.emptyBlobId ?? EMPTY_BLOB_ID,
221
221
  mode,
222
222
  { size: 0, mtime: Date.now() },
223
223
  { intentToAdd: true },
@@ -29,9 +29,10 @@ import {
29
29
  isSymbolicRef,
30
30
  type LoadedObjectReplacements,
31
31
  loadObjectReplacements,
32
+ objectFormatOf,
32
33
  overlayMethods,
33
34
  } from "@statewalker/vcs-core";
34
- import { OrderedMap, parseGitBool } from "@statewalker/vcs-utils";
35
+ import { type ObjectFormat, OrderedMap, parseGitBool } from "@statewalker/vcs-utils";
35
36
  import {
36
37
  type AttributesSourceResolver,
37
38
  basicStatMatches,
@@ -45,6 +46,7 @@ import {
45
46
  type Worktree,
46
47
  } from "@statewalker/vcs-working-tree";
47
48
  import { attributesSourceResolver } from "./commands/attributes-source.js";
49
+ import { checkAutoCommentChar } from "./commands/comment-char-config.js";
48
50
  import {
49
51
  configLoadError,
50
52
  createIdAbbreviator,
@@ -61,6 +63,7 @@ import {
61
63
  withoutCrud,
62
64
  } from "./commands/git-ident.js";
63
65
  import { indexHostOf, indexVersionConfigError } from "./commands/index-host.js";
66
+ import { loadLegacyRemote } from "./commands/legacy-remotes.js";
64
67
  import type { NotesContext } from "./commands/notes-support.js";
65
68
  import { postIndexChangeHookOf } from "./commands/post-index-change.js";
66
69
  import { createPromisorFetcher, promisorOf } from "./commands/promisor-remote.js";
@@ -437,6 +440,17 @@ export abstract class GitCommand<T> {
437
440
  return this.hookSession;
438
441
  }
439
442
 
443
+ /**
444
+ * Reads the legacy remote `name` (`$GIT_COMMON_DIR/remotes/<name>`, then `branches/<name>`)
445
+ * as git 2.x's `remote_get` does before it looks the remote up, so this working copy's
446
+ * `RemoteConfigStore`s see it (see `loadLegacyRemote`); nothing under git 3.0.
447
+ *
448
+ * @returns what git prints on stderr reading them, for this command's compatibility
449
+ */
450
+ protected async loadLegacyRemote(name: string): Promise<string[]> {
451
+ return (await loadLegacyRemote(this._workingCopy, name, this.hooks.compatibility)).messages;
452
+ }
453
+
440
454
  /**
441
455
  * Runs this command's hooks in another command's session: a command that runs another
442
456
  * (merge committing, rebase picking) gathers the output of both in one place. With `env`,
@@ -553,11 +567,12 @@ export abstract class GitCommand<T> {
553
567
  author: () => this.resolveAuthor(),
554
568
  committer: () => this.resolveCommitter(),
555
569
  reflogLine: (message) => this.reflogLine(message),
570
+ objectFormat: this.objectFormat,
556
571
  // a full object id is itself (get_oid_basic); the resolver would also look for refs
557
572
  // spelled as it, for an ambiguity warning the notes commands do not print — a ref
558
573
  // lookup per line of `git notes copy --stdin` that costs most of its time
559
574
  resolve: (name) =>
560
- /^[0-9a-fA-F]{40}$/.test(name)
575
+ name.length === this.objectFormat.hexLength && /^[0-9a-fA-F]+$/.test(name)
561
576
  ? Promise.resolve(name.toLowerCase())
562
577
  : this.revisionResolver()
563
578
  .resolve(name)
@@ -567,6 +582,19 @@ export abstract class GitCommand<T> {
567
582
 
568
583
  // ============ Store Accessors ============
569
584
 
585
+ /**
586
+ * The repository's object format (`extensions.objectFormat`): the length of its ids, its
587
+ * null id, empty tree and empty blob. SHA-1 unless the repository is SHA-256.
588
+ */
589
+ protected get objectFormat(): ObjectFormat {
590
+ return objectFormatOf(this._workingCopy.history);
591
+ }
592
+
593
+ /** Whether `id` is a full lowercase hex id of the repository's format (40, or 64 digits) */
594
+ protected isFullObjectId(id: string): boolean {
595
+ return id.length === this.objectFormat.hexLength && /^[0-9a-f]+$/.test(id);
596
+ }
597
+
570
598
  /**
571
599
  * Whether this command reads objects through replace refs and grafts (see {@link commits}).
572
600
  * git applies them to every object read but those of gc, prune, pack-objects, upload-pack,
@@ -1230,6 +1258,8 @@ export abstract class GitCommand<T> {
1230
1258
  protected checkConfigOnLoad(): void {
1231
1259
  const failure = configLoadError(this._workingCopy);
1232
1260
  if (failure) throw new InvalidConfigError(failure.key, failure.message);
1261
+ // repo_read_config's check_deprecated_config: core.commentChar=auto dies in git 3.0
1262
+ checkAutoCommentChar(this._workingCopy);
1233
1263
  // prepare_repo_settings, which every command but `git config` runs before its work
1234
1264
  const indexVersion = indexVersionConfigError(this._workingCopy);
1235
1265
  if (indexVersion) throw indexVersion;
package/src/git.ts CHANGED
@@ -132,7 +132,7 @@ export interface GitOptions {
132
132
  * ```
133
133
  */
134
134
  export class Git implements Disposable {
135
- private readonly _workingCopy: WorkingCopy;
135
+ private _workingCopy: WorkingCopy;
136
136
  private readonly transports?: GitTransportRegistry;
137
137
  private closed = false;
138
138
 
@@ -950,7 +950,13 @@ export class Git implements Disposable {
950
950
  */
951
951
  clone(): CloneCommand {
952
952
  this.checkClosed();
953
- return this.withTransports(new CloneCommand(this._workingCopy));
953
+ // a clone that switches the repository to the remote's object format reopens it: this
954
+ // facade then works on the reopened working copy
955
+ return this.withTransports(
956
+ new CloneCommand(this._workingCopy).onWorkingCopyReopened((workingCopy) => {
957
+ this._workingCopy = workingCopy;
958
+ }),
959
+ );
954
960
  }
955
961
 
956
962
  /**
@@ -1218,12 +1224,19 @@ export class Git implements Disposable {
1218
1224
  /**
1219
1225
  * Create a StashCreateCommand for stashing changes.
1220
1226
  *
1227
+ * Despite its name this is `git stash push`: the stash is stored in `refs/stash` and the
1228
+ * index and the worktree are reset to HEAD. git's `git stash create` (the stash commit
1229
+ * only: worktree, index and `refs/stash` untouched) is `stashCreate().setRef(null)`.
1230
+ *
1221
1231
  * @example
1222
1232
  * ```typescript
1223
- * // the working copy's index and worktree are stashed, then reset to HEAD
1233
+ * // git stash push -m "WIP: feature work": stashed, then reset to HEAD
1224
1234
  * const stashCommit = await git.stashCreate()
1225
1235
  * .setMessage("WIP: feature work")
1226
1236
  * .call();
1237
+ *
1238
+ * // git stash create "msg": the commit id only, nothing else changes
1239
+ * const id = await git.stashCreate().setRef(null).setMessage("msg").call();
1227
1240
  * ```
1228
1241
  */
1229
1242
  stashCreate(): StashCreateCommand {
@@ -6,8 +6,10 @@
6
6
 
7
7
  export {
8
8
  defaultFetchRefspec,
9
+ type LegacyRemote,
9
10
  listRemoteNames,
10
11
  type RemoteConfig,
11
12
  RemoteConfigStore,
13
+ setLegacyRemote,
12
14
  } from "./remote-config-store.js";
13
15
  export { deleteRefs, moveRefs, type RefMove } from "./remote-refs.js";