|
| 1 | +import type { ReleaseType } from 'semver'; |
| 2 | +import { UpdaterInterface } from '../interface/updaterInterface'; |
| 3 | +import * as core from '@actions/core'; |
| 4 | +import { calculateNextVersion, FileHandler, ManifestParser } from '../utils'; |
| 5 | + |
| 6 | +export class CustomUpdater implements UpdaterInterface { |
| 7 | + platform = 'custom'; |
| 8 | + private filePath: string; |
| 9 | + private variableName: string; |
| 10 | + private currentVersion: string | null = null; |
| 11 | + private fileHandler: FileHandler; |
| 12 | + private manifestParser: ManifestParser; |
| 13 | + |
| 14 | + constructor(filePath: string, variableName: string) { |
| 15 | + this.filePath = filePath; |
| 16 | + this.variableName = variableName; |
| 17 | + this.fileHandler = new FileHandler(); |
| 18 | + this.manifestParser = new ManifestParser(this.fileHandler); |
| 19 | + } |
| 20 | + |
| 21 | + canHandle(): boolean { |
| 22 | + // This updater is explicitly called, so it can always handle if constructed. |
| 23 | + return true; |
| 24 | + } |
| 25 | + |
| 26 | + getCurrentVersion(): string | null { |
| 27 | + if (this.currentVersion) { |
| 28 | + return this.currentVersion; |
| 29 | + } |
| 30 | + |
| 31 | + try { |
| 32 | + // eslint-disable-next-line no-useless-escape |
| 33 | + const regex = new RegExp(`(${this.variableName}\s*=\s*['"]?)([\\d.]+)(['"]?)`); |
| 34 | + this.currentVersion = this.manifestParser.getVersion(this.filePath, 'regex', { |
| 35 | + regex: regex, |
| 36 | + }); |
| 37 | + return this.currentVersion; |
| 38 | + } catch (error) { |
| 39 | + core.debug(`Could not read or parse version from ${this.filePath}: ${error}`); |
| 40 | + } |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + bumpVersion(releaseType: ReleaseType): string { |
| 45 | + const oldVersion = this.getCurrentVersion(); |
| 46 | + if (!oldVersion) { |
| 47 | + throw new Error( |
| 48 | + `Could not find current version for variable '${this.variableName}' in file '${this.filePath}'`, |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + const newVersion = calculateNextVersion(oldVersion, releaseType); |
| 53 | + // eslint-disable-next-line no-useless-escape |
| 54 | + const regexReplace = new RegExp(`(${this.variableName}\s*=\s*['"]?)${oldVersion}(['"]?)`); |
| 55 | + |
| 56 | + this.manifestParser.updateVersion(this.filePath, newVersion, 'regex', { |
| 57 | + regexReplace: regexReplace, |
| 58 | + }); |
| 59 | + |
| 60 | + core.info( |
| 61 | + `Bumped ${this.variableName} in ${this.filePath} from ${oldVersion} to ${newVersion}`, |
| 62 | + ); |
| 63 | + return newVersion; |
| 64 | + } |
| 65 | +} |
0 commit comments