Files
renovate/lib/modules/versioning/bazel-module/bzlmod-version.ts
Sebastian Poxhofer a1971afa78 fix(linters): add linting rule to enforce usage of our regEx utility (#44690)
* ci(linter): add renovate/require-regex-util rule

Adds a custom oxlint rule that flags raw RegExp usage in lib/
production code: any `new RegExp(...)` call and any regex literal
that is not the direct first argument of `regEx(...)`. The regEx()
helper from lib/util/regex.ts uses the RE2 engine for ReDoS-safe
matching and caches compiled patterns. lib/util/regex.ts itself is
exempt.

The rule is disabled for **/*.spec.ts, test/**, and tools/** via
config overrides, because vitest APIs such as expect.stringMatching
need bare RegExp instances (a past commit reverted regEx() there).

Severity is set to "warn" instead of "error": the repo currently has
197 pre-existing violations (above the agreed mechanical-fix
threshold of 80), and a number of them are deliberately
RE2-incompatible patterns (lookahead/lookbehind/named backreferences,
see TODO #12872/#12875 markers in e.g. lib/modules/versioning/rez/
pattern.ts and lib/modules/manager/dockerfile/extract.ts) that need
per-site judgment before they can be wrapped in regEx() or suppressed
with a justified disable comment. No violation fixes are included in
this commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci(linter): enforce renovate/require-regex-util at error

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: use regEx() for regex literals and RegExp construction in lib

Burn down all renovate/require-regex-util violations (197):

- wrap RE2-compatible regex literals and RegExp constructions in regEx()
- rewrite lookaround patterns where behavior is provably preserved:
  goproxy separator split, sbt-package link extraction, leiningen
  comment stripping and keyword search, npm GitHub owner validation
  (unit-count bound replaced by an explicit length check)
- keep native RegExp with disable comments where RE2 cannot be used:
  moo / good-enough-parser lexer patterns (moo rejects RE2 instances),
  MigrationsService propertyName (matched via isRegExp, which RE2
  instances fail), rez named backreferences and lookaheads, GitHub
  markdown link negative lookbehind, emoji astral-plane matching
- drop stale TODO #12875 comments for patterns current re2 handles

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: reduce require-regex-util disable comments

Rewrite the github massage-markdown-links URL regex to capture an
optional `api.` prefix in a named group (skipped in code) instead of
relying on a negative lookbehind, so both the base and global variants
can use regEx()/RE2 and their two disable comments are removed. Add
spec cases for api-prefixed URLs that match the URL shape.

Consolidate the four related line disables in rez/pattern.ts (bound and
range patterns emulating Python conditional patterns via named
backreferences and lookaheads, which RE2 cannot express) into a single
block disable/enable pair, matching the treatment of the lexer files.

Disable comment count drops from 13 to 8.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(datasource/sbt-package): use named capture group in link regex

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(manager/cake): restore original multiLineComment regex spelling

The [^] -> [\\s\\S] rewrite was only needed for an RE2 wrap that was
later reverted; keep the diff minimal.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(datasource/go): skip empty GOPROXY segments

The switch from a lookahead split to a capture-group split (needed because
RE2 has no lookahead support) changed how empty GOPROXY segments parse:
`a|,b` yielded `{ url: ',', fallback: '|' }` before and
`{ url: '', fallback: ',' }` after. The comma fallback only continues on
404/410, so a failing proxy ahead of an empty segment silently stopped the
lookup instead of falling through to the remaining proxies.

Empty segments carry no url to query, so drop them.

* refactor(datasource/go): use isTruthy for empty segment filter

* fix(datasource/go): filter empty segments before mapping

Filtering after the map broke the contextual typing from the
GoproxyItem[] annotation, widening fallback to string.

* refactor(platform/github): use regEx() for merge queue query stripping

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 14:30:46 +00:00

316 lines
9.2 KiB
TypeScript

/**
* @fileoverview Contains classes that represent a Bazel module version.
*/
import { isString } from '@sindresorhus/is';
import { regEx } from '../../../util/regex.ts';
/**
* Represents a single value in a VersionPart. For example, the version string
* `1.2.3` has three identifiers: `1`, `2`, `3`.
*/
export class Identifier {
/**
* Returns the identifier as a string.
*/
readonly asString: string;
/**
* If the identifier only contains digits, this is the numeric value.
* Otherwise, it is `0`.
*/
readonly asNumber: number;
/**
* Specifies whether the identifier only contains digits.
*/
readonly isDigitsOnly: boolean;
/**
* Regular expression used to identify whether an identifier value only
* contains digits.
*/
static readonly digitsOnlyMatcher = regEx(/^[0-9]+$/);
/**
* @param value The value that is parsed for the Bazel module version parts.
*/
constructor(value: string) {
if (value === '') {
throw new Error('Identifier value cannot be empty.');
}
this.asString = value;
if (Identifier.digitsOnlyMatcher.test(value)) {
this.isDigitsOnly = true;
this.asNumber = parseInt(value, 10);
} else {
this.isDigitsOnly = false;
this.asNumber = 0;
}
}
/**
* Determines whether this identifier and another identifier are equal.
*/
equals(other: Identifier): boolean {
return this.asString === other.asString;
}
/**
* Determines whether this identifier comes before the other identifier.
*/
isLessThan(other: Identifier): boolean {
// This logic mirrors the comparison logic in
// https://cs.opensource.google/bazel/bazel/+/refs/heads/master:src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Version.java
// isDigitsOnly: true first
if (this.isDigitsOnly !== other.isDigitsOnly) {
return this.isDigitsOnly;
}
if (this.asNumber !== other.asNumber) {
return this.asNumber < other.asNumber;
}
return this.asString < other.asString;
}
}
/**
* A collection of {@link Identifier} values that represent a portion of a
* Bazel module version.
*/
export class VersionPart extends Array<Identifier> {
/**
* Creates a {@link VersionPart} populated with the provided identifiers.
*/
static create(...items: (Identifier | string)[]): VersionPart {
const idents = items.map((item) => {
if (isString(item)) {
return new Identifier(item);
}
return item;
});
const vp = new VersionPart();
vp.push(...idents);
return vp;
}
/**
* The string representation of the version part.
*/
get asString(): string {
return this.map((ident) => ident.asString).join('.');
}
/**
* Specifies whether this contains any identifiers.
*/
get isEmpty(): boolean {
return this.length === 0;
}
/**
* Returns the equivalent of the a Semver major value.
*/
get major(): number {
return this.length > 0 ? this[0].asNumber : 0;
}
/**
* Returns the equivalent of the a Semver minor value.
*/
get minor(): number {
return this.length > 1 ? this[1].asNumber : 0;
}
/**
* Returns the equivalent of the a Semver patch value.
*/
get patch(): number {
return this.length > 2 ? this[2].asNumber : 0;
}
/**
* Determines whether this version part is equal to the other.
*/
equals(other: VersionPart): boolean {
if (this.length !== other.length) {
return false;
}
for (let i = 0; i < this.length; i++) {
const a = this[i];
const b = other[i];
if (!a.equals(b)) {
return false;
}
}
return true;
}
/**
* Determines whether this version part comes before the other.
*/
isLessThan(other: VersionPart): boolean {
// This logic mirrors the comparison logic in
// https://cs.opensource.google/bazel/bazel/+/refs/heads/master:src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Version.java
if (this.equals(other)) {
return false;
}
// Non-empty are first
if (this.length === 0 && other.length !== 0) {
return false;
}
if (other.length === 0 && this.length !== 0) {
return true;
}
const shortestLen = this.length < other.length ? this.length : other.length;
for (let i = 0; i < shortestLen; i++) {
const a = this[i];
const b = other[i];
if (!a.equals(b)) {
return a.isLessThan(b);
}
}
return this.length < other.length;
}
}
// Represents the capture groups produced by BzlmodVersion.versionMatcher.
interface VersionRegexResult {
release: string;
prerelease: string | undefined;
build: string | undefined;
}
/**
* Represents a version in the Bazel module system. The version format we support is
* `RELEASE[-PRERELEASE][+BUILD]`, where `RELEASE`, `PRERELEASE`, and `BUILD` are
* each a sequence of "identifiers" (defined as a non-empty sequence of ASCII alphanumerical
* characters and hyphens) separated by dots. The `RELEASE` part may not contain hyphens.
*
* Otherwise, this format is identical to SemVer, especially in terms of the comparison algorithm
* (https://semver.org/#spec-item-11). In other words, this format is intentionally looser than
* SemVer; in particular:
*
* - the "release" part isn't limited to exactly 3 segments (major, minor, patch), but can be
* fewer or more;
* - each segment in the "release" part can be identifiers instead of just numbers (so letters
* are also allowed -- although hyphens are not).
*
* Any valid SemVer version is a valid Bazel module version. Additionally, two SemVer versions
* `a` and `b` compare `a < b` iff the same holds when they're compared as Bazel * module versions.
*
* The special "empty string" version can also be used, and compares higher than everything else.
* It signifies that there is a NonRegistryOverride for a module.
*/
export class BzlmodVersion {
readonly original: string;
readonly release: VersionPart;
readonly prerelease: VersionPart;
readonly build: VersionPart;
/**
* The regular expression that identifies a valid Bazel module version.
*/
static readonly versionMatcher = regEx(
/^(?<release>[a-zA-Z0-9.]+)(?:-(?<prerelease>[a-zA-Z0-9.-]+))?(?:\+(?<build>[a-zA-Z0-9.-]+))?$/,
);
/**
* @param version The string that is parsed for the Bazel module version
* values.
*/
constructor(version: string) {
this.original = version;
if (version === '') {
this.release = VersionPart.create();
this.prerelease = VersionPart.create();
this.build = VersionPart.create();
return;
}
const vparts: Partial<VersionRegexResult> | undefined =
BzlmodVersion.versionMatcher.exec(version)?.groups;
if (!vparts) {
throw new Error(`Invalid Bazel module version: ${version}`);
}
// The regex check above ensures that we will have a release group.
const rparts = vparts.release!.split('.');
this.release = VersionPart.create(...rparts);
const pparts = vparts.prerelease ? vparts.prerelease.split('.') : [];
this.prerelease = VersionPart.create(...pparts);
// Do not parse the build value. Treat it as a single value.
const bparts = vparts.build ? [vparts.build] : [];
this.build = VersionPart.create(...bparts);
}
/**
* Specifies whether this is a pre-release version.
*/
get isPrerelease(): boolean {
return !this.prerelease.isEmpty;
}
// Comparison
/**
* Determines whether this Bazel module version is equal to the other.
*
* @param other The other version for the comparison.
* @param ignoreBuild? If specified, determines whether the build value is
* evaluated as part of the equality check. This is useful when
* determining precedence.
*/
equals(other: BzlmodVersion, ignoreBuild?: boolean): boolean {
if (ignoreBuild) {
return (
this.release.equals(other.release) &&
this.prerelease.equals(other.prerelease)
);
}
return (
this.release.equals(other.release) &&
this.prerelease.equals(other.prerelease) &&
this.build.equals(other.build)
);
}
/**
* Determines whether this Bazel module version comes before the other.
*/
isLessThan(other: BzlmodVersion): boolean {
// This logic mirrors the comparison logic in
// https://cs.opensource.google/bazel/bazel/+/refs/heads/master:src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Version.java
if (this.release.isLessThan(other.release)) {
return true;
}
// Ensure that prerelease is listed before regular releases
if (this.isPrerelease && !other.isPrerelease) {
return true;
}
if (this.prerelease.isLessThan(other.prerelease)) {
return true;
}
// NOTE: We ignore the build value for precedence comparison per the Semver spec.
// https://semver.org/#spec-item-10
return false;
}
/**
* Determines whether this Bazel module version comes after the other.
*/
isGreaterThan(other: BzlmodVersion): boolean {
return BzlmodVersion.defaultCompare(this, other) === 1;
}
/**
* Evaluates two Bazel module versions and returns a value specifying whether
* a < b (-1), a == b (0), or a > b (1).
*/
static defaultCompare(a: BzlmodVersion, b: BzlmodVersion): number {
if (a.equals(b, true)) {
return 0;
}
if (a.isLessThan(b)) {
return -1;
}
return 1;
}
}