/
kickout.js
181 lines (164 loc) · 7.57 KB
/
kickout.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env node
/*!
** Kickout -- Conveniently Release Git-Versioned NPM Package
** Copyright (c) 2017-2024 Dr. Ralf S. Engelschall <rse@engelschall.com>
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* external requirements */
const Promise = require("bluebird")
const fs = require("fs")
const yargs = require("yargs")
const execa = require("execa")
const getStream = require("get-stream")
const chalk = require("chalk")
const stripAnsi = require("strip-ansi")
const semver = require("semver")
const escRE = require("escape-string-regexp")
const UN = require("update-notifier")
;(async () => {
/* load my own information */
const my = require("./package.json")
/* automatic update notification (with 2 days check interval) */
const notifier = UN({ pkg: my, updateCheckInterval: 1000 * 60 * 60 * 24 * 2 })
notifier.notify()
/* command-line option parsing */
const argv = yargs
.usage("Usage: $0 [-h] [-V] [-C] [-m <message>] [-t <tag>] major|minor|patch|X.Y.Z")
.help("h").alias("h", "help").default("h", false)
.describe("h", "show usage help")
.boolean("V").alias("V", "version").default("V", false)
.describe("V", "show program version information")
.boolean("C").alias("C", "noColor").default("C", false)
.describe("C", "do not use any colors in output")
.boolean("n").alias("n", "noop").default("n", false)
.describe("n", "do not execute any destructive commands at all")
.string("m").nargs("m", 1).alias("m", "message").default("m", "")
.describe("m", "use custom commit message")
.string("t").nargs("t", 1).alias("t", "tag").default("t", "latest")
.describe("t", "set particular NPM package tag")
.strict()
.showHelpOnFail(true)
.demand(1)
.parse(process.argv.slice(2))
/* short-circuit processing of "-V" command-line option */
if (argv.version) {
process.stderr.write(my.name + " " + my.version + " <" + my.homepage + ">\n")
process.stderr.write(my.description + "\n")
process.stderr.write("Copyright (c) 2017-2024 " + my.author.name + " <" + my.author.url + ">\n")
process.stderr.write("Licensed under " + my.license + " <http://spdx.org/licenses/" + my.license + ".html>\n")
process.exit(0)
}
/* gather argument */
if (argv._.length !== 1)
throw new Error("invalid number of arguments")
const bump = argv._[0]
if (!bump.match(/^(?:major|minor|patch|\d+\.\d+\.\d+)$/))
throw new Error("invalid bumping mode")
/* helper functions */
const out = (txt) => {
if (argv.noColor)
txt = stripAnsi(txt)
process.stdout.write(txt)
}
const cmd = (cmd, noop) => {
if (noop) {
out(`$ ${chalk.blue("# " + cmd)}\n`)
return Promise.resolve({ stdout: "", stderr: "" })
}
else {
out(`$ ${chalk.blue(cmd)}\n`)
const child = execa(cmd, { shell: true })
child.stdout.pipe(process.stdout)
child.stderr.pipe(process.stderr)
return Promise.all([
child,
getStream(child.stdout),
getStream(child.stderr)
]).then(([ result, stdout, stderr ]) => {
result.stdout = stdout
result.stderr = stderr
return result
}).catch((/* err */) => {
throw new Error("shell command failed")
})
}
}
/* step 1: read old package configuration */
if (!fs.existsSync("package.json")) {
out(`** ${chalk.red.bold("ERROR:")} cannot find NPM package configuration file "package.json"\n`)
process.exit(1)
}
const pkgData = fs.readFileSync("package.json", { encoding: "utf8" })
const pkg = JSON.parse(pkgData)
if (typeof pkg !== "object") {
out(`** ${chalk.red.bold("ERROR:")} invalid NPM package configuration file "package.json"\n`)
process.exit(1)
}
/* step 2: check Git working copy status */
const status = await cmd("git status --porcelain", false).then(({ stdout, stderr }) => {
if (stdout === "" && stderr === "")
return "clean"
else if (stderr === "")
return "changes"
else
return "error"
}).catch((/* err */) => {
return "error"
})
if (status !== "clean") {
out(`** ${chalk.red.bold("ERROR:")} Git working copy status: ${chalk.bold(status)}\n`)
process.exit(1)
}
/* step 3: optionally run NPM pre-publish scripts */
if (typeof pkg.scripts === "object" && typeof pkg.scripts.prepublish === "string")
await cmd("npm run prepublish", argv.noop)
else if (typeof pkg.scripts === "object" && typeof pkg.scripts.prepublishOnly === "string")
await cmd("npm run prepublishOnly", argv.noop)
/* step 4: determine latest published NPM version */
let versionOld = await cmd(`npm view ${pkg.name} version`, false).then((res) => res.stdout)
versionOld = versionOld.replace(/\r?\n$/, "")
/* step 5: bump version number in package.json */
if (semver.neq(pkg.version, versionOld)) {
out(`** ${chalk.red.bold("ERROR:")} latest published NPM package version not equal current version in package.json\n`)
process.exit(1)
}
const versionNew = bump.match(/^(?:major|minor|patch)$/) ? semver.inc(pkg.version, bump) : bump
const re = new RegExp(`(["']version["'][ \t\r\n]*:[ \t\r\n]*["'])${escRE(versionOld)}(["'])`)
const pkgDataNew = pkgData.replace(re, `$1${versionNew}$2`)
if (pkgDataNew === pkgData)
throw new Error(`failed to update package configuration from version "${versionOld}" to "${versionNew}"`)
if (!argv.noop)
fs.writeFileSync("package.json", pkgDataNew, { encoding: "utf8" })
/* step 6: commit changes to Git */
let message = argv.message !== "" ? argv.message : `release version ${versionNew}`
message = message.replace(/"/g, "\\\"").replace(/\$/g, "\\$")
await cmd(`git commit -m "${message}" package.json`, argv.noop)
/* step 7: create a Git tag for the new version */
await cmd(`git tag ${versionNew}`, argv.noop)
/* step 8: push changes to upstream repository */
await cmd("git push && git push --tags", argv.noop)
/* step 9: publish new NPM package version */
await cmd(`npm publish --tag=${argv.tag}`, argv.noop)
})().catch((err) => {
/* fatal error */
process.stderr.write(`** ${chalk.red.bold("ERROR:")} ${err.toString()}\n`)
process.exit(1)
})