UNPKG

36.7 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
14 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
16 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17 return c > 3 && r && Object.defineProperty(target, key, r), r;
18};
19var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
20 return new (P || (P = Promise))(function (resolve, reject) {
21 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
24 step((generator = generator.apply(thisArg, _arguments || [])).next());
25 });
26};
27var __generator = (this && this.__generator) || function (thisArg, body) {
28 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30 function verb(n) { return function (v) { return step([n, v]); }; }
31 function step(op) {
32 if (f) throw new TypeError("Generator is already executing.");
33 while (_) try {
34 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
35 if (y = 0, t) op = [op[0] & 2, t.value];
36 switch (op[0]) {
37 case 0: case 1: t = op; break;
38 case 4: _.label++; return { value: op[1], done: false };
39 case 5: _.label++; y = op[1]; op = [0]; continue;
40 case 7: op = _.ops.pop(); _.trys.pop(); continue;
41 default:
42 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46 if (t[2]) _.ops.pop();
47 _.trys.pop(); continue;
48 }
49 op = body.call(thisArg, _);
50 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52 }
53};
54var __read = (this && this.__read) || function (o, n) {
55 var m = typeof Symbol === "function" && o[Symbol.iterator];
56 if (!m) return o;
57 var i = m.call(o), r, ar = [], e;
58 try {
59 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
60 }
61 catch (error) { e = { error: error }; }
62 finally {
63 try {
64 if (r && !r.done && (m = i["return"])) m.call(i);
65 }
66 finally { if (e) throw e.error; }
67 }
68 return ar;
69};
70var __spread = (this && this.__spread) || function () {
71 for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
72 return ar;
73};
74var __importStar = (this && this.__importStar) || function (mod) {
75 if (mod && mod.__esModule) return mod;
76 var result = {};
77 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
78 result["default"] = mod;
79 return result;
80};
81var __importDefault = (this && this.__importDefault) || function (mod) {
82 return (mod && mod.__esModule) ? mod : { "default": mod };
83};
84Object.defineProperty(exports, "__esModule", { value: true });
85var _a;
86var fs = __importStar(require("fs"));
87var lodash_chunk_1 = __importDefault(require("lodash.chunk"));
88var semver_1 = require("semver");
89var util_1 = require("util");
90var typescript_memoize_1 = require("typescript-memoize");
91var changelog_1 = __importDefault(require("./changelog"));
92var log_parse_1 = __importDefault(require("./log-parse"));
93var semver_2 = __importStar(require("./semver"));
94var exec_promise_1 = __importDefault(require("./utils/exec-promise"));
95var logger_1 = require("./utils/logger");
96var make_hooks_1 = require("./utils/make-hooks");
97var slack_1 = __importDefault(require("./utils/slack"));
98exports.defaultLabels = [
99 semver_2.default.major,
100 semver_2.default.minor,
101 semver_2.default.patch,
102 'skip-release',
103 'release',
104 'prerelease'
105];
106exports.isVersionLabel = function (label) {
107 return exports.defaultLabels.includes(label);
108};
109exports.defaultLabelDefinition = (_a = {},
110 _a[semver_2.default.major] = {
111 name: 'major',
112 title: '💥 Breaking Change',
113 description: 'Increment the major version when merged'
114 },
115 _a[semver_2.default.minor] = {
116 name: 'minor',
117 title: '🚀 Enhancement',
118 description: 'Increment the minor version when merged'
119 },
120 _a[semver_2.default.patch] = {
121 name: 'patch',
122 title: '🐛 Bug Fix',
123 description: 'Increment the patch version when merged'
124 },
125 _a['skip-release'] = {
126 name: 'skip-release',
127 description: 'Preserve the current version when merged'
128 },
129 _a.release = {
130 name: 'release',
131 description: 'Create a release when this pr is merged'
132 },
133 _a.prerelease = {
134 name: 'prerelease',
135 title: '🚧 Prerelease',
136 description: 'Create a pre-release version when merged'
137 },
138 _a.internal = {
139 name: 'internal',
140 title: '🏠 Internal',
141 description: 'Changes only affect the internal API'
142 },
143 _a.documentation = {
144 name: 'documentation',
145 title: '📝 Documentation',
146 description: 'Changes only affect the documentation'
147 },
148 _a);
149exports.getVersionMap = function (labels) {
150 if (labels === void 0) { labels = exports.defaultLabelDefinition; }
151 return Object.entries(labels).reduce(function (semVer, _a) {
152 var _b = __read(_a, 2), label = _b[0], labelDef = _b[1];
153 if (exports.isVersionLabel(label)) {
154 semVer.set(label, labelDef.name);
155 }
156 return semVer;
157 // tslint:disable-next-line align
158 }, new Map());
159};
160var readFile = util_1.promisify(fs.readFile);
161var writeFile = util_1.promisify(fs.writeFile);
162/**
163 * A class for interacting with the git remote
164 */
165var Release = /** @class */ (function () {
166 function Release(git, options, logger) {
167 if (options === void 0) { options = {
168 baseBranch: 'master',
169 skipReleaseLabels: [],
170 labels: exports.defaultLabelDefinition
171 }; }
172 if (logger === void 0) { logger = logger_1.dummyLog(); }
173 this.options = options;
174 this.logger = logger;
175 this.hooks = make_hooks_1.makeReleaseHooks();
176 this.versionLabels = exports.getVersionMap(options.labels);
177 this.git = git;
178 }
179 /**
180 * Generate a changelog from a range of commits.
181 *
182 * @param from sha or tag to start changelog from
183 * @param to sha or tag to end changelog at (defaults to HEAD)
184 */
185 Release.prototype.generateReleaseNotes = function (from, to) {
186 if (to === void 0) { to = 'HEAD'; }
187 return __awaiter(this, void 0, void 0, function () {
188 var commits, project, changelog;
189 return __generator(this, function (_a) {
190 switch (_a.label) {
191 case 0: return [4 /*yield*/, this.getCommitsInRelease(from, to)];
192 case 1:
193 commits = _a.sent();
194 return [4 /*yield*/, this.git.getProject()];
195 case 2:
196 project = _a.sent();
197 changelog = new changelog_1.default(this.logger, {
198 owner: this.git.options.owner,
199 repo: this.git.options.repo,
200 baseUrl: project.html_url,
201 jira: this.options.jira,
202 labels: this.options.labels,
203 baseBranch: this.options.baseBranch
204 });
205 this.hooks.onCreateChangelog.call(changelog);
206 changelog.loadDefaultHooks();
207 return [2 /*return*/, changelog.generateReleaseNotes(commits)];
208 }
209 });
210 });
211 };
212 Release.prototype.buildSearchQuery = function (commits) {
213 var repo = this.git.options.owner + "/" + this.git.options.repo;
214 var query = commits.reduce(function (q, commit) {
215 var subQuery = "repo:" + repo + " " + commit.hash;
216 return "\n " + q + "\n\n hash_" + commit.hash + ": search(query: \"" + subQuery + "\", type: ISSUE, first: 1) {\n edges {\n node {\n ... on PullRequest {\n number\n state\n labels(first: 10) {\n edges {\n node {\n name\n }\n }\n }\n }\n }\n }\n }\n ";
217 }, '');
218 if (!query) {
219 return;
220 }
221 return "{\n " + query + "\n rateLimit {\n limit\n cost\n remaining\n resetAt\n }\n }";
222 };
223 Release.prototype.getCommitsInRelease = function (from, to) {
224 if (to === void 0) { to = 'HEAD'; }
225 return __awaiter(this, void 0, void 0, function () {
226 var allCommits, allPrCommits, allPrCommitHashes, labelled, commitsWithoutPR, batches, queries, data;
227 var _this = this;
228 return __generator(this, function (_a) {
229 switch (_a.label) {
230 case 0: return [4 /*yield*/, this.getCommits(from, to)];
231 case 1:
232 allCommits = _a.sent();
233 return [4 /*yield*/, Promise.all(allCommits
234 .filter(function (commit) { return commit.pullRequest; })
235 .map(function (commit) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
236 return [2 /*return*/, this.git.getCommitsForPR(Number(commit.pullRequest.number))];
237 }); }); }))];
238 case 2:
239 allPrCommits = _a.sent();
240 allPrCommitHashes = allPrCommits
241 .filter(Boolean)
242 .reduce(function (all, pr) { return __spread(all, pr.map(function (subCommit) { return subCommit.sha; })); }, []);
243 labelled = allCommits.filter(function (commit) {
244 return (commit.pullRequest || !allPrCommitHashes.includes(commit.hash)) &&
245 !commit.subject.includes('[skip ci]');
246 });
247 commitsWithoutPR = labelled.filter(function (commit) { return !commit.pullRequest; });
248 batches = lodash_chunk_1.default(commitsWithoutPR, 10);
249 return [4 /*yield*/, Promise.all(batches.map(function (batch) {
250 var batchQuery = _this.buildSearchQuery(batch);
251 if (!batchQuery) {
252 return;
253 }
254 return _this.git.graphql(batchQuery);
255 }))];
256 case 3:
257 queries = _a.sent();
258 data = queries.filter(function (q) { return Boolean(q); });
259 if (!data.length) {
260 return [2 /*return*/, labelled];
261 }
262 data.map(function (results) {
263 Object.entries(results).map(function (_a) {
264 var _b = __read(_a, 2), key = _b[0], result = _b[1];
265 var hash = key.split('hash_')[1];
266 var commit = commitsWithoutPR.find(function (commitWithoutPR) { return commitWithoutPR.hash === hash; });
267 if (!commit) {
268 return;
269 }
270 if (result.edges.length > 0) {
271 var labels = result.edges[0].node.labels
272 ? result.edges[0].node.labels.edges.map(function (edge) { return edge.node; })
273 : [];
274 commit.labels = __spread(labels.map(function (label) { return label.name; }), commit.labels);
275 }
276 else {
277 commit.labels = __spread(['pushToBaseBranch'], commit.labels);
278 }
279 commit.subject = commit.subject.split('\n')[0];
280 });
281 });
282 return [2 /*return*/, labelled];
283 }
284 });
285 });
286 };
287 /**
288 * Prepend a set of release notes to the changelog.md
289 *
290 * @param releaseNotes Release notes to prepend to the changelog
291 * @param lastRelease Last release version of the code. Could be the first commit SHA
292 * @param currentVersion Current version of the code
293 * @param message Message to commit the changelog with
294 */
295 Release.prototype.addToChangelog = function (releaseNotes, lastRelease, currentVersion, message) {
296 if (message === void 0) { message = 'Update CHANGELOG.md [skip ci]'; }
297 return __awaiter(this, void 0, void 0, function () {
298 var title, date, newChangelog, oldChangelog;
299 var _this = this;
300 return __generator(this, function (_a) {
301 switch (_a.label) {
302 case 0:
303 this.hooks.createChangelogTitle.tapPromise('Default', function () { return __awaiter(_this, void 0, void 0, function () {
304 var version, bump;
305 return __generator(this, function (_a) {
306 switch (_a.label) {
307 case 0:
308 if (!lastRelease.match(/\d+\.\d+\.\d+/)) return [3 /*break*/, 2];
309 return [4 /*yield*/, this.calcNextVersion(lastRelease)];
310 case 1:
311 version = _a.sent();
312 return [3 /*break*/, 4];
313 case 2: return [4 /*yield*/, this.getSemverBump(lastRelease)];
314 case 3:
315 bump = _a.sent();
316 version = semver_1.inc(currentVersion, bump);
317 _a.label = 4;
318 case 4:
319 this.logger.verbose.info('Calculated next version to be:', version);
320 if (!version) {
321 return [2 /*return*/, ''];
322 }
323 return [2 /*return*/, this.options.noVersionPrefix || version.startsWith('v')
324 ? version
325 : "v" + version];
326 }
327 });
328 }); });
329 this.logger.verbose.info('Adding new changes to changelog.');
330 return [4 /*yield*/, this.hooks.createChangelogTitle.promise()];
331 case 1:
332 title = _a.sent();
333 date = new Date().toDateString();
334 newChangelog = '#';
335 if (title) {
336 newChangelog += " " + title;
337 }
338 newChangelog += " (" + date + ")\n\n" + releaseNotes;
339 if (!fs.existsSync('CHANGELOG.md')) return [3 /*break*/, 3];
340 this.logger.verbose.info('Old changelog exists, prepending changes.');
341 return [4 /*yield*/, readFile('CHANGELOG.md', 'utf8')];
342 case 2:
343 oldChangelog = _a.sent();
344 newChangelog = newChangelog + "\n\n---\n\n" + oldChangelog;
345 _a.label = 3;
346 case 3: return [4 /*yield*/, writeFile('CHANGELOG.md', newChangelog)];
347 case 4:
348 _a.sent();
349 this.logger.verbose.info('Wrote new changelog to filesystem.');
350 return [4 /*yield*/, exec_promise_1.default('git', ['add', 'CHANGELOG.md'])];
351 case 5:
352 _a.sent();
353 return [4 /*yield*/, exec_promise_1.default('git', ['commit', '-m', "\"" + message + "\"", '--no-verify'])];
354 case 6:
355 _a.sent();
356 this.logger.verbose.info('Commited new changelog.');
357 return [2 /*return*/];
358 }
359 });
360 });
361 };
362 /**
363 * Get a range of commits. The commits will have PR numbers and labels attached
364 *
365 * @param from Tag or SHA to start at
366 * @param to Tage or SHA to end at (defaults to HEAD)
367 */
368 Release.prototype.getCommits = function (from, to) {
369 if (to === void 0) { to = 'HEAD'; }
370 return __awaiter(this, void 0, void 0, function () {
371 var gitlog, logParse, commits;
372 var _this = this;
373 return __generator(this, function (_a) {
374 switch (_a.label) {
375 case 0:
376 this.logger.verbose.info("Getting commits from " + from + " to " + to);
377 return [4 /*yield*/, this.git.getGitLog(from, to)];
378 case 1:
379 gitlog = _a.sent();
380 this.logger.veryVerbose.info('Got gitlog:\n', gitlog);
381 return [4 /*yield*/, this.createLogParse()];
382 case 2:
383 logParse = _a.sent();
384 return [4 /*yield*/, logParse.normalizeCommits(gitlog)];
385 case 3:
386 commits = _a.sent();
387 this.logger.veryVerbose.info('Added labels to commits:\n', commits);
388 return [4 /*yield*/, Promise.all(commits.map(function (commit) { return __awaiter(_this, void 0, void 0, function () {
389 var resolvedAuthors, prCommits, author;
390 var _this = this;
391 return __generator(this, function (_a) {
392 switch (_a.label) {
393 case 0:
394 resolvedAuthors = [];
395 if (!commit.pullRequest) return [3 /*break*/, 3];
396 return [4 /*yield*/, this.git.getCommitsForPR(Number(commit.pullRequest.number))];
397 case 1:
398 prCommits = _a.sent();
399 if (!prCommits) {
400 return [2 /*return*/];
401 }
402 return [4 /*yield*/, Promise.all(prCommits.map(function (prCommit) { return __awaiter(_this, void 0, void 0, function () {
403 return __generator(this, function (_a) {
404 if (prCommit && prCommit.author) {
405 return [2 /*return*/, this.git.getUserByUsername(prCommit.author.login)];
406 }
407 return [2 /*return*/];
408 });
409 }); }))];
410 case 2:
411 resolvedAuthors = _a.sent();
412 return [3 /*break*/, 5];
413 case 3:
414 if (!commit.authorEmail) return [3 /*break*/, 5];
415 return [4 /*yield*/, this.git.getUserByEmail(commit.authorEmail)];
416 case 4:
417 author = _a.sent();
418 resolvedAuthors.push(author);
419 _a.label = 5;
420 case 5:
421 commit.authors = resolvedAuthors.map(function (author) { return (__assign({}, author, { username: author ? author.login : undefined })); });
422 commit.authors.map(function (author) {
423 _this.logger.veryVerbose.info("Found author: " + author.username);
424 });
425 return [2 /*return*/];
426 }
427 });
428 }); }))];
429 case 4:
430 _a.sent();
431 return [2 /*return*/, commits];
432 }
433 });
434 });
435 };
436 Release.prototype.addLabelsToProject = function (labels, options) {
437 if (options === void 0) { options = {}; }
438 return __awaiter(this, void 0, void 0, function () {
439 var oldLabels, labelsToCreate, repoMetadata, justLabelNames, state, state;
440 var _this = this;
441 return __generator(this, function (_a) {
442 switch (_a.label) {
443 case 0: return [4 /*yield*/, this.git.getProjectLabels()];
444 case 1:
445 oldLabels = _a.sent();
446 labelsToCreate = Object.entries(labels).filter(function (_a) {
447 var _b = __read(_a, 2), versionLabel = _b[0], labelDef = _b[1];
448 if (!labelDef) {
449 return;
450 }
451 if (versionLabel === 'release' &&
452 !_this.options.onlyPublishWithReleaseLabel) {
453 return;
454 }
455 if (versionLabel === 'skip-release' &&
456 _this.options.onlyPublishWithReleaseLabel) {
457 return;
458 }
459 return true;
460 });
461 if (!!options.dryRun) return [3 /*break*/, 3];
462 return [4 /*yield*/, Promise.all(labelsToCreate.map(function (_a) {
463 var _b = __read(_a, 2), label = _b[0], labelDef = _b[1];
464 return __awaiter(_this, void 0, void 0, function () {
465 return __generator(this, function (_c) {
466 switch (_c.label) {
467 case 0:
468 if (!labelDef) {
469 return [2 /*return*/];
470 }
471 if (!(oldLabels && oldLabels.includes(labelDef.name))) return [3 /*break*/, 2];
472 return [4 /*yield*/, this.git.updateLabel(label, labelDef)];
473 case 1:
474 _c.sent();
475 return [3 /*break*/, 4];
476 case 2: return [4 /*yield*/, this.git.createLabel(label, labelDef)];
477 case 3:
478 _c.sent();
479 _c.label = 4;
480 case 4: return [2 /*return*/];
481 }
482 });
483 });
484 }))];
485 case 2:
486 _a.sent();
487 _a.label = 3;
488 case 3: return [4 /*yield*/, this.git.getProject()];
489 case 4:
490 repoMetadata = _a.sent();
491 justLabelNames = labelsToCreate.map(function (_a) {
492 var _b = __read(_a, 1), name = _b[0];
493 return name;
494 });
495 if (justLabelNames.length > 0) {
496 state = options.dryRun ? 'Would have created' : 'Created';
497 this.logger.log.log(state + " labels: " + justLabelNames.join(', '));
498 }
499 else {
500 state = options.dryRun ? 'would have been' : 'were';
501 this.logger.log.log("No labels " + state + " created, they must have already been present on your project.");
502 }
503 if (options.dryRun) {
504 return [2 /*return*/];
505 }
506 this.logger.log.log("\nYou can see these, and more at " + repoMetadata.html_url + "/labels");
507 return [2 /*return*/];
508 }
509 });
510 });
511 };
512 /**
513 * Calculate the SEMVER bump over a range of commits using the PR labels
514 *
515 * @param from Tag or SHA to start at
516 * @param to Tage or SHA to end at (defaults to HEAD)
517 */
518 Release.prototype.getSemverBump = function (from, to) {
519 if (to === void 0) { to = 'HEAD'; }
520 return __awaiter(this, void 0, void 0, function () {
521 var commits, labels, _a, onlyPublishWithReleaseLabel, skipReleaseLabels, options, result;
522 return __generator(this, function (_b) {
523 switch (_b.label) {
524 case 0: return [4 /*yield*/, this.getCommits(from, to)];
525 case 1:
526 commits = _b.sent();
527 labels = commits.map(function (commit) { return commit.labels; });
528 _a = this.options, onlyPublishWithReleaseLabel = _a.onlyPublishWithReleaseLabel, skipReleaseLabels = _a.skipReleaseLabels;
529 options = { onlyPublishWithReleaseLabel: onlyPublishWithReleaseLabel, skipReleaseLabels: skipReleaseLabels };
530 this.logger.verbose.info('Calculating SEMVER bump using:\n', {
531 labels: labels,
532 versionLabels: this.versionLabels,
533 options: options
534 });
535 result = semver_2.calculateSemVerBump(labels, this.versionLabels, options);
536 this.logger.verbose.success('Calculated SEMVER bump:', result);
537 return [2 /*return*/, result];
538 }
539 });
540 });
541 };
542 /**
543 * Post the release notes to slack.
544 *
545 * @param releaseNotes Release notes to post to slack
546 * @param tag Version to include in the title of the slack message
547 */
548 Release.prototype.postToSlack = function (releaseNotes, tag) {
549 return __awaiter(this, void 0, void 0, function () {
550 var project;
551 return __generator(this, function (_a) {
552 switch (_a.label) {
553 case 0:
554 if (!this.options.slack) {
555 throw new Error('Slack url must be set to post a message to slack.');
556 }
557 return [4 /*yield*/, this.git.getProject()];
558 case 1:
559 project = _a.sent();
560 this.logger.verbose.info('Posting release notes to slack.');
561 return [4 /*yield*/, slack_1.default(releaseNotes, {
562 tag: tag,
563 owner: this.git.options.owner,
564 repo: this.git.options.repo,
565 baseUrl: project.html_url,
566 slackUrl: this.options.slack
567 })];
568 case 2:
569 _a.sent();
570 this.logger.verbose.info('Posted release notes to slack.');
571 return [2 /*return*/];
572 }
573 });
574 });
575 };
576 Release.prototype.calcNextVersion = function (lastTag) {
577 return __awaiter(this, void 0, void 0, function () {
578 var bump;
579 return __generator(this, function (_a) {
580 switch (_a.label) {
581 case 0: return [4 /*yield*/, this.getSemverBump(lastTag)];
582 case 1:
583 bump = _a.sent();
584 return [2 /*return*/, semver_1.inc(lastTag, bump)];
585 }
586 });
587 });
588 };
589 Release.prototype.createLogParse = function () {
590 return __awaiter(this, void 0, void 0, function () {
591 var logParse;
592 var _this = this;
593 return __generator(this, function (_a) {
594 logParse = new log_parse_1.default();
595 logParse.hooks.parseCommit.tapPromise('Labels', function (commit) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
596 return [2 /*return*/, this.addLabelsToCommit(commit)];
597 }); }); });
598 logParse.hooks.parseCommit.tapPromise('PR Commits', function (commit) { return __awaiter(_this, void 0, void 0, function () {
599 var prsSinceLastRelease;
600 return __generator(this, function (_a) {
601 switch (_a.label) {
602 case 0: return [4 /*yield*/, this.getPRsSinceLastRelease()];
603 case 1:
604 prsSinceLastRelease = _a.sent();
605 return [2 /*return*/, this.getPRForRebasedCommits(commit, prsSinceLastRelease)];
606 }
607 });
608 }); });
609 this.hooks.onCreateLogParse.call(logParse);
610 return [2 /*return*/, logParse];
611 });
612 });
613 };
614 Release.prototype.getPRsSinceLastRelease = function () {
615 return __awaiter(this, void 0, void 0, function () {
616 var lastRelease, error_1, firstCommit, _a, prsSinceLastRelease, data;
617 var _this = this;
618 return __generator(this, function (_b) {
619 switch (_b.label) {
620 case 0:
621 _b.trys.push([0, 2, , 5]);
622 return [4 /*yield*/, this.git.getLatestReleaseInfo()];
623 case 1:
624 lastRelease = _b.sent();
625 return [3 /*break*/, 5];
626 case 2:
627 error_1 = _b.sent();
628 return [4 /*yield*/, this.git.getFirstCommit()];
629 case 3:
630 firstCommit = _b.sent();
631 _a = {};
632 return [4 /*yield*/, this.git.getCommitDate(firstCommit)];
633 case 4:
634 lastRelease = (_a.published_at = _b.sent(),
635 _a);
636 return [3 /*break*/, 5];
637 case 5:
638 if (!lastRelease) {
639 return [2 /*return*/, []];
640 }
641 return [4 /*yield*/, this.git.searchRepo({
642 q: "is:pr is:merged merged:>=" + lastRelease.published_at
643 })];
644 case 6:
645 prsSinceLastRelease = _b.sent();
646 if (!prsSinceLastRelease || !prsSinceLastRelease.items) {
647 return [2 /*return*/, []];
648 }
649 return [4 /*yield*/, Promise.all(prsSinceLastRelease.items.map(function (pr) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
650 return [2 /*return*/, this.git.getPullRequest(Number(pr.number))];
651 }); }); }))];
652 case 7:
653 data = _b.sent();
654 return [2 /*return*/, data.map(function (item) { return item.data; })];
655 }
656 });
657 });
658 };
659 /**
660 * Add the PR labels to the commit
661 *
662 * @param commits Commits to modify
663 */
664 Release.prototype.addLabelsToCommit = function (commit) {
665 return __awaiter(this, void 0, void 0, function () {
666 var labels;
667 return __generator(this, function (_a) {
668 switch (_a.label) {
669 case 0:
670 if (!commit.labels) {
671 commit.labels = [];
672 }
673 if (!commit.pullRequest) return [3 /*break*/, 2];
674 return [4 /*yield*/, this.git.getLabels(commit.pullRequest.number)];
675 case 1:
676 labels = (_a.sent()) || [];
677 commit.labels = __spread(labels, commit.labels);
678 _a.label = 2;
679 case 2: return [2 /*return*/, commit];
680 }
681 });
682 });
683 };
684 /**
685 * Commits from rebased PRs do not have messages that tie them to a PR
686 * Instead we have to find all PRs since the last release and try to match
687 * their merge commit SHAs.
688 *
689 * @param commits Commits to modify
690 */
691 Release.prototype.getPRForRebasedCommits = function (commit, pullRequests) {
692 var matchPr = pullRequests.find(function (pr) { return pr.merge_commit_sha === commit.hash; });
693 if (!commit.pullRequest && matchPr) {
694 var labels = matchPr.labels.map(function (label) { return label.name; }) || [];
695 commit.labels = __spread(labels, commit.labels);
696 commit.pullRequest = {
697 number: matchPr.number
698 };
699 }
700 return commit;
701 };
702 __decorate([
703 typescript_memoize_1.Memoize()
704 ], Release.prototype, "createLogParse", null);
705 __decorate([
706 typescript_memoize_1.Memoize()
707 ], Release.prototype, "getPRsSinceLastRelease", null);
708 return Release;
709}());
710exports.default = Release;
711//# sourceMappingURL=release.js.map
\No newline at end of file