-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre-publish.mjs
96 lines (79 loc) · 2.46 KB
/
pre-publish.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import chalk from 'chalk';
import fs from 'fs-extra';
import semver from 'semver';
import path from 'node:path';
import op from 'object-path';
import inquirer from 'inquirer';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pkg = fs.readJsonSync(path.resolve(__dirname, 'package.json'));
const utils = {
normalize: (...args) => path.normalize(path.join(process.cwd(), ...args)),
prefix: chalk.magenta(' > '),
suffix: chalk.magenta(': '),
validate: (val, field) => {
switch (field) {
case 'version':
return !semver.valid(semver.coerce(val))
? `invalid version: ${chalk.magenta(val)}`
: true;
default:
return !val ? `${field} is required` : true;
}
},
};
const env = op.get(process.env, 'NODE_ENV');
const versionUpdater = async () => {
const { normalize, prefix, suffix, validate } = utils;
const pkgFilePath = normalize('package.json');
const currentVersion = pkg.version;
console.log('');
console.log(` Publishing ${chalk.magenta(pkg.name)}...`);
console.log('');
const { target } = await inquirer.prompt([
{
type: 'list',
message: `Current version is ${currentVersion}. Select target version:`,
name: 'target',
choices: [
'major',
'minor',
'patch',
'premajor',
'preminor',
'prepatch',
'prerelease',
],
default: 'patch',
},
]);
const defaultVer = semver.inc(pkg.version, target);
// Input version number
const { version } = await inquirer.prompt([
{
type: 'input',
prefix,
suffix,
name: 'version',
default: defaultVer,
message: chalk.cyan('Version'),
validate: (val) => validate(val, 'version'),
filter: (val) => semver.valid(val) || defaultVer,
},
]);
// Write package.json
if (env !== 'test') {
await Promise.all([
fs.writeFile(
pkgFilePath,
JSON.stringify({ ...pkg, version }, null, 2),
),
]);
}
console.log('');
if (env === 'test') {
console.log(JSON.stringify({ version }, null, 2));
console.log('');
}
};
versionUpdater();