-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrelease-specification.ts
455 lines (413 loc) · 16.2 KB
/
release-specification.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import fs, { WriteStream } from 'fs';
import YAML from 'yaml';
import { diff } from 'semver';
import { Editor } from './editor.js';
import { readFile } from './fs.js';
import {
debug,
hasProperty,
wrapError,
isObject,
runCommand,
} from './misc-utils.js';
import { Project } from './project.js';
import { isValidSemver, semver, SemVer } from './semver.js';
/**
* The SemVer-compatible parts of a version string that can be bumped by this
* tool.
*/
export enum IncrementableVersionParts {
major = 'major',
minor = 'minor',
patch = 'patch',
}
/**
* Describes how to update the version for a package, either by bumping a part
* of the version or by setting that version exactly.
*/
type VersionSpecifier = IncrementableVersionParts | SemVer;
/**
* User-provided instructions for how to update this project in order to prepare
* it for a new release.
*
* @property packages - A mapping of package names to version specifiers.
* @property path - The path to the original release specification file.
*/
export type ReleaseSpecification = {
packages: Record<string, VersionSpecifier>;
path: string;
};
const SKIP_PACKAGE_DIRECTIVE = null;
const INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE = 'intentionally-skip';
/**
* Generates a skeleton for a release specification, which describes how a
* project should be updated.
*
* @param args - The set of arguments to this function.
* @param args.project - Information about the project.
* @param args.isEditorAvailable - Whether or not an executable can be found on
* the user's computer to edit the release spec once it is generated.
* @returns The release specification template.
*/
export async function generateReleaseSpecificationTemplateForMonorepo({
project: { workspacePackages },
isEditorAvailable,
}: {
project: Project;
isEditorAvailable: boolean;
}) {
const afterEditingInstructions = isEditorAvailable
? `
# When you're finished, save this file and close it. The tool will update the
# versions of the packages you've listed and will move the changelog entries to
# a new section.`.trim()
: `
# When you're finished, save this file and then run create-release-branch again.
# The tool will update the versions of the packages you've listed and will move
# the changelog entries to a new section.`.trim();
const instructions = `
# This file (called the "release spec") allows you to specify which packages you
# want to include in this release along with the new versions they should
# receive.
#
# By default, all packages which have changed since their latest release are
# listed here. You can choose not to publish a package by removing it from this
# list.
#
# For each package you *do* want to release, you will need to specify how that
# version should be changed depending on the impact of the changes that will go
# into the release. To help you make this decision, all of the changes have been
# automatically added to the changelog for the package. This has been done
# in a new commit, so you can keep this file open, run \`git show\` in the
# terminal, review the set of changes, then return to this file to specify the
# version.
#
# A version specifier (the value that goes after each package in the list below)
# can be one of the following:
#
# - "major" (if you want to bump the major part of the package's version)
# - "minor" (if you want to bump the minor part of the package's version)
# - "patch" (if you want to bump the patch part of the package's version)
# - an exact version with major, minor, and patch parts (e.g. "1.2.3")
#
${afterEditingInstructions}
`.trim();
const changedWorkspacePackages = Object.values(workspacePackages).filter(
(pkg) => pkg.hasChangesSinceLatestRelease,
);
if (changedWorkspacePackages.length === 0) {
throw new Error(
'Could not generate release specification: There are no packages that have changed since their latest release.',
);
}
const packages = changedWorkspacePackages.reduce((obj, pkg) => {
return { ...obj, [pkg.validatedManifest.name]: SKIP_PACKAGE_DIRECTIVE };
}, {});
return [instructions, YAML.stringify({ packages })].join('\n\n');
}
/**
* Launches the given editor to allow the user to update the release spec
* file.
*
* @param releaseSpecificationPath - The path to the release spec file.
* @param editor - Information about the editor.
* @param stdout - A stream that can be used to write to standard out. Defaults
* to /dev/null.
* @returns A promise that resolves when the user has completed editing the
* file, i.e. when the editor process completes.
*/
export async function waitForUserToEditReleaseSpecification(
releaseSpecificationPath: string,
editor: Editor,
stdout: Pick<WriteStream, 'write'> = fs.createWriteStream('/dev/null'),
) {
let caughtError: unknown;
debug(
`Opening release spec file ${releaseSpecificationPath} with editor located at ${editor.path}...`,
);
const promiseForEditorCommand = runCommand(
editor.path,
[...editor.args, releaseSpecificationPath],
{
stdio: 'inherit',
shell: true,
},
);
stdout.write('Waiting for the release spec to be edited...');
try {
await promiseForEditorCommand;
} catch (error) {
caughtError = error;
}
// Clear the previous line
stdout.write('\r\u001B[K');
if (caughtError) {
throw wrapError(
'Encountered an error while waiting for the release spec to be edited.',
caughtError,
);
}
}
/**
* Looks over the release spec that the user has edited to ensure that:
*
* 1. the names of all packages match those within the project; and
* 2. the version specifiers for each package are valid.
*
* @param project - Information about the whole project (e.g., names of packages
* and where they can found).
* @param releaseSpecificationPath - The path to the release spec file.
* @returns The validated release spec.
* @throws If there are any issues with the file.
*/
export async function validateReleaseSpecification(
project: Project,
releaseSpecificationPath: string,
): Promise<ReleaseSpecification> {
const releaseSpecificationContents = await readFile(releaseSpecificationPath);
const indexOfFirstUsableLine = releaseSpecificationContents
.split('\n')
.findIndex((line) => !/^#|[ ]+/u.test(line));
let unvalidatedReleaseSpecification: {
packages: Record<string, string | null>;
};
const afterwordForAllErrorMessages = [
"The release spec file has been retained for you to edit again and make the necessary fixes. Once you've done this, re-run this tool.",
releaseSpecificationPath,
].join('\n\n');
try {
unvalidatedReleaseSpecification = YAML.parse(releaseSpecificationContents);
} catch (error) {
throw wrapError(
[
'Your release spec does not appear to be valid YAML.',
afterwordForAllErrorMessages,
].join('\n\n'),
error,
);
}
if (
!isObject(unvalidatedReleaseSpecification) ||
unvalidatedReleaseSpecification.packages === undefined
) {
const message = [
`Your release spec could not be processed because it needs to be an object with a \`packages\` property. The value of \`packages\` must itself be an object, where each key is a workspace package in the project and each value is a version specifier ("major", "minor", or "patch"; or a version string with major, minor, and patch parts, such as "1.2.3").`,
`Here is the parsed version of the file you provided:`,
JSON.stringify(unvalidatedReleaseSpecification, null, 2),
afterwordForAllErrorMessages,
].join('\n\n');
throw new Error(message);
}
const errors: { message: string | string[]; lineNumber?: number }[] = [];
Object.entries(unvalidatedReleaseSpecification.packages).forEach(
([changedPackageName, versionSpecifierOrDirective], index) => {
const lineNumber = indexOfFirstUsableLine + index + 2;
const changedPackage = project.workspacePackages[changedPackageName];
if (changedPackage === undefined) {
errors.push({
message: `${JSON.stringify(
changedPackageName,
)} is not a package in the project`,
lineNumber,
});
}
if (
versionSpecifierOrDirective !== SKIP_PACKAGE_DIRECTIVE &&
versionSpecifierOrDirective !== INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE &&
!hasProperty(IncrementableVersionParts, versionSpecifierOrDirective) &&
!isValidSemver(versionSpecifierOrDirective)
) {
errors.push({
message: [
`${JSON.stringify(
versionSpecifierOrDirective,
)} is not a valid version specifier for package "${changedPackageName}"`,
`(must be "major", "minor", or "patch"; or a version string with major, minor, and patch parts, such as "1.2.3")`,
],
lineNumber,
});
}
if (isValidSemver(versionSpecifierOrDirective)) {
const comparison = new SemVer(versionSpecifierOrDirective).compare(
changedPackage.validatedManifest.version,
);
if (comparison === 0) {
errors.push({
message: [
`${JSON.stringify(
versionSpecifierOrDirective,
)} is not a valid version specifier for package "${changedPackageName}"`,
`("${changedPackageName}" is already at version "${versionSpecifierOrDirective}")`,
],
lineNumber,
});
} else if (comparison < 0) {
errors.push({
message: [
`${JSON.stringify(
versionSpecifierOrDirective,
)} is not a valid version specifier for package "${changedPackageName}"`,
`("${changedPackageName}" is at a greater version "${project.workspacePackages[changedPackageName].validatedManifest.version}")`,
],
lineNumber,
});
}
}
// Check to compel users to release packages with breaking changes alongside their dependents
if (
versionSpecifierOrDirective === 'major' ||
(isValidSemver(versionSpecifierOrDirective) &&
diff(
changedPackage.validatedManifest.version,
versionSpecifierOrDirective,
) === 'major')
) {
const dependentNames = Object.keys(project.workspacePackages).filter(
(possibleDependentName) => {
const possibleDependent =
project.workspacePackages[possibleDependentName];
const { peerDependencies } = possibleDependent.validatedManifest;
return hasProperty(peerDependencies, changedPackageName);
},
);
const changedDependentNames = dependentNames.filter(
(possibleDependentName) => {
return project.workspacePackages[possibleDependentName]
.hasChangesSinceLatestRelease;
},
);
const missingDependentNames = changedDependentNames.filter(
(dependentName) => {
return !unvalidatedReleaseSpecification.packages[dependentName];
},
);
if (missingDependentNames.length > 0) {
errors.push({
message: [
`The following dependents of package '${changedPackageName}', which is being released with a major version bump, are missing from the release spec.`,
missingDependentNames
.map((dependent) => ` - ${dependent}`)
.join('\n'),
` Consider including them in the release spec so that they are compatible with the new '${changedPackageName}' version.`,
` If you are ABSOLUTELY SURE these packages are safe to omit, however, and want to postpone the release of a package, then list it with a directive of "intentionally-skip". For example:`,
YAML.stringify({
packages: missingDependentNames.reduce((object, dependent) => {
return {
...object,
[dependent]: INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE,
};
}, {}),
})
.trim()
.split('\n')
.map((line) => ` ${line}`)
.join('\n'),
].join('\n\n'),
});
}
}
// Check to compel users to release new versions of dependencies alongside their dependents
if (
changedPackage &&
versionSpecifierOrDirective &&
(hasProperty(IncrementableVersionParts, versionSpecifierOrDirective) ||
isValidSemver(versionSpecifierOrDirective))
) {
const missingDependencies = Object.keys({
...changedPackage.validatedManifest.dependencies,
...changedPackage.validatedManifest.peerDependencies,
}).filter((dependency) => {
return (
project.workspacePackages[dependency]
?.hasChangesSinceLatestRelease &&
!unvalidatedReleaseSpecification.packages[dependency]
);
});
if (missingDependencies.length > 0) {
errors.push({
message: [
`The following packages, which are dependencies or peer dependencies of the package '${changedPackageName}' being released, are missing from the release spec.`,
missingDependencies
.map((dependency) => ` - ${dependency}`)
.join('\n'),
` These packages may have changes that '${changedPackageName}' relies upon. Consider including them in the release spec.`,
` If you are ABSOLUTELY SURE these packages are safe to omit, however, and want to postpone the release of a package, then list it with a directive of "intentionally-skip". For example:`,
YAML.stringify({
packages: missingDependencies.reduce((object, dependency) => {
return {
...object,
[dependency]: INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE,
};
}, {}),
})
.trim()
.split('\n')
.map((line) => ` ${line}`)
.join('\n'),
].join('\n\n'),
});
}
}
},
);
if (errors.length > 0) {
const message = [
'Your release spec could not be processed due to the following issues:',
errors
.flatMap((error) => {
const itemPrefix = '* ';
if (error.lineNumber === undefined) {
return `${itemPrefix}${error.message}`;
}
const lineNumberPrefix = `Line ${error.lineNumber}: `;
if (Array.isArray(error.message)) {
return [
`${itemPrefix}${lineNumberPrefix}${error.message[0]}`,
...error.message.slice(1).map((line) => {
const indentedLineLength =
itemPrefix.length + lineNumberPrefix.length + line.length;
return line.padStart(indentedLineLength, ' ');
}),
];
}
return `${itemPrefix}${lineNumberPrefix}${error.message}`;
})
.join('\n'),
afterwordForAllErrorMessages,
].join('\n\n');
throw new Error(message);
}
const packages = Object.keys(unvalidatedReleaseSpecification.packages).reduce(
(obj, packageName) => {
const versionSpecifierOrDirective =
unvalidatedReleaseSpecification.packages[packageName];
if (
versionSpecifierOrDirective !== SKIP_PACKAGE_DIRECTIVE &&
versionSpecifierOrDirective !== INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE
) {
if (
Object.values(IncrementableVersionParts).includes(
// Typecast: It doesn't matter what type versionSpecifierOrDirective
// is as we are checking for inclusion.
versionSpecifierOrDirective as any,
)
) {
return {
...obj,
// Typecast: We know what this is as we've checked it above.
[packageName]:
versionSpecifierOrDirective as IncrementableVersionParts,
};
}
return {
...obj,
// Typecast: We know that this will safely parse.
[packageName]: semver.parse(versionSpecifierOrDirective) as SemVer,
};
}
return obj;
},
{} as ReleaseSpecification['packages'],
);
return { packages, path: releaseSpecificationPath };
}