generated from MetaMask/metamask-module-template
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
cli.ts
398 lines (366 loc) · 11.5 KB
/
cli.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
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
390
391
392
393
394
395
396
397
398
#!/usr/bin/env node
import { promises as fs, constants as fsConstants } from 'fs';
import path from 'path';
// Intentionally shadowing 'URL' global, which is equivalent
// Can't use global directly because of missing type, see:
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34960
// eslint-disable-next-line @typescript-eslint/no-shadow
import { URL } from 'url';
import semver from 'semver';
import yargs from 'yargs/yargs';
import type { Argv } from 'yargs';
import { hideBin } from 'yargs/helpers';
import { updateChangelog } from './update-changelog';
import { generateDiff } from './generate-diff';
import { createEmptyChangelog } from './init';
import { unreleased, Version } from './constants';
import {
ChangelogFormattingError,
InvalidChangelogError,
validateChangelog,
} from './validate-changelog';
import { getRepositoryUrl } from './repo';
const updateEpilog = `New commits will be added to the "${unreleased}" section (or \
to the section for the current release if the '--rc' flag is used) in reverse \
chronological order. Any commits for PRs that are represented already in the \
changelog will be ignored.
If the '--rc' flag is used and the section for the current release does not \
yet exist, it will be created.`;
const validateEpilog = `This does not ensure that the changelog is complete, \
or that each change is in the correct section. It just ensures that the \
formatting is correct. Verification of the contents is left for manual review.`;
// eslint-disable-next-line node/no-process-env
const npmPackageVersion = process.env.npm_package_version;
/**
* Determine whether the given URL is valid.
*
* @param proposedUrl - The URL to validate.
* @returns True if the URL is valid, false otherwise.
*/
function isValidUrl(proposedUrl: string) {
try {
// eslint-disable-next-line no-new
new URL(proposedUrl);
return true;
} catch (error) {
return false;
}
}
/**
* Exit the process with the given error.
*
* @param errorMessage - The error message to exit with.
*/
function exitWithError(errorMessage: string) {
console.error(errorMessage);
process.exitCode = 1;
}
/**
* Read the changelog contents from the filesystem.
*
* @param changelogPath - The path to the changelog file.
* @returns The changelog contents.
*/
async function readChangelog(changelogPath: string) {
return await fs.readFile(changelogPath, {
encoding: 'utf8',
});
}
/**
* Save the changelog to the filesystem.
*
* @param changelogPath - The path to the changelog file.
* @param newChangelogContent - The new changelog contents to save.
*/
async function saveChangelog(
changelogPath: string,
newChangelogContent: string,
) {
await fs.writeFile(changelogPath, newChangelogContent);
}
type UpdateOptions = {
changelogPath: string;
currentVersion?: Version;
repoUrl: string;
isReleaseCandidate: boolean;
projectRootDirectory?: string;
tagPrefix: string;
};
/**
* Update the changelog.
*
* @param options - Update options.
* @param options.changelogPath - The path to the changelog file.
* @param options.currentVersion - The current project version.
* @param options.isReleaseCandidate - Whether the current branch is a release candidate or not.
* @param options.repoUrl - The GitHub repository URL for the current project.
* @param options.projectRootDirectory - The root project directory.
* @param options.tagPrefix - The prefix used in tags before the version number.
*/
async function update({
changelogPath,
currentVersion,
isReleaseCandidate,
repoUrl,
projectRootDirectory,
tagPrefix,
}: UpdateOptions) {
const changelogContent = await readChangelog(changelogPath);
const newChangelogContent = await updateChangelog({
changelogContent,
currentVersion,
repoUrl,
isReleaseCandidate,
projectRootDirectory,
tagPrefixes: [tagPrefix],
});
if (newChangelogContent) {
await saveChangelog(changelogPath, newChangelogContent);
console.log('CHANGELOG.md updated.');
} else {
console.log('There are no new commits to add to the changelog.');
}
}
type ValidateOptions = {
changelogPath: string;
currentVersion?: Version;
isReleaseCandidate: boolean;
repoUrl: string;
tagPrefix: string;
};
/**
* Validate the changelog.
*
* @param options - Validation options.
* @param options.changelogPath - The path to the changelog file.
* @param options.currentVersion - The current project version.
* @param options.isReleaseCandidate - Whether the current branch is a release candidate or not.
* @param options.repoUrl - The GitHub repository URL for the current project.
* @param options.tagPrefix - The prefix used in tags before the version number.
*/
async function validate({
changelogPath,
currentVersion,
isReleaseCandidate,
repoUrl,
tagPrefix,
}: ValidateOptions) {
const changelogContent = await readChangelog(changelogPath);
try {
validateChangelog({
changelogContent,
currentVersion,
repoUrl,
isReleaseCandidate,
tagPrefix,
});
} catch (error) {
if (error instanceof ChangelogFormattingError) {
const { validChangelog, invalidChangelog } = error.data;
const diff = generateDiff(validChangelog, invalidChangelog);
exitWithError(`Changelog not well-formatted. Diff:\n\n${diff}`);
return;
} else if (error instanceof InvalidChangelogError) {
exitWithError(`Changelog is invalid: ${error.message}`);
return;
}
throw error;
}
}
type InitOptions = {
changelogPath: string;
repoUrl: string;
tagPrefix: string;
};
/**
* Create a new empty changelog.
*
* @param options - Initialization options.
* @param options.changelogPath - The path to the changelog file.
* @param options.repoUrl - The GitHub repository URL for the current project.
* @param options.tagPrefix - The prefix used in tags before the version number.
*/
async function init({ changelogPath, repoUrl, tagPrefix }: InitOptions) {
const changelogContent = await createEmptyChangelog({ repoUrl, tagPrefix });
await saveChangelog(changelogPath, changelogContent);
}
const rootDescription = `The root project directory. This determines where we \
look for changes since the last release (defaults to the entire repository at \
the current working directory), and where the changelog path is resolved from \
(defaults to the current working directory).`;
/**
* Configure options that are common to all commands.
*
* @param _yargs - The yargs instance to configure.
* @returns A Yargs instance configured with all common commands.
*/
function configureCommonCommandOptions(_yargs: Argv) {
return _yargs
.option('file', {
default: 'CHANGELOG.md',
description: 'The changelog file path',
type: 'string',
})
.option('repo', {
default: getRepositoryUrl(),
description: `The GitHub repository URL`,
type: 'string',
})
.option('root', {
description: rootDescription,
type: 'string',
})
.option('tagPrefix', {
default: 'v',
description: 'The prefix used in tags before the version number.',
type: 'string',
});
}
/**
* The entrypoint for the auto-changelog CLI.
*/
async function main() {
const { argv } = yargs(hideBin(process.argv))
.command(
'update',
'Update CHANGELOG.md with any changes made since the most recent release.\nUsage: $0 update [options]',
(_yargs) =>
configureCommonCommandOptions(_yargs)
.option('rc', {
default: false,
description: `Add new changes to the current release header, rather than to the '${unreleased}' section.`,
type: 'boolean',
})
.option('currentVersion', {
default: npmPackageVersion,
description:
'The current version of the project that the changelog belongs to.',
type: 'string',
})
.epilog(updateEpilog),
)
.command(
'validate',
'Validate the changelog, ensuring that it is well-formatted.\nUsage: $0 validate [options]',
(_yargs) =>
configureCommonCommandOptions(_yargs)
.option('rc', {
default: false,
description: `Verify that the current version has a release header in the changelog`,
type: 'boolean',
})
.option('currentVersion', {
default: npmPackageVersion,
description:
'The current version of the project that the changelog belongs to.',
type: 'string',
})
.epilog(validateEpilog),
)
.command('init', 'Initialize a new empty changelog', (_yargs) => {
configureCommonCommandOptions(_yargs);
})
.strict()
.demandCommand()
.help('help')
.usage(
`Utilities for validating and updating "Keep a Changelog" formatted changelogs.\nUsage: $0 [command] [options]`,
);
const {
currentVersion,
file: changelogFilename,
rc: isReleaseCandidate,
repo: repoUrl,
root: projectRootDirectory,
tagPrefix,
} = argv;
if (isReleaseCandidate && !currentVersion) {
exitWithError(
`Version not found. Please set the --currentVersion flag, or run this as an npm script from a project with the 'version' field set.`,
);
return;
} else if (currentVersion && semver.valid(currentVersion) === null) {
exitWithError(`Current version is not valid SemVer: '${currentVersion}'`);
return;
} else if (!repoUrl) {
exitWithError(
`npm package repository URL not found. Please set the '--repo' flag, or run this as an npm script from a project with the 'repository' field set.`,
);
return;
} else if (!isValidUrl(repoUrl)) {
exitWithError(`Invalid repo URL: '${repoUrl}'`);
return;
}
if (projectRootDirectory) {
try {
const stat = await fs.stat(projectRootDirectory);
if (!stat.isDirectory()) {
exitWithError(
`Project root must be a directory: '${projectRootDirectory}'`,
);
return;
}
} catch (error) {
if (error.code === 'ENOENT') {
exitWithError(
`Root directory specified does not exist: '${projectRootDirectory}'`,
);
return;
} else if (error.code === 'EACCES') {
exitWithError(
`Access to root directory is forbidden by file access permissions: '${projectRootDirectory}'`,
);
return;
}
throw error;
}
}
let changelogPath = changelogFilename;
if (!path.isAbsolute(changelogFilename) && projectRootDirectory) {
changelogPath = path.resolve(projectRootDirectory, changelogFilename);
}
if (!argv._) {
throw new Error('No command provided');
}
const command = argv._[0];
if (command !== 'init') {
try {
// eslint-disable-next-line no-bitwise
await fs.access(changelogPath, fsConstants.F_OK | fsConstants.W_OK);
} catch (error) {
if (error.code === 'ENOENT') {
exitWithError(`File does not exist: '${changelogPath}'`);
} else {
exitWithError(`File is not writable: '${changelogPath}'`);
}
return;
}
}
if (command === 'update') {
await update({
changelogPath,
currentVersion,
isReleaseCandidate,
repoUrl,
projectRootDirectory,
tagPrefix,
});
} else if (command === 'validate') {
await validate({
changelogPath,
currentVersion,
isReleaseCandidate,
repoUrl,
tagPrefix,
});
} else if (command === 'init') {
await init({
changelogPath,
repoUrl,
tagPrefix,
});
}
}
main().catch((error) => {
exitWithError(error);
});