@git-stunts/git-cas 6.2.0 → 6.4.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.
@@ -1,7 +1,8 @@
1
1
  import { Policy } from '@git-stunts/alfred';
2
2
  import GitRefPort from '../../ports/GitRefPort.js';
3
3
  import { CasError, ErrorCodes } from '../../domain/errors/index.js';
4
- import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
4
+ import { errorDetailsText, isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
5
+ import Oid from '../../domain/value-objects/Oid.js';
5
6
 
6
7
  /**
7
8
  * Default resilience policy: 30 s timeout (no retry).
@@ -12,6 +13,9 @@ import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
12
13
  * an unref'd timer that allows Node to exit before the next attempt starts.
13
14
  */
14
15
  const DEFAULT_POLICY = Policy.timeout(30_000);
16
+ const FORBIDDEN_REF_CHARACTERS = new Set(['~', '^', ':', '?', '*', '[', '\\']);
17
+ const MAX_REF_ITERATION_LIMIT = 1001;
18
+ const REF_NAME_ENCODER = new globalThis.TextEncoder();
15
19
 
16
20
  /**
17
21
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -112,7 +116,17 @@ export default class GitRefAdapter extends GitRefPort {
112
116
  * @returns {Promise<void>}
113
117
  */
114
118
  async updateRef({ ref, newOid, expectedOldOid }) {
115
- const args = ['update-ref', ref, newOid];
119
+ assertRefName(ref);
120
+ const symbolicTarget = await this.#resolveSymbolicRef(ref);
121
+ if (symbolicTarget !== null) {
122
+ throw refConflict({
123
+ ref,
124
+ expectedOldOid: expectedOldOid ?? null,
125
+ actualOldOid: null,
126
+ actualSymref: symbolicTarget,
127
+ });
128
+ }
129
+ const args = ['update-ref', '--no-deref', ref, newOid];
116
130
  if (expectedOldOid !== undefined) {
117
131
  args.push(expectedOldOid ?? '0'.repeat(newOid.length));
118
132
  }
@@ -120,4 +134,342 @@ export default class GitRefAdapter extends GitRefPort {
120
134
  this.plumbing.execute({ args }),
121
135
  );
122
136
  }
137
+
138
+ /** @override */
139
+ async anchorRef({ sourceRef, expectedSourceOid, targetRef }) {
140
+ assertRefName(sourceRef);
141
+ assertRefName(targetRef);
142
+ const generation = Oid.from(expectedSourceOid).toString();
143
+ // Git 2.43 cannot atomically assert ref type. Preflight rejects observed
144
+ // symrefs; --no-deref contains any subsequent race to the managed names.
145
+ if (
146
+ await this.#resolveSymbolicRef(sourceRef) !== null ||
147
+ await this.#resolveSymbolicRef(targetRef) !== null
148
+ ) {
149
+ return false;
150
+ }
151
+ const input = [
152
+ 'start',
153
+ `verify ${sourceRef} ${generation}`,
154
+ `create ${targetRef} ${generation}`,
155
+ 'prepare',
156
+ 'commit',
157
+ '',
158
+ ].join('\n');
159
+ try {
160
+ await this.policy.execute(() =>
161
+ this.plumbing.execute({ args: ['update-ref', '--no-deref', '--stdin'], input }),
162
+ );
163
+ return true;
164
+ } catch (error) {
165
+ if (isUpdateRefConflict(error, [sourceRef, targetRef])) {
166
+ return false;
167
+ }
168
+ throw error;
169
+ }
170
+ }
171
+
172
+ /** @override */
173
+ async deleteRef({ ref, expectedOldOid }) {
174
+ assertRefName(ref);
175
+ const expectedGeneration = Oid.from(expectedOldOid).toString();
176
+ // A post-probe type race may delete this managed symref name, never its
177
+ // referent. The expected OID still gates the no-dereference mutation.
178
+ const symbolicTarget = await this.#resolveSymbolicRef(ref);
179
+ if (symbolicTarget !== null) {
180
+ throw refConflict({
181
+ ref,
182
+ expectedOldOid: expectedGeneration,
183
+ actualOldOid: null,
184
+ actualSymref: symbolicTarget,
185
+ });
186
+ }
187
+ try {
188
+ await this.policy.execute(() =>
189
+ this.plumbing.execute({
190
+ args: ['update-ref', '--no-deref', '-d', ref, expectedGeneration],
191
+ }),
192
+ );
193
+ } catch (error) {
194
+ if (!isUpdateRefConflict(error, [ref])) {
195
+ throw error;
196
+ }
197
+ const racedSymbolicTarget = await this.#resolveSymbolicRef(ref);
198
+ if (racedSymbolicTarget !== null) {
199
+ throw refConflict({
200
+ ref,
201
+ expectedOldOid: expectedGeneration,
202
+ actualOldOid: null,
203
+ actualSymref: racedSymbolicTarget,
204
+ originalError: error,
205
+ });
206
+ }
207
+ const actual = await this.#inspectDirectRef(ref);
208
+ throw refConflict({
209
+ ref,
210
+ expectedOldOid: expectedGeneration,
211
+ actualOldOid: actual?.oid ?? null,
212
+ actualSymref: actual?.symref ?? null,
213
+ originalError: error,
214
+ });
215
+ }
216
+ return true;
217
+ }
218
+
219
+ /** @override */
220
+ async *iterateRefs({ prefix = 'refs/', after = null, limit } = {}) {
221
+ assertRefPrefix(prefix);
222
+ assertRefCursor(prefix, after);
223
+ assertRefIterationLimit(limit);
224
+ if (typeof this.plumbing?.executeStream !== 'function') {
225
+ throw new CasError(
226
+ 'Git ref inventory requires streaming plumbing',
227
+ ErrorCodes.GIT_ERROR,
228
+ { prefix },
229
+ );
230
+ }
231
+ const args = refInventoryArgs({ prefix, after, limit });
232
+ const stream = await this.policy.execute(() => this.plumbing.executeStream({ args }));
233
+ yield* paginatedRefRecords({ stream, prefix, after, limit });
234
+ }
235
+
236
+ async #inspectDirectRef(ref) {
237
+ const output = await this.policy.execute(() =>
238
+ this.plumbing.execute({
239
+ args: [
240
+ 'for-each-ref',
241
+ '--format=%(refname)%09%(objectname)%09%(symref)',
242
+ '--count=1',
243
+ ref,
244
+ ],
245
+ }),
246
+ );
247
+ const line = String(output).replace(/\r?\n$/u, '');
248
+ if (line.length === 0) {
249
+ return null;
250
+ }
251
+ const fields = line.split('\t');
252
+ if (
253
+ (fields.length !== 2 && fields.length !== 3) ||
254
+ fields[0] !== ref ||
255
+ !Oid.isValid(fields[1]) ||
256
+ (fields[2] !== undefined && fields[2] !== '' && !isValidRefSyntax(fields[2], false))
257
+ ) {
258
+ throw invalidRefInventory(ref, line);
259
+ }
260
+ return Object.freeze({
261
+ ref,
262
+ oid: Oid.from(fields[1]).toString(),
263
+ symref: fields[2] || null,
264
+ });
265
+ }
266
+
267
+ async #resolveSymbolicRef(ref) {
268
+ try {
269
+ const output = await this.policy.execute(() =>
270
+ this.plumbing.execute({ args: ['symbolic-ref', '--quiet', ref] }),
271
+ );
272
+ const target = String(output).trim();
273
+ return target.length > 0 ? target : null;
274
+ } catch (error) {
275
+ if (isQuietSymbolicRefMiss(error, ref)) {
276
+ return null;
277
+ }
278
+ throw error;
279
+ }
280
+ }
281
+ }
282
+
283
+ function assertRefPrefix(prefix) {
284
+ assertRefSyntax(prefix, { allowTrailingSlash: true });
285
+ }
286
+
287
+ function assertRefName(ref) {
288
+ assertRefSyntax(ref, { allowTrailingSlash: false });
289
+ }
290
+
291
+ function assertRefCursor(prefix, after) {
292
+ if (after === null) {
293
+ return;
294
+ }
295
+ assertRefName(after);
296
+ if (!after.startsWith(prefix)) {
297
+ throw invalidRefName(after);
298
+ }
299
+ }
300
+
301
+ function assertRefIterationLimit(limit) {
302
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_REF_ITERATION_LIMIT) {
303
+ throw new CasError(
304
+ `Git ref inventory limit must be between 1 and ${MAX_REF_ITERATION_LIMIT}`,
305
+ ErrorCodes.GIT_ERROR,
306
+ { limit },
307
+ );
308
+ }
309
+ }
310
+
311
+ function assertRefSyntax(value, { allowTrailingSlash }) {
312
+ if (typeof value !== 'string' || !isValidRefSyntax(value, allowTrailingSlash)) {
313
+ throw invalidRefName(value);
314
+ }
315
+ }
316
+
317
+ function isValidRefSyntax(value, allowTrailingSlash) {
318
+ if (!value.startsWith('refs/') || (!allowTrailingSlash && value.endsWith('/'))) {
319
+ return false;
320
+ }
321
+ if (['//', '..', '@{'].some((pattern) => value.includes(pattern))) {
322
+ return false;
323
+ }
324
+ if (value.endsWith('.') || hasForbiddenRefCharacter(value)) {
325
+ return false;
326
+ }
327
+ const trimmed = allowTrailingSlash && value.endsWith('/') ? value.slice(0, -1) : value;
328
+ return !trimmed.split('/').some(isInvalidRefSegment);
329
+ }
330
+
331
+ function isInvalidRefSegment(part) {
332
+ return part.length === 0 || part.startsWith('.') || part.endsWith('.lock');
333
+ }
334
+
335
+ function compareRefNames(left, right) {
336
+ const leftBytes = REF_NAME_ENCODER.encode(left);
337
+ const rightBytes = REF_NAME_ENCODER.encode(right);
338
+ const sharedLength = Math.min(leftBytes.length, rightBytes.length);
339
+ for (let index = 0; index < sharedLength; index += 1) {
340
+ if (leftBytes[index] !== rightBytes[index]) {
341
+ return leftBytes[index] - rightBytes[index];
342
+ }
343
+ }
344
+ return leftBytes.length - rightBytes.length;
345
+ }
346
+
347
+ function refInventoryArgs({ prefix, after, limit }) {
348
+ const args = [
349
+ 'for-each-ref',
350
+ '--format=%(refname)%09%(objectname)%09%(symref)',
351
+ '--sort=refname',
352
+ ];
353
+ if (after === null) {
354
+ args.push(`--count=${limit}`);
355
+ }
356
+ args.push(prefix);
357
+ return args;
358
+ }
359
+
360
+ async function* paginatedRefRecords({ stream, prefix, after, limit }) {
361
+ let returned = 0;
362
+ for await (const line of consumeRefLines(stream)) {
363
+ const record = parseIteratedRef(prefix, line);
364
+ if (after !== null && compareRefNames(record.ref, after) <= 0) {
365
+ continue;
366
+ }
367
+ yield record;
368
+ returned += 1;
369
+ if (after !== null && returned >= limit) {
370
+ return;
371
+ }
372
+ }
373
+ }
374
+
375
+ function hasForbiddenRefCharacter(value) {
376
+ return typeof value === 'string' && [...value].some((character) => {
377
+ const code = character.codePointAt(0);
378
+ return code <= 0x20 || code === 0x7f || FORBIDDEN_REF_CHARACTERS.has(character);
379
+ });
380
+ }
381
+
382
+ async function* consumeRefLines(stream) {
383
+ const decoder = new globalThis.TextDecoder();
384
+ let pending = '';
385
+ for await (const chunk of stream) {
386
+ pending += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
387
+ let newline = pending.indexOf('\n');
388
+ while (newline !== -1) {
389
+ const line = pending.slice(0, newline).replace(/\r$/u, '');
390
+ pending = pending.slice(newline + 1);
391
+ if (line.length > 0) {
392
+ yield line;
393
+ }
394
+ newline = pending.indexOf('\n');
395
+ }
396
+ }
397
+ pending += decoder.decode();
398
+ if (pending.length > 0) {
399
+ yield pending.replace(/\r$/u, '');
400
+ }
401
+ const result = await stream.finished;
402
+ if (result?.code !== 0) {
403
+ throw new CasError('Git ref inventory failed', ErrorCodes.GIT_ERROR, {
404
+ stderr: result?.stderr,
405
+ });
406
+ }
407
+ }
408
+
409
+ function invalidRefInventory(prefix, output) {
410
+ return new CasError(
411
+ 'Git ref inventory returned invalid structured output',
412
+ ErrorCodes.GIT_ERROR,
413
+ { prefix, output: String(output) },
414
+ );
415
+ }
416
+
417
+ function parseIteratedRef(prefix, line) {
418
+ const fields = line.split('\t');
419
+ if (!isValidIteratedRef(fields, prefix)) {
420
+ throw invalidRefInventory(prefix, line);
421
+ }
422
+ return Object.freeze({
423
+ ref: fields[0],
424
+ oid: Oid.from(fields[1]).toString(),
425
+ symref: fields[2] || null,
426
+ });
427
+ }
428
+
429
+ function isValidIteratedRef(fields, prefix) {
430
+ return fields.length === 3
431
+ && fields[0].startsWith(prefix)
432
+ && Oid.isValid(fields[1])
433
+ && (fields[2] === '' || isValidRefSyntax(fields[2], false));
434
+ }
435
+
436
+ function invalidRefName(ref) {
437
+ return new CasError('Git ref name or prefix is invalid', ErrorCodes.GIT_ERROR, { ref });
438
+ }
439
+
440
+ function isUpdateRefConflict(error, refs) {
441
+ const text = errorDetailsText(error).toLowerCase();
442
+ return refs.some((ref) => text.includes(ref.toLowerCase()))
443
+ && (
444
+ text.includes('cannot lock ref') ||
445
+ text.includes('but expected') ||
446
+ text.includes('reference already exists') ||
447
+ text.includes('unable to resolve reference') ||
448
+ text.includes('zero <oldvalue>') ||
449
+ text.includes('is a symref')
450
+ );
451
+ }
452
+
453
+ function isQuietSymbolicRefMiss(error, ref) {
454
+ const details = error instanceof Error && error.details && typeof error.details === 'object'
455
+ ? error.details
456
+ : {};
457
+ return details.code === 1
458
+ && Array.isArray(details.args)
459
+ && details.args[0] === 'symbolic-ref'
460
+ && details.args.at(-1) === ref;
461
+ }
462
+
463
+ function refConflict({
464
+ ref,
465
+ expectedOldOid,
466
+ actualOldOid,
467
+ actualSymref = null,
468
+ originalError,
469
+ }) {
470
+ return new CasError(
471
+ `Git ref changed before checked mutation: ${ref}`,
472
+ ErrorCodes.GIT_REF_CONFLICT,
473
+ { ref, expectedOldOid, actualOldOid, actualSymref, originalError },
474
+ );
123
475
  }
@@ -72,19 +72,19 @@ export default class GitRepositoryInspectionAdapter extends RepositoryInspection
72
72
  }
73
73
  }
74
74
 
75
- async *iterateRefs() {
75
+ async *iterateRefs({ prefix = 'refs/' } = {}) {
76
+ if (typeof prefix !== 'string' || !prefix.startsWith('refs/') || prefix.includes('..')) {
77
+ throw new CasError(
78
+ 'Git ref inventory prefix is invalid',
79
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID,
80
+ { prefix },
81
+ );
82
+ }
76
83
  const stream = await this.#stream({
77
- args: ['for-each-ref', '--format=%(refname)%09%(objectname)', 'refs/'],
84
+ args: ['for-each-ref', '--format=%(refname)%09%(objectname)%09%(symref)', prefix],
78
85
  });
79
86
  for await (const line of consumeLines(stream, 'ref inventory')) {
80
- const fields = line.split('\t');
81
- if (fields.length !== 2 || !fields[0].startsWith('refs/')) {
82
- throw invalidOutput('ref inventory', line);
83
- }
84
- yield Object.freeze({
85
- ref: fields[0],
86
- oid: parseOid(fields[1], 'ref inventory', line),
87
- });
87
+ yield parseRefRecord(line);
88
88
  }
89
89
  }
90
90
 
@@ -137,6 +137,24 @@ function parseOid(value, operation, output) {
137
137
  return Oid.from(value).toString();
138
138
  }
139
139
 
140
+ function parseRefRecord(line) {
141
+ const fields = line.split('\t');
142
+ if (!isValidRefRecord(fields)) {
143
+ throw invalidOutput('ref inventory', line);
144
+ }
145
+ return Object.freeze({
146
+ ref: fields[0],
147
+ oid: parseOid(fields[1], 'ref inventory', line),
148
+ symref: fields[2] || null,
149
+ });
150
+ }
151
+
152
+ function isValidRefRecord(fields) {
153
+ return fields.length === 3
154
+ && fields[0].startsWith('refs/')
155
+ && (fields[2] === '' || fields[2].startsWith('refs/'));
156
+ }
157
+
140
158
  function parseType(value, operation, output) {
141
159
  if (!OBJECT_TYPES.has(value)) {
142
160
  throw invalidOutput(operation, output);
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.2.0';
1
+ export const PACKAGE_VERSION = '6.4.0';
@@ -1,3 +1,6 @@
1
+ import createCasError from '../domain/errors/createCasError.js';
2
+ import { ErrorCodes } from '../domain/errors/index.js';
3
+
1
4
  /**
2
5
  * Abstract port for Git ref and commit operations.
3
6
  * @abstract
@@ -55,4 +58,47 @@ export default class GitRefPort {
55
58
  async updateRef(_options) {
56
59
  throw new Error('Not implemented');
57
60
  }
61
+
62
+ /**
63
+ * Atomically verifies one source ref and creates a new ref to its generation.
64
+ * @param {Object} _options
65
+ * @param {string} _options.sourceRef
66
+ * @param {string} _options.expectedSourceOid
67
+ * @param {string} _options.targetRef
68
+ * @returns {Promise<boolean>} Whether the source generation was anchored.
69
+ */
70
+ async anchorRef(_options) {
71
+ throw unsupportedAcquisitionCapability('anchorRef');
72
+ }
73
+
74
+ /**
75
+ * Deletes a ref only when it still names the expected object.
76
+ * @param {Object} _options
77
+ * @param {string} _options.ref
78
+ * @param {string} _options.expectedOldOid
79
+ * @returns {Promise<boolean>} Whether the ref existed and was deleted.
80
+ */
81
+ async deleteRef(_options) {
82
+ throw unsupportedAcquisitionCapability('deleteRef');
83
+ }
84
+
85
+ /**
86
+ * Streams refs below a canonical Git ref prefix.
87
+ * @param {Object} _options
88
+ * @param {string} [_options.prefix]
89
+ * @param {string|null} [_options.after] Exclusive ref-name continuation cursor.
90
+ * @param {number} _options.limit Maximum records to request from Git.
91
+ * @returns {AsyncIterable<{ref: string, oid: string, symref: string|null}>}
92
+ */
93
+ iterateRefs(_options) {
94
+ throw unsupportedAcquisitionCapability('iterateRefs');
95
+ }
96
+ }
97
+
98
+ function unsupportedAcquisitionCapability(capability) {
99
+ return createCasError(
100
+ `Git ref adapter does not implement cache acquisition capability: ${capability}`,
101
+ ErrorCodes.CACHE_ACQUISITION_INVALID,
102
+ { capability },
103
+ );
58
104
  }
@@ -21,8 +21,11 @@ export default class RepositoryInspectionPort {
21
21
  throw new Error('Not implemented');
22
22
  }
23
23
 
24
- /** @returns {AsyncIterable<{ ref: string, oid: string }>} */
25
- iterateRefs() {
24
+ /**
25
+ * @param {{ prefix?: string }} [_options]
26
+ * @returns {AsyncIterable<{ ref: string, oid: string, symref: string|null }>}
27
+ */
28
+ iterateRefs(_options) {
26
29
  throw new Error('Not implemented');
27
30
  }
28
31