ShtukbaseStandard
package file→ .shtukbase/packages/std-keep-a-changelog/checks/semver.ts

checks/semver.ts

22 lines, 1.1 KB.

  1. // The SemVer 2.0.0 grammar and precedence (https://semver.org/spec/v2.0.0.html), enough to order changelog releases.
  2. export const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
  3. export function compare(a: string, b: string): number {
  4. const x = SEMVER.exec(a);
  5. const y = SEMVER.exec(b);
  6. if (!x || !y) return 0;
  7. for (let i = 1; i <= 3; i++) if (Number(x[i]) !== Number(y[i])) return Number(x[i]) - Number(y[i]);
  8. const p = x[4] ? x[4].split('.') : [];
  9. const q = y[4] ? y[4].split('.') : [];
  10. if (!p.length || !q.length) return (p.length ? -1 : 0) + (q.length ? 1 : 0);
  11. for (let i = 0; i < Math.max(p.length, q.length); i++) {
  12. if (p[i] === undefined) return -1;
  13. if (q[i] === undefined) return 1;
  14. const np = /^\d+$/.test(p[i]);
  15. const nq = /^\d+$/.test(q[i]);
  16. if (np && nq && Number(p[i]) !== Number(q[i])) return Number(p[i]) - Number(q[i]);
  17. if (np !== nq) return np ? -1 : 1;
  18. if (p[i] !== q[i]) return p[i] < q[i] ? -1 : 1;
  19. }
  20. return 0;
  21. }