包文件→ .shtukbase/packages/std-semver/checks/semverlib.ts
checks/semverlib.ts
132 行, 5.6 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Semantic Versioning 2.0.0 (https://semver.org/spec/v2.0.0.html): the version grammar, comparison, and where the
- // project writes its versions (package.json, Cargo.toml, pyproject.toml, package.md).
- import { git, list, projectFiles, readTextFile, settings, excluder } from './lib/std.ts';
- export const PKG = 'std-semver';
- export const DEFAULTS = {
- manifests: ['package.json', 'Cargo.toml', 'pyproject.toml', 'package.md'],
- exclude: ['**/fixtures/**', '**/testdata/**', '**/archive/**'],
- versionFile: '',
- tagPrefix: 'v',
- zeroMajor: 'minor',
- };
- export type Config = typeof DEFAULTS;
- export function config(): Config {
- const c = settings('semver', DEFAULTS);
- return { ...c, manifests: list(c.manifests), exclude: list(c.exclude), versionFile: String(c.versionFile ?? '').trim(), tagPrefix: String(c.tagPrefix ?? ''), zeroMajor: String(c.zeroMajor ?? 'minor') };
- }
- /** The regular expression the specification itself suggests (semver.org, FAQ), with named groups. */
- export const SEMVER = /^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<pre>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
- export type Ver = { major: number; minor: number; patch: number; pre: string[] };
- export function parse(v: string): Ver | null {
- const m = SEMVER.exec(v.trim());
- if (!m?.groups) return null;
- return { major: Number(m.groups.major), minor: Number(m.groups.minor), patch: Number(m.groups.patch), pre: m.groups.pre ? m.groups.pre.split('.') : [] };
- }
- /** Precedence by section 11: numbers, then a pre-release is lower than the release, then identifiers one by one. */
- export function compare(a: Ver, b: Ver): number {
- for (const k of ['major', 'minor', 'patch'] as const) if (a[k] !== b[k]) return a[k] - b[k];
- if (!a.pre.length || !b.pre.length) return (a.pre.length ? -1 : 0) + (b.pre.length ? 1 : 0);
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
- const x = a.pre[i];
- const y = b.pre[i];
- if (x === undefined) return -1;
- if (y === undefined) return 1;
- const nx = /^\d+$/.test(x);
- const ny = /^\d+$/.test(y);
- if (nx && ny && Number(x) !== Number(y)) return Number(x) - Number(y);
- if (nx !== ny) return nx ? -1 : 1;
- if (x !== y) return x < y ? -1 : 1;
- }
- return 0;
- }
- export type Found = { file: string; line: number; version: string };
- /** The `version` of a TOML table (`[package]`, `[project]`, `[tool.poetry]`); `version.workspace = true` is no version. */
- function tomlVersion(text: string, tables: string[]): { line: number; version: string } | null {
- let table = '';
- const lines = text.split('\n');
- for (let i = 0; i < lines.length; i++) {
- const l = lines[i].trim();
- const t = /^\[([^\[\]]+)\]\s*(#.*)?$/.exec(l);
- if (t) {
- table = t[1].trim();
- continue;
- }
- if (!tables.includes(table)) continue;
- const v = /^version\s*=\s*(["'])(.*?)\1\s*(#.*)?$/.exec(l);
- if (v) return { line: i + 1, version: v[2] };
- }
- return null;
- }
- /** The version a manifest declares, or null when it declares none (a private package.json without version, a
- * workspace member that takes the workspace version, a dynamic pyproject version). */
- export function manifestVersion(file: string, text: string): { line: number; version: string } | null {
- const base = file.split('/').pop() ?? '';
- if (base === 'package.json') {
- let j: unknown;
- try {
- j = JSON.parse(text);
- } catch {
- return null;
- }
- const v = (j as Record<string, unknown>)?.version;
- if (typeof v !== 'string') return null;
- const line = text.split('\n').findIndex((l) => /"version"\s*:/.test(l)) + 1;
- return { line: line || 1, version: v };
- }
- if (base === 'Cargo.toml') return tomlVersion(text, ['package', 'workspace.package']);
- if (base === 'pyproject.toml') return tomlVersion(text, ['project', 'tool.poetry']);
- if (base === 'package.md') {
- const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
- if (!m) return null;
- const lines = m[1].split('\n');
- if (!lines.some((l) => /^type:\s*["']?Package["']?\s*$/.test(l))) return null;
- const i = lines.findIndex((l) => /^version:/.test(l));
- if (i < 0) return null;
- return { line: i + 2, version: lines[i].replace(/^version:\s*/, '').replace(/\s+#.*$/, '').replace(/^["']|["']$/g, '').trim() };
- }
- return null;
- }
- export function manifests(cfg: Config): Found[] {
- const skip = excluder(cfg.exclude);
- const out: Found[] = [];
- for (const f of projectFiles()) {
- if (skip(f) || !cfg.manifests.includes(f.split('/').pop() ?? '')) continue;
- const text = readTextFile(f);
- if (text === null) continue;
- const v = manifestVersion(f, text);
- if (v) out.push({ file: f, ...v });
- }
- return out;
- }
- /** The project's own version: `versionFile` from the settings, else the first manifest in the root that has one. */
- export function projectVersion(cfg: Config): Found | null {
- const candidates = cfg.versionFile ? [cfg.versionFile] : cfg.manifests;
- for (const f of candidates) {
- const text = readTextFile(f);
- if (text === null) continue;
- const v = manifestVersion(f, text);
- if (v) return { file: f, ...v };
- }
- return null;
- }
- /** Release tags: `<prefix>X.Y.Z…` reachable from HEAD, newest version first. */
- export function releaseTags(cfg: Config): { tag: string; ver: Ver | null }[] {
- const out = git(['tag', '--merged', 'HEAD']);
- if (out === null) return [];
- const p = cfg.tagPrefix;
- return out.split('\n').map((t) => t.trim()).filter((t) => t.startsWith(p) && /^\d/.test(t.slice(p.length)))
- .map((tag) => ({ tag, ver: parse(tag.slice(p.length)) }));
- }