smartversion/ts/index.ts
2022-04-28 12:20:09 +02:00

101 lines
2.7 KiB
TypeScript

import * as plugins from './smartversion.plugins.js';
export class SmartVersion {
public static fromFuzzyString(fuzzyString: string): SmartVersion {
return new SmartVersion(plugins.semver.minVersion(fuzzyString).version, fuzzyString);
}
public originalVersionString: string;
public semver: plugins.semver.SemVer;
public get versionString(): string {
return this.semver.version;
};
constructor(semVerStringArg: string, originalStringArg?: string) {
this.originalVersionString = originalStringArg;
this.semver = new plugins.semver.SemVer(semVerStringArg);
}
public get major() {
return this.semver.major;
}
public get minor() {
return this.semver.minor;
}
public get patch() {
return this.semver.patch;
}
public greaterThan(smartVersionArg: SmartVersion) {
return this.greaterThanString(smartVersionArg.versionString);
}
/**
* compares the version of this against a string
*/
public greaterThanString(versionStringArg: string) {
return plugins.semver.gt(this.versionString, versionStringArg);
}
public lessThan(smartVersionArg: SmartVersion) {
return this.lessThanString(smartVersionArg.versionString);
}
/**
* compares the version of this against a string
*/
public lessThanString(versionStringArg: string) {
return plugins.semver.lt(this.versionString, versionStringArg);
}
/**
* tries to get the best match from a range of available versions
*/
public getBestMatch(availableVersions: string[]): string {
let bestMatchingVersion: string;
for (const versionArg of availableVersions) {
if (!plugins.semver.satisfies(versionArg, this.originalVersionString)) {
continue;
}
if(!bestMatchingVersion) {
bestMatchingVersion = versionArg;
} else {
if (plugins.semver.lt(bestMatchingVersion, versionArg)) {
bestMatchingVersion = versionArg;
}
}
}
return bestMatchingVersion;
}
public getNewPatchVersion() {
const newInstance = new SmartVersion(`${this.semver.major}.${this.semver.minor}.${this.semver.patch + 1}`);
return newInstance;
}
public getNewMinorVersion() {
const newInstance = new SmartVersion(`${this.semver.major}.${this.semver.minor + 1}.${0}`);
return newInstance;
}
public getNewMajorVersion() {
const newInstance = new SmartVersion(`${this.semver.major + 1}.${0}.${0}`);
return newInstance;
}
public getNewVersion(typeArg: 'patch' | 'minor' | 'major') {
switch (typeArg) {
case 'patch':
return this.getNewPatchVersion();
case 'minor':
return this.getNewMinorVersion();
case 'major':
return this.getNewMajorVersion();
default:
throw new Error('unknown new version type.');
}
}
}