-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
62 lines (52 loc) · 1.49 KB
/
index.mjs
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
57
58
59
60
61
62
import { resolve } from 'node:path'
import { readFileSync, writeFileSync } from 'node:fs'
import { setFailed, setOutput, getInput } from '@actions/core'
import { context } from '@actions/github'
import { parse } from 'semver'
/**
* Analyze package.json and prepare a new version
*/
const getNewVersion = () => {
const commitHash = context.sha.substring(0, 7)
let version = getInput('version')
const path = resolve(process.cwd(), 'package.json')
const file = readFileSync(path, 'utf8')
const pkg = JSON.parse(file)
if (!version)
version = pkg.version
if (!version)
throw new Error('No version found in package.json')
const semver = parse(version, { loose: true })
semver.prerelease = [...semver.prerelease, commitHash]
const newVersion = semver.format()
pkg.version = newVersion
const newPkg = JSON.stringify(pkg, null, 2)
return {
/**
* New version
* @type {string}
*/
version: newVersion,
/**
* Write new version to package.json
*/
writeFile: () => writeFileSync(path, newPkg, 'utf8')
}
}
try {
// Get new version
const { version, writeFile } = getNewVersion()
console.log(`New version: ${version}`)
// Write new version to package.json
const dryRun = getInput('dry-run')
if (dryRun !== 'true') {
writeFile()
console.log('package.json updated')
} else {
console.log('Dry run detected, package.json was not updated')
}
// Set output
setOutput('version', version)
} catch (error) {
setFailed(error.message)
}