@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
@@ -638,6 +638,17 @@ function normalizeHostPath(path: string): string {
638
638
  return `/${normalizeFilesPath(path)}`;
639
639
  }
640
640
 
641
+ /**
642
+ * A file of a working copy's common git directory (`remotes/<name>`, `packed-refs`) as the
643
+ * repository's FilesApi names it; undefined when the working copy has no files layout.
644
+ */
645
+ export async function commonGitFileOf(
646
+ workingCopy: WorkingCopy,
647
+ name: string,
648
+ ): Promise<{ files: FilesApi; path: string } | undefined> {
649
+ return new HookSession(hookHostOf(workingCopy)).commonGitFile(name);
650
+ }
651
+
641
652
  /** The common git directory of `gitDir` (its `commondir` file), as a FilesApi path. */
642
653
  async function commonDirOf(files: FilesApi, gitDir: string): Promise<string> {
643
654
  const path = joinFilesPath(gitDir, "commondir");
@@ -412,7 +412,7 @@ export class IndexAdder {
412
412
  await this.storeEmptyBlob();
413
413
  if (indexed) {
414
414
  if (!this.pretend) this.touched.add(name);
415
- return indexed.objectId === EMPTY_BLOB_ID ? "same" : "added";
415
+ return indexed.objectId === this.emptyBlobId ? "same" : "added";
416
416
  }
417
417
  if (this.pretend) return "added";
418
418
  this.resolve(name);
@@ -423,7 +423,7 @@ export class IndexAdder {
423
423
  this.editor.add(
424
424
  new UpdateStagingEntry(
425
425
  name,
426
- EMPTY_BLOB_ID,
426
+ this.emptyBlobId,
427
427
  mode,
428
428
  { size: 0, mtime: 0 },
429
429
  { intentToAdd: true },
@@ -500,7 +500,7 @@ export class IndexAdder {
500
500
  this.editor.add(
501
501
  new UpdateStagingEntry(
502
502
  path,
503
- EMPTY_BLOB_ID,
503
+ this.emptyBlobId,
504
504
  FileMode.GITLINK,
505
505
  { size: 0, mtime: 0 },
506
506
  { intentToAdd: true },
@@ -542,6 +542,11 @@ export class IndexAdder {
542
542
  }
543
543
 
544
544
  /** git's `set_object_name_for_intent_to_add_entry`: the empty blob written (once). */
545
+ /** The empty blob's id in the repository's format (the id an intent-to-add entry gets) */
546
+ private get emptyBlobId(): ObjectId {
547
+ return this.blobs.objectFormat?.emptyBlobId ?? EMPTY_BLOB_ID;
548
+ }
549
+
545
550
  private async storeEmptyBlob(): Promise<void> {
546
551
  if (this.emptyBlobStored) return;
547
552
  this.emptyBlobStored = true;
@@ -12,8 +12,10 @@ export * from "./checkout-paths.js";
12
12
  export * from "./cherry-pick-command.js";
13
13
  export * from "./clean-command.js";
14
14
  export * from "./clone-command.js";
15
+ export * from "./comment-char-config.js";
15
16
  export * from "./commit-command.js";
16
17
  export * from "./date-format.js";
18
+ export * from "./default-branch.js";
17
19
  export * from "./describe-command.js";
18
20
  export * from "./diff-command.js";
19
21
  export * from "./diff-textconv.js";
@@ -10,10 +10,18 @@ import {
10
10
  createGitFilesHistoryFromFiles,
11
11
  FileStagingStore,
12
12
  probeCaseFolding,
13
+ readProtectedConfig,
14
+ readRepositoryFormat,
13
15
  resolveLinkedGitDir,
14
16
  } from "@statewalker/vcs-store-files";
15
17
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
16
- import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils";
18
+ import {
19
+ decodeGitPath,
20
+ encodeGitPath,
21
+ type ObjectFormat,
22
+ objectFormatByName,
23
+ SHA1_OBJECT_FORMAT,
24
+ } from "@statewalker/vcs-utils";
17
25
  import {
18
26
  createMemoryCheckout,
19
27
  type GitHostEnvironment,
@@ -24,6 +32,12 @@ import {
24
32
 
25
33
  import { Git } from "../git.js";
26
34
  import type { InitResult } from "../results/init-result.js";
35
+ import {
36
+ defaultInitialBranch,
37
+ defaultRefFormat,
38
+ InvalidInitialBranchError,
39
+ isValidBranchName,
40
+ } from "./default-branch.js";
27
41
 
28
42
  /**
29
43
  * Command to initialize a new Git repository.
@@ -67,13 +81,35 @@ export class InitCommand {
67
81
  private directory?: string;
68
82
  private gitDir?: string;
69
83
  private bare = false;
70
- private initialBranch = "main";
84
+ /** `--initial-branch`; undefined: git's default (see {@link defaultInitialBranch}) */
85
+ private initialBranch?: string;
71
86
  private stagingStore?: Staging;
72
87
  private worktreeEnabled = false;
73
88
  private worktreeStore?: Worktree;
74
89
  private environment?: GitHostEnvironment;
90
+ /** `--object-format`; undefined: `$GIT_DEFAULT_HASH`, `init.defaultObjectFormat`, else sha1 */
91
+ private objectFormatName?: string;
92
+ /** `--ref-format`; undefined: git's default (see {@link defaultRefFormat}) */
93
+ private refFormat?: string;
75
94
  private callable = true;
76
95
 
96
+ /**
97
+ * Set the object format of the new repository (`git init --object-format=<format>`):
98
+ * `sha1` (git's default) or `sha256`. Without it, `$GIT_DEFAULT_HASH`
99
+ * (`GitHostEnvironment.defaultHash`), then `init.defaultObjectFormat` from the system or
100
+ * global configuration (or `git -c`), else SHA-1. A name git does not know fails the call
101
+ * (`UnknownHashAlgorithmError`), and so does re-initialising an existing repository with
102
+ * another format (`ReinitializeHashError`); an existing repository keeps its own otherwise.
103
+ *
104
+ * @param format `sha1` or `sha256`
105
+ * @returns this for method chaining
106
+ */
107
+ setObjectFormat(format: string): this {
108
+ this.checkCallable();
109
+ this.objectFormatName = format;
110
+ return this;
111
+ }
112
+
77
113
  /**
78
114
  * Set the FilesApi implementation for storage.
79
115
  *
@@ -136,8 +172,9 @@ export class InitCommand {
136
172
  /**
137
173
  * Set the initial branch name.
138
174
  *
139
- * This is the branch that HEAD will point to after initialization.
140
- * Defaults to "main".
175
+ * This is the branch that HEAD will point to after initialization. Without it, git's
176
+ * default: `init.defaultBranch` from the system or global configuration (or `git -c`),
177
+ * else `master`, or `main` with `GitHostEnvironment.breakingChanges` (git 3.0).
141
178
  *
142
179
  * @param branch The initial branch name
143
180
  * @returns this for method chaining
@@ -148,6 +185,21 @@ export class InitCommand {
148
185
  return this;
149
186
  }
150
187
 
188
+ /**
189
+ * Set the ref storage format of a new repository (`git init --ref-format`): `files` (loose
190
+ * refs and packed-refs) or `reftable` (`.git/reftable`). Without it, git's default:
191
+ * `$GIT_DEFAULT_REF_FORMAT`, `init.defaultRefFormat`, else `files`, or `reftable` with
192
+ * `GitHostEnvironment.breakingChanges` (git 3.0). An existing repository keeps its format.
193
+ *
194
+ * @param format "files" or "reftable"
195
+ * @returns this for method chaining
196
+ */
197
+ setRefFormat(format: "files" | "reftable" | string): this {
198
+ this.checkCallable();
199
+ this.refFormat = format;
200
+ return this;
201
+ }
202
+
151
203
  /**
152
204
  * Set a custom staging store.
153
205
  *
@@ -243,6 +295,29 @@ export class InitCommand {
243
295
  this.checkCallable();
244
296
  this.setCallable(false);
245
297
 
298
+ // git's -b / init.defaultBranch / built-in default (repo_default_branch_name), worked out
299
+ // only for a repository without HEAD (create_reference_database runs only then): an
300
+ // existing repository keeps its HEAD, ignores -b with a warning and checks no name
301
+ let initialBranch = "";
302
+ let hints: string[] | undefined;
303
+ const warnings: string[] = [];
304
+ const chooseBranch = async () => {
305
+ if (this.initialBranch !== undefined && !isValidBranchName(this.initialBranch)) {
306
+ throw new InvalidInitialBranchError(this.initialBranch);
307
+ }
308
+ const chosen =
309
+ this.initialBranch !== undefined
310
+ ? { name: this.initialBranch }
311
+ : await defaultInitialBranch(this.environment);
312
+ initialBranch = chosen.name;
313
+ hints = chosen.hint;
314
+ };
315
+
316
+ // an explicit --object-format git does not know dies before anything is written
317
+ const explicitFormat =
318
+ this.objectFormatName === undefined ? undefined : knownHashAlgorithm(this.objectFormatName);
319
+ let objectFormat: ObjectFormat = SHA1_OBJECT_FORMAT;
320
+
246
321
  // Use in-memory FilesApi if none provided
247
322
  const files = this.files ?? createInMemoryFilesApi();
248
323
 
@@ -264,12 +339,33 @@ export class InitCommand {
264
339
  // A repository with a config but no HEAD (damaged or half-made) is opened, not
265
340
  // re-created: creating rewrites the config, and its remotes and settings with it.
266
341
  const fresh = !hasHead && !(await isFile(`${dir}/config`));
342
+ if (fresh) {
343
+ objectFormat = explicitFormat ?? (await this.defaultObjectFormat(warnings));
344
+ } else {
345
+ // validate_hash_algorithm: an existing repository keeps its format, and refuses
346
+ // another one asked for explicitly (git 2.5x ignores $GIT_DEFAULT_HASH there)
347
+ objectFormat = (await readRepositoryFormat(repoFiles, dir)).objectFormat;
348
+ if (explicitFormat && explicitFormat.name !== objectFormat.name) {
349
+ throw new ReinitializeHashError();
350
+ }
351
+ }
352
+ if (!hasHead) await chooseBranch();
353
+ else if (this.initialBranch !== undefined) {
354
+ warnings.push(`warning: re-init: ignored --initial-branch=${this.initialBranch}`);
355
+ }
356
+ // the ref storage of a repository created here (an existing one keeps its own)
357
+ const refFormat = fresh
358
+ ? await defaultRefFormat(this.environment, this.refFormat)
359
+ : undefined;
360
+ if (refFormat) warnings.push(...refFormat.warnings);
267
361
  const open = (create: boolean) =>
268
362
  createGitFilesHistoryFromFiles({
269
363
  files: repoFiles,
270
364
  gitDir,
271
365
  create,
272
- defaultBranch: this.initialBranch,
366
+ defaultBranch: initialBranch,
367
+ ...(create ? { objectFormat } : {}),
368
+ ...(create && refFormat ? { refFormat: refFormat.format } : {}),
273
369
  ...(this.environment ? { environment: this.environment } : {}),
274
370
  });
275
371
  if (fresh && this.bare && dir !== ".") {
@@ -282,6 +378,14 @@ export class InitCommand {
282
378
  history = await open(fresh);
283
379
  }
284
380
  await history.initialize();
381
+ if (hasHead) {
382
+ // the branch an existing repository's HEAD names (empty when detached)
383
+ const head = await history.refs.get("HEAD");
384
+ initialBranch =
385
+ head && "target" in head && head.target.startsWith("refs/heads/")
386
+ ? head.target.slice("refs/heads/".length)
387
+ : "";
388
+ }
285
389
  if (fresh) {
286
390
  // git init's probe: a filesystem that folds case or Unicode composition
287
391
  const folding = await probeCaseFolding(repoFiles as PosixFilesApi, dir);
@@ -292,7 +396,7 @@ export class InitCommand {
292
396
  }
293
397
  }
294
398
  if (!hasHead && !fresh) {
295
- await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
399
+ await history.refs.setSymbolic("HEAD", `refs/heads/${initialBranch}`);
296
400
  }
297
401
  // The index lives in the repository too: a reopened repository keeps what was staged
298
402
  // (its last commit's files), so the next commit does not drop them.
@@ -301,15 +405,18 @@ export class InitCommand {
301
405
  } else if (this.bare) {
302
406
  staging = new MemoryStagingStore();
303
407
  } else {
304
- const fileStaging = new FileStagingStore(repoFiles, `${dir}/index`);
305
- await fileStaging.read();
408
+ const fileStaging = new FileStagingStore(repoFiles, `${dir}/index`, { objectFormat });
409
+ // a SHA-256 repository's index is not read yet: its first use refuses
410
+ if (objectFormat.name === "sha1") await fileStaging.read();
306
411
  staging = fileStaging;
307
412
  }
308
413
  } else {
309
- history = createMemoryHistory();
414
+ objectFormat = explicitFormat ?? (await this.defaultObjectFormat(warnings));
415
+ await chooseBranch();
416
+ history = createMemoryHistory({ objectFormat });
310
417
  await history.initialize();
311
418
  // Set initial branch by creating symbolic ref for HEAD
312
- await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
419
+ await history.refs.setSymbolic("HEAD", `refs/heads/${initialBranch}`);
313
420
  staging = this.stagingStore ?? new MemoryStagingStore();
314
421
  }
315
422
 
@@ -405,12 +512,34 @@ export class InitCommand {
405
512
  git,
406
513
  workingCopy,
407
514
  repository: history,
408
- initialBranch: this.initialBranch,
515
+ initialBranch,
516
+ ...(hints ? { hints } : {}),
517
+ ...(warnings.length > 0 ? { warnings } : {}),
409
518
  bare: this.bare,
410
519
  gitDir,
411
520
  };
412
521
  }
413
522
 
523
+ /**
524
+ * The format of a new repository without `--object-format` (validate_hash_algorithm):
525
+ * `$GIT_DEFAULT_HASH` (an unknown name dies), else `init.defaultObjectFormat` (git 2.45+;
526
+ * an unknown name warns and is ignored), else SHA-1.
527
+ */
528
+ private async defaultObjectFormat(warnings: string[]): Promise<ObjectFormat> {
529
+ const env = this.environment?.defaultHash;
530
+ if (env !== undefined) return knownHashAlgorithm(env);
531
+ const config = await readProtectedConfig(this.environment);
532
+ const configured = config
533
+ .filter((e) => e.key.toLowerCase() === "init.defaultobjectformat")
534
+ .at(-1);
535
+ if (configured?.value !== undefined) {
536
+ const found = objectFormatByName(configured.value);
537
+ if (found) return found;
538
+ warnings.push(`warning: unknown hash algorithm '${configured.value}'`);
539
+ }
540
+ return SHA1_OBJECT_FORMAT;
541
+ }
542
+
414
543
  /**
415
544
  * Resolve the git directory path based on configuration.
416
545
  */
@@ -453,6 +582,33 @@ export class InitCommand {
453
582
  }
454
583
  }
455
584
 
585
+ /** `--object-format` or `$GIT_DEFAULT_HASH` names no format git knows: git dies (exit 128). */
586
+ export class UnknownHashAlgorithmError extends Error {
587
+ override name = "UnknownHashAlgorithmError";
588
+ readonly lines: string[];
589
+ constructor(readonly value: string) {
590
+ const line = `fatal: unknown hash algorithm '${value}'`;
591
+ super(line);
592
+ this.lines = [line];
593
+ }
594
+ }
595
+
596
+ /** `--object-format` names another format than the existing repository's: git dies (exit 128). */
597
+ export class ReinitializeHashError extends Error {
598
+ override name = "ReinitializeHashError";
599
+ readonly lines = ["fatal: attempt to reinitialize repository with different hash"];
600
+ constructor() {
601
+ super("fatal: attempt to reinitialize repository with different hash");
602
+ }
603
+ }
604
+
605
+ /** The format named `name`, or `UnknownHashAlgorithmError` (git's `hash_algo_by_name`). */
606
+ function knownHashAlgorithm(name: string): ObjectFormat {
607
+ const found = objectFormatByName(name);
608
+ if (!found) throw new UnknownHashAlgorithmError(name);
609
+ return found;
610
+ }
611
+
456
612
  /** Sets `core.bare = true` in a config file written by the git directory layout. */
457
613
  async function markBare(files: FilesApi, configPath: string): Promise<void> {
458
614
  await setCoreValue(files, configPath, "bare", "true");
@@ -0,0 +1,224 @@
1
+ /**
2
+ * git 2.x's legacy remotes: a remote defined by a file `$GIT_COMMON_DIR/remotes/<name>` or
3
+ * `$GIT_COMMON_DIR/branches/<name>` instead of the configuration (remote.c
4
+ * `read_remotes_file`, `read_branches_file`). git reads them when it looks a remote up by
5
+ * name and the configuration gives that name no URL; git 3.0 (`WITH_BREAKING_CHANGES`,
6
+ * `GitHostEnvironment.breakingChanges`) never reads them.
7
+ *
8
+ * @example
9
+ * ```text
10
+ * $ cat .git/remotes/upstream $ cat .git/branches/vendor
11
+ * URL: https://example.com/r.git https://example.com/v.git#stable
12
+ * Pull: refs/heads/main:refs/heads/upstream
13
+ * Push: refs/heads/main:refs/heads/main
14
+ * ```
15
+ *
16
+ * The branches file fetches `refs/heads/stable:refs/heads/vendor` and pushes
17
+ * `HEAD:refs/heads/stable`; without `#<branch>` the branch is `init.defaultBranch`, else
18
+ * `master`.
19
+ */
20
+
21
+ import { parseGitBool } from "@statewalker/vcs-utils";
22
+ import type { FilesApi } from "@statewalker/vcs-utils/files";
23
+ import type { WorkingCopy } from "@statewalker/vcs-working-tree";
24
+
25
+ import { type LegacyRemote, RemoteConfigStore, setLegacyRemote } from "../remote-config/index.js";
26
+ import { defaultBranchHint } from "./default-branch.js";
27
+ import { commonGitFileOf } from "./git-hooks.js";
28
+ import { hostEnvironmentOf } from "./git-ident.js";
29
+
30
+ /** What {@link loadLegacyRemote} found, and the lines git prints on stderr reading it. */
31
+ export interface LegacyRemoteLoad {
32
+ remote?: LegacyRemote;
33
+ /**
34
+ * git's stderr while it reads the files, each entry one message (lines joined by `\n`):
35
+ * 2.5x's deprecation warning per file read, and the `advice.defaultBranchName` hint of a
36
+ * branches file without `#<branch>` (2.43 prints only the hint, in its own words)
37
+ */
38
+ messages: string[];
39
+ }
40
+
41
+ /**
42
+ * Reads the legacy remote `name` of a working copy, as remote.c's `remotes_remote_get_1`
43
+ * does, and records it for the working copy's {@link RemoteConfigStore}s (they see it while
44
+ * the configuration gives the name no URL): nothing under git 3.0, for a name that is no
45
+ * valid remote nickname (empty, `.`, `..`, a `/`), or for a remote the configuration gives a
46
+ * URL; else `remotes/<name>`, then, while there is still no URL, `branches/<name>`.
47
+ *
48
+ * @param compatibility The git whose stderr to give: 2.43 has no deprecation warning
49
+ */
50
+ export async function loadLegacyRemote(
51
+ workingCopy: WorkingCopy,
52
+ name: string,
53
+ compatibility: "2.43" | "2.56" = "2.56",
54
+ ): Promise<LegacyRemoteLoad> {
55
+ const messages: string[] = [];
56
+ const store = RemoteConfigStore.from(workingCopy);
57
+ setLegacyRemote(workingCopy, name, undefined);
58
+ if (hostEnvironmentOf(workingCopy)?.breakingChanges) return { messages };
59
+ if (!isValidRemoteNick(name) || store.remoteUrls(name).length > 0) return { messages };
60
+
61
+ let remote: LegacyRemote | undefined;
62
+ const remotesFile = await readGitFile(workingCopy, `remotes/${name}`);
63
+ if (remotesFile !== undefined) {
64
+ if (compatibility !== "2.43") messages.push(deprecationWarning("remotes", name));
65
+ remote = { ...parseRemotesFile(remotesFile), origin: "remotes", followTags: false };
66
+ }
67
+ if (!remote || remote.urls.length === 0) {
68
+ const branchesFile = await readGitFile(workingCopy, `branches/${name}`);
69
+ if (branchesFile !== undefined) {
70
+ if (compatibility !== "2.43") messages.push(deprecationWarning("branches", name));
71
+ const line = trimGitSpace(branchesFile.split("\n")[0] ?? "");
72
+ if (line) {
73
+ const at = line.indexOf("#");
74
+ let branch: string;
75
+ if (at >= 0) branch = line.slice(at + 1);
76
+ else {
77
+ const found = defaultBranchName(store, compatibility);
78
+ branch = found.name;
79
+ if (found.hint) messages.push(found.hint);
80
+ }
81
+ const url = at >= 0 ? line.slice(0, at) : line;
82
+ remote = {
83
+ origin: "branches",
84
+ urls: [...(remote?.urls ?? []), url],
85
+ fetchRefspecs: [
86
+ ...(remote?.fetchRefspecs ?? []),
87
+ `refs/heads/${branch}:refs/heads/${name}`,
88
+ ],
89
+ pushRefspecs: [...(remote?.pushRefspecs ?? []), `HEAD:refs/heads/${branch}`],
90
+ followTags: true,
91
+ };
92
+ }
93
+ }
94
+ }
95
+ setLegacyRemote(workingCopy, name, remote);
96
+ return { remote, messages };
97
+ }
98
+
99
+ /**
100
+ * Removes the file a legacy remote was read from (builtin/remote.c `migrate_file`'s
101
+ * `unlink_or_warn`) and forgets the remote; a file already gone is no error.
102
+ */
103
+ export async function removeLegacyRemoteFile(
104
+ workingCopy: WorkingCopy,
105
+ origin: "remotes" | "branches",
106
+ name: string,
107
+ ): Promise<void> {
108
+ const file = await commonGitFileOf(workingCopy, `${origin}/${name}`);
109
+ if (file) await file.files.remove(file.path).catch(() => false);
110
+ setLegacyRemote(workingCopy, name, undefined);
111
+ }
112
+
113
+ /** remote.c's `valid_remote_nick`: not empty, `.` or `..`, and no `/`. */
114
+ export function isValidRemoteNick(name: string): boolean {
115
+ return name !== "" && name !== "." && name !== ".." && !name.includes("/");
116
+ }
117
+
118
+ /**
119
+ * Parses a `remotes/<name>` file as `read_remotes_file`: each line, its trailing
120
+ * whitespace (git's `isspace`: space, `\t`, `\n`, `\r`) dropped, is a `URL:`, `Push:` or `Pull:` line (the value's leading whitespace
121
+ * dropped) or ignored.
122
+ */
123
+ export function parseRemotesFile(
124
+ text: string,
125
+ ): Pick<LegacyRemote, "urls" | "fetchRefspecs" | "pushRefspecs"> {
126
+ const urls: string[] = [];
127
+ const fetchRefspecs: string[] = [];
128
+ const pushRefspecs: string[] = [];
129
+ const lines = text.split("\n");
130
+ if (lines.at(-1) === "") lines.pop();
131
+ for (const raw of lines) {
132
+ const line = raw.replace(/[\t\n\r ]+$/, "");
133
+ const value = (prefix: string) => line.slice(prefix.length).replace(/^[\t\n\r ]+/, "");
134
+ if (line.startsWith("URL:")) urls.push(value("URL:"));
135
+ else if (line.startsWith("Push:")) pushRefspecs.push(value("Push:"));
136
+ else if (line.startsWith("Pull:")) fetchRefspecs.push(value("Pull:"));
137
+ }
138
+ return { urls, fetchRefspecs, pushRefspecs };
139
+ }
140
+
141
+ /**
142
+ * `strbuf_trim`: leading and trailing whitespace dropped as git's `isspace` (sane_ctype.h:
143
+ * space, `\t`, `\n`, `\r` only; a vertical tab or form feed is kept, as JavaScript's
144
+ * `trim()` would not).
145
+ */
146
+ function trimGitSpace(text: string): string {
147
+ return text.replace(/^[\t\n\r ]+/, "").replace(/[\t\n\r ]+$/, "");
148
+ }
149
+
150
+ /** 2.5x's `warn_about_deprecated_remote_type`, as `warning()` prints it. */
151
+ function deprecationWarning(type: "remotes" | "branches", name: string): string {
152
+ return [
153
+ `warning: reading remote from "${type}/${name}", which is nominated for removal.`,
154
+ "",
155
+ 'If you still use the "remotes/" directory it is recommended to',
156
+ "migrate to config-based remotes:",
157
+ "",
158
+ `\tgit remote rename ${name} ${name}`,
159
+ "",
160
+ "If you cannot, please let us know why you still need to use it by",
161
+ "sending an e-mail to <git@vger.kernel.org>.",
162
+ ].join("\n");
163
+ }
164
+
165
+ /**
166
+ * refs.c's `repo_default_branch_name(repo, 0)`: `init.defaultBranch` (every scope of the
167
+ * working copy's configuration), else `master` with the `advice.defaultBranchName` hint.
168
+ */
169
+ function defaultBranchName(
170
+ store: RemoteConfigStore,
171
+ compatibility: "2.43" | "2.56",
172
+ ): { name: string; hint?: string } {
173
+ const configured = store.value("init.defaultBranch");
174
+ if (configured !== undefined && configured !== "") return { name: configured };
175
+ const name = "master";
176
+ const advice = store.value("advice.defaultBranchName");
177
+ if (advice !== undefined && parseGitBool(advice) === false) return { name };
178
+ const hint =
179
+ compatibility === "2.43" ? defaultBranchHint243(name) : defaultBranchHint(name, false);
180
+ return { name, hint: hint.join("\n") };
181
+ }
182
+
183
+ /** git 2.43's `default_branch_name_advice` (an empty line is `hint: `, with its space). */
184
+ function defaultBranchHint243(name: string): string[] {
185
+ return [
186
+ `Using '${name}' as the name for the initial branch. This default branch name`,
187
+ "is subject to change. To configure the initial branch name to use in all",
188
+ "of your new repositories, which will suppress this warning, call:",
189
+ "",
190
+ "\tgit config --global init.defaultBranch <name>",
191
+ "",
192
+ "Names commonly chosen instead of 'master' are 'main', 'trunk' and",
193
+ "'development'. The just-created branch can be renamed via this command:",
194
+ "",
195
+ "\tgit branch -m <name>",
196
+ ].map((line) => `hint: ${line}`);
197
+ }
198
+
199
+ /**
200
+ * A file of the common git directory as text, or undefined when it is not a regular file
201
+ * (absent, a directory: `fopen_or_warn` reads nothing from either).
202
+ */
203
+ async function readGitFile(workingCopy: WorkingCopy, name: string): Promise<string | undefined> {
204
+ const file = await commonGitFileOf(workingCopy, name);
205
+ if (!file) return undefined;
206
+ return readText(file.files, file.path);
207
+ }
208
+
209
+ async function readText(files: FilesApi, path: string): Promise<string | undefined> {
210
+ try {
211
+ if ((await files.stats(path))?.kind !== "file") return undefined;
212
+ const chunks: Uint8Array[] = [];
213
+ for await (const chunk of files.read(path)) chunks.push(chunk);
214
+ const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
215
+ let at = 0;
216
+ for (const chunk of chunks) {
217
+ bytes.set(chunk, at);
218
+ at += chunk.length;
219
+ }
220
+ return new TextDecoder().decode(bytes);
221
+ } catch {
222
+ return undefined;
223
+ }
224
+ }