@statewalker/vcs-commands 0.12.0 → 0.14.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 (106) hide show
  1. package/dist/commands/archive/archive-command.d.ts +6 -2
  2. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  3. package/dist/commands/archive/remote-archive-command.d.ts +23 -1
  4. package/dist/commands/archive/remote-archive-command.d.ts.map +1 -1
  5. package/dist/commands/archive/upload-archive-writer.d.ts +11 -5
  6. package/dist/commands/archive/upload-archive-writer.d.ts.map +1 -1
  7. package/dist/commands/bundle/bundle-format.d.ts +6 -1
  8. package/dist/commands/bundle/bundle-format.d.ts.map +1 -1
  9. package/dist/commands/bundle/bundle-uri-host.d.ts +12 -1
  10. package/dist/commands/bundle/bundle-uri-host.d.ts.map +1 -1
  11. package/dist/commands/bundle/bundle-uri.d.ts +7 -1
  12. package/dist/commands/bundle/bundle-uri.d.ts.map +1 -1
  13. package/dist/commands/bundle/bundle-verify.d.ts +4 -1
  14. package/dist/commands/bundle/bundle-verify.d.ts.map +1 -1
  15. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  16. package/dist/commands/check-ignore-command.d.ts.map +1 -1
  17. package/dist/commands/clone-command.d.ts +15 -0
  18. package/dist/commands/clone-command.d.ts.map +1 -1
  19. package/dist/commands/commit-command.d.ts +10 -1
  20. package/dist/commands/commit-command.d.ts.map +1 -1
  21. package/dist/commands/default-branch.d.ts +17 -3
  22. package/dist/commands/default-branch.d.ts.map +1 -1
  23. package/dist/commands/fetch-command.d.ts +2 -1
  24. package/dist/commands/fetch-command.d.ts.map +1 -1
  25. package/dist/commands/fsck/fsck-object-checks.d.ts.map +1 -1
  26. package/dist/commands/git-hooks.d.ts +3 -3
  27. package/dist/commands/git-hooks.d.ts.map +1 -1
  28. package/dist/commands/http-config.d.ts +1 -1
  29. package/dist/commands/http-config.d.ts.map +1 -1
  30. package/dist/commands/index.js +6 -6
  31. package/dist/commands/init-command.d.ts.map +1 -1
  32. package/dist/commands/local-transport.d.ts +11 -1
  33. package/dist/commands/local-transport.d.ts.map +1 -1
  34. package/dist/commands/ls-tree-command.d.ts +10 -0
  35. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  36. package/dist/commands/merge-command.d.ts +11 -1
  37. package/dist/commands/merge-command.d.ts.map +1 -1
  38. package/dist/commands/merge-support.d.ts +19 -2
  39. package/dist/commands/merge-support.d.ts.map +1 -1
  40. package/dist/commands/plumbing-input.d.ts.map +1 -1
  41. package/dist/commands/promisor-remote-reply.d.ts +31 -4
  42. package/dist/commands/promisor-remote-reply.d.ts.map +1 -1
  43. package/dist/commands/promisor-remote.d.ts +8 -1
  44. package/dist/commands/promisor-remote.d.ts.map +1 -1
  45. package/dist/commands/push-command.d.ts.map +1 -1
  46. package/dist/commands/ref-filter/index.d.ts +1 -0
  47. package/dist/commands/ref-filter/index.d.ts.map +1 -1
  48. package/dist/commands/ref-filter/peel-limit.d.ts +8 -0
  49. package/dist/commands/ref-filter/peel-limit.d.ts.map +1 -0
  50. package/dist/commands/ref-filter/ref-filter.d.ts.map +1 -1
  51. package/dist/commands/ref-filter/ref-format.d.ts.map +1 -1
  52. package/dist/commands/serve-repository.d.ts +4 -3
  53. package/dist/commands/serve-repository.d.ts.map +1 -1
  54. package/dist/commands/signing.d.ts +29 -2
  55. package/dist/commands/signing.d.ts.map +1 -1
  56. package/dist/commands/split-cmdline.d.ts +6 -0
  57. package/dist/commands/split-cmdline.d.ts.map +1 -0
  58. package/dist/{commands-C2E51T1z.js → commands-C9M78Chn.js} +1186 -1036
  59. package/dist/errors/commit-errors.d.ts +17 -1
  60. package/dist/errors/commit-errors.d.ts.map +1 -1
  61. package/dist/errors/index.js +18 -3
  62. package/dist/{fsck-BjlxStsM.js → fsck-C4US3l0B.js} +2 -2
  63. package/dist/index.js +7 -7
  64. package/dist/{maintenance-run-command-G_eWdA8O.js → maintenance-run-command-CoJFKr2p.js} +85 -33
  65. package/dist/{remote-transport-CSgTJ1BH.js → remote-transport-C43eykfK.js} +51 -16
  66. package/dist/results/index.js +1 -1
  67. package/dist/{results-Dg1KHG8y.js → results-B0CWLCAp.js} +398 -54
  68. package/dist/transport-command.d.ts +3 -0
  69. package/dist/transport-command.d.ts.map +1 -1
  70. package/package.json +21 -13
  71. package/src/commands/archive/archive-command.ts +7 -3
  72. package/src/commands/archive/remote-archive-command.ts +37 -3
  73. package/src/commands/archive/upload-archive-writer.ts +34 -22
  74. package/src/commands/bundle/bundle-format.ts +10 -2
  75. package/src/commands/bundle/bundle-uri-host.ts +71 -11
  76. package/src/commands/bundle/bundle-uri.ts +11 -4
  77. package/src/commands/bundle/bundle-verify.ts +4 -1
  78. package/src/commands/cat-file/cat-file-command.ts +1 -33
  79. package/src/commands/check-ignore-command.ts +60 -15
  80. package/src/commands/clone-command.ts +89 -11
  81. package/src/commands/commit-command.ts +42 -7
  82. package/src/commands/default-branch.ts +19 -5
  83. package/src/commands/fetch-command.ts +13 -2
  84. package/src/commands/fsck/fsck-object-checks.ts +3 -1
  85. package/src/commands/git-hooks.ts +11 -5
  86. package/src/commands/http-config.ts +47 -1
  87. package/src/commands/init-command.ts +24 -4
  88. package/src/commands/local-transport.ts +53 -9
  89. package/src/commands/ls-tree-command.ts +20 -12
  90. package/src/commands/merge-command.ts +32 -8
  91. package/src/commands/merge-support.ts +42 -4
  92. package/src/commands/plumbing-input.ts +3 -1
  93. package/src/commands/promisor-remote-reply.ts +338 -56
  94. package/src/commands/promisor-remote.ts +25 -3
  95. package/src/commands/push-command.ts +5 -1
  96. package/src/commands/read-tree-command.ts +2 -2
  97. package/src/commands/ref-filter/index.ts +1 -0
  98. package/src/commands/ref-filter/peel-limit.ts +7 -0
  99. package/src/commands/ref-filter/ref-filter.ts +9 -3
  100. package/src/commands/ref-filter/ref-format.ts +2 -1
  101. package/src/commands/repack-command.ts +1 -1
  102. package/src/commands/serve-repository.ts +8 -3
  103. package/src/commands/signing.ts +93 -10
  104. package/src/commands/split-cmdline.ts +32 -0
  105. package/src/errors/commit-errors.ts +24 -2
  106. package/src/transport-command.ts +31 -1
@@ -6,8 +6,13 @@
6
6
  * `partialCloneFilter` and `token` of a remote it already has), and which remotes its lazy
7
7
  * fetches then try first ({@link acceptedPromisorRemotes}).
8
8
  *
9
- * Not yet: `promisor.acceptFromServerUrl` (2.56: remotes created from an advertised URL) and
10
- * `--filter=auto`.
9
+ * `promisor.acceptFromServerUrl` (git 2.56) is consulted first: an advertised URL matching one
10
+ * of its globs (`[<name>=]<url pattern>`, urlmatch.c's normalization, `*` within the host or
11
+ * the path) is accepted whatever `acceptFromServer` says, an unknown remote being created as
12
+ * `remote.<name>.url`/`promisor`/`advertisedAs` (the pattern's name, else
13
+ * `promisor-auto-<sanitized url>`, `-<n>` added while another URL holds the name). The filters
14
+ * the accepted remotes advertised make `--filter=auto` (git 2.54,
15
+ * {@link promisorAutoFilter}).
11
16
  *
12
17
  * @example
13
18
  * ```ts
@@ -18,14 +23,15 @@
18
23
  * ```
19
24
  */
20
25
 
21
- import { ObjectFilterError, parseObjectFilter } from "@statewalker/vcs-core";
26
+ import { isValidRefName, ObjectFilterError, parseObjectFilter } from "@statewalker/vcs-core";
22
27
  import {
23
28
  encodePromisorRemoteNames,
24
29
  type PromisorRemoteInfo,
25
30
  type PromisorRemoteReply,
26
31
  parsePromisorRemoteInfo,
27
32
  } from "@statewalker/vcs-transport";
28
- import type { WorkingCopy } from "@statewalker/vcs-working-tree";
33
+ import { isUrlNormalizeError, type NormalizedUrl, normalizeUrl } from "@statewalker/vcs-utils";
34
+ import { type WorkingCopy, wildmatchBytes } from "@statewalker/vcs-working-tree";
29
35
  import { RemoteConfigStore } from "../remote-config/index.js";
30
36
  import { promisorRemotes } from "./promisor-remote.js";
31
37
 
@@ -38,6 +44,13 @@ const KNOWN_FIELDS = new Map([
38
44
  ]);
39
45
 
40
46
  const accepted = new WeakMap<object, Set<string>>();
47
+ /** The filter each accepted remote advertised (git's `promisor_remote.advertised_filter`). */
48
+ const advertisedFilters = new WeakMap<object, Map<string, string>>();
49
+
50
+ /** An advertised remote accepted under the name it has here (git's `local_name`). */
51
+ interface Accepted extends PromisorRemoteInfo {
52
+ localName: string;
53
+ }
41
54
 
42
55
  /**
43
56
  * The promisor remotes a server's `promisor-remote` advertisement made this repository
@@ -48,6 +61,18 @@ export function acceptedPromisorRemotes(workingCopy: WorkingCopy): ReadonlySet<s
48
61
  return accepted.get(keyOf(workingCopy)) ?? new Set();
49
62
  }
50
63
 
64
+ /**
65
+ * Forgets what earlier `promisor-remote` answers accepted for this repository, as each git
66
+ * process starts with none (`promisor_remote.accepted`, `advertised_filter`): a fetch or clone
67
+ * calls it before it connects, so `--filter=auto` and the lazy fetches' order follow only the
68
+ * server it talks to now.
69
+ */
70
+ export function resetPromisorAcceptance(workingCopy: WorkingCopy): void {
71
+ const key = keyOf(workingCopy);
72
+ accepted.delete(key);
73
+ advertisedFilters.delete(key);
74
+ }
75
+
51
76
  function keyOf(workingCopy: WorkingCopy): object {
52
77
  try {
53
78
  return workingCopy.history?.objects ?? workingCopy;
@@ -61,10 +86,15 @@ function keyOf(workingCopy: WorkingCopy): object {
61
86
  * `fetchFromConnection` (`FetchClientOptions.promisorRemote`). `stderr` gets git's lines
62
87
  * (warnings, `Storing new filter from server ...`), each without its newline. Each call reads
63
88
  * the configuration afresh: a stored field is not stored (nor told) again.
89
+ *
90
+ * `remember: false` answers as a child process of git would (a lazy fetch's `git fetch`): its
91
+ * acceptance changes the configuration it writes, not the remotes this repository's lazy
92
+ * fetches try first nor `--filter=auto`.
64
93
  */
65
94
  export function promisorRemoteReplyOf(
66
95
  workingCopy: WorkingCopy,
67
96
  stderr: (line: string) => void,
97
+ options: { remember?: boolean } = {},
68
98
  ): PromisorRemoteReply {
69
99
  // fields_checked / fields_stored warn about unknown names once per process
70
100
  const warnedFields = new Set<string>();
@@ -90,71 +120,118 @@ export function promisorRemoteReplyOf(
90
120
  return async (info) => {
91
121
  const store = RemoteConfigStore.from(workingCopy);
92
122
  const policy = acceptPolicyOf(store, stderr);
93
- if (policy === "none") return undefined;
123
+ const acceptUrls = loadAcceptFromServerUrl(store, stderr);
124
+ if (policy === "none" && acceptUrls.length === 0) return undefined;
94
125
  const { remotes, warnings } = parsePromisorRemoteInfo(info);
95
126
  for (const w of warnings) stderr(`warning: ${w}`);
96
127
  const checked = fieldsOf(store, "promisor.checkFields");
128
+ // config_info and store_info: the promisor remotes as this call found them (a remote it
129
+ // creates is not one of them before the next call)
97
130
  const local = configuredPromisors(store, checked);
98
- const accepting: PromisorRemoteInfo[] = [];
99
- for (const advertised of remotes) {
100
- if (shouldAccept(policy, advertised, local, checked, stderr)) accepting.push(advertised);
101
- }
102
- if (accepting.length === 0) return undefined;
103
- // promisor_store_advertised_fields: only for a remote configured here
104
131
  const storedFields = fieldsOf(store, "promisor.storeFields");
132
+ const current = configuredPromisors(store, storedFields);
133
+ const accepting: Accepted[] = [];
105
134
  let changed = false;
106
- if (storedFields.length > 0) {
107
- const current = configuredPromisors(store, storedFields);
108
- for (const advertised of accepting) {
109
- const mine = current.find((p) => p.name === advertised.name);
110
- if (!mine) continue;
111
- if (
112
- storedFields.includes("partialCloneFilter") &&
113
- advertised.filter !== undefined &&
114
- validFilter(advertised.filter, advertised.name, stderr)
115
- ) {
116
- changed =
117
- storeField(
118
- store,
119
- advertised.name,
120
- "filter",
121
- "partialCloneFilter",
122
- advertised.filter,
123
- mine.filter,
124
- stderr,
125
- ) || changed;
126
- }
127
- if (
128
- storedFields.includes("token") &&
129
- advertised.token !== undefined &&
130
- validToken(advertised.token, advertised.name, stderr)
131
- ) {
132
- changed =
133
- storeField(
134
- store,
135
- advertised.name,
136
- "token",
137
- "token",
138
- advertised.token,
139
- mine.token,
140
- stderr,
141
- ) || changed;
142
- }
135
+ for (const advertised of remotes) {
136
+ const decision = shouldAccept(policy, advertised, local, checked, acceptUrls, store, stderr);
137
+ if (decision.created) changed = true;
138
+ if (decision.localName === undefined) continue;
139
+ const accepted: Accepted = { ...advertised, localName: decision.localName };
140
+ accepting.push(accepted);
141
+ // promisor_store_advertised_fields: only for a remote configured here
142
+ const mine = current.find((p) => p.name === accepted.localName);
143
+ if (!mine || storedFields.length === 0) continue;
144
+ if (
145
+ storedFields.includes("partialCloneFilter") &&
146
+ advertised.filter !== undefined &&
147
+ validFilter(advertised.filter, accepted.localName, stderr)
148
+ ) {
149
+ changed =
150
+ storeField(
151
+ store,
152
+ accepted.localName,
153
+ "filter",
154
+ "partialCloneFilter",
155
+ advertised.filter,
156
+ mine.filter,
157
+ stderr,
158
+ ) || changed;
159
+ }
160
+ if (
161
+ storedFields.includes("token") &&
162
+ advertised.token !== undefined &&
163
+ validToken(advertised.token, accepted.localName, stderr)
164
+ ) {
165
+ changed =
166
+ storeField(
167
+ store,
168
+ accepted.localName,
169
+ "token",
170
+ "token",
171
+ advertised.token,
172
+ mine.token,
173
+ stderr,
174
+ ) || changed;
143
175
  }
144
176
  }
145
177
  if (changed) await store.save();
146
- // the accepted remotes that are promisor remotes here are tried first by lazy fetches
178
+ if (accepting.length === 0) return undefined;
179
+ if (options.remember === false) return encodePromisorRemoteNames(accepting.map((r) => r.name));
180
+ // the accepted remotes that are promisor remotes here are tried first by lazy fetches,
181
+ // and their advertised filters make `--filter=auto`
147
182
  const promisors = new Set(
148
183
  promisorRemotes(RemoteConfigStore.from(workingCopy)).map((r) => r.name),
149
184
  );
150
185
  const key = keyOf(workingCopy);
151
186
  const set = accepted.get(key) ?? new Set<string>();
152
- for (const r of accepting) if (promisors.has(r.name)) set.add(r.name);
187
+ const filters = advertisedFilters.get(key) ?? new Map<string, string>();
188
+ for (const r of accepting) {
189
+ if (!promisors.has(r.localName)) continue;
190
+ set.add(r.localName);
191
+ if (r.filter !== undefined) filters.set(r.localName, r.filter);
192
+ }
153
193
  accepted.set(key, set);
194
+ advertisedFilters.set(key, filters);
195
+ // the reply names each remote as the server advertised it
154
196
  return encodePromisorRemoteNames(accepting.map((r) => r.name));
155
197
  };
156
198
  }
157
199
 
200
+ /**
201
+ * git's `promisor_remote_construct_filter`: the filter `--filter=auto` stands for, from the
202
+ * promisor remotes (in config order) a server's `promisor-remote` made this repository accept
203
+ * that advertised one, expanded (`blob:limit=5k` as `blob:limit=5120`); undefined when none
204
+ * did. An invalid one is skipped with git's warning.
205
+ *
206
+ * @throws Error where git hits its `BUG()`: two accepted remotes advertising valid filters
207
+ */
208
+ export function promisorAutoFilter(
209
+ workingCopy: WorkingCopy,
210
+ stderr: (line: string) => void,
211
+ ): string | undefined {
212
+ const key = keyOf(workingCopy);
213
+ const acceptedNames = accepted.get(key);
214
+ const filters = advertisedFilters.get(key);
215
+ if (!acceptedNames || !filters) return undefined;
216
+ let result: string | undefined;
217
+ for (const { name } of promisorRemotes(RemoteConfigStore.from(workingCopy))) {
218
+ const filter = filters.get(name);
219
+ if (!acceptedNames.has(name) || filter === undefined) continue;
220
+ let parsed: ReturnType<typeof parseObjectFilter>;
221
+ try {
222
+ parsed = parseObjectFilter(filter);
223
+ } catch (error) {
224
+ const reason = error instanceof ObjectFilterError ? error.message : String(error);
225
+ stderr(`warning: promisor remote '${name}' advertised invalid filter '${filter}': ${reason}`);
226
+ continue;
227
+ }
228
+ // gently_parse_list_objects_filter over an already parsed filter
229
+ if (result !== undefined) throw new Error("BUG: filter_options already populated");
230
+ result = parsed.choice === "blob:limit" ? `blob:limit=${parsed.limit}` : filter;
231
+ }
232
+ return result;
233
+ }
234
+
158
235
  /** accept_from_server: the last `promisor.acceptFromServer`, case-insensitive. */
159
236
  function acceptPolicyOf(store: RemoteConfigStore, stderr: (line: string) => void): AcceptPolicy {
160
237
  const value = store.value("promisor.acceptfromserver");
@@ -195,25 +272,230 @@ function configuredPromisors(
195
272
  return out;
196
273
  }
197
274
 
198
- /** should_accept_remote (without `promisor.acceptFromServerUrl`). */
275
+ /** should_accept_remote: the name the advertised remote is accepted under, if it is. */
199
276
  function shouldAccept(
200
277
  policy: AcceptPolicy,
201
278
  advertised: PromisorRemoteInfo,
202
279
  local: readonly PromisorRemoteInfo[],
203
280
  checked: readonly string[],
281
+ acceptUrls: readonly AllowedUrl[],
282
+ store: RemoteConfigStore,
204
283
  stderr: (line: string) => void,
205
- ): boolean {
284
+ ): { localName?: string; created?: boolean } {
285
+ const yes = (ok: boolean) => (ok ? { localName: advertised.name } : {});
206
286
  const mine = local.find((p) => p.name === advertised.name);
207
- if (!mine) return policy === "all" && allFieldsMatch(advertised, local, undefined, checked);
208
- if (policy === "all") return allFieldsMatch(advertised, local, undefined, checked);
209
- if (policy === "knownName") return allFieldsMatch(advertised, local, mine, checked);
287
+ if (!mine) {
288
+ // should_accept_new_remote_url: a URL the allowlist names makes (or reuses) a remote
289
+ const allowed = urlMatchesAcceptList(acceptUrls, advertised.url);
290
+ if (allowed) {
291
+ const name = handleMatchingAllowedUrl(store, allowed.remoteName, advertised, stderr);
292
+ if (name !== undefined) return { localName: name, created: true };
293
+ }
294
+ return yes(policy === "all" && allFieldsMatch(advertised, local, undefined, checked));
295
+ }
296
+ // a known remote whose URL is the one advertised and allowlisted
297
+ if (mine.url === advertised.url && urlMatchesAcceptList(acceptUrls, advertised.url)) {
298
+ return yes(allFieldsMatch(advertised, local, mine, checked));
299
+ }
300
+ if (policy === "all") return yes(allFieldsMatch(advertised, local, undefined, checked));
301
+ if (policy === "knownName") return yes(allFieldsMatch(advertised, local, mine, checked));
210
302
  if (mine.url !== advertised.url) {
211
303
  stderr(
212
304
  `warning: known remote named '${advertised.name}' but with URL '${mine.url}' instead of '${advertised.url}', ignoring this remote`,
213
305
  );
306
+ return {};
307
+ }
308
+ return yes(policy === "knownUrl" && allFieldsMatch(advertised, local, mine, checked));
309
+ }
310
+
311
+ /** A `promisor.acceptFromServerUrl` entry (git's `struct allowed_url`). */
312
+ interface AllowedUrl {
313
+ /** The name before `=`, if any */
314
+ remoteName?: string;
315
+ pattern: NormalizedUrl;
316
+ }
317
+
318
+ /** git's iscntrl over the bytes of a string (C locale). */
319
+ function hasControlChar(text: string): boolean {
320
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: git's iscntrl check
321
+ return /[\x00-\x1f\x7f]/.test(text);
322
+ }
323
+
324
+ /** valid_remote_name: `refs/remotes/<name>/test` a valid ref name (in a valid refspec). */
325
+ function validRemoteName(name: string): boolean {
326
+ return name.length > 0 && isValidRefName(`refs/remotes/${name}/test`);
327
+ }
328
+
329
+ /** load_accept_from_server_url and valid_accept_url: the valid entries, in config order. */
330
+ function loadAcceptFromServerUrl(
331
+ store: RemoteConfigStore,
332
+ stderr: (line: string) => void,
333
+ ): AllowedUrl[] {
334
+ const out: AllowedUrl[] = [];
335
+ for (const entry of store.values("promisor.acceptfromserverurl")) {
336
+ const eq = entry.indexOf("=");
337
+ let remoteName: string | undefined;
338
+ let pattern = entry;
339
+ if (eq >= 0) {
340
+ remoteName = entry.slice(0, eq);
341
+ if (!validRemoteName(remoteName)) {
342
+ stderr(
343
+ `warning: invalid remote name '${remoteName}' before '=' sign in '${entry}' from promisor.acceptFromServerUrl config`,
344
+ );
345
+ continue;
346
+ }
347
+ pattern = entry.slice(eq + 1);
348
+ }
349
+ const normalized = hasControlChar(pattern)
350
+ ? undefined
351
+ : normalizeUrl(pattern, { allowGlobs: true });
352
+ if (normalized === undefined || isUrlNormalizeError(normalized)) {
353
+ stderr(
354
+ `warning: invalid url pattern '${pattern}' in '${entry}' from promisor.acceptFromServerUrl config`,
355
+ );
356
+ continue;
357
+ }
358
+ out.push({ ...(remoteName !== undefined ? { remoteName } : {}), pattern: normalized });
359
+ }
360
+ return out;
361
+ }
362
+
363
+ /** A byte string (one character per byte, as `normalizeUrl` gives) as its bytes. */
364
+ function bytesOf(text: string): Uint8Array {
365
+ const out = new Uint8Array(text.length);
366
+ for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i) & 0xff;
367
+ return out;
368
+ }
369
+
370
+ /** match_one_url: scheme and port exactly, host and path each through wildmatch. */
371
+ function matchOneUrl(p: NormalizedUrl, u: NormalizedUrl): boolean {
372
+ if (
373
+ p.schemeLength !== u.schemeLength ||
374
+ p.url.slice(0, p.schemeLength) !== u.url.slice(0, u.schemeLength)
375
+ ) {
214
376
  return false;
215
377
  }
216
- return policy === "knownUrl" && allFieldsMatch(advertised, local, mine, checked);
378
+ const part = (n: NormalizedUrl, offset: number, length: number) =>
379
+ n.url.slice(offset, offset + length);
380
+ if (
381
+ p.portLength !== u.portLength ||
382
+ part(p, p.portOffset, p.portLength) !== part(u, u.portOffset, u.portLength)
383
+ ) {
384
+ return false;
385
+ }
386
+ return (
387
+ wildmatchBytes(
388
+ bytesOf(part(p, p.hostOffset, p.hostLength)),
389
+ bytesOf(part(u, u.hostOffset, u.hostLength)),
390
+ ) &&
391
+ wildmatchBytes(
392
+ bytesOf(part(p, p.pathOffset, p.pathLength)),
393
+ bytesOf(part(u, u.pathOffset, u.pathLength)),
394
+ )
395
+ );
396
+ }
397
+
398
+ /** url_matches_accept_list: the first entry matching the (normalized) URL. */
399
+ function urlMatchesAcceptList(
400
+ acceptUrls: readonly AllowedUrl[],
401
+ url: string,
402
+ ): AllowedUrl | undefined {
403
+ if (acceptUrls.length === 0) return undefined;
404
+ const normalized = normalizeUrl(url);
405
+ if (isUrlNormalizeError(normalized)) return undefined;
406
+ return acceptUrls.find((a) => matchOneUrl(a.pattern, normalized));
407
+ }
408
+
409
+ /** isalnum in the C locale */
410
+ const isAlnum = (c: string) => /^[A-Za-z0-9]$/.test(c);
411
+
412
+ /** promisor_remote_name_from_url and sanitize_remote_name. */
413
+ function promisorRemoteNameFromUrl(
414
+ url: string,
415
+ stderr: (line: string) => void,
416
+ ): string | undefined {
417
+ const n = normalizeUrl(url);
418
+ if (isUrlNormalizeError(n)) {
419
+ stderr(`warning: couldn't normalize advertised url '${url}', ignoring this remote`);
420
+ return undefined;
421
+ }
422
+ let buf = "";
423
+ if (n.hostLength) buf += `${n.url.slice(n.hostOffset, n.hostOffset + n.hostLength)}-`;
424
+ if (n.portLength) buf += `${n.url.slice(n.portOffset, n.portOffset + n.portLength)}-`;
425
+ if (n.pathLength) {
426
+ let path = n.url.slice(n.pathOffset, n.pathOffset + n.pathLength);
427
+ // strbuf_trim_trailing_dir_sep, then strbuf_strip_suffix(".git")
428
+ path = path.replace(/\/+$/, "");
429
+ if (path.endsWith(".git")) path = path.slice(0, -4);
430
+ buf += path;
431
+ }
432
+ // every byte but an alphanumeric one a '-', no leading or repeated '-'
433
+ let out = "";
434
+ let prev = "-";
435
+ for (const ch of buf) {
436
+ const c = isAlnum(ch) ? ch : "-";
437
+ if (prev === "-" && c === "-") continue;
438
+ out += c;
439
+ prev = c;
440
+ }
441
+ if (out.endsWith("-")) out = out.slice(0, -1);
442
+ if (out === "") {
443
+ stderr(
444
+ `warning: couldn't generate a valid remote name from advertised url '${url}', ignoring this remote`,
445
+ );
446
+ return undefined;
447
+ }
448
+ out = `promisor-auto-${out}`;
449
+ if (!validRemoteName(out)) {
450
+ stderr(
451
+ `warning: generated remote name '${out}' from advertised url '${url}' is invalid, ignoring this remote`,
452
+ );
453
+ return undefined;
454
+ }
455
+ return out;
456
+ }
457
+
458
+ const MAX_REMOTES_WITH_SIMILAR_NAMES = 20;
459
+
460
+ /**
461
+ * handle_matching_allowed_url and configure_auto_promisor_remote: the name the remote gets
462
+ * (a free one, or one already holding the URL, reused), written to the configuration.
463
+ */
464
+ function handleMatchingAllowedUrl(
465
+ store: RemoteConfigStore,
466
+ allowedName: string | undefined,
467
+ advertised: PromisorRemoteInfo,
468
+ stderr: (line: string) => void,
469
+ ): string | undefined {
470
+ const basename = allowedName ?? promisorRemoteNameFromUrl(advertised.url, stderr);
471
+ if (basename === undefined) return undefined;
472
+ let name = basename;
473
+ let reuse = false;
474
+ let i = 0;
475
+ while (i < MAX_REMOTES_WITH_SIMILAR_NAMES) {
476
+ const existing = store.value(`remote.${name}.url`);
477
+ if (existing === undefined) break;
478
+ if (existing === advertised.url) {
479
+ reuse = true;
480
+ break;
481
+ }
482
+ i++;
483
+ name = `${basename}-${i}`;
484
+ }
485
+ if (i >= MAX_REMOTES_WITH_SIMILAR_NAMES) {
486
+ stderr(
487
+ `warning: too many remotes accepted with name like '${basename}-X', ignoring this remote`,
488
+ );
489
+ return undefined;
490
+ }
491
+ if (!reuse) {
492
+ stderr(`Auto-creating promisor remote '${name}' for URL '${advertised.url}'`);
493
+ store.setValue(`remote.${name}.url`, advertised.url);
494
+ }
495
+ // reusing promotes an existing non-promisor remote
496
+ store.setValue(`remote.${name}.promisor`, "true");
497
+ store.setValue(`remote.${name}.advertisedAs`, advertised.name);
498
+ return name;
217
499
  }
218
500
 
219
501
  /** all_fields_match: every checked field advertised and equal to one remote's (or `mine`'s). */
@@ -34,6 +34,7 @@ import {
34
34
  FetchCheckError,
35
35
  fetchPromisedObjects,
36
36
  type GitTransportRegistry,
37
+ type HttpCredentialHelper,
37
38
  unpackLimitOf,
38
39
  } from "@statewalker/vcs-transport";
39
40
  import { parseGitBool } from "@statewalker/vcs-utils";
@@ -41,7 +42,7 @@ import type { WorkingCopy } from "@statewalker/vcs-working-tree";
41
42
  import { RemoteConfigStore } from "../remote-config/index.js";
42
43
  import { hostEnvironmentOf } from "./git-ident.js";
43
44
  import { httpClientSettingsOf } from "./http-config.js";
44
- import { acceptedPromisorRemotes } from "./promisor-remote-reply.js";
45
+ import { acceptedPromisorRemotes, promisorRemoteReplyOf } from "./promisor-remote-reply.js";
45
46
 
46
47
  /** A promisor remote (git's `struct promisor_remote`). */
47
48
  export interface PromisorRemote {
@@ -133,6 +134,13 @@ export interface PromisorFetcherOptions {
133
134
  credentials?: Credentials;
134
135
  headers?: Record<string, string>;
135
136
  timeout?: number;
137
+ /**
138
+ * Asked for HTTP credentials after a 401, per URL (git's child fetch reads
139
+ * `credential.helper`): an answer for one host never goes to another
140
+ */
141
+ credentialHelper?: HttpCredentialHelper;
142
+ /** git's `warning:` lines of the HTTP client (`rate limited, waiting ...`) */
143
+ warningCallback?: (line: string) => void;
136
144
  /**
137
145
  * git's behaviour to follow: 2.43 knows no `GIT_NO_LAZY_FETCH` (default: the host's hook
138
146
  * runner's, else 2.56)
@@ -215,8 +223,16 @@ export function createPromisorFetcher(
215
223
  ...(options.headers ? { headers: options.headers } : {}),
216
224
  ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),
217
225
  protocolVersion: protocolVersionOf(config),
218
- httpSettings: (remoteUrl) =>
219
- httpClientSettingsOf(config, remoteUrl, environment, { compatibility }),
226
+ httpSettings: (remoteUrl) => {
227
+ const settings = httpClientSettingsOf(config, remoteUrl, environment, {
228
+ compatibility,
229
+ ...(options.warningCallback ? { onWarning: options.warningCallback } : {}),
230
+ });
231
+ return options.warningCallback
232
+ ? { ...settings, onWarning: options.warningCallback }
233
+ : settings;
234
+ },
235
+ ...(options.credentialHelper ? { credentialHelper: options.credentialHelper } : {}),
220
236
  },
221
237
  async (connection) => {
222
238
  try {
@@ -225,6 +241,12 @@ export function createPromisorFetcher(
225
241
  ids,
226
242
  filter: "blob:none",
227
243
  url: anonymizeUrl(url),
244
+ // the child fetch's fetch-pack answers the server's promisor-remote too
245
+ promisorRemote: promisorRemoteReplyOf(
246
+ workingCopy,
247
+ (line) => promisor()?.warnings.push(line),
248
+ { remember: false },
249
+ ),
228
250
  compatibility,
229
251
  ...(fsck ? { fsckObjects: fsck } : {}),
230
252
  // the child fetch's fetch.unpackLimit: whether fetch-pack keeps the pack itself
@@ -470,7 +470,11 @@ export class PushCommand extends TransportCommand<PushResult> {
470
470
  private pushCertSigner(remoteUrl: string): PushCertSigner {
471
471
  const committer = () => committerIdentOf(this.workingCopy);
472
472
  return {
473
- pusher: () => signingKeyIdOf(this.workingCopy, "", committer()),
473
+ pusher: () =>
474
+ signingKeyIdOf(this.workingCopy, "", committer(), {
475
+ host: this.hooks,
476
+ compatibility: this.compatibility ?? this.hooks.compatibility,
477
+ }),
474
478
  pushee: anonymizeUrl(remoteUrl),
475
479
  date: () => {
476
480
  const timestamp = Math.floor(Date.now() / 1000);
@@ -337,8 +337,8 @@ export class ReadTreeCommand extends GitCommand<ReadTreeResult> {
337
337
  const [h, m] = treeIds as [ObjectId, ObjectId];
338
338
  const refusal = await switchTrees(
339
339
  sequencerCtx,
340
- await flatTree(this.trees, h),
341
- await flatTree(this.trees, m),
340
+ await flatTree(this.trees, h, { asIndex: true }),
341
+ await flatTree(this.trees, m, { asIndex: true }),
342
342
  {
343
343
  action: "merge",
344
344
  operation: "read-tree",
@@ -1,4 +1,5 @@
1
1
  export * from "./for-each-ref-command.js";
2
+ export * from "./peel-limit.js";
2
3
  export * from "./ref-atoms.js";
3
4
  export * from "./ref-filter.js";
4
5
  export * from "./ref-format.js";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * How many tags the ref filter peels through before it gives up. git's own peeling has no
3
+ * bound, so a tag cycle made through replace refs (tag A replaced by tag B, which names A)
4
+ * makes native `--points-at`, `--contains` and `%(*atom)` loop forever; ours stops here and
5
+ * treats the chain as reaching nothing (statewalker/webrun-vcs#263).
6
+ */
7
+ export const MAX_REF_FILTER_PEEL_DEPTH = 1000;
@@ -20,6 +20,7 @@ import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils";
20
20
  import { wildmatch } from "@statewalker/vcs-working-tree";
21
21
 
22
22
  import { RefFilterError } from "../../errors/index.js";
23
+ import { MAX_REF_FILTER_PEEL_DEPTH } from "./peel-limit.js";
23
24
  import {
24
25
  type RefFilterItem,
25
26
  type RefFormat,
@@ -213,7 +214,7 @@ export interface FilteredRefs {
213
214
  /** The commit an object peels to (lookup_commit_reference_gently), undefined when none. */
214
215
  async function commitOf(source: RefFilterSource, id: ObjectId): Promise<ObjectId | undefined> {
215
216
  let current = id;
216
- for (let depth = 0; depth < 1000; depth++) {
217
+ for (let depth = 0; depth < MAX_REF_FILTER_PEEL_DEPTH; depth++) {
217
218
  const object = await source.readObject(current);
218
219
  if (!object) return undefined;
219
220
  if (object.type === "commit") return current;
@@ -225,7 +226,11 @@ async function commitOf(source: RefFilterSource, id: ObjectId): Promise<ObjectId
225
226
  return undefined;
226
227
  }
227
228
 
228
- /** match_points_at: the ref's object, or one a tag on the way names, is wanted. */
229
+ /**
230
+ * match_points_at: the ref's object, or one a tag on the way names, is wanted. A chain longer
231
+ * than {@link MAX_REF_FILTER_PEEL_DEPTH} (a tag cycle through replace refs, where git loops
232
+ * forever) does not match.
233
+ */
229
234
  async function matchPointsAt(
230
235
  source: RefFilterSource,
231
236
  wanted: ReadonlySet<ObjectId>,
@@ -235,7 +240,8 @@ async function matchPointsAt(
235
240
  if (wanted.has(id)) return true;
236
241
  let object = await source.readObject(id);
237
242
  let current = id;
238
- while (object && object.type === "tag") {
243
+ for (let depth = 0; object && object.type === "tag"; depth++) {
244
+ if (depth >= MAX_REF_FILTER_PEEL_DEPTH) return false;
239
245
  const target = tagHeader(decodeGitPath(object.bytes)).object;
240
246
  if (!target) {
241
247
  object = undefined;
@@ -24,6 +24,7 @@ import { type DateMode, parseDateMode, type ShowDateContext, showDate } from "..
24
24
  import type { Mailmap } from "../mailmap.js";
25
25
  import { sanitizedSubject } from "../pretty-format.js";
26
26
  import { appendTrailers, type TrailerConfig } from "../trailers.js";
27
+ import { MAX_REF_FILTER_PEEL_DEPTH } from "./peel-limit.js";
27
28
  import { type AtomCmpType, parseAtom, type UsedAtom } from "./ref-atoms.js";
28
29
  import { quoteRefValue, type RefQuoteStyle } from "./ref-quote.js";
29
30
 
@@ -715,7 +716,7 @@ export class RefFormat {
715
716
  private async peel(id: ObjectId, object: RefFormatObject): Promise<ObjectId | undefined> {
716
717
  let current = object;
717
718
  let currentId = id;
718
- for (let depth = 0; current.type === "tag" && depth < 1000; depth++) {
719
+ for (let depth = 0; current.type === "tag" && depth < MAX_REF_FILTER_PEEL_DEPTH; depth++) {
719
720
  const header = tagHeader(decodeGitPath(current.bytes));
720
721
  if (!header.object || !header.type) return undefined;
721
722
  const next = await this.source.readObject(header.object);
@@ -401,7 +401,7 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
401
401
  });
402
402
  const result = noDelta && worktree?.batch ? await worktree.batch(run) : await run();
403
403
  const output: string[] = [];
404
- if (!result && !this._quiet) output.push("Nothing new to pack.");
404
+ if ((!result || result.nothingNew) && !this._quiet) output.push("Nothing new to pack.");
405
405
  return {
406
406
  repack: result,
407
407
  output,