aboutsummaryrefslogtreecommitdiffstats
path: root/packages/monorepo-scripts/src/utils/semver_utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/monorepo-scripts/src/utils/semver_utils.ts')
-rw-r--r--packages/monorepo-scripts/src/utils/semver_utils.ts56
1 files changed, 56 insertions, 0 deletions
diff --git a/packages/monorepo-scripts/src/utils/semver_utils.ts b/packages/monorepo-scripts/src/utils/semver_utils.ts
new file mode 100644
index 000000000..d5c6b2d17
--- /dev/null
+++ b/packages/monorepo-scripts/src/utils/semver_utils.ts
@@ -0,0 +1,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];
+ },
+};