version.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { isNumber } from 'lodash';
  2. const versionPattern = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z\.]+))?/;
  3. export class SemVersion {
  4. major: number;
  5. minor: number;
  6. patch: number;
  7. meta: string;
  8. constructor(version: string) {
  9. this.major = 0;
  10. this.minor = 0;
  11. this.patch = 0;
  12. this.meta = '';
  13. const match = versionPattern.exec(version);
  14. if (match) {
  15. this.major = Number(match[1]);
  16. this.minor = Number(match[2] || 0);
  17. this.patch = Number(match[3] || 0);
  18. this.meta = match[4];
  19. }
  20. }
  21. isGtOrEq(version: string): boolean {
  22. const compared = new SemVersion(version);
  23. for (let i = 0; i < this.comparable.length; ++i) {
  24. if (this.comparable[i] > compared.comparable[i]) {
  25. return true;
  26. }
  27. if (this.comparable[i] < compared.comparable[i]) {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33. isValid(): boolean {
  34. return isNumber(this.major);
  35. }
  36. get comparable() {
  37. return [this.major, this.minor, this.patch];
  38. }
  39. }
  40. export function isVersionGtOrEq(a: string, b: string): boolean {
  41. const aSemver = new SemVersion(a);
  42. return aSemver.isGtOrEq(b);
  43. }