@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
@@ -1,14 +1,35 @@
1
1
  import { GitApiError, HookFailedError, InvalidArgumentError, InvalidConfigError, NoHeadError, NotACommitError, RefNotFoundError, RevisionError } from "./errors/index.js";
2
- import { DEFAULT_ABBREV_LENGTH, FileMode, MINIMUM_ABBREV_LENGTH, autoAbbrevLength, createReplacedBlobs, createReplacedCommits, createReplacedTags, createReplacedTrees, findAbbrevLengths, formatPersonIdent, graftFileBaseDir, graftFileReader, hasReplacements, historyWithoutLazyFetch, isSymbolicRef, isValidRefName, isValidWorktreePath, listObjectsWithPrefix, loadObjectReplacements, overlayMethods, parseCoreAbbrev } from "@statewalker/vcs-core";
2
+ import { DEFAULT_ABBREV_LENGTH, FileMode, MINIMUM_ABBREV_LENGTH, autoAbbrevLength, createReplacedBlobs, createReplacedCommits, createReplacedTags, createReplacedTrees, findAbbrevLengths, formatPersonIdent, graftFileBaseDir, graftFileReader, hasReplacements, historyWithoutLazyFetch, isSymbolicRef, isValidRefName, isValidWorktreePath, listObjectsWithPrefix, loadObjectReplacements, objectFormatOf, overlayMethods, parseCoreAbbrev } from "@statewalker/vcs-core";
3
3
  import { foldAsciiCase } from "@statewalker/vcs-utils/encoding";
4
- import { AttributesResolver, DIR_HIDE_EMPTY_DIRECTORIES, DIR_SHOW_OTHER_DIRECTORIES, IndexChangedError, IndexPathLookup, NULL_OID, attributesIndexOf, attributesSourceSetting, basicStatMatches, clearSkipWorktreeFromPresentFiles, compareWithWorktree, entryStatOf, excludeFileOid, expandUserPath, getWorktreeEntries, invalidateGitignore, newUntrackedCache, newUntrackedCacheDir, parseSharedRepository, parseSparseCheckoutPatterns, readTreeAttributesFile, resolveAttributesSource, statDataOf, untrackedCacheIdent, untrackedCacheIdentIs, wholeSeconds, xdgConfigPath, zeroStatData } from "@statewalker/vcs-working-tree";
5
- import { OrderedMap, compilePosixRegex, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1 } from "@statewalker/vcs-utils";
4
+ import { AttributesResolver, DIR_HIDE_EMPTY_DIRECTORIES, DIR_SHOW_OTHER_DIRECTORIES, IndexChangedError, IndexPathLookup, attributesIndexOf, attributesSourceSetting, basicStatMatches, clearSkipWorktreeFromPresentFiles, compareWithWorktree, entryStatOf, excludeFileOid, expandUserPath, getWorktreeEntries, invalidateGitignore, newUntrackedCache, newUntrackedCacheDir, parseSharedRepository, parseSparseCheckoutPatterns, readTreeAttributesFile, resolveAttributesSource, statDataOf, untrackedCacheIdent, untrackedCacheIdentIs, wholeSeconds, xdgConfigPath, zeroStatData } from "@statewalker/vcs-working-tree";
5
+ import { OrderedMap, approxidateCareful, compilePosixRegex, formatRfc2822Date, isNullObjectId, localTimezoneOffset, parseGitBool as parseGitBool$1, parseGitDate, parseGitInt as parseGitInt$1 } from "@statewalker/vcs-utils";
6
+ import { SHA1_OBJECT_FORMAT as SHA1_OBJECT_FORMAT$1 } from "@statewalker/vcs-utils/hash";
7
+ import { readProtectedConfig } from "@statewalker/vcs-store-files";
6
8
  import { FetchCheckError, anonymizeUrl, createDefaultTransports, createRepositoryFacade, fetchPromisedObjects, matchDestination, matchSource, parseRefSpec } from "@statewalker/vcs-transport";
7
9
  //#region src/remote-config/remote-config-store.ts
8
10
  /** The default fetch refspec `git remote add` writes for a remote. */
9
11
  function defaultFetchRefspec(name) {
10
12
  return `+refs/heads/*:refs/remotes/${name}/*`;
11
13
  }
14
+ /** The legacy remotes loaded for each working copy, by name. */
15
+ const legacyRemotes = /* @__PURE__ */ new WeakMap();
16
+ /**
17
+ * Records (or, with undefined, forgets) the legacy remote `name` of a working copy, for
18
+ * every {@link RemoteConfigStore} of it. `loadLegacyRemote` calls it each time it reads the
19
+ * files, so what the stores see is what the files held at the last load.
20
+ */
21
+ function setLegacyRemote(workingCopy, name, remote) {
22
+ let byName = legacyRemotes.get(workingCopy);
23
+ if (remote === void 0) {
24
+ byName?.delete(name);
25
+ return;
26
+ }
27
+ if (!byName) {
28
+ byName = /* @__PURE__ */ new Map();
29
+ legacyRemotes.set(workingCopy, byName);
30
+ }
31
+ byName.set(name, remote);
32
+ }
12
33
  const GIT_CONFIG_METHODS = [
13
34
  "get",
14
35
  "getAll",
@@ -117,8 +138,10 @@ var PlainObjectConfig = class {
117
138
  */
118
139
  var RemoteConfigStore = class RemoteConfigStore {
119
140
  config;
120
- constructor(config) {
141
+ owner;
142
+ constructor(config, owner) {
121
143
  this.config = config;
144
+ this.owner = owner;
122
145
  }
123
146
  /**
124
147
  * Wrap a working copy's configuration.
@@ -128,18 +151,47 @@ var RemoteConfigStore = class RemoteConfigStore {
128
151
  */
129
152
  static from(workingCopy) {
130
153
  const config = workingCopy.config;
131
- if (isGitConfigLike(config)) return new RemoteConfigStore(config);
132
- return new RemoteConfigStore(new PlainObjectConfig(config ?? {}));
154
+ if (isGitConfigLike(config)) return new RemoteConfigStore(config, workingCopy);
155
+ return new RemoteConfigStore(new PlainObjectConfig(config ?? {}), workingCopy);
133
156
  }
134
- /** Remote names that have a config section. */
157
+ /** Remote names that have a config section (git's `for_each_remote`: no legacy remotes). */
135
158
  configuredNames() {
136
159
  return this.config.subsections("remote");
137
160
  }
138
- /** Whether the remote has a config section. */
161
+ /**
162
+ * Whether the remote is configured (git's `remote_is_configured`): it has a config section,
163
+ * or a legacy remote file loaded for it defines it ({@link legacyOrigin}).
164
+ */
139
165
  isConfigured(name) {
166
+ return this.hasSection(name) || this.legacy(name) !== void 0;
167
+ }
168
+ /** Whether the remote has a `[remote "<name>"]` config section. */
169
+ hasSection(name) {
140
170
  return this.configuredNames().includes(name);
141
171
  }
142
172
  /**
173
+ * The file a remote was read from when a legacy remote file defines it (`remotes` or
174
+ * `branches`, see {@link LegacyRemote}); undefined for a remote of the configuration.
175
+ */
176
+ legacyOrigin(name) {
177
+ return this.legacy(name)?.origin;
178
+ }
179
+ /** Whether a fetch from the remote follows tags whatever its refspecs (a branches file). */
180
+ followsTagsAlways(name) {
181
+ return this.legacy(name)?.followTags ?? false;
182
+ }
183
+ /**
184
+ * The legacy remote `name`, while it applies: git reads the files only for a remote the
185
+ * configuration gives no URL (remote.c `remotes_remote_get_1`'s `valid_remote`), and then
186
+ * adds what they say to what the configuration says.
187
+ */
188
+ legacy(name) {
189
+ if (!this.owner) return void 0;
190
+ const remote = legacyRemotes.get(this.owner)?.get(name);
191
+ if (!remote || this.urlList(name, "url").length > 0) return void 0;
192
+ return remote;
193
+ }
194
+ /**
143
195
  * Read a remote, filling in the default fetch refspec when none is
144
196
  * configured, exactly as `git remote -v` reports one: its URLs as remote.c's
145
197
  * `alias_all_urls` leaves them (an empty `url`/`pushurl` line clearing the ones before it,
@@ -148,21 +200,27 @@ var RemoteConfigStore = class RemoteConfigStore {
148
200
  * when none applies: the fetch URLs are pushed to).
149
201
  */
150
202
  read(name) {
151
- const fetchRefspecs = this.strings(name, "fetch");
203
+ const fetchRefspecs = this.configuredFetchRefspecs(name);
204
+ const fallback = this.legacy(name) ? [] : [defaultFetchRefspec(name)];
152
205
  return {
153
206
  name,
154
207
  urls: this.remoteUrls(name),
155
208
  pushUrls: this.aliasedPushUrls(name),
156
- fetchRefspecs: fetchRefspecs.length > 0 ? fetchRefspecs : [defaultFetchRefspec(name)],
157
- pushRefspecs: this.strings(name, "push")
209
+ fetchRefspecs: fetchRefspecs.length > 0 ? fetchRefspecs : fallback,
210
+ pushRefspecs: this.pushRefspecs(name)
158
211
  };
159
212
  }
160
213
  /**
161
214
  * The `remote.<name>.fetch` lines as configured, without the default {@link read} fills
162
- * in: a remote without any fetches only its HEAD, as `git fetch <name>` does.
215
+ * in: a remote without any fetches only its HEAD, as `git fetch <name>` does. A legacy
216
+ * remote's refspecs ({@link LegacyRemote}) follow the configuration's.
163
217
  */
164
218
  configuredFetchRefspecs(name) {
165
- return this.strings(name, "fetch");
219
+ return [...this.strings(name, "fetch"), ...this.legacy(name)?.fetchRefspecs ?? []];
220
+ }
221
+ /** The `remote.<name>.push` lines, then a legacy remote's push refspecs. */
222
+ pushRefspecs(name) {
223
+ return [...this.strings(name, "push"), ...this.legacy(name)?.pushRefspecs ?? []];
166
224
  }
167
225
  /** Write every field of a remote, replacing whatever was there. */
168
226
  write(remote) {
@@ -293,7 +351,12 @@ var RemoteConfigStore = class RemoteConfigStore {
293
351
  * clears those before it: git's `add_url`), each rewritten by `url.<base>.insteadOf`.
294
352
  */
295
353
  remoteUrls(name) {
296
- return this.urlList(name, "url").map((url) => this.aliasUrl(url) ?? url);
354
+ return this.rawUrls(name).map((url) => this.aliasUrl(url) ?? url);
355
+ }
356
+ /** The `remote.<name>.url` lines (see {@link urlList}), else a legacy remote's URLs. */
357
+ rawUrls(name) {
358
+ const configured = this.urlList(name, "url");
359
+ return configured.length > 0 ? configured : this.legacy(name)?.urls ?? [];
297
360
  }
298
361
  /**
299
362
  * A remote's push URLs as git's `alias_all_urls` and `push_url_of_remote` give them: the
@@ -312,6 +375,14 @@ var RemoteConfigStore = class RemoteConfigStore {
312
375
  */
313
376
  aliasedPushUrls(name) {
314
377
  const pushUrls = this.urlList(name, "pushurl").map((url) => this.aliasUrl(url) ?? url);
378
+ const legacy = this.legacy(name);
379
+ if (legacy) {
380
+ for (const url of legacy.urls) {
381
+ const alias = this.aliasUrl(url, { push: true });
382
+ if (alias !== void 0) pushUrls.push(alias);
383
+ }
384
+ return pushUrls;
385
+ }
315
386
  if (pushUrls.length > 0) return pushUrls;
316
387
  const aliased = [];
317
388
  for (const url of this.urlList(name, "url")) {
@@ -392,6 +463,16 @@ var RemoteConfigStore = class RemoteConfigStore {
392
463
  value: e.text
393
464
  }));
394
465
  }
466
+ /**
467
+ * Every value of the variables `keys` (canonical, lower case) in the configuration's order,
468
+ * with where each was read (file, scope; none for the command line); undefined when the
469
+ * config cannot list its variables.
470
+ */
471
+ entriesWithOriginFor(keys) {
472
+ if (!this.config.listWithOrigin) return void 0;
473
+ const wanted = new Set(keys.map((k) => k.toLowerCase()));
474
+ return this.config.listWithOrigin().filter((e) => wanted.has(e.key));
475
+ }
395
476
  /** Every value of a config variable (`branch.main.merge` may repeat). */
396
477
  values(key) {
397
478
  return this.config.getAll(key).filter((value) => value !== void 0 && value !== null).map((value) => String(value));
@@ -400,6 +481,10 @@ var RemoteConfigStore = class RemoteConfigStore {
400
481
  setValue(key, value) {
401
482
  this.config.set(key, value);
402
483
  }
484
+ /** Adds a value to a config variable after the ones it has (`git config --add`). */
485
+ addValue(key, value) {
486
+ this.config.add(key, value);
487
+ }
403
488
  /** Sets every value of a config variable, in order (none: unset). */
404
489
  setValues(key, values) {
405
490
  if (values.length === 0) {
@@ -538,949 +623,6 @@ function refused(result) {
538
623
  return /* @__PURE__ */ new Error(`Cannot update refs: ${why}`);
539
624
  }
540
625
  //#endregion
541
- //#region src/commands/git-date.ts
542
- const MONTH_NAMES = [
543
- "January",
544
- "February",
545
- "March",
546
- "April",
547
- "May",
548
- "June",
549
- "July",
550
- "August",
551
- "September",
552
- "October",
553
- "November",
554
- "December"
555
- ];
556
- const WEEKDAY_NAMES = [
557
- "Sundays",
558
- "Mondays",
559
- "Tuesdays",
560
- "Wednesdays",
561
- "Thursdays",
562
- "Fridays",
563
- "Saturdays"
564
- ];
565
- /** git's `timezone_names`: name, offset in hours, summer time (one hour more). */
566
- const TIMEZONE_NAMES = [
567
- [
568
- "IDLW",
569
- -12,
570
- 0
571
- ],
572
- [
573
- "NT",
574
- -11,
575
- 0
576
- ],
577
- [
578
- "CAT",
579
- -10,
580
- 0
581
- ],
582
- [
583
- "HST",
584
- -10,
585
- 0
586
- ],
587
- [
588
- "HDT",
589
- -10,
590
- 1
591
- ],
592
- [
593
- "YST",
594
- -9,
595
- 0
596
- ],
597
- [
598
- "YDT",
599
- -9,
600
- 1
601
- ],
602
- [
603
- "PST",
604
- -8,
605
- 0
606
- ],
607
- [
608
- "PDT",
609
- -8,
610
- 1
611
- ],
612
- [
613
- "MST",
614
- -7,
615
- 0
616
- ],
617
- [
618
- "MDT",
619
- -7,
620
- 1
621
- ],
622
- [
623
- "CST",
624
- -6,
625
- 0
626
- ],
627
- [
628
- "CDT",
629
- -6,
630
- 1
631
- ],
632
- [
633
- "EST",
634
- -5,
635
- 0
636
- ],
637
- [
638
- "EDT",
639
- -5,
640
- 1
641
- ],
642
- [
643
- "AST",
644
- -3,
645
- 0
646
- ],
647
- [
648
- "ADT",
649
- -3,
650
- 1
651
- ],
652
- [
653
- "WAT",
654
- -1,
655
- 0
656
- ],
657
- [
658
- "GMT",
659
- 0,
660
- 0
661
- ],
662
- [
663
- "UTC",
664
- 0,
665
- 0
666
- ],
667
- [
668
- "Z",
669
- 0,
670
- 0
671
- ],
672
- [
673
- "WET",
674
- 0,
675
- 0
676
- ],
677
- [
678
- "BST",
679
- 0,
680
- 1
681
- ],
682
- [
683
- "CET",
684
- 1,
685
- 0
686
- ],
687
- [
688
- "MET",
689
- 1,
690
- 0
691
- ],
692
- [
693
- "MEWT",
694
- 1,
695
- 0
696
- ],
697
- [
698
- "MEST",
699
- 1,
700
- 1
701
- ],
702
- [
703
- "CEST",
704
- 1,
705
- 1
706
- ],
707
- [
708
- "MESZ",
709
- 1,
710
- 1
711
- ],
712
- [
713
- "FWT",
714
- 1,
715
- 0
716
- ],
717
- [
718
- "FST",
719
- 1,
720
- 1
721
- ],
722
- [
723
- "EET",
724
- 2,
725
- 0
726
- ],
727
- [
728
- "EEST",
729
- 2,
730
- 1
731
- ],
732
- [
733
- "WAST",
734
- 7,
735
- 0
736
- ],
737
- [
738
- "WADT",
739
- 7,
740
- 1
741
- ],
742
- [
743
- "CCT",
744
- 8,
745
- 0
746
- ],
747
- [
748
- "JST",
749
- 9,
750
- 0
751
- ],
752
- [
753
- "EAST",
754
- 10,
755
- 0
756
- ],
757
- [
758
- "EADT",
759
- 10,
760
- 1
761
- ],
762
- [
763
- "GST",
764
- 10,
765
- 0
766
- ],
767
- [
768
- "NZT",
769
- 12,
770
- 0
771
- ],
772
- [
773
- "NZST",
774
- 12,
775
- 0
776
- ],
777
- [
778
- "NZDT",
779
- 12,
780
- 1
781
- ],
782
- [
783
- "IDLE",
784
- 12,
785
- 0
786
- ]
787
- ];
788
- /** 2099-12-31T23:59:59Z: the last second `tm_to_time_t` can give (git 2.5x's bound). */
789
- const TIMESTAMP_MAX = 4102444799;
790
- const MDAYS = [
791
- 0,
792
- 31,
793
- 59,
794
- 90,
795
- 120,
796
- 151,
797
- 181,
798
- 212,
799
- 243,
800
- 273,
801
- 304,
802
- 334
803
- ];
804
- const isDigit = (c) => c !== void 0 && c >= "0" && c <= "9";
805
- const isAlpha = (c) => c !== void 0 && (c >= "a" && c <= "z" || c >= "A" && c <= "Z");
806
- const isAlnum$1 = (c) => isDigit(c) || isAlpha(c);
807
- const isSpace = (c) => c !== void 0 && " \n\v\f\r".includes(c);
808
- const upper = (c) => c >= "a" && c <= "z" ? c.toUpperCase() : c;
809
- /** C's conversion of a wide integer to `int`. */
810
- const toInt = (n) => Number.isFinite(n) ? Number(BigInt.asIntN(32, BigInt(n))) : -1;
811
- /** C's `strtol` / `strtoul` at `start`: whitespace, a sign, digits; `end` at start if none. */
812
- function strtol(s, start) {
813
- let i = start;
814
- while (isSpace(s[i])) i++;
815
- let sign = 1;
816
- if (s[i] === "+" || s[i] === "-") {
817
- if (s[i] === "-") sign = -1;
818
- i++;
819
- }
820
- const from = i;
821
- while (isDigit(s[i])) i++;
822
- if (i === from) return {
823
- value: 0,
824
- end: start
825
- };
826
- return {
827
- value: sign * Number(s.slice(from, i)),
828
- end: i
829
- };
830
- }
831
- /** The digits at `start` (which is one): their value and where they end. */
832
- function digitsAt(s, start) {
833
- let i = start;
834
- while (isDigit(s[i])) i++;
835
- const text = s.slice(start, i);
836
- return {
837
- value: Number(text),
838
- text,
839
- end: i
840
- };
841
- }
842
- /** git's `tm_to_time_t`: the fields as UTC seconds, -1 outside 1970..2099. */
843
- function tmToTime(tm) {
844
- const year = tm.year - 70;
845
- const month = tm.mon;
846
- let day = tm.mday;
847
- if (year < 0 || year > 129) return -1;
848
- if (month < 0 || month > 11) return -1;
849
- if (month < 2 || (year + 2) % 4) day--;
850
- if (tm.hour < 0 || tm.min < 0 || tm.sec < 0) return -1;
851
- return (year * 365 + Math.trunc((year + 1) / 4) + MDAYS[month] + day) * 24 * 60 * 60 + tm.hour * 60 * 60 + tm.min * 60 + tm.sec;
852
- }
853
- /** `gmtime_r`: the UTC fields of `seconds` (a year past git's range when too large). */
854
- function gmtime(seconds) {
855
- if (!(Math.abs(seconds) < 864e10)) return {
856
- year: 1e6,
857
- mon: 0,
858
- mday: 1,
859
- hour: 0,
860
- min: 0,
861
- sec: 0
862
- };
863
- const d = /* @__PURE__ */ new Date(seconds * 1e3);
864
- return {
865
- year: d.getUTCFullYear() - 1900,
866
- mon: d.getUTCMonth(),
867
- mday: d.getUTCDate(),
868
- hour: d.getUTCHours(),
869
- min: d.getUTCMinutes(),
870
- sec: d.getUTCSeconds()
871
- };
872
- }
873
- /** The local offset, in seconds east of UTC, at the instant `seconds`. */
874
- function localOffsetAt(seconds) {
875
- return -(/* @__PURE__ */ new Date(seconds * 1e3)).getTimezoneOffset() * 60;
876
- }
877
- /**
878
- * glibc's `mktime` with `tm_isdst = -1` for the local time `wall` (its fields read as UTC
879
- * seconds): from a guess of UTC, each step moves by the local offset found, until it
880
- * settles. In a spring-forward gap the steps swing between two instants; glibc then takes
881
- * the one in summer time (the larger offset), which is the wall time in the offset before
882
- * the change.
883
- */
884
- function mktimeLocal(wall) {
885
- const seen = [];
886
- let t = wall;
887
- for (let probe = 0; probe < 8; probe++) {
888
- const next = wall - localOffsetAt(t);
889
- if (next === t) return t;
890
- if (seen.length > 0 && next === seen[seen.length - 1]) return localOffsetAt(t) >= localOffsetAt(next) ? t : next;
891
- seen.push(t);
892
- t = next;
893
- }
894
- return t;
895
- }
896
- /** git's `match_string`: how many characters of `str` the text at `i` spells. */
897
- function matchString(s, i, str) {
898
- let k = 0;
899
- for (; i + k < s.length; k++) {
900
- const c = s[i + k];
901
- const d = str[k] ?? "";
902
- if (c === d) continue;
903
- if (d !== "" && upper(c) === upper(d)) continue;
904
- if (!isAlnum$1(c)) break;
905
- return 0;
906
- }
907
- return k;
908
- }
909
- /** git's `match_alpha`: a month, a weekday, a zone, AM / PM, ISO's `T`, or skipped. */
910
- function matchAlpha(s, i, state) {
911
- const { tm } = state;
912
- for (const [index, name] of MONTH_NAMES.entries()) {
913
- const match = matchString(s, i, name);
914
- if (match >= 3) {
915
- tm.mon = index;
916
- return match;
917
- }
918
- }
919
- for (const name of WEEKDAY_NAMES) {
920
- const match = matchString(s, i, name);
921
- if (match >= 3) return match;
922
- }
923
- for (const [name, hours, dst] of TIMEZONE_NAMES) {
924
- const match = matchString(s, i, name);
925
- if (match >= 3 || match === name.length) {
926
- if (state.offset === -1) state.offset = 60 * (hours + dst);
927
- return match;
928
- }
929
- }
930
- if (matchString(s, i, "PM") === 2) {
931
- tm.hour = tm.hour % 12 + 12;
932
- return 2;
933
- }
934
- if (matchString(s, i, "AM") === 2) {
935
- tm.hour = tm.hour % 12 + 0;
936
- return 2;
937
- }
938
- if (s[i] === "T" && isDigit(s[i + 1]) && tm.hour === -1) {
939
- tm.min = 0;
940
- tm.sec = 0;
941
- return 1;
942
- }
943
- let k = 1;
944
- while (isAlpha(s[i + k])) k++;
945
- return k;
946
- }
947
- /** git's `set_date`: 0 when taken, else non-zero (`tm` may still have changed). */
948
- function setDate(year, month, day, nowTm, now, tm) {
949
- if (!(month > 0 && month < 13 && day > 0 && day < 32)) return -1;
950
- const r = nowTm ? { ...tm } : tm;
951
- r.mon = month - 1;
952
- r.mday = day;
953
- if (year === -1) {
954
- if (!nowTm) return 1;
955
- r.year = nowTm.year;
956
- } else if (year >= 1970 && year < 2100) r.year = year - 1900;
957
- else if (year > 70 && year < 100) r.year = year;
958
- else if (year < 38) r.year = year + 100;
959
- else return -1;
960
- if (!nowTm) return 0;
961
- const specified = tmToTime(r);
962
- if (specified !== -1 && now + 864e3 < specified) return -1;
963
- tm.mon = r.mon;
964
- tm.mday = r.mday;
965
- if (year !== -1) tm.year = r.year;
966
- return 0;
967
- }
968
- /** git's `set_time`: 0 when in range (the 61st second for a leap second). */
969
- function setTime(hour, minute, second, tm) {
970
- if (0 <= hour && hour <= 24 && 0 <= minute && minute < 60 && 0 <= second && second <= 60) {
971
- tm.hour = hour;
972
- tm.min = minute;
973
- tm.sec = second;
974
- return 0;
975
- }
976
- return -1;
977
- }
978
- const isDateKnown = (tm) => tm.year !== -1 && tm.mon !== -1 && tm.mday !== -1;
979
- const noDate = (tm) => tm.year < 0 && tm.mon < 0 && tm.mday < 0 && tm.hour < 0 && tm.min < 0 && tm.sec < 0;
980
- const maybeIso8601 = (tm) => tm.hour === -1 && tm.min === 0 && tm.sec === 0;
981
- /** git's `match_multi_number`: `num<c>num2[<c>num3]`, a time or a date; 0 when neither. */
982
- function matchMultiNumber(num, c, s, start, at, tm, nowArg = 0) {
983
- let end = at;
984
- const second = strtol(s, end + 1);
985
- const num2 = second.value;
986
- end = second.end;
987
- let num3 = -1;
988
- if (s[end] === c && isDigit(s[end + 1])) {
989
- const third = strtol(s, end + 1);
990
- num3 = third.value;
991
- end = third.end;
992
- }
993
- if (c === ":") {
994
- if (num3 < 0) num3 = 0;
995
- if (setTime(num, num2, num3, tm) !== 0) return 0;
996
- if (s[end] === "." && isDigit(s[end + 1]) && isDateKnown(tm)) end = strtol(s, end + 1).end;
997
- return end - start;
998
- }
999
- const now = nowArg || Math.floor(Date.now() / 1e3);
1000
- const refuseFuture = gmtime(now);
1001
- const [n1, n2, n3] = [
1002
- toInt(num),
1003
- toInt(num2),
1004
- toInt(num3)
1005
- ];
1006
- if (num > 70) {
1007
- if (setDate(n1, n2, n3, void 0, now, tm) === 0) return end - start;
1008
- if (setDate(n1, n3, n2, void 0, now, tm) === 0) return end - start;
1009
- }
1010
- if (c !== "." && setDate(n3, n1, n2, refuseFuture, now, tm) === 0) return end - start;
1011
- if (setDate(n3, n2, n1, refuseFuture, now, tm) === 0) return end - start;
1012
- if (c === "." && setDate(n3, n1, n2, refuseFuture, now, tm) === 0) return end - start;
1013
- return 0;
1014
- }
1015
- /** git's `match_digit`: seconds, a time, a date, a year, an offset, a day or a month. */
1016
- function matchDigit(s, i, state) {
1017
- const { tm } = state;
1018
- const { value: num, end } = digitsAt(s, i);
1019
- if (num >= 1e8 && noDate(tm)) {
1020
- state.tm = gmtime(num);
1021
- state.gmt = true;
1022
- return end - i;
1023
- }
1024
- if (":./-".includes(s[end] ?? "x") && isDigit(s[end + 1])) {
1025
- const match = matchMultiNumber(num, s[end], s, i, end, tm);
1026
- if (match) return match;
1027
- }
1028
- const n = end - i;
1029
- if (n === 8 || n === 6) {
1030
- const num1 = Math.trunc(num / 1e4);
1031
- const num2 = Math.trunc(num % 1e4 / 100);
1032
- const num3 = num % 100;
1033
- let after = end;
1034
- if (n === 8) setDate(num1, num2, num3, void 0, 0, tm);
1035
- else if (setTime(num1, num2, num3, tm) === 0 && s[end] === "." && isDigit(s[end + 1])) after = strtol(s, end + 1).end;
1036
- return after - i;
1037
- }
1038
- if (maybeIso8601(tm)) {
1039
- let num1 = num;
1040
- let num2 = 0;
1041
- if (n === 4) {
1042
- num1 = Math.trunc(num / 100);
1043
- num2 = num % 100;
1044
- }
1045
- if ((n === 4 || n === 2) && !noDate(tm) && setTime(num1, num2, 0, tm) === 0) return n;
1046
- tm.min = -1;
1047
- tm.sec = -1;
1048
- }
1049
- if (n === 4) {
1050
- if (num <= 1400 && state.offset === -1) state.offset = Math.trunc(num / 100) * 60 + num % 100;
1051
- else if (num > 1900 && num < 2100) tm.year = num - 1900;
1052
- return n;
1053
- }
1054
- if (n > 2) return n;
1055
- if (num > 0 && num < 32 && tm.mday < 0) {
1056
- tm.mday = num;
1057
- return n;
1058
- }
1059
- if (n === 2 && tm.year < 0) {
1060
- if (num < 10 && tm.mday >= 0) {
1061
- tm.year = num + 100;
1062
- return n;
1063
- }
1064
- if (num >= 70) {
1065
- tm.year = num;
1066
- return n;
1067
- }
1068
- }
1069
- if (num > 0 && num < 13 && tm.mon < 0) tm.mon = num - 1;
1070
- return n;
1071
- }
1072
- /** git's `match_tz`: `+HHMM`, `+HH:MM`, `+HH`; out of range ones ignored. */
1073
- function matchTz(s, i, state) {
1074
- const digits = digitsAt(s, i + 1);
1075
- let hour = digits.value;
1076
- let end = digits.end;
1077
- const n = end - (i + 1);
1078
- let min = 0;
1079
- if (n === 4) {
1080
- min = hour % 100;
1081
- hour = Math.trunc(hour / 100);
1082
- } else if (n !== 2) min = 99;
1083
- else if (s[end] === ":") {
1084
- const minutes = strtol(s, end + 1);
1085
- min = minutes.value;
1086
- end = minutes.end;
1087
- if (end - (i + 1) !== 5) min = 99;
1088
- }
1089
- if (min < 60 && hour < 24) {
1090
- const offset = hour * 60 + min;
1091
- state.offset = s[i] === "-" ? -offset : offset;
1092
- }
1093
- return end - i;
1094
- }
1095
- /** git's `match_object_header_date`: `<seconds> <+-HHMM>` after an `@`, alone. */
1096
- function matchObjectHeaderDate(s, i) {
1097
- if (!isDigit(s[i])) return void 0;
1098
- const stamp = digitsAt(s, i);
1099
- if (s[stamp.end] !== " ") return void 0;
1100
- if (BigInt(stamp.text) >= 2n ** 64n - 1n) return void 0;
1101
- const sign = s[stamp.end + 1];
1102
- if (sign !== "+" && sign !== "-") return void 0;
1103
- const at = stamp.end + 2;
1104
- const ofs = strtol(s, at);
1105
- const after = s[ofs.end];
1106
- if (after !== void 0 && after !== "\n" || ofs.end !== at + 4) return void 0;
1107
- let offset = Math.trunc(ofs.value / 100) * 60 + ofs.value % 100;
1108
- if (sign === "-") offset = -offset;
1109
- return {
1110
- timestamp: stamp.value,
1111
- offset
1112
- };
1113
- }
1114
- /** A timezone offset in minutes as git writes it (`+HHMM`). */
1115
- function formatOffset(minutes) {
1116
- const sign = minutes < 0 ? "-" : "+";
1117
- const abs = Math.abs(minutes);
1118
- return `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}${String(abs % 60).padStart(2, "0")}`;
1119
- }
1120
- /**
1121
- * The local timezone offset at `timestamp` (seconds; default now) as git writes it
1122
- * (`+HHMM`): `Date#getTimezoneOffset`, which every JavaScript host has.
1123
- */
1124
- function localTimezoneOffset(timestamp) {
1125
- return formatOffset(-(timestamp === void 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(timestamp * 1e3)).getTimezoneOffset());
1126
- }
1127
- /**
1128
- * A date as git's `parse_date` reads `GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE`, undefined
1129
- * where git refuses it (`fatal: invalid date format`). See the module comment for the forms.
1130
- */
1131
- function parseGitDate(text) {
1132
- const s = text.split("\0")[0];
1133
- if (s[0] === "@") {
1134
- const raw = matchObjectHeaderDate(s, 1);
1135
- if (raw) {
1136
- if (!Number.isSafeInteger(raw.timestamp)) return void 0;
1137
- return {
1138
- timestamp: raw.timestamp,
1139
- tzOffset: formatOffset(raw.offset)
1140
- };
1141
- }
1142
- }
1143
- const state = {
1144
- tm: {
1145
- year: -1,
1146
- mon: -1,
1147
- mday: -1,
1148
- hour: -1,
1149
- min: -1,
1150
- sec: -1
1151
- },
1152
- offset: -1,
1153
- gmt: false
1154
- };
1155
- let i = 0;
1156
- while (i < s.length && s[i] !== "\n") {
1157
- const c = s[i];
1158
- let match = 0;
1159
- if (isAlpha(c)) match = matchAlpha(s, i, state);
1160
- else if (isDigit(c)) match = matchDigit(s, i, state);
1161
- else if ((c === "-" || c === "+") && isDigit(s[i + 1])) match = matchTz(s, i, state);
1162
- i += match || 1;
1163
- }
1164
- let timestamp = tmToTime(state.tm);
1165
- if (timestamp === -1) return void 0;
1166
- let offset = state.offset;
1167
- if (offset === -1) {
1168
- const local = mktimeLocal(timestamp);
1169
- offset = Math.trunc((timestamp - local) / 60);
1170
- }
1171
- if (!state.gmt) {
1172
- if (offset > 0 && offset * 60 > timestamp) return void 0;
1173
- if (offset < 0 && -offset * 60 > TIMESTAMP_MAX - timestamp) return void 0;
1174
- timestamp -= offset * 60;
1175
- }
1176
- return {
1177
- timestamp,
1178
- tzOffset: formatOffset(offset)
1179
- };
1180
- }
1181
- /** The standard and the summer offsets (seconds east of UTC) of the year `seconds` is in. */
1182
- function yearOffsets(seconds) {
1183
- const year = (/* @__PURE__ */ new Date(seconds * 1e3)).getUTCFullYear();
1184
- const jan = localOffsetAt(Date.UTC(year, 0, 1) / 1e3);
1185
- const jul = localOffsetAt(Date.UTC(year, 6, 1) / 1e3);
1186
- return {
1187
- std: Math.min(jan, jul),
1188
- dst: Math.max(jan, jul)
1189
- };
1190
- }
1191
- /** `localtime_r`: the local fields of `seconds`, `tm_isdst` included. */
1192
- function localtime(seconds) {
1193
- const d = /* @__PURE__ */ new Date(seconds * 1e3);
1194
- const { std, dst } = yearOffsets(seconds);
1195
- return {
1196
- year: d.getFullYear() - 1900,
1197
- mon: d.getMonth(),
1198
- mday: d.getDate(),
1199
- hour: d.getHours(),
1200
- min: d.getMinutes(),
1201
- sec: d.getSeconds(),
1202
- wday: d.getDay(),
1203
- isdst: dst !== std && localOffsetAt(seconds) === dst ? 1 : 0
1204
- };
1205
- }
1206
- /**
1207
- * glibc's `mktime`: the local fields as seconds since the epoch, out-of-range fields
1208
- * carried. `tm_isdst` is honoured as glibc honours it: a time on the other side of a
1209
- * summer-time change from what `isdst` says is read in the offset `isdst` names (git's
1210
- * approxidate keeps now's `tm_isdst`, so "june" asked in November is an hour off).
1211
- */
1212
- function mktime(tm) {
1213
- const d = /* @__PURE__ */ new Date(0);
1214
- d.setUTCFullYear(tm.year + 1900, tm.mon, tm.mday);
1215
- d.setUTCHours(tm.hour, tm.min, tm.sec);
1216
- const wall = Math.floor(d.getTime() / 1e3);
1217
- const t = mktimeLocal(wall);
1218
- if (tm.isdst < 0) return t;
1219
- const { std, dst } = yearOffsets(t);
1220
- if (std === dst) return t;
1221
- if ((localOffsetAt(t) === dst ? 1 : 0) === (tm.isdst > 0 ? 1 : 0)) return t;
1222
- return wall - (tm.isdst > 0 ? dst : std);
1223
- }
1224
- /** git's `update_tm`: the missing fields from `now`, `sec` seconds back; `tm` refilled. */
1225
- function updateTm(tm, now, sec) {
1226
- let back = sec;
1227
- if (tm.mday < 0) {
1228
- const offset = tm.mday + 1;
1229
- if (back === 0 && offset < 0) back = -offset * 24 * 60 * 60;
1230
- tm.mday = now.mday;
1231
- }
1232
- if (tm.mon < 0) tm.mon = now.mon;
1233
- if (tm.year < 0) {
1234
- tm.year = now.year;
1235
- if (tm.mon > now.mon) tm.year--;
1236
- }
1237
- const n = mktime(tm) - back;
1238
- Object.assign(tm, localtime(n));
1239
- return n;
1240
- }
1241
- /** git's `pending_number`: a number seen last is a day, a month or a year. */
1242
- function pendingNumber(tm, num) {
1243
- const number = num.value;
1244
- if (!number) return;
1245
- num.value = 0;
1246
- if (tm.mday < 0 && number < 32) tm.mday = number;
1247
- else if (tm.mon < 0 && number < 13) tm.mon = number - 1;
1248
- else if (tm.year < 0) {
1249
- if (number > 1969 && number < 2100) tm.year = number - 1900;
1250
- else if (number > 69 && number < 100) tm.year = number;
1251
- else if (number < 38) tm.year = 100 + number;
1252
- }
1253
- }
1254
- /** git's `date_time`: `hour` o'clock, yesterday's when today's is still to come. */
1255
- function dateTime(tm, hour) {
1256
- if (tm.mday < 0 && tm.hour < hour) tm.mday = -2;
1257
- tm.hour = hour;
1258
- tm.min = 0;
1259
- tm.sec = 0;
1260
- }
1261
- /** git's `special` words. */
1262
- const SPECIALS = [
1263
- ["yesterday", (tm, now, num) => {
1264
- num.value = 0;
1265
- tm.mday = -1;
1266
- updateTm(tm, now, 86400);
1267
- }],
1268
- ["noon", (tm, _now, num) => {
1269
- pendingNumber(tm, num);
1270
- dateTime(tm, 12);
1271
- }],
1272
- ["midnight", (tm, _now, num) => {
1273
- pendingNumber(tm, num);
1274
- dateTime(tm, 0);
1275
- }],
1276
- ["tea", (tm, _now, num) => {
1277
- pendingNumber(tm, num);
1278
- dateTime(tm, 17);
1279
- }],
1280
- ["PM", (tm, _now, num) => {
1281
- let hour = tm.hour;
1282
- if (num.value) {
1283
- hour = num.value;
1284
- tm.min = 0;
1285
- tm.sec = 0;
1286
- }
1287
- num.value = 0;
1288
- tm.hour = hour % 12 + 12;
1289
- }],
1290
- ["AM", (tm, _now, num) => {
1291
- let hour = tm.hour;
1292
- if (num.value) {
1293
- hour = num.value;
1294
- tm.min = 0;
1295
- tm.sec = 0;
1296
- }
1297
- num.value = 0;
1298
- tm.hour = hour % 12;
1299
- }],
1300
- ["never", (tm, _now, num) => {
1301
- Object.assign(tm, localtime(0));
1302
- num.value = 0;
1303
- }],
1304
- ["now", (tm, now, num) => {
1305
- num.value = 0;
1306
- updateTm(tm, now, 0);
1307
- }],
1308
- ["today", (tm, now, num) => {
1309
- if (tm.hour === now.hour && tm.min === now.min && tm.sec === now.sec) dateTime(tm, 0);
1310
- num.value = 0;
1311
- tm.mday = -1;
1312
- updateTm(tm, now, 0);
1313
- }]
1314
- ];
1315
- const NUMBER_NAMES = [
1316
- "zero",
1317
- "one",
1318
- "two",
1319
- "three",
1320
- "four",
1321
- "five",
1322
- "six",
1323
- "seven",
1324
- "eight",
1325
- "nine",
1326
- "ten"
1327
- ];
1328
- const TYPE_LENGTHS = [
1329
- ["seconds", 1],
1330
- ["minutes", 60],
1331
- ["hours", 3600],
1332
- ["days", 86400],
1333
- ["weeks", 604800]
1334
- ];
1335
- /** git's `approxidate_alpha`: a word; returns where it ends. */
1336
- function approxidateAlpha(s, i, tm, now, num, touched) {
1337
- let end = i + 1;
1338
- while (isAlpha(s[end])) end++;
1339
- for (let m = 0; m < 12; m++) if (matchString(s, i, MONTH_NAMES[m] ?? "") >= 3) {
1340
- tm.mon = m;
1341
- touched.value = true;
1342
- return end;
1343
- }
1344
- for (const [name, fn] of SPECIALS) if (matchString(s, i, name) === name.length) {
1345
- fn(tm, now, num);
1346
- touched.value = true;
1347
- return end;
1348
- }
1349
- if (!num.value) {
1350
- for (let n = 1; n < 11; n++) {
1351
- const name = NUMBER_NAMES[n] ?? "";
1352
- if (matchString(s, i, name) === name.length) {
1353
- num.value = n;
1354
- touched.value = true;
1355
- return end;
1356
- }
1357
- }
1358
- if (matchString(s, i, "last") === 4) {
1359
- num.value = 1;
1360
- touched.value = true;
1361
- }
1362
- return end;
1363
- }
1364
- for (const [type, length] of TYPE_LENGTHS) if (matchString(s, i, type) >= type.length - 1) {
1365
- updateTm(tm, now, length * num.value);
1366
- num.value = 0;
1367
- touched.value = true;
1368
- return end;
1369
- }
1370
- for (let w = 0; w < 7; w++) if (matchString(s, i, WEEKDAY_NAMES[w] ?? "") >= 3) {
1371
- let n = num.value - 1;
1372
- num.value = 0;
1373
- let diff = tm.wday - w;
1374
- if (diff <= 0) n++;
1375
- diff += 7 * n;
1376
- updateTm(tm, now, diff * 24 * 60 * 60);
1377
- touched.value = true;
1378
- return end;
1379
- }
1380
- if (matchString(s, i, "months") >= 5) {
1381
- updateTm(tm, now, 0);
1382
- let n = tm.mon - num.value;
1383
- num.value = 0;
1384
- while (n < 0) {
1385
- n += 12;
1386
- tm.year--;
1387
- }
1388
- tm.mon = n;
1389
- touched.value = true;
1390
- return end;
1391
- }
1392
- if (matchString(s, i, "years") >= 4) {
1393
- updateTm(tm, now, 0);
1394
- tm.year -= num.value;
1395
- num.value = 0;
1396
- touched.value = true;
1397
- return end;
1398
- }
1399
- return end;
1400
- }
1401
- /** git's `approxidate_digit`: a number, or a date or time written with numbers. */
1402
- function approxidateDigit(s, i, tm, num, now) {
1403
- const { value: number, end } = digitsAt(s, i);
1404
- if (":./-".includes(s[end] ?? "x") && isDigit(s[end + 1])) {
1405
- const match = matchMultiNumber(number, s[end] ?? "", s, i, end, tm, now);
1406
- if (match) return i + match;
1407
- }
1408
- if (s[i] !== "0" || end - i <= 2) num.value = toInt(number);
1409
- return end;
1410
- }
1411
- /**
1412
- * git's `approxidate_careful`: a date as `parse_date` reads it, else git's approximate
1413
- * forms (`yesterday`, `2.weeks.ago`, `noon`, `last friday`, `3 hours ago`, `Dec 6`), in
1414
- * local time relative to `now` (seconds, default the current time). `error` is set when
1415
- * nothing in the text was a date (git then rejects `<ref>@{<text>}`).
1416
- *
1417
- * @example
1418
- * ```typescript
1419
- * approxidateCareful("1700000000 +0000"); // { timestamp: 1700000000, error: false }
1420
- * approxidateCareful("2.hours.ago"); // { timestamp: now - 7200, error: false }
1421
- * approxidateCareful("blah"); // { error: true, ... }
1422
- * ```
1423
- */
1424
- function approxidateCareful(text, now = Math.floor(Date.now() / 1e3)) {
1425
- const parsed = parseGitDate(text);
1426
- if (parsed) return {
1427
- timestamp: parsed.timestamp,
1428
- error: false
1429
- };
1430
- const nowTm = localtime(now);
1431
- const tm = {
1432
- ...nowTm,
1433
- year: -1,
1434
- mon: -1,
1435
- mday: -1
1436
- };
1437
- const num = { value: 0 };
1438
- const touched = { value: false };
1439
- const s = text.split("\0")[0] ?? "";
1440
- let i = 0;
1441
- while (i < s.length) {
1442
- const c = s[i];
1443
- if (isDigit(c)) {
1444
- pendingNumber(tm, num);
1445
- i = approxidateDigit(s, i, tm, num, now);
1446
- touched.value = true;
1447
- continue;
1448
- }
1449
- if (isAlpha(c)) {
1450
- i = approxidateAlpha(s, i, tm, nowTm, num, touched);
1451
- continue;
1452
- }
1453
- i++;
1454
- }
1455
- pendingNumber(tm, num);
1456
- return {
1457
- timestamp: updateTm(tm, nowTm, 0),
1458
- error: !touched.value
1459
- };
1460
- }
1461
- const SHORT_WEEKDAYS = [
1462
- "Sun",
1463
- "Mon",
1464
- "Tue",
1465
- "Wed",
1466
- "Thu",
1467
- "Fri",
1468
- "Sat"
1469
- ];
1470
- const SHORT_MONTHS = MONTH_NAMES.map((m) => m.slice(0, 3));
1471
- /**
1472
- * A timestamp in git's RFC 2822 date mode (`show_date(..., DATE_RFC2822)`), in the given
1473
- * offset: `Thu, 7 Apr 2005 22:13:13 +0000`.
1474
- */
1475
- function formatRfc2822Date(timestamp, tzOffset) {
1476
- const sign = tzOffset.startsWith("-") ? -1 : 1;
1477
- const digits = tzOffset.replace(/^[+-]/, "").padStart(4, "0");
1478
- const minutes = sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2, 4)));
1479
- const d = /* @__PURE__ */ new Date((timestamp + minutes * 60) * 1e3);
1480
- const pad = (n) => String(n).padStart(2, "0");
1481
- return `${SHORT_WEEKDAYS[d.getUTCDay()]}, ${d.getUTCDate()} ${SHORT_MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} ${formatOffset(minutes)}`;
1482
- }
1483
- //#endregion
1484
626
  //#region src/commands/git-ident.ts
1485
627
  /** The identity of a commit nobody is configured for (the ref stores' reflog identity). */
1486
628
  const DEFAULT_IDENT = {
@@ -1698,7 +840,7 @@ function conflictStyleOf(workingCopy) {
1698
840
  }
1699
841
  //#endregion
1700
842
  //#region src/commands/attributes-source.ts
1701
- const FULL_ID = /^[0-9a-fA-F]{40}$/;
843
+ const FULL_ID = /^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/;
1702
844
  /**
1703
845
  * Resolves attribute sources through `resolver` (a fresh one per lookup). A full object id
1704
846
  * stands for itself, stored or not (git's `get_oid` does not look it up): a missing object
@@ -1747,6 +889,116 @@ function bareAttributesResolver(o) {
1747
889
  }, { ignoreCase: configBool(workingCopy, "core.ignoreCase", false) });
1748
890
  }
1749
891
  //#endregion
892
+ //#region src/commands/comment-char-config.ts
893
+ const KEYS = ["core.commentchar", "core.commentstring"];
894
+ const NAMES = ["core.commentChar", "core.commentString"];
895
+ /** `core.commentChar=auto` in a git 3.0 build: every command but `git config` dies (exit 128). */
896
+ var AutoCommentCharRemovedError = class extends InvalidConfigError {
897
+ /** git's stderr: the fatal line and its hints */
898
+ lines;
899
+ constructor(lines) {
900
+ super("core.commentChar", lines.join("\n"));
901
+ this.name = "AutoCommentCharRemovedError";
902
+ this.lines = lines;
903
+ }
904
+ };
905
+ /**
906
+ * git's lines about an `auto` comment character, or undefined when the last value of the two
907
+ * keys is not exactly `auto`: `removed` gives git 3.0's death (`fatal:`), `deprecated` git
908
+ * 2.5x's warning (`warning:`), each followed by the advice.
909
+ */
910
+ function autoCommentCharLines(workingCopy, kind) {
911
+ const config = RemoteConfigStore.from(workingCopy);
912
+ const entries = config.entriesWithOriginFor([...KEYS]);
913
+ if (!entries) {
914
+ if (config.lastValueOf([...NAMES]) !== "auto") return void 0;
915
+ return [headline(kind, "core.commentChar")];
916
+ }
917
+ let lastKey = 0;
918
+ let autoSet = false;
919
+ let autoSetInFile = false;
920
+ const items = [];
921
+ const seenTwice = /* @__PURE__ */ new Set();
922
+ for (const entry of entries) {
923
+ const keyId = KEYS.indexOf(entry.key);
924
+ lastKey = keyId;
925
+ autoSet = entry.text === "auto";
926
+ if (entry.scope === "command" || entry.file === void 0) continue;
927
+ const id = `${keyId}\0${entry.file}`;
928
+ if (items.some((item) => `${item.keyId}\0${item.file}` === id)) seenTwice.add(id);
929
+ else items.push({
930
+ keyId,
931
+ scope: entry.scope,
932
+ file: entry.file
933
+ });
934
+ autoSetInFile = autoSet;
935
+ }
936
+ if (!autoSet) return void 0;
937
+ const lines = [headline(kind, NAMES[lastKey])];
938
+ if (autoSetInFile && items.length > 0) {
939
+ const environment = hostEnvironmentOf(workingCopy);
940
+ const unset = items.map((item) => ` git config unset ${scopeArg(item, environment)}${seenTwice.has(`${item.keyId}\0${item.file}`) ? "--all " : ""}${NAMES[item.keyId]}`);
941
+ lines.push(...hint(`\nTo use the default comment string (#) please run\n\n${unset.join("\n")}\n`));
942
+ const last = items[items.length - 1];
943
+ const set = ` git config set ${scopeArg(last, environment)}${NAMES[last.keyId]} <comment string>`;
944
+ lines.push(...hint(`\nTo set a custom comment string please run\n\n${set}\n\nwhere '<comment string>' is the string you wish to use.\n`));
945
+ }
946
+ return lines;
947
+ }
948
+ /**
949
+ * The git 3.0 check every command runs as it reads the configuration (`check_deprecated_config`
950
+ * in `repo_read_config`): throws with git's lines when the comment character is `auto` and the
951
+ * host asked for git 3.0 (`GitHostEnvironment.breakingChanges`).
952
+ */
953
+ function checkAutoCommentChar(workingCopy) {
954
+ if (!hostEnvironmentOf(workingCopy)?.breakingChanges) return;
955
+ const lines = autoCommentCharLines(workingCopy, "removed");
956
+ if (lines) throw new AutoCommentCharRemovedError(lines);
957
+ }
958
+ function headline(kind, key) {
959
+ return kind === "removed" ? `fatal: Support for '${key}=auto' has been removed in Git 3.0` : `warning: Support for '${key}=auto' is deprecated and will be removed in Git 3.0`;
960
+ }
961
+ /** advice.c's `vadvise`: each line as `hint: <line>`, an empty one as `hint:`. */
962
+ function hint(text) {
963
+ const out = [];
964
+ const parts = text.split("\n");
965
+ if (parts[parts.length - 1] === "") parts.pop();
966
+ for (const part of parts) out.push(part === "" ? "hint:" : `hint: ${part}`);
967
+ return out;
968
+ }
969
+ /**
970
+ * config.c's `add_config_scope_arg`: the option naming the file a value came from. The
971
+ * system file is taken as writable (git recommends `--global` when it is not; the FilesApi
972
+ * cannot tell).
973
+ */
974
+ function scopeArg(item, environment) {
975
+ const base = item.file.split("/").pop() ?? item.file;
976
+ if (item.scope === "system" && item.file === environment?.systemConfig) return "--system ";
977
+ if (item.scope === "global" && isGlobalFile(item.file, environment)) return "--global ";
978
+ if (item.scope === "local" && base === "config") return "";
979
+ if (item.scope === "worktree" && base === "config.worktree") return "--worktree ";
980
+ let path = item.file;
981
+ let prefix = "";
982
+ const home = environment?.home;
983
+ if (home && path.startsWith(home)) {
984
+ path = path.slice(home.length).replace(/^\//, "");
985
+ prefix = "~/";
986
+ }
987
+ return `--file ${prefix}${quotePretty(path)} `;
988
+ }
989
+ function isGlobalFile(file, environment) {
990
+ if (!environment) return false;
991
+ if (environment.globalConfig !== void 0) return file === environment.globalConfig;
992
+ const home = environment.home?.replace(/\/+$/, "");
993
+ const xdg = environment.xdgConfigHome ?? (home ? `${home}/.config` : void 0);
994
+ return home !== void 0 && file === `${home}/.gitconfig` || xdg !== void 0 && file === `${xdg}/git/config`;
995
+ }
996
+ /** quote.c's `sq_quote_buf_pretty`: as is when every byte is safe, else single-quoted. */
997
+ function quotePretty(path) {
998
+ if (path !== "" && /^[A-Za-z0-9+,\-./:=@_^]+$/.test(path)) return path;
999
+ return `'${path.replace(/'/g, "'\\''").replace(/!/g, "'\\!'")}'`;
1000
+ }
1001
+ //#endregion
1750
1002
  //#region src/commands/core-config.ts
1751
1003
  /**
1752
1004
  * The `core.*` settings that decide how the worktree is read and written.
@@ -1836,7 +1088,8 @@ function createIdAbbreviator(workingCopy, options = {}) {
1836
1088
  let autoLength;
1837
1089
  const listings = options.cacheListings ? { cache: /* @__PURE__ */ new Map() } : void 0;
1838
1090
  const lengths = async (ids, minLength) => {
1839
- let start = minLength ?? parseCoreAbbrev(RemoteConfigStore.from(workingCopy).value("core.abbrev")) ?? -1;
1091
+ const hexLength = objectFormatOf(workingCopy.history).hexLength;
1092
+ let start = minLength ?? parseCoreAbbrev(RemoteConfigStore.from(workingCopy).value("core.abbrev"), hexLength) ?? -1;
1840
1093
  const objects = workingCopy.history?.objects;
1841
1094
  if (objects) {
1842
1095
  if (start < 0) {
@@ -1845,7 +1098,7 @@ function createIdAbbreviator(workingCopy, options = {}) {
1845
1098
  }
1846
1099
  return findAbbrevLengths(objects, ids, start, listings);
1847
1100
  }
1848
- const fixed = start < 0 ? DEFAULT_ABBREV_LENGTH : start === 0 ? 40 : Math.min(start, 40);
1101
+ const fixed = start < 0 ? DEFAULT_ABBREV_LENGTH : start === 0 ? hexLength : Math.min(start, hexLength);
1849
1102
  return new Map([...ids].map((id) => [id, fixed]));
1850
1103
  };
1851
1104
  return {
@@ -2242,6 +1495,13 @@ async function gitfileTarget(files, path) {
2242
1495
  function normalizeHostPath(path) {
2243
1496
  return `/${normalizeFilesPath(path)}`;
2244
1497
  }
1498
+ /**
1499
+ * A file of a working copy's common git directory (`remotes/<name>`, `packed-refs`) as the
1500
+ * repository's FilesApi names it; undefined when the working copy has no files layout.
1501
+ */
1502
+ async function commonGitFileOf(workingCopy, name) {
1503
+ return new HookSession(hookHostOf(workingCopy)).commonGitFile(name);
1504
+ }
2245
1505
  /** The common git directory of `gitDir` (its `commondir` file), as a FilesApi path. */
2246
1506
  async function commonDirOf(files, gitDir) {
2247
1507
  const path = joinFilesPath(gitDir, "commondir");
@@ -4178,7 +3438,7 @@ function newUntrackedCacheFlags(config) {
4178
3438
  * `core.untrackedCache` (an add needs the worktree's location and the system's name, git's
4179
3439
  * ident), then offered to the scan.
4180
3440
  */
4181
- function openUntrackedCache(staging, config, environment, host) {
3441
+ function openUntrackedCache(staging, config, environment, host, objectFormat = SHA1_OBJECT_FORMAT$1) {
4182
3442
  const supported = typeof staging.getUntrackedCache === "function";
4183
3443
  let cache = supported ? staging.getUntrackedCache?.() : void 0;
4184
3444
  let changed = false;
@@ -4189,7 +3449,7 @@ function openUntrackedCache(staging, config, environment, host) {
4189
3449
  changed = true;
4190
3450
  } else if (supported && setting === "write" && ident) {
4191
3451
  if (!cache || !untrackedCacheIdentIs(cache, ident)) {
4192
- cache = newUntrackedCache(ident, newUntrackedCacheFlags(config));
3452
+ cache = newUntrackedCache(ident, newUntrackedCacheFlags(config), objectFormat);
4193
3453
  changed = true;
4194
3454
  }
4195
3455
  }
@@ -4205,15 +3465,15 @@ function openUntrackedCache(staging, config, environment, host) {
4205
3465
  if (!untrackedCacheIdentIs(cache, ident)) return void 0;
4206
3466
  if (cache.dirFlags !== flags) {
4207
3467
  if (cache.dirFlags === newUntrackedCacheFlags(config)) return void 0;
4208
- cache = newUntrackedCache(ident, flags);
3468
+ cache = newUntrackedCache(ident, flags, objectFormat);
4209
3469
  changed = true;
4210
3470
  }
4211
3471
  if (!cache.root) {
4212
- cache.root = newUntrackedCacheDir("");
3472
+ cache.root = newUntrackedCacheDir("", objectFormat.nullId);
4213
3473
  changed = true;
4214
3474
  }
4215
- const info = await readExcludeFile(await host.readInfoExclude?.());
4216
- const excludes = await readExcludesFile(config, environment);
3475
+ const info = await readExcludeFile(await host.readInfoExclude?.(), objectFormat);
3476
+ const excludes = await readExcludesFile(config, environment, objectFormat);
4217
3477
  if (info.oid !== cache.infoExclude.oid) {
4218
3478
  invalidateGitignore(cache, cache.root);
4219
3479
  cache.infoExclude = info;
@@ -4233,40 +3493,35 @@ function openUntrackedCache(staging, config, environment, host) {
4233
3493
  };
4234
3494
  }
4235
3495
  /** An exclude file's id and stat as git's `add_patterns` records them (no istate). */
4236
- async function readExcludeFile(read) {
3496
+ async function readExcludeFile(read, objectFormat) {
4237
3497
  if (!read) return {
4238
3498
  stat: zeroStatData(),
4239
- oid: NULL_OID
3499
+ oid: objectFormat.nullId
4240
3500
  };
4241
3501
  return {
4242
3502
  stat: statDataOf(read.stat),
4243
- oid: await excludeFileOid(read.bytes)
3503
+ oid: await excludeFileOid(read.bytes, objectFormat)
4244
3504
  };
4245
3505
  }
4246
3506
  /**
4247
3507
  * `core.excludesFile` (`~/` expanded), else `$XDG_CONFIG_HOME/git/ignore`, read through the
4248
3508
  * host (git's `setup_standard_excludes`): the null id when it is not there.
4249
3509
  */
4250
- async function readExcludesFile(config, environment) {
4251
- if (!environment) return {
3510
+ async function readExcludesFile(config, environment, objectFormat) {
3511
+ const none = {
4252
3512
  stat: zeroStatData(),
4253
- oid: NULL_OID
3513
+ oid: objectFormat.nullId
4254
3514
  };
3515
+ if (!environment) return none;
4255
3516
  const configured = config.value("core.excludesFile");
4256
3517
  const path = configured !== void 0 && configured !== "" ? expandUserPath(configured, environment) : xdgConfigPath(environment, "ignore");
4257
- if (!path) return {
4258
- stat: zeroStatData(),
4259
- oid: NULL_OID
4260
- };
3518
+ if (!path) return none;
4261
3519
  const bytes = await environment.readFile(path).catch(() => void 0);
4262
- if (!bytes) return {
4263
- stat: zeroStatData(),
4264
- oid: NULL_OID
4265
- };
3520
+ if (!bytes) return none;
4266
3521
  const stat = await environment.statFile?.(path).catch(() => void 0);
4267
3522
  return {
4268
3523
  stat: stat ? statDataOf(stat) : zeroStatData(),
4269
- oid: await excludeFileOid(bytes)
3524
+ oid: await excludeFileOid(bytes, objectFormat)
4270
3525
  };
4271
3526
  }
4272
3527
  //#endregion
@@ -4482,6 +3737,354 @@ function indexHostOf(workingCopy, staging, trees) {
4482
3737
  };
4483
3738
  }
4484
3739
  //#endregion
3740
+ //#region src/commands/default-branch.ts
3741
+ /**
3742
+ * The initial branch of a new repository, as git's `repo_default_branch_name` (refs.c) picks
3743
+ * it: `init.defaultBranch` from the configuration a new repository sees (system, global, the
3744
+ * command line), else `master`, or `main` in a git built with `WITH_BREAKING_CHANGES`
3745
+ * (`GitHostEnvironment.breakingChanges`, git 3.0). With no name configured, git explains the
3746
+ * default in an `advice.defaultBranchName` hint, which {@link DefaultBranch.hint} holds.
3747
+ *
3748
+ * ```typescript
3749
+ * const { name, hint } = await defaultInitialBranch(environment);
3750
+ * // name: "master"; hint: ["hint: Using 'master' as the name for the initial branch. ...", ...]
3751
+ * ```
3752
+ */
3753
+ /** `init.defaultBranch` names no valid branch: git dies (exit 128). */
3754
+ var InvalidDefaultBranchError = class extends Error {
3755
+ value;
3756
+ name = "InvalidDefaultBranchError";
3757
+ lines;
3758
+ constructor(value) {
3759
+ const line = `fatal: invalid branch name: init.defaultBranch = ${value}`;
3760
+ super(line);
3761
+ this.value = value;
3762
+ this.lines = [line];
3763
+ }
3764
+ };
3765
+ /**
3766
+ * `init.defaultBranch` without a value (`[init] defaultBranch`): git's config parser dies
3767
+ * (`missing value`, then the variable's location), exit 128.
3768
+ */
3769
+ var MissingDefaultBranchValueError = class extends Error {
3770
+ name = "MissingDefaultBranchValueError";
3771
+ lines;
3772
+ constructor(file, line) {
3773
+ const lines = ["error: missing value for 'init.defaultbranch'", file !== void 0 && line !== void 0 ? `fatal: bad config variable 'init.defaultbranch' in file '${file}' at line ${line}` : "fatal: unable to parse 'init.defaultbranch' from command-line config"];
3774
+ super(lines.join("\n"));
3775
+ this.lines = lines;
3776
+ }
3777
+ };
3778
+ /** `--initial-branch` names no valid branch: git dies (exit 128). */
3779
+ var InvalidInitialBranchError = class extends Error {
3780
+ value;
3781
+ name = "InvalidInitialBranchError";
3782
+ lines;
3783
+ constructor(value) {
3784
+ const line = `fatal: invalid initial branch name: '${value}'`;
3785
+ super(line);
3786
+ this.value = value;
3787
+ this.lines = [line];
3788
+ }
3789
+ };
3790
+ /** Whether `name` is a valid branch name (`check_refname_format("refs/heads/<name>")`). */
3791
+ function isValidBranchName$1(name) {
3792
+ return name !== "" && isValidRefName(`refs/heads/${name}`);
3793
+ }
3794
+ /**
3795
+ * The initial branch of a repository created now. Reads the protected configuration (the
3796
+ * repository's own does not exist yet); without an environment, nothing is configured.
3797
+ *
3798
+ * @throws InvalidDefaultBranchError when `init.defaultBranch` names no valid branch (empty too)
3799
+ * @throws MissingDefaultBranchValueError when `init.defaultBranch` has no value
3800
+ */
3801
+ async function defaultInitialBranch(environment) {
3802
+ const config = await readProtectedConfig(environment);
3803
+ const last = (key) => config.filter((e) => e.key === key).at(-1);
3804
+ const configured = last("init.defaultbranch");
3805
+ if (configured && configured.value === void 0) throw new MissingDefaultBranchValueError(configured.file, configured.line);
3806
+ if (configured?.value !== void 0) {
3807
+ if (!isValidBranchName$1(configured.value)) throw new InvalidDefaultBranchError(configured.value);
3808
+ return { name: configured.value };
3809
+ }
3810
+ const name = environment?.breakingChanges ? "main" : "master";
3811
+ const advice = last("advice.defaultbranchname");
3812
+ return advice === void 0 || parseGitBool$1(advice.value ?? "true") !== false ? {
3813
+ name,
3814
+ hint: defaultBranchHint(name, environment?.breakingChanges)
3815
+ } : { name };
3816
+ }
3817
+ /** git's `default_branch_name_advice` (2.5x, or 3.0), as `advise_if_enabled` prints it. */
3818
+ function defaultBranchHint(name, breakingChanges) {
3819
+ return `${breakingChanges ? `Using '${name}' as the name for the initial branch since Git 3.0.\nIf you expected Git to create 'master', the just-created
3820
+ branch can be renamed via this command:
3821
+
3822
+ git branch -m master
3823
+ ` : `Using '${name}' as the name for the initial branch. This default branch name\nwill change to "main" in Git 3.0. To configure the initial branch name
3824
+ to use in all of your new repositories, which will suppress this warning,
3825
+ call:
3826
+
3827
+ git config --global init.defaultBranch <name>
3828
+
3829
+ Names commonly chosen instead of 'master' are 'main', 'trunk' and
3830
+ 'development'. The just-created branch can be renamed via this command:
3831
+
3832
+ git branch -m <name>
3833
+ `}\nDisable this message with "git config set ${breakingChanges ? "--global " : ""}advice.defaultBranchName false"`.split("\n").map((line) => line === "" ? "hint:" : `hint: ${line}`);
3834
+ }
3835
+ /** A ref storage format git does not know: git dies (exit 128). */
3836
+ var UnknownRefFormatError = class extends Error {
3837
+ value;
3838
+ name = "UnknownRefFormatError";
3839
+ lines;
3840
+ constructor(value, source) {
3841
+ const line = source === "command line" ? `fatal: unknown ref storage format specified via command line: '${value}'` : `fatal: unknown ref storage format specified via GIT_DEFAULT_REF_FORMAT: '${value}'`;
3842
+ super(line);
3843
+ this.value = value;
3844
+ this.lines = [line];
3845
+ }
3846
+ };
3847
+ const refFormatOf = (value) => value === "files" || value === "reftable" ? value : void 0;
3848
+ /**
3849
+ * The ref storage format git gives a new repository (setup.c `repository_format_configure`):
3850
+ * `requested` (`git init --ref-format`), else `$GIT_DEFAULT_REF_FORMAT`
3851
+ * (`GitHostEnvironment.defaultRefFormat`), else `init.defaultRefFormat` from the system,
3852
+ * global and command-line config (`feature.experimental` choosing reftable while that is
3853
+ * unset), else `files`, or `reftable` with `GitHostEnvironment.breakingChanges` (git 3.0).
3854
+ * An unknown name given or in the environment dies (`UnknownRefFormatError`); one in the
3855
+ * config warns and is passed over.
3856
+ *
3857
+ * @example
3858
+ * ```typescript
3859
+ * const { format } = await defaultRefFormat(environment); // "reftable" under git 3.0
3860
+ * ```
3861
+ */
3862
+ async function defaultRefFormat(environment, requested) {
3863
+ const warnings = [];
3864
+ if (requested !== void 0) {
3865
+ const format = refFormatOf(requested);
3866
+ if (!format) throw new UnknownRefFormatError(requested, "command line");
3867
+ return {
3868
+ format,
3869
+ warnings
3870
+ };
3871
+ }
3872
+ const env = environment?.defaultRefFormat;
3873
+ if (env !== void 0) {
3874
+ const format = refFormatOf(env);
3875
+ if (!format) throw new UnknownRefFormatError(env, "GIT_DEFAULT_REF_FORMAT");
3876
+ return {
3877
+ format,
3878
+ warnings
3879
+ };
3880
+ }
3881
+ let configured;
3882
+ for (const e of await readProtectedConfig(environment)) if (e.key === "init.defaultrefformat" || e.key === "init.defaultrefstorageformat") {
3883
+ const value = e.value ?? "";
3884
+ configured = refFormatOf(value);
3885
+ if (!configured) warnings.push(`warning: unknown ref storage format '${value}'`);
3886
+ } else if (e.key === "feature.experimental" && configured === void 0 && parseGitBool$1(e.value ?? "true") === true) configured = "reftable";
3887
+ if (configured) return {
3888
+ format: configured,
3889
+ warnings
3890
+ };
3891
+ return {
3892
+ format: environment?.breakingChanges ? "reftable" : "files",
3893
+ warnings
3894
+ };
3895
+ }
3896
+ //#endregion
3897
+ //#region src/commands/legacy-remotes.ts
3898
+ /**
3899
+ * git 2.x's legacy remotes: a remote defined by a file `$GIT_COMMON_DIR/remotes/<name>` or
3900
+ * `$GIT_COMMON_DIR/branches/<name>` instead of the configuration (remote.c
3901
+ * `read_remotes_file`, `read_branches_file`). git reads them when it looks a remote up by
3902
+ * name and the configuration gives that name no URL; git 3.0 (`WITH_BREAKING_CHANGES`,
3903
+ * `GitHostEnvironment.breakingChanges`) never reads them.
3904
+ *
3905
+ * @example
3906
+ * ```text
3907
+ * $ cat .git/remotes/upstream $ cat .git/branches/vendor
3908
+ * URL: https://example.com/r.git https://example.com/v.git#stable
3909
+ * Pull: refs/heads/main:refs/heads/upstream
3910
+ * Push: refs/heads/main:refs/heads/main
3911
+ * ```
3912
+ *
3913
+ * The branches file fetches `refs/heads/stable:refs/heads/vendor` and pushes
3914
+ * `HEAD:refs/heads/stable`; without `#<branch>` the branch is `init.defaultBranch`, else
3915
+ * `master`.
3916
+ */
3917
+ /**
3918
+ * Reads the legacy remote `name` of a working copy, as remote.c's `remotes_remote_get_1`
3919
+ * does, and records it for the working copy's {@link RemoteConfigStore}s (they see it while
3920
+ * the configuration gives the name no URL): nothing under git 3.0, for a name that is no
3921
+ * valid remote nickname (empty, `.`, `..`, a `/`), or for a remote the configuration gives a
3922
+ * URL; else `remotes/<name>`, then, while there is still no URL, `branches/<name>`.
3923
+ *
3924
+ * @param compatibility The git whose stderr to give: 2.43 has no deprecation warning
3925
+ */
3926
+ async function loadLegacyRemote(workingCopy, name, compatibility = "2.56") {
3927
+ const messages = [];
3928
+ const store = RemoteConfigStore.from(workingCopy);
3929
+ setLegacyRemote(workingCopy, name, void 0);
3930
+ if (hostEnvironmentOf(workingCopy)?.breakingChanges) return { messages };
3931
+ if (!isValidRemoteNick(name) || store.remoteUrls(name).length > 0) return { messages };
3932
+ let remote;
3933
+ const remotesFile = await readGitFile(workingCopy, `remotes/${name}`);
3934
+ if (remotesFile !== void 0) {
3935
+ if (compatibility !== "2.43") messages.push(deprecationWarning("remotes", name));
3936
+ remote = {
3937
+ ...parseRemotesFile(remotesFile),
3938
+ origin: "remotes",
3939
+ followTags: false
3940
+ };
3941
+ }
3942
+ if (!remote || remote.urls.length === 0) {
3943
+ const branchesFile = await readGitFile(workingCopy, `branches/${name}`);
3944
+ if (branchesFile !== void 0) {
3945
+ if (compatibility !== "2.43") messages.push(deprecationWarning("branches", name));
3946
+ const line = trimGitSpace(branchesFile.split("\n")[0] ?? "");
3947
+ if (line) {
3948
+ const at = line.indexOf("#");
3949
+ let branch;
3950
+ if (at >= 0) branch = line.slice(at + 1);
3951
+ else {
3952
+ const found = defaultBranchName(store, compatibility);
3953
+ branch = found.name;
3954
+ if (found.hint) messages.push(found.hint);
3955
+ }
3956
+ const url = at >= 0 ? line.slice(0, at) : line;
3957
+ remote = {
3958
+ origin: "branches",
3959
+ urls: [...remote?.urls ?? [], url],
3960
+ fetchRefspecs: [...remote?.fetchRefspecs ?? [], `refs/heads/${branch}:refs/heads/${name}`],
3961
+ pushRefspecs: [...remote?.pushRefspecs ?? [], `HEAD:refs/heads/${branch}`],
3962
+ followTags: true
3963
+ };
3964
+ }
3965
+ }
3966
+ }
3967
+ setLegacyRemote(workingCopy, name, remote);
3968
+ return {
3969
+ remote,
3970
+ messages
3971
+ };
3972
+ }
3973
+ /**
3974
+ * Removes the file a legacy remote was read from (builtin/remote.c `migrate_file`'s
3975
+ * `unlink_or_warn`) and forgets the remote; a file already gone is no error.
3976
+ */
3977
+ async function removeLegacyRemoteFile(workingCopy, origin, name) {
3978
+ const file = await commonGitFileOf(workingCopy, `${origin}/${name}`);
3979
+ if (file) await file.files.remove(file.path).catch(() => false);
3980
+ setLegacyRemote(workingCopy, name, void 0);
3981
+ }
3982
+ /** remote.c's `valid_remote_nick`: not empty, `.` or `..`, and no `/`. */
3983
+ function isValidRemoteNick(name) {
3984
+ return name !== "" && name !== "." && name !== ".." && !name.includes("/");
3985
+ }
3986
+ /**
3987
+ * Parses a `remotes/<name>` file as `read_remotes_file`: each line, its trailing
3988
+ * whitespace (git's `isspace`: space, `\t`, `\n`, `\r`) dropped, is a `URL:`, `Push:` or `Pull:` line (the value's leading whitespace
3989
+ * dropped) or ignored.
3990
+ */
3991
+ function parseRemotesFile(text) {
3992
+ const urls = [];
3993
+ const fetchRefspecs = [];
3994
+ const pushRefspecs = [];
3995
+ const lines = text.split("\n");
3996
+ if (lines.at(-1) === "") lines.pop();
3997
+ for (const raw of lines) {
3998
+ const line = raw.replace(/[\t\n\r ]+$/, "");
3999
+ const value = (prefix) => line.slice(prefix.length).replace(/^[\t\n\r ]+/, "");
4000
+ if (line.startsWith("URL:")) urls.push(value("URL:"));
4001
+ else if (line.startsWith("Push:")) pushRefspecs.push(value("Push:"));
4002
+ else if (line.startsWith("Pull:")) fetchRefspecs.push(value("Pull:"));
4003
+ }
4004
+ return {
4005
+ urls,
4006
+ fetchRefspecs,
4007
+ pushRefspecs
4008
+ };
4009
+ }
4010
+ /**
4011
+ * `strbuf_trim`: leading and trailing whitespace dropped as git's `isspace` (sane_ctype.h:
4012
+ * space, `\t`, `\n`, `\r` only; a vertical tab or form feed is kept, as JavaScript's
4013
+ * `trim()` would not).
4014
+ */
4015
+ function trimGitSpace(text) {
4016
+ return text.replace(/^[\t\n\r ]+/, "").replace(/[\t\n\r ]+$/, "");
4017
+ }
4018
+ /** 2.5x's `warn_about_deprecated_remote_type`, as `warning()` prints it. */
4019
+ function deprecationWarning(type, name) {
4020
+ return [
4021
+ `warning: reading remote from "${type}/${name}", which is nominated for removal.`,
4022
+ "",
4023
+ "If you still use the \"remotes/\" directory it is recommended to",
4024
+ "migrate to config-based remotes:",
4025
+ "",
4026
+ `\tgit remote rename ${name} ${name}`,
4027
+ "",
4028
+ "If you cannot, please let us know why you still need to use it by",
4029
+ "sending an e-mail to <git@vger.kernel.org>."
4030
+ ].join("\n");
4031
+ }
4032
+ /**
4033
+ * refs.c's `repo_default_branch_name(repo, 0)`: `init.defaultBranch` (every scope of the
4034
+ * working copy's configuration), else `master` with the `advice.defaultBranchName` hint.
4035
+ */
4036
+ function defaultBranchName(store, compatibility) {
4037
+ const configured = store.value("init.defaultBranch");
4038
+ if (configured !== void 0 && configured !== "") return { name: configured };
4039
+ const name = "master";
4040
+ const advice = store.value("advice.defaultBranchName");
4041
+ if (advice !== void 0 && parseGitBool$1(advice) === false) return { name };
4042
+ return {
4043
+ name,
4044
+ hint: (compatibility === "2.43" ? defaultBranchHint243(name) : defaultBranchHint(name, false)).join("\n")
4045
+ };
4046
+ }
4047
+ /** git 2.43's `default_branch_name_advice` (an empty line is `hint: `, with its space). */
4048
+ function defaultBranchHint243(name) {
4049
+ return [
4050
+ `Using '${name}' as the name for the initial branch. This default branch name`,
4051
+ "is subject to change. To configure the initial branch name to use in all",
4052
+ "of your new repositories, which will suppress this warning, call:",
4053
+ "",
4054
+ " git config --global init.defaultBranch <name>",
4055
+ "",
4056
+ "Names commonly chosen instead of 'master' are 'main', 'trunk' and",
4057
+ "'development'. The just-created branch can be renamed via this command:",
4058
+ "",
4059
+ " git branch -m <name>"
4060
+ ].map((line) => `hint: ${line}`);
4061
+ }
4062
+ /**
4063
+ * A file of the common git directory as text, or undefined when it is not a regular file
4064
+ * (absent, a directory: `fopen_or_warn` reads nothing from either).
4065
+ */
4066
+ async function readGitFile(workingCopy, name) {
4067
+ const file = await commonGitFileOf(workingCopy, name);
4068
+ if (!file) return void 0;
4069
+ return readText(file.files, file.path);
4070
+ }
4071
+ async function readText(files, path) {
4072
+ try {
4073
+ if ((await files.stats(path))?.kind !== "file") return void 0;
4074
+ const chunks = [];
4075
+ for await (const chunk of files.read(path)) chunks.push(chunk);
4076
+ const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
4077
+ let at = 0;
4078
+ for (const chunk of chunks) {
4079
+ bytes.set(chunk, at);
4080
+ at += chunk.length;
4081
+ }
4082
+ return new TextDecoder().decode(bytes);
4083
+ } catch {
4084
+ return;
4085
+ }
4086
+ }
4087
+ //#endregion
4485
4088
  //#region src/commands/promisor-remote.ts
4486
4089
  /**
4487
4090
  * A partial clone's promisor remotes and their lazy fetch (git's promisor-remote.c): the
@@ -4595,7 +4198,7 @@ function createPromisorFetcher(workingCopy, options = {}) {
4595
4198
  const history = historyWithoutLazyFetch(workingCopy.history);
4596
4199
  const compatibility = compatibilityOf();
4597
4200
  const run = async () => {
4598
- const { fetchFsckOf } = await import("./commands-DnmlfwGV.js").then((n) => n.st);
4201
+ const { fetchFsckOf } = await import("./commands-DIJ91NnD.js").then((n) => n.lt);
4599
4202
  const environment = hostEnvironmentOf(workingCopy);
4600
4203
  const fsckWarnings = [];
4601
4204
  const fsck = await fetchFsckOf({
@@ -4608,7 +4211,7 @@ function createPromisorFetcher(workingCopy, options = {}) {
4608
4211
  home: environment.home
4609
4212
  } : {}
4610
4213
  });
4611
- const { prepareRemote, protocolVersionOf, withRemoteUploadPack } = await import("./commands-DnmlfwGV.js").then((n) => n.Bt);
4214
+ const { prepareRemote, protocolVersionOf, withRemoteUploadPack } = await import("./commands-DIJ91NnD.js").then((n) => n.Wt);
4612
4215
  await withRemoteUploadPack(await prepareRemote(workingCopy, url, options.transports ?? createDefaultTransports()), {
4613
4216
  ...options.credentials ? { credentials: options.credentials } : {},
4614
4217
  ...options.headers ? { headers: options.headers } : {},
@@ -5385,8 +4988,7 @@ async function installTracking(workingCopy, newBranch, plan) {
5385
4988
  //#region src/commands/revision-resolver.ts
5386
4989
  const HEX_DIGIT = /^[0-9a-fA-F]$/;
5387
4990
  const isHexDigit = (c) => c !== void 0 && HEX_DIGIT.test(c);
5388
- const ZERO_ID = "0000000000000000000000000000000000000000";
5389
- const HEX_ID = /^[0-9a-fA-F]{40}$/;
4991
+ const HEX_DIGITS = /^[0-9a-fA-F]+$/;
5390
4992
  /** git's `object_name_msg` advice after a 40-hex name that is also a ref. */
5391
4993
  const OBJECT_NAME_ADVICE = [
5392
4994
  "Git normally never creates a ref that ends with 40 hex characters",
@@ -5443,6 +5045,13 @@ var RevisionResolver = class {
5443
5045
  constructor(sources, now = () => Math.floor(Date.now() / 1e3)) {
5444
5046
  this.sources = sources;
5445
5047
  this.now = now;
5048
+ this.hexLength = objectFormatOf(sources.objects).hexLength;
5049
+ }
5050
+ /** The repository's full hex id length: 40, or 64 in a SHA-256 repository (git's hexsz) */
5051
+ hexLength;
5052
+ /** Whether `str` is a full hex object id of the repository's format, in any case */
5053
+ isFullHex(str) {
5054
+ return str.length === this.hexLength && HEX_DIGITS.test(str);
5446
5055
  }
5447
5056
  /**
5448
5057
  * The object `name` names, or undefined when it names none (git's `unknown revision`).
@@ -5517,6 +5126,7 @@ var RevisionResolver = class {
5517
5126
  throw this.fatal(revision, `no upstream configured for branch '${name}'`);
5518
5127
  }
5519
5128
  const src = merges[0] ?? "";
5129
+ await loadLegacyRemote(this.sources.workingCopy, remote);
5520
5130
  let dst = applyRefspecs(config.configuredFetchRefspecs(remote), src);
5521
5131
  if (dst === void 0 && remote === ".") {
5522
5132
  const found = await this.dwimRefAll(src, false);
@@ -5546,12 +5156,13 @@ var RevisionResolver = class {
5546
5156
  const config = this.remoteConfig();
5547
5157
  const refname = `refs/heads/${name}`;
5548
5158
  const remote = this.pushRemoteOf(name);
5159
+ await loadLegacyRemote(this.sources.workingCopy, remote);
5549
5160
  const trackingFor = (dst) => {
5550
5161
  const tracking = applyRefspecs(config.configuredFetchRefspecs(remote), dst);
5551
5162
  if (tracking === void 0) throw this.fatal(revision, `push destination '${dst}' on remote '${remote}' has no local tracking branch`);
5552
5163
  return tracking;
5553
5164
  };
5554
- const pushSpecs = config.values(`remote.${remote}.push`);
5165
+ const pushSpecs = config.pushRefspecs(remote);
5555
5166
  if (pushSpecs.length > 0) {
5556
5167
  const dst = applyRefspecs(pushSpecs, refname);
5557
5168
  if (dst === void 0) throw this.fatal(revision, `push refspecs for '${remote}' do not include '${name}'`);
@@ -5661,7 +5272,7 @@ var RevisionResolver = class {
5661
5272
  * object or not), a ref, `<ref>@{<n>|<date>}`, `@{-N}`.
5662
5273
  */
5663
5274
  async basic(str, flags = {}) {
5664
- if (HEX_ID.test(str)) {
5275
+ if (this.isFullHex(str)) {
5665
5276
  if (this.warnAmbiguousRefs() && (await this.dwimRefAll(str)).length > 0) {
5666
5277
  this.warnings.push(`warning: refname '${str}' is ambiguous.`);
5667
5278
  if (parseGitBool$1(this.remoteConfig().value("advice.objectNameWarning")) !== false) this.warnings.push(OBJECT_NAME_ADVICE);
@@ -5691,7 +5302,7 @@ var RevisionResolver = class {
5691
5302
  if (len > 0 && ambiguousPath(base)) return void 0;
5692
5303
  if (nthPrior) {
5693
5304
  const prior = await this.nthPriorCheckout(base);
5694
- if (typeof prior === "object" && HEX_ID.test(prior.value)) return await this.objectType(prior.value.toLowerCase()) ? prior.value.toLowerCase() : void 0;
5305
+ if (typeof prior === "object" && this.isFullHex(prior.value)) return await this.objectType(prior.value.toLowerCase()) ? prior.value.toLowerCase() : void 0;
5695
5306
  }
5696
5307
  let all;
5697
5308
  if (len === 0 && reflogLen > 0) all = await this.dwimRefAll("HEAD");
@@ -5719,7 +5330,7 @@ var RevisionResolver = class {
5719
5330
  if (len === 0) shown = found.ref.startsWith("refs/heads/") ? found.ref.slice(11) : "HEAD";
5720
5331
  if (atTime) {
5721
5332
  if (!flags.quiet) this.warnings.push(`warning: log for '${shown}' only goes back to ${formatRfc2822Date(read.cutoffTime, read.cutoffTz)}`);
5722
- } else if (!(nth === read.cutoffCount && read.id !== ZERO_ID)) throw this.fatal(str, `log for '${shown}' only has ${read.cutoffCount} entries`);
5333
+ } else if (!(nth === read.cutoffCount && !isNullObjectId(read.id))) throw this.fatal(str, `log for '${shown}' only has ${read.cutoffCount} entries`);
5723
5334
  }
5724
5335
  return read.id;
5725
5336
  }
@@ -5731,14 +5342,14 @@ var RevisionResolver = class {
5731
5342
  const log = await this.sources.refs.getReflog?.(ref);
5732
5343
  const entries = log ? await log.getReverseEntries() : [];
5733
5344
  let cnt = nth;
5734
- let ooid = ZERO_ID;
5345
+ let ooid;
5735
5346
  let reccnt = 0;
5736
5347
  let id = current;
5737
5348
  for (const entry of entries) {
5738
5349
  const timestamp = entry.who.timestamp;
5739
5350
  if (timestamp <= atTime || cnt === 0) {
5740
5351
  const date = formatRfc2822Date(timestamp, entry.who.tzOffset);
5741
- if (ooid !== ZERO_ID) {
5352
+ if (ooid !== void 0 && !isNullObjectId(ooid)) {
5742
5353
  id = entry.newId;
5743
5354
  if (ooid !== entry.newId) this.warnings.push(`warning: log for ref ${ref} has gap after ${date}`);
5744
5355
  } else if (timestamp === atTime) id = entry.newId;
@@ -5768,7 +5379,7 @@ var RevisionResolver = class {
5768
5379
  const oldest = entries[entries.length - 1];
5769
5380
  if (!oldest) throw this.fatal(ref, `log for ${ref} is empty`);
5770
5381
  id = oldest.oldId;
5771
- if (atTime && id === ZERO_ID) id = oldest.newId;
5382
+ if (atTime && isNullObjectId(id)) id = oldest.newId;
5772
5383
  return {
5773
5384
  id,
5774
5385
  missing: true,
@@ -6130,7 +5741,7 @@ var RevisionResolver = class {
6130
5741
  }
6131
5742
  }
6132
5743
  /**
6133
- * git's `get_short_oid`: the one stored object whose id starts with `name` (4 to 40 hex
5744
+ * git's `get_short_oid`: the one stored object whose id starts with `name` (4 to 40 hex, 64 in a SHA-256 repository,
6134
5745
  * digits, any case). Of several, the one the hint (`flags.hint`, else `core.disambiguate`)
6135
5746
  * accepts, when it accepts exactly one. An ambiguity is reported, unless quiet, as git
6136
5747
  * reports it: `error: short object ID <prefix> is ambiguous` and `hint:` lines listing the
@@ -6138,7 +5749,7 @@ var RevisionResolver = class {
6138
5749
  * when it accepts several.
6139
5750
  */
6140
5751
  async shortOid(name, flags = {}) {
6141
- if (name.length < MINIMUM_ABBREV_LENGTH || name.length > 40 || !/^[0-9a-fA-F]+$/.test(name)) return { status: "invalid" };
5752
+ if (name.length < MINIMUM_ABBREV_LENGTH || name.length > this.hexLength || !HEX_DIGITS.test(name)) return { status: "invalid" };
6142
5753
  const prefix = name.toLowerCase();
6143
5754
  const candidates = await this.objectsWithPrefix(prefix);
6144
5755
  if (candidates.length === 0) return { status: "missing" };
@@ -6694,6 +6305,16 @@ var GitCommand = class {
6694
6305
  return this.hookSession;
6695
6306
  }
6696
6307
  /**
6308
+ * Reads the legacy remote `name` (`$GIT_COMMON_DIR/remotes/<name>`, then `branches/<name>`)
6309
+ * as git 2.x's `remote_get` does before it looks the remote up, so this working copy's
6310
+ * `RemoteConfigStore`s see it (see `loadLegacyRemote`); nothing under git 3.0.
6311
+ *
6312
+ * @returns what git prints on stderr reading them, for this command's compatibility
6313
+ */
6314
+ async loadLegacyRemote(name) {
6315
+ return (await loadLegacyRemote(this._workingCopy, name, this.hooks.compatibility)).messages;
6316
+ }
6317
+ /**
6697
6318
  * Runs this command's hooks in another command's session: a command that runs another
6698
6319
  * (merge committing, rebase picking) gathers the output of both in one place. With `env`,
6699
6320
  * this command's hooks also get those variables, as the hooks of a git command git runs as
@@ -6807,10 +6428,22 @@ var GitCommand = class {
6807
6428
  author: () => this.resolveAuthor(),
6808
6429
  committer: () => this.resolveCommitter(),
6809
6430
  reflogLine: (message) => this.reflogLine(message),
6810
- resolve: (name) => /^[0-9a-fA-F]{40}$/.test(name) ? Promise.resolve(name.toLowerCase()) : this.revisionResolver().resolve(name).catch(() => void 0)
6431
+ objectFormat: this.objectFormat,
6432
+ resolve: (name) => name.length === this.objectFormat.hexLength && /^[0-9a-fA-F]+$/.test(name) ? Promise.resolve(name.toLowerCase()) : this.revisionResolver().resolve(name).catch(() => void 0)
6811
6433
  };
6812
6434
  }
6813
6435
  /**
6436
+ * The repository's object format (`extensions.objectFormat`): the length of its ids, its
6437
+ * null id, empty tree and empty blob. SHA-1 unless the repository is SHA-256.
6438
+ */
6439
+ get objectFormat() {
6440
+ return objectFormatOf(this._workingCopy.history);
6441
+ }
6442
+ /** Whether `id` is a full lowercase hex id of the repository's format (40, or 64 digits) */
6443
+ isFullObjectId(id) {
6444
+ return id.length === this.objectFormat.hexLength && /^[0-9a-f]+$/.test(id);
6445
+ }
6446
+ /**
6814
6447
  * Whether this command reads objects through replace refs and grafts (see {@link commits}).
6815
6448
  * git applies them to every object read but those of gc, prune, pack-objects, upload-pack,
6816
6449
  * index-pack, fsck and commit-graph; the commands doing those override this to read the
@@ -7358,6 +6991,7 @@ var GitCommand = class {
7358
6991
  checkConfigOnLoad() {
7359
6992
  const failure = configLoadError(this._workingCopy);
7360
6993
  if (failure) throw new InvalidConfigError(failure.key, failure.message);
6994
+ checkAutoCommentChar(this._workingCopy);
7361
6995
  const indexVersion = indexVersionConfigError(this._workingCopy);
7362
6996
  if (indexVersion) throw indexVersion;
7363
6997
  }
@@ -7609,4 +7243,4 @@ function concatBytes(chunks) {
7609
7243
  return out;
7610
7244
  }
7611
7245
  //#endregion
7612
- export { pruneEmptyParents as $, deleteRefs as $t, registerPartialClone as A, coreBool as At, pushSparseWarnings as B, InvalidIdentError as Bt, updateHeadExpecting as C, isKnownHook as Ct, installPromisorFetcher as D, sequencerPostCommit as Dt, hasPromisorRemote as E, runPostCheckoutHook as Et, takeIndexWarnings as F, configValue as Ft, sparsePathAdvice as G, identConfigOf as Gt, readSparseCheckoutPatterns as H, committerIdentOf as Ht, openUntrackedCache as I, conflictStyleOf as It, IndexCaseFolding as J, resolveIdentDate as Jt, sparseWarningText as K, resolveAuthorIdent as Kt, SparseUnpack as L, DEFAULT_IDENT as Lt, indexFormatDefault as M, worktreeModeTrust as Mt, indexVersionConfigError as N, bareAttributesResolver as Nt, promisorOf as O, sequencerPrepareMessage as Ot, markReaddedEntries as P, configBool as Pt, overwriteMessage as Q, parseGitDate as Qt, cleanTrackedSparseDirectories as R, IdentityUnknownError as Rt, updateHead as S, hookSettingsFromEntries as St, createPromisorFetcher as T, refTransactionHookOf as Tt, sparseCheckoutConfig as U, findIdent as Ut, readSparseCheckoutFile as V, authorIdentOf as Vt, sparseDirectoriesOf as W, hostEnvironmentOf as Wt, findInTheWay as X, formatRfc2822Date as Xt, entryNotUptodate as Y, withoutCrud as Yt, flaggedEntryDiffers as Z, localTimezoneOffset as Zt, unknownRevisionMessage as _, gitCommitAfterHooks as _t, guessRemoteBranch as a, worktreeDiffers as at, reflogMessages as b, hookRunnerOf as bt, trackableStart as c, planFlatRestore as ct, lstatExists as d, writeTreeRestorePlan as dt, moveRefs as en, removeCaseVariants as et, parseRevisionAndPathArgs as f, markIndexUpdate as ft, parseRevisionArgs as g, configuredHooks as gt, handleRevisionArg as h, configuredHookEntries as ht, endOfSymbolicChain as i, untrackedUnder as it, IndexVersionConfigError as j, createIdAbbreviator as jt, promisorRemotes as k, abbrevLengths as kt, checkFilename as l, planTreeRestore as lt, verifyNonFilename as m, LOCAL_REPO_ENV as mt, RevisionResolver as n, defaultFetchRefspec as nn, statFollowingLinks as nt, installTracking as o, worktreeModified as ot, verifyFilename as p, HookSession as pt, updateSparsity as q, resolveCommitterIdent as qt, TrackMode as r, listRemoteNames as rn, statThroughLeadingLinks as rt, planTracking as s, checkoutFreshTree as st, GitCommand as t, RemoteConfigStore as tn, removeDirectoryIfEmpty as tt, looksLikePathspec as u, restoreCaseOptions as ut, committerIdent as v, gitCommitMessageHooks as vt, LAZY_FETCH_DISABLED_WARNING as w, nullIdLike as wt, reflogSubject as x, hookSettingsCheck as xt, reflogLine as y, hookHostOf as yt, entryList as z, InvalidDateError as zt };
7246
+ export { sparseDirectoriesOf as $, InvalidIdentError as $t, registerPartialClone as A, hookRunnerOf as At, IndexVersionConfigError as B, coreBool as Bt, updateHeadExpecting as C, LOCAL_REPO_ENV as Ct, installPromisorFetcher as D, gitCommitAfterHooks as Dt, hasPromisorRemote as E, configuredHooks as Et, UnknownRefFormatError as F, refTransactionHookOf as Ft, openUntrackedCache as G, checkAutoCommentChar as Gt, indexVersionConfigError as H, worktreeModeTrust as Ht, defaultBranchHint as I, runPostCheckoutHook as It, entryList as J, configValue as Jt, SparseUnpack as K, bareAttributesResolver as Kt, defaultInitialBranch as L, sequencerPostCommit as Lt, InvalidDefaultBranchError as M, hookSettingsFromEntries as Mt, InvalidInitialBranchError as N, isKnownHook as Nt, promisorOf as O, gitCommitMessageHooks as Ot, MissingDefaultBranchValueError as P, nullIdLike as Pt, sparseCheckoutConfig as Q, InvalidDateError as Qt, defaultRefFormat as R, sequencerPrepareMessage as Rt, updateHead as S, HookSession as St, createPromisorFetcher as T, configuredHookEntries as Tt, markReaddedEntries as U, AutoCommentCharRemovedError as Ut, indexFormatDefault as V, createIdAbbreviator as Vt, takeIndexWarnings as W, autoCommentCharLines as Wt, readSparseCheckoutFile as X, DEFAULT_IDENT as Xt, pushSparseWarnings as Y, conflictStyleOf as Yt, readSparseCheckoutPatterns as Z, IdentityUnknownError as Zt, unknownRevisionMessage as _, planFlatRestore as _t, guessRemoteBranch as a, resolveAuthorIdent as an, findInTheWay as at, reflogMessages as b, writeTreeRestorePlan as bt, trackableStart as c, withoutCrud as cn, pruneEmptyParents as ct, lstatExists as d, parseGitDate as dn, statFollowingLinks as dt, authorIdentOf as en, sparsePathAdvice as et, parseRevisionAndPathArgs as f, deleteRefs as fn, statThroughLeadingLinks as ft, parseRevisionArgs as g, listRemoteNames as gn, checkoutFreshTree as gt, handleRevisionArg as h, defaultFetchRefspec as hn, worktreeModified as ht, endOfSymbolicChain as i, identConfigOf as in, entryNotUptodate as it, removeLegacyRemoteFile as j, hookSettingsCheck as jt, promisorRemotes as k, hookHostOf as kt, checkFilename as l, formatRfc2822Date as ln, removeCaseVariants as lt, verifyNonFilename as m, RemoteConfigStore as mn, worktreeDiffers as mt, RevisionResolver as n, findIdent as nn, updateSparsity as nt, installTracking as o, resolveCommitterIdent as on, flaggedEntryDiffers as ot, verifyFilename as p, moveRefs as pn, untrackedUnder as pt, cleanTrackedSparseDirectories as q, configBool as qt, TrackMode as r, hostEnvironmentOf as rn, IndexCaseFolding as rt, planTracking as s, resolveIdentDate as sn, overwriteMessage as st, GitCommand as t, committerIdentOf as tn, sparseWarningText as tt, looksLikePathspec as u, localTimezoneOffset as un, removeDirectoryIfEmpty as ut, committerIdent as v, planTreeRestore as vt, LAZY_FETCH_DISABLED_WARNING as w, commonGitFileOf as wt, reflogSubject as x, markIndexUpdate as xt, reflogLine as y, restoreCaseOptions as yt, isValidBranchName$1 as z, abbrevLengths as zt };