main
1// git's `version:refname` order (tag --sort=version:refname, for-each-ref). versioncmp.c is glibc strverscmp
2// (the state names below are its S_N / S_I / S_F / S_Z) plus versionsort.suffix: a configured suffix that touches
3// the first byte where the two names differ sorts before a name without it, and earlier in the suffix list sorts
4// first. The empty suffix is the release itself, so it can sit between prereleases.
5//
6// Names are compared as the bytes git stores. A well-formed string is its UTF-8 (bytewise UTF-8 order is code-point
7// order, which is not UTF-16 code-unit order for a character outside the BMP). A surrogate-escaped string from
8// decodeBytes is the original bytes. An interior NUL ends the comparison, as versioncmp stops on the C string.
9// Pure: no I/O, so no span. A tag list's span belongs to the ls-refs that fetched the names.
10//
11// A suffix list that places the release among prereleases makes versioncmp not a strict weak order.
12// With ['-alpha', '-beta', '', '-gamma', '-delta'], 00.1-gamma < 00.2-alpha < 00.10-alpha and 00.10-alpha < 00.1-gamma.
13// With ['', '-rc'], 00.1-rc1 < 00.2 < 00.10 and 00.10 < 00.1-rc1. The names differ once inside a digit run
14// (the longer run wins) and once at a suffix the list reorders.
15// Two names are versioncmp, which is the order `git tag -l --sort=version:refname` prints for those two names.
16// A longer listing is git's qsort of that relation, and a cyclic relation has no listing that keeps every pair,
17// so a whole tag list sorted here follows versioncmp.
18import { encodeBytes } from './bytes.js';
19import { fail } from './errors.js';
20import type { ErrorOf } from './errors.js';
21import { err, getOrElse, ok } from './result.js';
22import type { Result } from './result.js';
23import { atOr, fromNullish, withDefaults } from './absent.js';
24import type { Input } from './absent.js';
26/** `versionsort.suffix`, in the order git config lists them. `''` is the release, placed among the suffixes. */
27export type VersionRefnameOrderConfig = {
28 readonly suffixes: readonly string[];
29};
30/** What a caller passes: any of the config. A missing (or null) `suffixes` is none configured. */
31export type VersionRefnameOrder = Input<VersionRefnameOrderConfig>;
33// glibc strverscmp, as versioncmp.c carries it. The state is the row (normal, integral, fractional, leading zeros)
34// plus the class of the byte just read: not a digit, a non-zero digit, or '0'. Rows are 3 apart so the class fits
35// in the low part of the index (versioncmp.c's S_N=0, S_I=3, S_F=6, S_Z=9).
36const S_N = 0;
37const S_I = 3;
38const S_F = 6;
39const S_Z = 9;
40const CLASS_X = 0;
41const CLASS_D = 1;
42const CLASS_Z = 2;
43const CMP = 2;
44const LEN = 3;
45const NUL = 0;
46const DIGIT_ZERO = 0x30;
47const DIGIT_NINE = 0x39;
49// Next row after consuming a byte of the given class. Index = row + class.
50const NEXT_ROW: readonly number[] = Object.freeze([
51 S_N, S_I, S_Z, // S_N, then x / d / 0
52 S_N, S_I, S_I, // S_I
53 S_N, S_F, S_F, // S_F
54 S_N, S_F, S_Z, // S_Z
55]);
57// How the first differing bytes decide. Index = (row + class of the left byte) * 3 + class of the right byte.
58// CMP: the byte difference. LEN: the longer remaining digit run wins, else the byte difference.
59// -1 / +1: that side wins regardless of the bytes (a leading zero against an integral digit).
60const RESULT: readonly number[] = Object.freeze([
61 CMP, CMP, CMP, CMP, LEN, CMP, CMP, CMP, CMP, // S_N
62 CMP, -1, -1, 1, LEN, LEN, 1, LEN, LEN, // S_I
63 CMP, CMP, CMP, CMP, CMP, CMP, CMP, CMP, CMP, // S_F
64 CMP, 1, 1, -1, CMP, CMP, -1, CMP, CMP, // S_Z
65]);
67type ResultKind = -1 | 1 | typeof CMP | typeof LEN;
69// Past the end reads as NUL (the C string's terminator). Indices here are never negative.
70function byteAt(bytes: Uint8Array, i: number): number {
71 return atOr(bytes, i, NUL);
72}
74// '0' is its own class: a leading zero is fractional, not a longer integer.
75function digitClass(c: number): number {
76 if (c === DIGIT_ZERO) return CLASS_Z;
77 // Stryker disable next-line EqualityOperator: '0' already returned CLASS_Z above
78 if (c > DIGIT_ZERO && c <= DIGIT_NINE) return CLASS_D;
79 return CLASS_X;
80}
82function isDigit(c: number): boolean {
83 return c >= DIGIT_ZERO && c <= DIGIT_NINE;
84}
86// The row those bytes leave us in. `state` is always a NEXT_ROW index (0..11): it starts as a class and then
87// becomes a row plus the next byte's class.
88function nextRow(state: number): number {
89 // oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- see above
90 return NEXT_ROW[state] as number;
91}
93function resultKind(state: number, class2: number): ResultKind {
94 // oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- state is 0..11 and class2 is 0..2, so the index is 0..35
95 const kind = RESULT[(state * 3) + class2] as ResultKind;
96 return kind;
97}
99// strverscmp's LEN: p1 and p2 already point past the first differing digits. A longer run of digits is greater;
100// the same length keeps the byte difference. The increments match versioncmp.c, including the byte each side
101// consumes while testing the run.
102function byDigitLength(left: Uint8Array, i1: number, right: Uint8Array, i2: number, diff: number): number {
103 let a = i1;
104 let b = i2;
105 while (isDigit(byteAt(left, a))) {
106 a += 1;
107 if (!isDigit(byteAt(right, b))) return 1;
108 b += 1;
109 }
110 return isDigit(byteAt(right, b)) ? -1 : diff;
111}
113type SuffixHit = { readonly confPos: number; readonly start: number; readonly len: number };
115const noHit = (off: number): SuffixHit => ({ confPos: -1, start: off, len: -1 });
117function startsWithAt(tag: Uint8Array, i: number, suffix: Uint8Array): boolean {
118 for (let k = 0; k < suffix.length; k++) {
119 if (byteAt(tag, i + k) !== byteAt(suffix, k)) return false;
120 }
121 return true;
122}
124// A better hit starts earlier, or at the same offset and longer (versioncmp.c find_better_matching_suffix).
125// The search runs left to right and keeps the first hit inside that window, so the earliest start wins and an
126// equal-length suffix does not replace one already found.
127function betterHit(tag: Uint8Array, suffix: Uint8Array, start: number, confPos: number, hit: SuffixHit): SuffixHit {
128 const end = hit.len < suffix.length ? hit.start : hit.start - 1;
129 for (let i = start; i <= end; i++) {
130 if (startsWithAt(tag, i, suffix)) return { confPos, start: i, len: suffix.length };
131 }
132 return hit;
133}
135// Non-null when a configured suffix touches `off` (the first differing byte) on one side only, or the two sides
136// matched different suffixes: the result is then the suffix-list order, not the bytes.
137function suffixOrder(left: Uint8Array, right: Uint8Array, off: number, suffixes: readonly Uint8Array[]): number | null {
138 let hitL = noHit(off);
139 let hitR = noHit(off);
140 let i = 0;
141 for (const suffix of suffixes) {
142 // Stryker disable next-line EqualityOperator,ConditionalExpression: a start before 0 reads no suffix byte, and a suffix as long as the offset already starts at 0
143 const start = suffix.length < off ? off - suffix.length : 0;
144 hitL = betterHit(left, suffix, start, i, hitL);
145 hitR = betterHit(right, suffix, start, i, hitR);
146 i += 1;
147 }
148 // Stryker disable next-line ConditionalExpression: both misses share one confPos, and the next comparison returns null
149 if (hitL.confPos < 0 && hitR.confPos < 0) return null;
150 if (hitL.confPos === hitR.confPos) return null;
151 if (hitL.confPos >= 0 && hitR.confPos >= 0) return hitL.confPos - hitR.confPos;
152 return hitL.confPos >= 0 ? -1 : 1;
153}
155function versioncmp(left: Uint8Array, right: Uint8Array, suffixes: readonly Uint8Array[]): number {
156 let i1 = 0;
157 let i2 = 0;
158 let c1 = byteAt(left, i1);
159 let c2 = byteAt(right, i2);
160 i1 += 1;
161 i2 += 1;
162 let state = S_N + digitClass(c1);
163 let diff = c1 - c2;
164 while (diff === 0) {
165 if (c1 === NUL) return 0;
166 state = nextRow(state);
167 c1 = byteAt(left, i1);
168 c2 = byteAt(right, i2);
169 i1 += 1;
170 i2 += 1;
171 state += digitClass(c1);
172 diff = c1 - c2;
173 }
174 const ordered = suffixOrder(left, right, i1 - 1, suffixes);
175 if (ordered !== null) return ordered;
176 const kind = resultKind(state, digitClass(c2));
177 if (kind === LEN) return byDigitLength(left, i1, right, i2, diff);
178 if (kind === CMP) return diff;
179 return kind;
180}
182// Which argument was not a byte string. `left` / `right` are the names; `suffix` is a versionsort.suffix entry.
183export type VersionRefnameWhich = 'left' | 'right' | 'suffix';
184// `not_string`: the value is not a string. `not_bytes`: it is a string encodeBytes refuses (a lone surrogate, or
185// escaped bytes that already spell UTF-8). git's versioncmp only sees bytes, so both are typed refusals.
186// A union of intersections, not one object whose `kind` is a union: matchKind / Extract narrow a discriminant.
187type VersionRefnameBase = { readonly which: VersionRefnameWhich };
188export type VersionRefnameError =
189 | (ErrorOf<'bad_request'> & { readonly kind: 'not_string' } & VersionRefnameBase)
190 | (ErrorOf<'bad_request'> & { readonly kind: 'not_bytes' } & VersionRefnameBase);
192const nameOf = (which: VersionRefnameWhich): string => (which === 'suffix' ? 'versionsort.suffix' : 'refname');
194function notString(which: VersionRefnameWhich): Result<never, VersionRefnameError> {
195 const what = nameOf(which);
196 const made = fail('bad_request', `${what} must be a string`, { what });
197 return err(Object.assign(made.error, { kind: 'not_string' as const, which }));
198}
200function asBytes(value: unknown, which: VersionRefnameWhich): Result<Uint8Array<ArrayBuffer>, VersionRefnameError> {
201 if (typeof value !== 'string') return notString(which);
202 const encoded = encodeBytes(value, nameOf(which));
203 if (encoded.ok) return encoded;
204 return err(Object.assign(encoded.error, { kind: 'not_bytes' as const, which }));
205}
207/**
208 * git `versioncmp` for two refnames, with `versionsort.suffix` applied.
209 * Negative when `a` sorts first. The value is versioncmp's own: a byte difference, a longer digit run, or the
210 * distance between two matched suffixes. Equal names compare equal.
211 * A non-string is `not_string`. A string that is not a byte sequence is `not_bytes`. Pure: no span of its own (I39);
212 * a caller records `error.kind` from the `Err`.
213 */
214export function compareVersionRefnames(a: unknown, b: unknown, order: VersionRefnameOrder | null = null): Result<number, VersionRefnameError> {
215 // A null `suffixes` is none, as the nullish read had it: withDefaults keeps a given null, fromNullish drops it.
216 const listed = getOrElse(fromNullish(withDefaults<VersionRefnameOrderConfig>(order, { suffixes: [] }).suffixes), []);
217 const suffixes: Array<Uint8Array<ArrayBuffer>> = [];
218 for (const suffix of listed) {
219 const encoded = asBytes(suffix, 'suffix');
220 if (!encoded.ok) return encoded;
221 suffixes.push(encoded.value);
222 }
223 const left = asBytes(a, 'left');
224 if (!left.ok) return left;
225 const right = asBytes(b, 'right');
226 if (!right.ok) return right;
227 return ok(versioncmp(left.value, right.value, suffixes));
228}
Diagnostics4 git calls · 29 ms
CallStatusSizeTime029 ms
discover200152 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=38434 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=38434 git.pkt.payload.max=38339 git.sideband.band1.bytes=38338 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=63 git.pack.bytes=38338 git.pack.ofs_delta=0 git.pack.ref_delta=8 git.pack.chain.max=8 git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77 git.pack.full=55Open pack map
fetch2003.9 KiB · hit25 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=25 git.response.bytes=4020 git.response.cache=HIT git.response.duration_ms=25 git.fetch.wants=597561944bef5659ea3b2789c830a4b1b81290cd git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=4020 git.pkt.payload.max=3999 git.sideband.band1.bytes=3998 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e2bab0a899cf46
- Request
- d181e009…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format