aboutsummaryrefslogtreecommitdiffstats
path: root/packages/monorepo-scripts/src/utils/semver_utils.ts
blob: d5c6b2d1735e5bfece6bd6887b1d5af36ebba882 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import * as _ from 'lodash';
import semverSort = require('semver-sort');

// Regex that matches semantic versions only including digits and dots.
const SEM_VER_REGEX = /^(\d+\.){1}(\d+\.){1}(\d+){1}$/gm;

export const semverUtils = {
    /**
     * Checks whether version a is lessThan version b. Supplied versions must be
     * Semantic Versions containing only numbers and dots (e.g 1.4.0).
     * @param a version of interest
     * @param b version to compare a against
     * @return Whether version a is lessThan version b
     */
    lessThan(a: string, b: string): boolean {
        this.assertValidSemVer('a', a);
        this.assertValidSemVer('b', b);
        if (a === b) {
            return false;
        }
        const sortedVersions = semverSort.desc([a, b]);
        const isALessThanB = sortedVersions[0] === b;
        return isALessThanB;
    },
    /**
     * Checks whether version a is greaterThan version b. Supplied versions must be
     * Semantic Versions containing only numbers and dots (e.g 1.4.0).
     * @param a version of interest
     * @param b version to compare a against
     * @return Whether version a is greaterThan version b
     */
    greaterThan(a: string, b: string): boolean {
        this.assertValidSemVer('a', a);
        this.assertValidSemVer('b', b);
        if (a === b) {
            return false;
        }
        const sortedVersions = semverSort.desc([a, b]);
        const isAGreaterThanB = sortedVersions[0] === a;
        return isAGreaterThanB;
    },
    assertValidSemVer(variableName: string, version: string): void {
        if (!version.match(SEM_VER_REGEX)) {
            throw new Error(
                `SemVer versions should only contain numbers and dots. Encountered: ${variableName} = ${version}`,
            );
        }
    },
    getLatestVersion(versions: string[]): string {
        _.each(versions, version => {
            this.assertValidSemVer('version', version);
        });
        const sortedVersions = semverSort.desc(versions);
        return sortedVersions[0];
    },
};