ShtukbaseStandard
包文件→ .shtukbase/packages/std-semver/checks/semverlib.ts

checks/semverlib.ts

132 行, 5.6 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Semantic Versioning 2.0.0 (https://semver.org/spec/v2.0.0.html): the version grammar, comparison, and where the
  2. // project writes its versions (package.json, Cargo.toml, pyproject.toml, package.md).
  3. import { git, list, projectFiles, readTextFile, settings, excluder } from './lib/std.ts';
  4. export const PKG = 'std-semver';
  5. export const DEFAULTS = {
  6. manifests: ['package.json', 'Cargo.toml', 'pyproject.toml', 'package.md'],
  7. exclude: ['**/fixtures/**', '**/testdata/**', '**/archive/**'],
  8. versionFile: '',
  9. tagPrefix: 'v',
  10. zeroMajor: 'minor',
  11. };
  12. export type Config = typeof DEFAULTS;
  13. export function config(): Config {
  14. const c = settings('semver', DEFAULTS);
  15. return { ...c, manifests: list(c.manifests), exclude: list(c.exclude), versionFile: String(c.versionFile ?? '').trim(), tagPrefix: String(c.tagPrefix ?? ''), zeroMajor: String(c.zeroMajor ?? 'minor') };
  16. }
  17. /** The regular expression the specification itself suggests (semver.org, FAQ), with named groups. */
  18. 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-]+)*))?$/;
  19. export type Ver = { major: number; minor: number; patch: number; pre: string[] };
  20. export function parse(v: string): Ver | null {
  21. const m = SEMVER.exec(v.trim());
  22. if (!m?.groups) return null;
  23. return { major: Number(m.groups.major), minor: Number(m.groups.minor), patch: Number(m.groups.patch), pre: m.groups.pre ? m.groups.pre.split('.') : [] };
  24. }
  25. /** Precedence by section 11: numbers, then a pre-release is lower than the release, then identifiers one by one. */
  26. export function compare(a: Ver, b: Ver): number {
  27. for (const k of ['major', 'minor', 'patch'] as const) if (a[k] !== b[k]) return a[k] - b[k];
  28. if (!a.pre.length || !b.pre.length) return (a.pre.length ? -1 : 0) + (b.pre.length ? 1 : 0);
  29. for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
  30. const x = a.pre[i];
  31. const y = b.pre[i];
  32. if (x === undefined) return -1;
  33. if (y === undefined) return 1;
  34. const nx = /^\d+$/.test(x);
  35. const ny = /^\d+$/.test(y);
  36. if (nx && ny && Number(x) !== Number(y)) return Number(x) - Number(y);
  37. if (nx !== ny) return nx ? -1 : 1;
  38. if (x !== y) return x < y ? -1 : 1;
  39. }
  40. return 0;
  41. }
  42. export type Found = { file: string; line: number; version: string };
  43. /** The `version` of a TOML table (`[package]`, `[project]`, `[tool.poetry]`); `version.workspace = true` is no version. */
  44. function tomlVersion(text: string, tables: string[]): { line: number; version: string } | null {
  45. let table = '';
  46. const lines = text.split('\n');
  47. for (let i = 0; i < lines.length; i++) {
  48. const l = lines[i].trim();
  49. const t = /^\[([^\[\]]+)\]\s*(#.*)?$/.exec(l);
  50. if (t) {
  51. table = t[1].trim();
  52. continue;
  53. }
  54. if (!tables.includes(table)) continue;
  55. const v = /^version\s*=\s*(["'])(.*?)\1\s*(#.*)?$/.exec(l);
  56. if (v) return { line: i + 1, version: v[2] };
  57. }
  58. return null;
  59. }
  60. /** The version a manifest declares, or null when it declares none (a private package.json without version, a
  61. * workspace member that takes the workspace version, a dynamic pyproject version). */
  62. export function manifestVersion(file: string, text: string): { line: number; version: string } | null {
  63. const base = file.split('/').pop() ?? '';
  64. if (base === 'package.json') {
  65. let j: unknown;
  66. try {
  67. j = JSON.parse(text);
  68. } catch {
  69. return null;
  70. }
  71. const v = (j as Record<string, unknown>)?.version;
  72. if (typeof v !== 'string') return null;
  73. const line = text.split('\n').findIndex((l) => /"version"\s*:/.test(l)) + 1;
  74. return { line: line || 1, version: v };
  75. }
  76. if (base === 'Cargo.toml') return tomlVersion(text, ['package', 'workspace.package']);
  77. if (base === 'pyproject.toml') return tomlVersion(text, ['project', 'tool.poetry']);
  78. if (base === 'package.md') {
  79. const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
  80. if (!m) return null;
  81. const lines = m[1].split('\n');
  82. if (!lines.some((l) => /^type:\s*["']?Package["']?\s*$/.test(l))) return null;
  83. const i = lines.findIndex((l) => /^version:/.test(l));
  84. if (i < 0) return null;
  85. return { line: i + 2, version: lines[i].replace(/^version:\s*/, '').replace(/\s+#.*$/, '').replace(/^["']|["']$/g, '').trim() };
  86. }
  87. return null;
  88. }
  89. export function manifests(cfg: Config): Found[] {
  90. const skip = excluder(cfg.exclude);
  91. const out: Found[] = [];
  92. for (const f of projectFiles()) {
  93. if (skip(f) || !cfg.manifests.includes(f.split('/').pop() ?? '')) continue;
  94. const text = readTextFile(f);
  95. if (text === null) continue;
  96. const v = manifestVersion(f, text);
  97. if (v) out.push({ file: f, ...v });
  98. }
  99. return out;
  100. }
  101. /** The project's own version: `versionFile` from the settings, else the first manifest in the root that has one. */
  102. export function projectVersion(cfg: Config): Found | null {
  103. const candidates = cfg.versionFile ? [cfg.versionFile] : cfg.manifests;
  104. for (const f of candidates) {
  105. const text = readTextFile(f);
  106. if (text === null) continue;
  107. const v = manifestVersion(f, text);
  108. if (v) return { file: f, ...v };
  109. }
  110. return null;
  111. }
  112. /** Release tags: `<prefix>X.Y.Z…` reachable from HEAD, newest version first. */
  113. export function releaseTags(cfg: Config): { tag: string; ver: Ver | null }[] {
  114. const out = git(['tag', '--merged', 'HEAD']);
  115. if (out === null) return [];
  116. const p = cfg.tagPrefix;
  117. return out.split('\n').map((t) => t.trim()).filter((t) => t.startsWith(p) && /^\d/.test(t.slice(p.length)))
  118. .map((tag) => ({ tag, ver: parse(tag.slice(p.length)) }));
  119. }