/
release.ts
635 lines (542 loc) · 18.9 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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
import { AsyncReturnType } from "type-fest";
import on from "await-to-js";
import * as fs from "fs";
import chunk from "lodash.chunk";
import { inc, ReleaseType } from "semver";
import { promisify } from "util";
import { AsyncSeriesBailHook, SyncHook } from "tapable";
import { Memoize as memoize } from "typescript-memoize";
import { ICreateLabelsOptions } from "./auto-args";
import Changelog from "./changelog";
import Git from "./git";
import LogParse, { ICommitAuthor, IExtendedCommit } from "./log-parse";
import SEMVER, {
calculateSemVerBump,
IVersionLabels,
isVersionLabel,
ILabelDefinition,
defaultLabels,
} from "./semver";
import execPromise from "./utils/exec-promise";
import { dummyLog, ILogger } from "./utils/logger";
import { makeReleaseHooks } from "./utils/make-hooks";
import { execSync } from "child_process";
import {
buildSearchQuery,
ISearchResult,
processQueryResult,
ISearchQuery,
} from "./match-sha-to-pr";
import { LoadedAutoRc } from "./types";
/** Construct a map of label => semver label */
export const getVersionMap = (labels = defaultLabels) =>
labels.reduce<IVersionLabels>((semVer, { releaseType: type, name }) => {
if (type && (isVersionLabel(type) || type === "none")) {
const list = semVer.get(type) || [];
semVer.set(type, [...list, name]);
}
return semVer;
}, new Map());
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
export interface IReleaseHooks {
/** This is where you hook into the changelog's hooks. This hook is exposed for convenience on during `this.hooks.onCreateRelease` and at the root `this.hooks` */
onCreateChangelog: SyncHook<[Changelog, SEMVER | undefined]>;
/** Control the titles in the `CHANGELOG.md` */
createChangelogTitle: AsyncSeriesBailHook<[], string | void>;
/** This is where you hook into the LogParse's hooks. This hook is exposed for convenience on during `this.hooks.onCreateRelease` and at the root `this.hooks` */
onCreateLogParse: SyncHook<[LogParse]>;
}
/**
* A class for interacting with the git remote
*/
export default class Release {
/** Plugin entry points */
readonly hooks: IReleaseHooks;
/** Options Release was initialized with */
readonly config: LoadedAutoRc;
/** A class that handles interacting with git and GitHub */
private readonly git: Git;
/** A logger that uses log levels */
private readonly logger: ILogger;
/** The version bump being used during "shipit" */
private readonly versionLabels: IVersionLabels;
/** Initialize the release manager */
constructor(git: Git, config: LoadedAutoRc, logger: ILogger = dummyLog()) {
this.config = config;
this.logger = logger;
this.hooks = makeReleaseHooks();
this.versionLabels = getVersionMap(config.labels);
this.git = git;
}
/** Make the class that will generate changelogs for the project */
@memoize()
async makeChangelog(version?: SEMVER) {
const project = await this.git.getProject();
const changelog = new Changelog(this.logger, {
owner: this.git.options.owner,
repo: this.git.options.repo,
baseUrl: project.html_url,
labels: this.config.labels,
baseBranch: this.config.baseBranch,
prereleaseBranches: this.config.prereleaseBranches,
});
this.hooks.onCreateChangelog.call(changelog, version);
changelog.loadDefaultHooks();
return changelog;
}
/**
* Generate a changelog from a range of commits.
*
* @param from - sha or tag to start changelog from
* @param to - sha or tag to end changelog at (defaults to HEAD)
*/
async generateReleaseNotes(
from: string,
to = "HEAD",
version?: SEMVER
): Promise<string> {
const commits = await this.getCommitsInRelease(from, to);
const changelog = await this.makeChangelog(version);
return changelog.generateReleaseNotes(commits);
}
/** Get all the commits that will be included in a release */
async getCommitsInRelease(from: string, to = "HEAD") {
const allCommits = await this.getCommits(from, to);
const allPrCommits = await Promise.all(
allCommits
.filter((commit) => commit.pullRequest)
.map(async (commit) => {
const [err, commits = []] = await on(
this.git.getCommitsForPR(Number(commit.pullRequest!.number))
);
return err ? [] : commits;
})
);
const allPrCommitHashes = allPrCommits
.filter(Boolean)
.reduce<string[]>(
(all, pr) => [...all, ...pr.map((subCommit) => subCommit.sha)],
[]
);
const uniqueCommits = allCommits.filter(
(commit) =>
(commit.pullRequest || !allPrCommitHashes.includes(commit.hash)) &&
!commit.subject.includes("[skip ci]")
);
const commitsWithoutPR = uniqueCommits.filter(
(commit) => !commit.pullRequest
);
const batches = chunk(commitsWithoutPR, 10);
const queries = await Promise.all(
batches
.map((batch) =>
buildSearchQuery(
this.git.options.owner,
this.git.options.repo,
batch.map((c) => c.hash)
)
)
.filter((q): q is string => Boolean(q))
.map((q) => this.git.graphql<ISearchQuery>(q))
);
const data = queries.filter((q): q is ISearchQuery => Boolean(q));
if (!data.length) {
return uniqueCommits;
}
const commitsInRelease: Array<IExtendedCommit | undefined> = [
...uniqueCommits,
];
const logParse = await this.createLogParse();
type QueryEntry = [string, ISearchResult];
const entries = data.reduce<QueryEntry[]>(
(acc, result) => [...acc, ...Object.entries(result)],
[]
);
await Promise.all(
entries
.filter((result): result is QueryEntry => Boolean(result[1]))
.map(([key, result]) =>
processQueryResult({
sha: key,
result,
commitsWithoutPR,
owner: this.git.options.owner,
prereleaseBranches: this.config.prereleaseBranches,
})
)
.filter((commit): commit is IExtendedCommit => Boolean(commit))
.map(async (commit) => {
const index = commitsInRelease.findIndex(
(c) => c && c.hash === commit.hash
);
commitsInRelease[index] = await logParse.normalizeCommit(commit);
})
);
return commitsInRelease.filter((commit): commit is IExtendedCommit =>
Boolean(commit)
);
}
/** Update a changelog with a new set of release notes */
async updateChangelogFile(
title: string,
releaseNotes: string,
changelogPath: string
) {
const date = new Date().toDateString();
let newChangelog = "#";
if (title) {
newChangelog += ` ${title}`;
}
newChangelog += ` (${date})\n\n${releaseNotes}`;
if (fs.existsSync(changelogPath)) {
this.logger.verbose.info("Old changelog exists, prepending changes.");
const oldChangelog = await readFile(changelogPath, "utf8");
newChangelog = `${newChangelog}\n\n---\n\n${oldChangelog}`;
} else {
newChangelog += "\n";
}
await writeFile(changelogPath, newChangelog);
this.logger.verbose.info("Wrote new changelog to filesystem.");
await execPromise("git", ["add", changelogPath]);
}
/**
* Prepend a set of release notes to the changelog.md
*
* @param releaseNotes - Release notes to prepend to the changelog
* @param lastRelease - Last release version of the code. Could be the first commit SHA
* @param currentVersion - Current version of the code
*/
async addToChangelog(
releaseNotes: string,
lastRelease: string,
currentVersion: string
) {
this.hooks.createChangelogTitle.tapPromise("Default", async () => {
let version;
if (lastRelease.match(/\d+\.\d+\.\d+/)) {
version = await this.calcNextVersion(lastRelease);
} else {
// lastRelease is a git sha. no releases have been made
const bump = await this.getSemverBump(lastRelease);
version = inc(currentVersion, bump as ReleaseType);
}
this.logger.verbose.info("Calculated next version to be:", version);
if (!version) {
return "";
}
return this.config.noVersionPrefix || version.startsWith("v")
? version
: `v${version}`;
});
this.logger.verbose.info("Adding new changes to changelog.");
const title = await this.hooks.createChangelogTitle.promise();
await this.updateChangelogFile(title || "", releaseNotes, "CHANGELOG.md");
}
/**
* Get a range of commits. The commits will have PR numbers and labels attached
*
* @param from - Tag or SHA to start at
* @param to - Tag or SHA to end at (defaults to HEAD)
*/
@memoize()
async getCommits(from: string, to = "HEAD"): Promise<IExtendedCommit[]> {
this.logger.verbose.info(`Getting commits from ${from} to ${to}`);
const gitlog = await this.git.getGitLog(from, to);
this.logger.veryVerbose.info("Got gitlog:\n", gitlog);
const logParse = await this.createLogParse();
const commits = (await logParse.normalizeCommits(gitlog)).filter(
(commit) => {
let released: boolean;
try {
// This determines: Is this commit an ancestor of this commit?
// ↓ ↓
execSync(`git merge-base --is-ancestor ${from} ${commit.hash}`, {
encoding: "utf8",
});
released = false;
} catch (error) {
try {
// --is-ancestor returned false so the commit might be **before** "from"
// so test if it is and do not release this commit again
// This determines: Is this commit an ancestor of this commit?
// ↓ ↓
execSync(`git merge-base --is-ancestor ${commit.hash} ${from}`, {
encoding: "utf8",
});
released = true;
} catch (error) {
// neither commit is a parent of the other so include it
released = false;
}
}
if (released) {
const shortHash = commit.hash.slice(0, 8);
this.logger.verbose.warn(
`Commit already released, omitting: ${shortHash}: "${commit.subject}"`
);
}
return !released;
}
);
this.logger.veryVerbose.info("Added labels to commits:\n", commits);
return commits;
}
/** Go through the configured labels and either add them to the project or update them */
async addLabelsToProject(
labels: ILabelDefinition[],
options: ICreateLabelsOptions = {}
) {
const oldLabels = ((await this.git.getProjectLabels()) || []).map((l) =>
l.toLowerCase()
);
const labelsToCreate = labels.filter((label) => {
if (
label.releaseType === "release" &&
!this.config.onlyPublishWithReleaseLabel
) {
return false;
}
if (
label.releaseType === "skip" &&
this.config.onlyPublishWithReleaseLabel
) {
return false;
}
return true;
});
if (!options.dryRun) {
await Promise.all(
labelsToCreate.map(async (label) => {
if (oldLabels.some((o) => label.name.toLowerCase() === o)) {
return this.git.updateLabel(label);
}
return this.git.createLabel(label);
})
);
}
const repoMetadata = await this.git.getProject();
const justLabelNames = labelsToCreate.reduce<string[]>(
(acc, label) => [...acc, label.name],
[]
);
if (justLabelNames.length > 0) {
const state = options.dryRun ? "Would have created" : "Created";
this.logger.log.log(`${state} labels: ${justLabelNames.join(", ")}`);
} else {
const state = options.dryRun ? "would have been" : "were";
this.logger.log.log(
`No labels ${state} created, they must have already been present on your project.`
);
}
if (options.dryRun) {
return;
}
this.logger.log.log(
`\nYou can see these, and more at ${repoMetadata.html_url}/labels`
);
}
/**
* Calculate the SEMVER bump over a range of commits using the PR labels
*
* @param from - Tag or SHA to start at
* @param to - Tag or SHA to end at (defaults to HEAD)
*/
async getSemverBump(from: string, to = "HEAD"): Promise<SEMVER> {
const commits = await this.getCommits(from, to);
const labels = commits.map((commit) => commit.labels);
const { onlyPublishWithReleaseLabel } = this.config;
const options = { onlyPublishWithReleaseLabel };
this.logger.verbose.info("Calculating SEMVER bump using:\n", {
labels,
versionLabels: this.versionLabels,
options,
});
const result = calculateSemVerBump(labels, this.versionLabels, {
...this.config,
...options,
});
this.logger.verbose.success("Calculated SEMVER bump:", result);
return result;
}
/** Given a tag get the next incremented version */
async calcNextVersion(lastTag: string) {
const bump = await this.getSemverBump(lastTag);
return inc(lastTag, bump as ReleaseType);
}
/** Create the class that will parse the log for PR info */
private async createLogParse() {
const logParse = new LogParse();
logParse.hooks.parseCommit.tapPromise("Author Info", async (commit) =>
this.attachAuthor(commit)
);
logParse.hooks.parseCommit.tapPromise("PR Information", async (commit) =>
this.addPrInfoToCommit(commit)
);
logParse.hooks.parseCommit.tapPromise("PR Commits", async (commit) => {
const prsSinceLastRelease = await this.getPRsSinceLastRelease();
return this.getPRForRebasedCommits(commit, prsSinceLastRelease);
});
this.hooks.onCreateLogParse.call(logParse);
return logParse;
}
/** Get a the PRs that have been merged since the last GitHub release. */
@memoize()
private async getPRsSinceLastRelease() {
let lastRelease: {
/** Date the last release was published */
published_at: string | null;
};
try {
lastRelease = await this.git.getLatestReleaseInfo();
} catch (error) {
const firstCommit = await this.git.getFirstCommit();
lastRelease = {
published_at: await this.git.getCommitDate(firstCommit),
};
}
if (!lastRelease) {
return [];
}
const prsSinceLastRelease = await this.git.searchRepo({
q: `is:pr is:merged merged:>=${lastRelease.published_at}`,
});
if (!prsSinceLastRelease || !prsSinceLastRelease.items) {
return [];
}
const data = await Promise.all(
prsSinceLastRelease.items.map(
async (pr: {
/** The issue number of the pull request */
number: number;
}) => this.git.getPullRequest(Number(pr.number))
)
);
return data.map((item) => item.data);
}
/**
* Add the PR info (labels and body) to the commit
*
* @param commit - Commit to modify
*/
private async addPrInfoToCommit(commit: IExtendedCommit) {
const modifiedCommit = { ...commit };
if (!modifiedCommit.labels) {
modifiedCommit.labels = [];
}
if (modifiedCommit.pullRequest) {
const [err, info] = await on(
this.git.getPr(modifiedCommit.pullRequest.number)
);
if (err || !info || !info.data) {
return modifiedCommit;
}
const labels = info
? info.data.labels
.map((l) => (typeof l === "string" ? l : l.name))
.filter((l): l is string => Boolean(l))
: [];
modifiedCommit.labels = [
...new Set([...labels, ...modifiedCommit.labels]),
];
modifiedCommit.pullRequest.body = info.data.body;
modifiedCommit.subject = info.data.title || modifiedCommit.subject;
const hasPrOpener = modifiedCommit.authors.some(
(author) => author.username === info.data.user?.login
);
// If we can't find the use who opened the PR in authors attempt
// to add that user.
if (!hasPrOpener && info.data.user) {
const user = await this.git.getUserByUsername(info.data.user.login);
if (user) {
modifiedCommit.authors.push({ ...user, username: user.login });
}
}
}
return modifiedCommit;
}
/**
* Commits from rebased PRs do not have messages that tie them to a PR
* Instead we have to find all PRs since the last release and try to match
* their merge commit SHAs.
*/
private getPRForRebasedCommits(
commit: IExtendedCommit,
pullRequests: Array<AsyncReturnType<Git["getPullRequest"]>["data"]>
) {
const matchPr = pullRequests.find(
(pr) => pr.merge_commit_sha === commit.hash
);
if (!commit.pullRequest && matchPr) {
const labels = matchPr.labels
.map((label) => label.name)
.filter((l): l is string => Boolean(l));
commit.labels = [...new Set([...labels, ...commit.labels])];
commit.pullRequest = {
number: matchPr.number,
};
}
return commit;
}
/** Parse the commit for information about the author and any other author that might have helped. */
private async attachAuthor(commit: IExtendedCommit) {
const modifiedCommit = { ...commit };
let resolvedAuthors: Array<
| (ICommitAuthor & {
/** The GitHub user name of the git committer */
login?: string;
})
| Partial<AsyncReturnType<Git["getUserByUsername"]>>
> = [];
// If there is a pull request we will attempt to get the authors
// from any commit in the PR
if (modifiedCommit.pullRequest) {
const [prCommitsErr, prCommits] = await on(
this.git.getCommitsForPR(Number(modifiedCommit.pullRequest.number))
);
if (prCommitsErr || !prCommits) {
return commit;
}
resolvedAuthors = await Promise.all(
prCommits.map(async (prCommit) => {
if (!prCommit.author) {
return prCommit.commit.author || undefined;
}
return {
...prCommit.author,
...(await this.git.getUserByUsername(prCommit.author.login)),
hash: prCommit.sha,
};
})
);
} else {
const [, response] = await on(this.git.getCommit(commit.hash));
if (response?.data?.author?.login) {
const username = response.data.author.login;
const author = await this.git.getUserByUsername(username);
resolvedAuthors.push({
name: commit.authorName,
email: commit.authorEmail,
...author,
hash: commit.hash,
});
} else if (commit.authorEmail) {
resolvedAuthors.push({
email: commit.authorEmail,
name: commit.authorName,
hash: commit.hash,
});
}
}
modifiedCommit.authors = resolvedAuthors.map((author) => ({
...author,
...(author && "login" in author ? { username: author.login } : {}),
}));
modifiedCommit.authors.forEach((author) => {
this.logger.veryVerbose.info(
`Found author: ${author.username} ${author.email} ${author.name}`
);
});
return modifiedCommit;
}
}