/
release.js
executable file
·334 lines (302 loc) · 9.43 KB
/
release.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env node
import { readFile, writeFile } from 'fs/promises';
import { fileURLToPath } from 'node:url';
import { chdir, exit } from 'process';
import GitHub from 'github-api';
import inquirer from 'inquirer';
import semverInc from 'semver/functions/inc.js';
import semverParse from 'semver/functions/parse.js';
import semverPreRelease from 'semver/functions/prerelease.js';
import { cyan, red } from './colors.js';
import { runAndGetStdout, runWithEcho } from './helpers.js';
// We execute everything from the main directory
chdir(fileURLToPath(new URL('..', import.meta.url)));
const MAIN_BRANCH = 'master';
const MAIN_PKG = 'package.json';
const BROWSER_PKG = 'browser/package.json';
const CHANGELOG = 'CHANGELOG.md';
const [gh, currentBranch] = await Promise.all([
getGithubApi(),
runAndGetStdout('git', ['branch', '--show-current']),
runWithEcho('git', ['pull', '--ff-only'])
]);
const [pkg, browserPkg, repo, issues, changelog] = await Promise.all([
readJson(MAIN_PKG),
readJson(BROWSER_PKG),
gh.getRepo('rollup', 'rollup'),
gh.getIssues('rollup', 'rollup'),
readFile(CHANGELOG, 'utf8')
]);
const isMainBranch = currentBranch === MAIN_BRANCH;
const [newVersion, includedPRs] = await Promise.all([
getNewVersion(pkg, isMainBranch),
getIncludedPRs(changelog, repo)
]);
if (isMainBranch) {
await addStubChangelogEntry(newVersion, repo, includedPRs, changelog);
}
await installDependenciesBuildAndTest();
const changelogEntry = isMainBranch ? await waitForChangelogUpdate(newVersion) : '';
await updatePackages(pkg, browserPkg);
const gitTag = `v${newVersion}`;
await commitChanges(newVersion, gitTag);
await releasePackages(newVersion);
await pushChanges(gitTag);
if (changelogEntry) {
await createReleaseNotes(changelogEntry, gitTag);
}
await postReleaseComments(includedPRs, issues, newVersion);
async function getGithubApi() {
const GITHUB_TOKEN = '.github_token';
try {
const token = (await readFile(GITHUB_TOKEN, 'utf8')).trim();
return new GitHub({ token });
} catch (err) {
if (err.code === 'ENOENT') {
console.error(
`Could not find GitHub token file. Please create "${GITHUB_TOKEN}" containing a token with the following permissions:
- public_repo`
);
exit(1);
} else {
throw err;
}
}
}
async function readJson(file) {
const content = await readFile(file, 'utf8');
return JSON.parse(content);
}
async function getNewVersion(pkg, isMainBranch) {
const { version } = pkg;
const availableIncrements = isMainBranch
? ['patch', 'minor']
: semverPreRelease(version)
? ['prerelease']
: ['premajor', 'preminor', 'prepatch'];
const { newVersion } = await inquirer.prompt([
{
choices: availableIncrements.map(increment => {
const value = semverInc(version, increment);
return {
name: `${increment} (${value})`,
short: increment,
value
};
}),
message: `Select type of release (currently "${version}" on branch "${currentBranch}"):`,
name: 'newVersion',
type: 'list'
}
]);
return newVersion;
}
async function addStubChangelogEntry(version, repo, changelog, includedPRs) {
const { currentVersion, index } = getFirstChangelogEntry(changelog);
if (currentVersion === version) {
console.error(
`Changelog entry for version "${version}" already exists. Please remove the entry and commit the change before trying again.`
);
exit(1);
}
await writeFile(
CHANGELOG,
changelog.slice(0, index) +
getNewLogEntry(version, includedPRs) +
'\n\n' +
changelog.slice(index)
);
console.log(
cyan(`A stub for the release notes was added to the beginning of "${CHANGELOG}".
Please edit this file to add useful information about bug fixes, features and
breaking changes in the release while the tests are running.`)
);
}
function getFirstChangelogEntry(changelog) {
const match = changelog.match(
/(?<text>## (?<currentVersion>\d+\.\d+\.\d+)[\s\S]*?)\n+## (?<previousVersion>\d+\.\d+\.\d+)/
);
if (!match) {
throw new Error('Could not detect any changelog entry.');
}
const {
groups: { text, currentVersion, previousVersion },
index
} = match;
return { currentVersion, index, previousVersion, text };
}
async function getIncludedPRs(changelog, repo) {
const { currentVersion } = getFirstChangelogEntry(changelog);
const commits = await runAndGetStdout('git', [
'--no-pager',
'log',
`v${currentVersion}..HEAD`,
'--pretty=tformat:%s'
]);
const getPrRegExp = /^([^(]+)\s\(#(\d+)\)$/gm;
const prs = [];
let match;
while ((match = getPrRegExp.exec(commits))) {
prs.push({ pr: match[2], text: match[1].split('\n')[0] });
}
prs.sort((a, b) => (a.pr > b.pr ? 1 : -1));
return Promise.all(
prs.map(async ({ pr, text }) => {
const { data } = await repo.getPullRequest(pr);
const bodyWithoutComments = data.body.replace(/<!--[\s\S]*?-->/g, '');
const closedIssuesRegexp = /(fix(es|ed)?|(close|resolve)[sd]?) #(\d+)/g;
const closed = [];
while ((match = closedIssuesRegexp.exec(bodyWithoutComments))) {
closed.push(match[4]);
}
return {
author: data.user.login,
closed,
pr,
text
};
})
);
}
function getNewLogEntry(version, prs) {
if (prs.length === 0) {
throw new Error(`Release does not contain any PRs`);
}
const firstPr = prs[0].pr;
const date = new Date().toISOString().slice(0, 10);
const { minor, patch } = semverParse(version);
let sections = getDummyLogSection('Bug Fixes', firstPr);
if (patch === 0) {
sections = getDummyLogSection('Features', firstPr) + sections;
if (minor === 0) {
sections = getDummyLogSection('Breaking Changes', firstPr) + sections;
}
}
return `## ${version}
_${date}_
${sections}### Pull Requests
${prs
.map(
({ text, pr, author }) =>
`- [#${pr}](https://github.com/rollup/rollup/pull/${pr}): ${text} (@${author})`
)
.join('\n')}`;
}
function getDummyLogSection(headline, pr) {
return `### ${headline}
- [replace me] (#${pr})
`;
}
async function installDependenciesBuildAndTest() {
await Promise.all([runWithEcho('npm', ['ci']), runWithEcho('npm', ['audit'])]);
await Promise.all([
runWithEcho('npm', ['run', 'lint:nofix']),
runWithEcho('npm', ['run', 'build:bootstrap'])
]);
await runWithEcho('npm', ['run', 'test:all']);
}
async function waitForChangelogUpdate(version) {
const { changelogUpdated } = await inquirer.prompt([
{
message: `Please confirm that the changelog has been updated to continue`,
name: 'changelogUpdated',
type: 'confirm'
}
]);
if (!changelogUpdated) {
console.log(red`Aborting release.`);
exit();
}
let changelogEntry = '';
while (true) {
await runWithEcho('npx', ['prettier', '--write', CHANGELOG]);
const changelog = await readFile(CHANGELOG, 'utf8');
const { text: newEntry } = getFirstChangelogEntry(changelog);
if (newEntry !== changelogEntry) {
changelogEntry = newEntry;
console.log(cyan('You generated the following changelog entry:\n') + changelogEntry);
const { changelogConfirmed } = await inquirer.prompt([
{
message: `Please edit the changelog again or confirm the changelog is acceptable to continue to release "${version}".`,
name: 'changelogConfirmed',
type: 'confirm'
}
]);
if (!changelogConfirmed) {
console.log(red`Aborting release.`);
exit();
}
continue;
}
break;
}
console.log(cyan('No further changes, continuing release.'));
return changelogEntry;
}
function updatePackages(pkg, browserPkg) {
return Promise.all([
writeFile(MAIN_PKG, getPkgStringWithVersion(pkg, newVersion)),
writeFile(BROWSER_PKG, getPkgStringWithVersion(browserPkg, newVersion))
]);
}
function getPkgStringWithVersion(pkg, version) {
return JSON.stringify({ ...pkg, version }, null, 2) + '\n';
}
async function commitChanges(newVersion, gitTag) {
await runWithEcho('git', ['add', MAIN_PKG, BROWSER_PKG]);
await runWithEcho('git', ['commit', '-m', newVersion]);
await runWithEcho('git', ['tag', gitTag]);
}
function releasePackages(newVersion) {
const releaseEnv = { ...process.env, ROLLUP_RELEASE: 'releasing' };
const releaseTag = semverPreRelease(newVersion) ? ['--tag', 'beta'] : [];
return Promise.all([
runWithEcho('npm', ['publish', ...releaseTag], {
cwd: new URL('..', import.meta.url),
env: releaseEnv
}),
runWithEcho('npm', ['publish', ...releaseTag], {
cwd: new URL('../browser', import.meta.url),
env: releaseEnv
})
]);
}
function pushChanges(gitTag) {
return Promise.all([
runWithEcho('git', ['push', 'origin', 'HEAD']),
runWithEcho('git', ['push', 'origin', gitTag])
]);
}
function createReleaseNotes(changelog, tag) {
return repo.createRelease({
body: changelog,
name: tag,
tag_name: tag
});
}
function postReleaseComments(includedPRs, issues, version) {
const isPreRelease = semverPreRelease(newVersion);
const installNote = isPreRelease
? `Note that this is a pre-release, so to test it, you need to install Rollup via \`npm install rollup@${newVersion}\` or \`npm install rollup@beta\`. It will likely become part of a regular release later.`
: 'You can test it via `npm install rollup`.';
return Promise.all(
includedPRs.map(({ pr, closed }) =>
Promise.all([
issues
.createIssueComment(
pr,
`This PR has been released as part of rollup@${version}. ${installNote}`,
...closed.map(closedPr =>
issues
.createIssueComment(
closedPr,
`This issue has been resolved via #${pr} as part of rollup@${version}. ${installNote}`
)
.then(() => console.log(cyan(`Added fix comment to #${closedPr} via #${pr}.`)))
)
)
.then(() => console.log(cyan(`Added release comment to #${pr}.`)))
])
)
);
}