version.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import _ 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. const match = versionPattern.exec(version);
  10. if (match) {
  11. this.major = Number(match[1]);
  12. this.minor = Number(match[2] || 0);
  13. this.patch = Number(match[3] || 0);
  14. this.meta = match[4];
  15. }
  16. }
  17. isGtOrEq(version: string): boolean {
  18. const compared = new SemVersion(version);
  19. for (let i = 0; i < this.comparable.length; ++i) {
  20. if (this.comparable[i] > compared.comparable[i]) {
  21. return true;
  22. }
  23. if (this.comparable[i] < compared.comparable[i]) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. isValid(): boolean {
  30. return _.isNumber(this.major);
  31. }
  32. get comparable() {
  33. return [this.major, this.minor, this.patch];
  34. }
  35. }
  36. export function isVersionGtOrEq(a: string, b: string): boolean {
  37. const aSemver = new SemVersion(a);
  38. return aSemver.isGtOrEq(b);
  39. }