/
release.ts
265 lines (211 loc) Β· 8.23 KB
/
release.ts
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
import 'source-map-support/register';
import { join } from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import parser from 'conventional-commits-parser';
import chalk from 'chalk';
import execa from 'execa';
import semver from 'semver';
import writePackage from 'write-pkg';
import yargs from 'yargs-parser';
const { log } = console;
const parserOptions = {
noteKeywords: ['BREAKING CHANGE', 'Breaking Change']
};
const reBreaking = new RegExp(`(${parserOptions.noteKeywords.join(')|(')})`);
const dryRun = process.argv.includes('--dry');
const noPublish = process.argv.includes('--no-publish');
const noPush = process.argv.includes('--no-push');
const noTag = process.argv.includes('--no-tag');
type Commit = parser.Commit<string | number | symbol>;
interface BreakingCommit {
breaking: boolean;
}
interface Notes {
breaking: string[];
features: string[];
fixes: string[];
updates: string[];
}
interface RepoPackage {
[key: string]: any;
name: string;
version: string;
}
const commitChanges = async (cwd: string, shortName: string, version: string) => {
if (dryRun) {
log(chalk`{yellow Skipping Git Commit}`);
return;
}
log(chalk`{blue Committing} CHANGELOG.md, package.json`);
let params = ['add', cwd];
await execa('git', params);
params = ['commit', '--m', `chore(release): ${shortName} v${version}`];
await execa('git', params);
};
const getCommits = async (shortName: string, stripScope: string[]) => {
log(chalk`{blue Gathering Commits}`);
let params = ['tag', '--list', `${shortName}-v*`, '--sort', '-v:refname'];
const { stdout: tags } = await execa('git', params);
const [latestTag] = tags.split('\n');
log(chalk`{blue Last Release Tag}: ${latestTag || '<none>'}`);
params = ['--no-pager', 'log', `${latestTag}..HEAD`, '--format=%B%n-hash-%n%Hππ¨π'];
const scope = stripScope.reduce((prev, strip) => prev.replace(strip, ''), shortName);
const rePlugin = new RegExp(`^[\\w\\!]+\\(([\\w,]+)?${scope}([\\w,]+)?\\)`, 'i');
let { stdout } = await execa('git', params);
if (!stdout) {
if (latestTag) params.splice(2, 1, `${latestTag}`);
else params.splice(2, 1, 'HEAD');
({ stdout } = await execa('git', params));
}
const commits = stdout
.split('ππ¨π')
.filter((commit: string) => {
const chunk = commit.trim();
return chunk && rePlugin.test(chunk);
})
.map((commit) => {
const node = parser.sync(commit);
const body = (node.body || node.footer) as string;
((node as unknown) as BreakingCommit).breaking =
reBreaking.test(body) || /!:/.test(node.header as string);
return node;
});
return commits;
};
const getNewVersion = (version: string, commits: Commit[]): string | null => {
log(chalk`{blue Determining New Version}`);
const intersection = process.argv.filter((arg) =>
['--major', '--minor', '--patch'].includes(arg)
);
if (intersection.length) {
// we found an edge case in the typescript-eslint plguin
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return semver.inc(version, intersection[0].substring(2) as semver.ReleaseType);
}
const types = new Set(commits.map(({ type }) => type));
const breaking = commits.some((commit) => !!commit.breaking);
const level = breaking ? 'major' : types.has('feat') || types.has('feature') ? 'minor' : 'patch';
return semver.inc(version, level);
};
const publish = async (cwd: string) => {
if (dryRun || noPublish) {
log(chalk`{yellow Skipping Publish}`);
return;
}
log(chalk`\n{cyan Publishing to NPM}`);
await execa('npm', ['publish', '--no-git-checks'], { cwd, stdio: 'inherit' });
};
const pull = async (main: string) => {
log(chalk`{blue Pulling Latest Changes from Remote and Rebasing}`);
await execa('git', ['checkout', '.npmrc']);
await execa('git', ['pull', 'origin', main, '--no-edit']);
const { stdout } = await execa('git', ['status']);
console.log({ stdout });
await execa('git', ['rebase']);
};
const push = async () => {
if (dryRun || noPush) {
log(chalk`{yellow Skipping Git Push}`);
return;
}
const { stdout: branches } = await execa('git', ['branch']);
const main = branches.includes('main') ? 'main' : 'master';
await pull(main);
const params = ['push', 'origin', `HEAD:${main}`];
log(chalk`{blue Pushing Release and Tags}`);
await execa('git', params);
await execa('git', [...params, '--tags']);
};
const tag = async (cwd: string, shortName: string, version: string) => {
if (dryRun || noTag) {
log(chalk`{yellow Skipping Git Tag}`);
return;
}
const tagName = `${shortName}-v${version}`;
log(chalk`\n{blue Tagging} {grey ${tagName}}`);
await execa('git', ['tag', tagName], { cwd, stdio: 'inherit' });
};
const updateChangelog = (commits: Commit[], cwd: string, shortName: string, version: string) => {
log(chalk`{blue Gathering Changes}`);
const plugin = shortName === 'pluginutils' ? shortName : `plugin-${shortName}`;
const title = `# @rollup/${plugin} ChangeLog`;
const [date] = new Date().toISOString().split('T');
const logPath = join(cwd, 'CHANGELOG.md');
const logFile = existsSync(logPath) ? readFileSync(logPath, 'utf-8') : '';
const oldNotes = logFile.startsWith(title) ? logFile.slice(title.length).trim() : logFile;
const notes: Notes = { breaking: [], features: [], fixes: [], updates: [] };
for (const { breaking, hash, header, type } of commits) {
const ref = /\(#\d+\)/.test(header as string) ? '' : ` (${hash?.substring(0, 7)})`;
const message = header?.trim().replace(/\(.+\)/, '') + ref;
if (breaking) {
notes.breaking.push(message);
} else if (type === 'fix') {
notes.fixes.push(message);
} else if (type === 'feat' || type === 'feature') {
notes.features.push(message);
} else {
notes.updates.push(message);
}
}
const parts = [
`## v${version}`,
`_${date}_`,
notes.breaking.length ? `### Breaking Changes\n\n- ${notes.breaking.join('\n- ')}`.trim() : '',
notes.fixes.length ? `### Bugfixes\n\n- ${notes.fixes.join('\n- ')}`.trim() : '',
notes.features.length ? `### Features\n\n- ${notes.features.join('\n- ')}`.trim() : '',
notes.updates.length ? `### Updates\n\n- ${notes.updates.join('\n- ')}`.trim() : ''
].filter(Boolean);
const newLog = parts.join('\n\n');
if (dryRun) {
log(chalk`{blue New ChangeLog}:\n${newLog}`);
return;
}
log(chalk`{blue Updating} CHANGELOG.md`);
const content = [title, newLog, oldNotes].filter(Boolean).join('\n\n');
writeFileSync(logPath, content, 'utf-8');
};
const updatePackage = async (cwd: string, pkg: RepoPackage, version: string) => {
if (dryRun) {
log(chalk`{yellow Skipping package.json Update}`);
return;
}
log(chalk`{blue Updating} package.json`);
// eslint-disable-next-line no-param-reassign
pkg.version = version;
await writePackage(cwd, pkg);
};
(async () => {
try {
const argv = yargs(process.argv.slice(2));
const packagePath = argv.packagePath || 'packages';
const stripScope = argv.stripScope?.split(',') || [];
const packageName = argv.pkg;
const shortName = packageName.replace(/^@.+\//, '').replace('plugin-', '');
const cwd = join(process.cwd(), `/${packagePath}/`, shortName);
if (!cwd || !existsSync(cwd)) {
throw new RangeError(`Could not find directory for package: ${packageName}`);
}
const { default: pkg }: RepoPackage = await import(join(cwd, 'package.json'));
if (dryRun) {
log(chalk`{magenta DRY RUN}: No files will be modified`);
}
log(chalk`{cyan Releasing \`${packageName}\`} from {grey packages/${shortName}}\n`);
const commits = await getCommits(shortName, stripScope);
if (!commits.length) {
log(chalk`\n{red No Commits Found}. Did you mean to publish ${packageName}?`);
return;
}
log(chalk`{blue Found} {bold ${commits.length}} Commits\n`);
const newVersion = getNewVersion(pkg.version, commits) as string;
log(chalk`{blue New Version}: ${newVersion}\n`);
await updatePackage(cwd, pkg, newVersion);
updateChangelog(commits, cwd, shortName, newVersion);
await commitChanges(cwd, shortName, newVersion);
await publish(cwd);
await tag(cwd, shortName, newVersion);
await push();
} catch (e) {
log(e);
process.exit(1);
}
})();