-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathversioner.ts
More file actions
executable file
·389 lines (318 loc) · 12 KB
/
versioner.ts
File metadata and controls
executable file
·389 lines (318 loc) · 12 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import 'source-map-support';
import { dirname, join, resolve } from 'path';
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { getLog } from '@dot/log';
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 argv = yargs(process.argv.slice(2));
const {
commitScopes = true,
dry: dryRun,
publish: doPublish,
push: doPush,
shortName: shortNameOverride,
tag: doTag
} = argv;
const log = getLog({ brand: '@dot', name: '\u001b[1D/versioner' });
const parserOptions = {
noteKeywords: ['BREAKING CHANGE', 'Breaking Change']
};
const reBreaking = new RegExp(`(${parserOptions.noteKeywords.join(')|(')})`);
const NPM_CLI_SPEC = 'npm@11.5.1';
const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
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) => {
const commitMessage = commitScopes
? `chore(release): ${shortName} v${version}`
: `chore(release): v${version}`;
if (dryRun) {
log.warn(chalk`{yellow Skipping Git Commit}: ${commitMessage}`);
return;
}
log.info(chalk`{blue Committing} CHANGELOG.md, package.json`);
let params = ['add', cwd];
await execa('git', params);
params = ['commit', '--m', commitMessage];
await execa('git', params);
};
const getCommits = async (shortName: string) => {
const tagPattern = commitScopes ? `${shortName}-v*` : 'v*';
log.info(chalk`{blue Gathering Commits for tags:} ${tagPattern}`);
let params = ['tag', '--list', tagPattern, '--sort', '-v:refname'];
const { stdout: tags } = await execa('git', params);
const [latestTag] = tags.split('\n');
log.info(chalk`{blue Last Release Tag}: ${latestTag || '<none>'}`);
params = ['--no-pager', 'log', `${latestTag}..HEAD`, '--format=%B%n-hash-%n%H🐒💨🙊'];
const individuals = `(([\\w-]+,)+)?${shortName}((,[\\w-]+)+)?`;
const scopeExpression = commitScopes ? `\\((${individuals}|\\*)\\)` : '(.+)';
const rePlugin = new RegExp(`^[\\w\\!]+${scopeExpression}`, '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, {
// eslint-disable-next-line no-useless-escape
headerPattern: /^(\w*)(?:\(([\w\$\.\-\*, ]*)\))?\:\s?(.*)$/
});
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.info(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 getRepoUrls = async () => {
try {
const { stdout: remoteUrl } = await execa('git', ['config', '--get', 'remote.origin.url']);
const match = remoteUrl.match(
/(?:https:\/\/github\.com\/|git@github\.com:)(?<owner>[^/]+)\/(?<repo>[^.]+)(?:\.git)?/
);
if (!match?.groups) return null;
const { owner, repo } = match.groups;
return {
commit: `https://github.com/${owner}/${repo}/commit`,
// Note: github has a redirect from /issues to /pull for pull requests
issue: `https://github.com/${owner}/${repo}/issues`
};
} catch (error) {
return null;
}
};
const publish = async (cwd: string) => {
if (dryRun || doPublish === false) {
log.warn(chalk`{yellow Skipping Publish}`);
return;
}
const registryOverrideRaw = argv.registry;
if (argv.registry && typeof argv.registry !== 'string') {
throw new TypeError(
`--registry must be a string (e.g. "${DEFAULT_NPM_REGISTRY}"), received ${typeof registryOverrideRaw}: ${String(
argv.registry
)}`
);
}
const registry = argv.registry || DEFAULT_NPM_REGISTRY;
log.info(chalk`\n{cyan Publishing to NPM}: {grey ${registry}}`);
const packDir = mkdtempSync(join(tmpdir(), 'versioner-pack-'));
try {
await execa('pnpm', ['pack', '--pack-destination', packDir], { cwd, stdio: 'inherit' });
const tarballs = readdirSync(packDir)
.filter((file) => file.endsWith('.tgz'))
.sort();
if (tarballs.length !== 1) {
throw new RangeError(
`Expected exactly 1 packed tarball in: ${packDir} for cwd=${cwd} (found ${
tarballs.length
}): ${tarballs.join(', ')}`
);
}
const tarballPath = join(packDir, tarballs[0]);
const hasOidcEnv =
!!process.env.ACTIONS_ID_TOKEN_REQUEST_URL && !!process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
const provenanceArgs = hasOidcEnv ? ['--provenance'] : [];
log.info(chalk`{grey Using npm CLI:} ${NPM_CLI_SPEC}`);
await execa(
'pnpm',
[
'dlx',
NPM_CLI_SPEC,
'publish',
'--no-git-checks',
'--registry',
registry,
...provenanceArgs,
tarballPath
],
{ cwd, stdio: 'inherit' }
);
} finally {
rmSync(packDir, { force: true, recursive: true });
}
};
const pull = async () => {
if (dryRun || doPush === false) {
log.warn(chalk`{yellow Skipping Git Pull and Rebase}`);
return;
}
log.info(chalk`{blue Pulling Latest Changes from Remote and Rebasing}`);
const { stdout: branches } = await execa('git', ['branch']);
const main = branches.includes('main') ? 'main' : 'master';
await execa('git', ['pull', 'origin', main, '--no-edit']);
await execa('git', ['rebase', '--autostash']);
};
const push = async () => {
if (dryRun || doPush === false) {
log.warn(chalk`{yellow Skipping Git Push}`);
return;
}
const { stdout: branches } = await execa('git', ['branch']);
const main = branches.includes('main') ? 'main' : 'master';
const params = ['push', 'origin', `HEAD:${main}`];
log.info(chalk`{blue Pushing Release and Tags}`);
await execa('git', params);
await execa('git', [...params, '--tags']);
};
const tag = async (cwd: string, shortName: string, version: string) => {
const prefix = commitScopes ? `${shortName}-` : '';
const tagName = `${prefix}v${version}`;
if (dryRun || doTag === false) {
log.warn(chalk`{yellow Skipping Git Tag}: ${tagName}`);
return;
}
log.info(chalk`\n{blue Tagging} {grey ${tagName}}`);
await execa('git', ['tag', tagName], { cwd, stdio: 'inherit' });
};
const updateChangelog = async (
commits: Commit[],
cwd: string,
targetName: string,
shortName: string,
version: string
) => {
log.info(chalk`{blue Gathering Changes}`);
const title = `# ${targetName} 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: [] };
const individuals = `(([\\w-]+,)+)?${shortName}((,[\\w-]+)+)?`;
const reScope = new RegExp(`^[\\w\\!]+\\((${individuals}|\\*)\\)`, 'i');
const reIssue = /\(#\d+\)/;
const repoUrls = await getRepoUrls();
for (const { breaking, hash, header, type } of commits) {
const ref = header?.match(reIssue)?.[0] || `(${hash?.substring(0, 7)})`;
const cleaned = header?.trim().replace(reScope, '$1').replace(ref, '').trim();
const [, hashMark = '', linkRef] = ref.match(/\(([#])?(.+?)\)/)!;
const link = repoUrls
? `([${hashMark}${linkRef}](${
reIssue.test(ref) ? repoUrls.issue : repoUrls.commit
}/${linkRef}))`
: ref;
const message = `${cleaned} ${link}`;
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.info(chalk`{blue New ChangeLog}:\n${newLog}`);
return;
}
log.info(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.warn(chalk`{yellow Skipping package.json Update}`);
return;
}
log.info(chalk`{blue Updating} package.json`);
// eslint-disable-next-line no-param-reassign
pkg.version = version;
await writePackage(cwd, pkg);
};
(async () => {
try {
const cwd = argv.target;
const stripScope: string[] = argv.stripScope?.split(',') || ['^@.+/'];
const { name: targetName }: { name: string } = await import(join(cwd, 'package.json'));
const shortName =
shortNameOverride ||
stripScope.reduce((prev, strip) => prev.replace(new RegExp(strip), ''), targetName);
const parentDirName = dirname(resolve(cwd, '..'));
if (!cwd || !existsSync(cwd)) {
throw new RangeError(`Could not find directory for package: ${targetName} → ${cwd}`);
}
const pkgPath = join(cwd, 'package.json');
const { default: pkg }: RepoPackage = await import(pkgPath);
if (!pkg?.version) {
throw new RangeError(`${pkgPath} doesn't contain a "version" property. please add one.`);
}
if (dryRun) {
log.warn(chalk`{magenta DRY RUN}: No files will be modified`);
}
const from = chalk` from {grey ${parentDirName}/${targetName}}`;
log.info(chalk`{cyan Releasing \`${targetName}\`}${from}\n`);
log.info(chalk`{blue Target Short Name}: ${shortName}`);
if (argv.stripScope)
log.info(chalk`{blue Modifying Target Commit Scope} with: ${stripScope.toString()}`);
const commits = await getCommits(shortName);
if (!commits.length) {
log.info(chalk`\n{red No Commits Found}. Did you mean to publish ${targetName}?`);
return;
}
log.info(chalk`{blue Found} {bold ${commits.length}} Commits\n`);
const newVersion = getNewVersion(pkg.version, commits) as string;
log.info(chalk`{blue New Version}: ${newVersion}\n`);
await updatePackage(cwd, pkg, newVersion);
updateChangelog(commits, cwd, targetName, shortName, newVersion);
await commitChanges(cwd, shortName, newVersion);
// Note: We want to pull here in case there's an error, so nothing gets published
await pull();
await publish(cwd);
await tag(cwd, shortName, newVersion);
await push();
} catch (e) {
log.error(e);
process.exit(1);
}
})();