-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcreateReleasePR.ts
executable file
·432 lines (372 loc) · 11 KB
/
createReleasePR.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
/* eslint-disable no-console */
import chalk from 'chalk';
import dotenv from 'dotenv';
import semver from 'semver';
import generationCommitText from '../ci/codegen/text';
import { getNbGitDiff } from '../ci/utils';
import {
LANGUAGES,
ROOT_ENV_PATH,
run,
MAIN_BRANCH,
OWNER,
REPO,
getOctokit,
ensureGitHubToken,
TODAY,
} from '../common';
import { getPackageVersionDefault } from '../config';
import { RELEASED_TAG } from './common';
import TEXT from './text';
import type {
Versions,
VersionsBeforeBump,
PassedCommit,
Commit,
Scope,
Changelog,
} from './types';
import { updateAPIVersions } from './updateAPIVersions';
dotenv.config({ path: ROOT_ENV_PATH });
export const COMMON_SCOPES = ['specs', 'clients'];
export function readVersions(): VersionsBeforeBump {
return Object.fromEntries(
LANGUAGES.map((lang) => [lang, { current: getPackageVersionDefault(lang) }])
);
}
export function getVersionChangesText(versions: Versions): string {
return LANGUAGES.map((lang) => {
const { current, releaseType, noCommit, skipRelease, next } =
versions[lang];
if (noCommit) {
return `- ~${lang}: ${current} (${TEXT.noCommit})~`;
}
if (!current) {
return `- ~${lang}: (${TEXT.currentVersionNotFound})~`;
}
if (skipRelease) {
return [
`- ~${lang}: ${current} -> **\`${releaseType}\` _(e.g. ${next})_**~`,
TEXT.descriptionForSkippedLang,
].join('\n');
}
return `- ${lang}: ${current} -> **\`${releaseType}\` _(e.g. ${next})_**`;
}).join('\n');
}
export function getSkippedCommitsText({
commitsWithoutLanguageScope,
commitsWithUnknownLanguageScope,
}: {
commitsWithoutLanguageScope: string[];
commitsWithUnknownLanguageScope: string[];
}): string {
if (
commitsWithoutLanguageScope.length === 0 &&
commitsWithUnknownLanguageScope.length === 0
) {
return '_(None)_';
}
// GitHub API restrict the size of a PR body, if we send too many commits
// we might end up with 502 errors when trying to send the pull request
// So we limit the size of the missed commits
return `
<p>${TEXT.skippedCommitsDesc}</p>
<details>
<summary>
<i>Commits without language scope:</i>
</summary>
${commitsWithoutLanguageScope
.slice(0, 15)
.map((commit) => `- ${commit}`)
.join('\n')}
</details>
<details>
<summary>
<i>Commits with unknown language scope:</i>
</summary>
${commitsWithUnknownLanguageScope
.slice(0, 15)
.map((commit) => `- ${commit}`)
.join('\n')}
</details>`;
}
export function parseCommit(commit: string): Commit {
const LENGTH_SHA1 = 8;
const hash = commit.slice(0, LENGTH_SHA1);
let message = commit.slice(LENGTH_SHA1 + 1);
let type = message.slice(0, message.indexOf(':'));
const matchResult = type.match(/(.+)\((.+)\)/);
if (
message
.toLocaleLowerCase()
.startsWith(generationCommitText.commitStartMessage)
) {
return {
error: 'generation-commit',
};
}
if (!matchResult) {
return {
error: 'missing-language-scope',
};
}
message = message.slice(message.indexOf(':') + 1).trim();
type = matchResult[1];
const scope = matchResult[2] as Scope;
// A spec commit should be added to every clients, as it mostly imply a client change.
const allowedScopes = [...LANGUAGES, ...COMMON_SCOPES];
if (!allowedScopes.includes(scope)) {
return { error: 'unknown-language-scope' };
}
return {
hash,
type, // `fix` | `feat` | `chore` | ...
scope, // `clients` | `specs` | `javascript` | `php` | `java` | ...
message,
raw: commit,
};
}
/**
* Returns the next version of the client.
*/
export function getNextVersion(
current: string,
releaseType: semver.ReleaseType | null
): string {
if (releaseType === null) {
return current;
}
let nextVersion: string | null = current;
// snapshots should not be bumped as prerelease
if (!current.endsWith('-SNAPSHOT')) {
nextVersion = semver.inc(current, releaseType);
} else {
nextVersion = `${semver.inc(
current.replace('-SNAPSHOT', ''),
releaseType
)}-SNAPSHOT`;
}
if (!nextVersion) {
throw new Error(
`Unable to bump version: '${current}' with release type: '${releaseType}'`
);
}
console.log(
`Next version is '${nextVersion}', release type: '${releaseType}'`
);
return nextVersion;
}
/* eslint-disable no-param-reassign */
export function decideReleaseStrategy({
versions,
commits,
}: {
versions: VersionsBeforeBump;
commits: PassedCommit[];
}): Versions {
return Object.entries(versions).reduce(
(versionsWithReleaseType: Versions, [lang, version]) => {
const commitsPerLang = commits.filter(
(commit) =>
commit.scope === lang || COMMON_SCOPES.includes(commit.scope)
);
const currentVersion = versions[lang].current;
if (commitsPerLang.length === 0) {
versionsWithReleaseType[lang] = {
...version,
noCommit: true,
releaseType: null,
next: getNextVersion(currentVersion, null),
};
return versionsWithReleaseType;
}
console.log(`Deciding next version bump for ${lang}.`);
// snapshots should not be bumped as prerelease
if (
semver.prerelease(currentVersion) &&
!currentVersion.endsWith('-SNAPSHOT')
) {
// if version is like 0.1.2-beta.1, it increases to 0.1.2-beta.2, even if there's a breaking change.
versionsWithReleaseType[lang] = {
...version,
releaseType: 'prerelease',
next: getNextVersion(currentVersion, 'prerelease'),
};
return versionsWithReleaseType;
}
if (
commitsPerLang.some((commit) =>
commit.message.includes('BREAKING CHANGE')
)
) {
versionsWithReleaseType[lang] = {
...version,
releaseType: 'major',
next: getNextVersion(currentVersion, 'major'),
};
return versionsWithReleaseType;
}
const commitTypes = new Set(commitsPerLang.map(({ type }) => type));
if (commitTypes.has('feat')) {
versionsWithReleaseType[lang] = {
...version,
releaseType: 'minor',
next: getNextVersion(currentVersion, 'minor'),
};
return versionsWithReleaseType;
}
versionsWithReleaseType[lang] = {
...version,
releaseType: 'patch',
...(commitTypes.has('fix') ? undefined : { skipRelease: true }),
next: getNextVersion(currentVersion, 'patch'),
};
return versionsWithReleaseType;
},
{}
);
}
/* eslint-enable no-param-reassign */
/**
* Returns commits separated in categories used to compute the next release version.
*
* Gracefully exits if there is none.
*/
async function getCommits(): Promise<{
validCommits: PassedCommit[];
skippedCommits: string;
}> {
// Reading commits since last release
const latestCommits = (
await run(`git log --oneline --abbrev=8 ${RELEASED_TAG}..${MAIN_BRANCH}`)
)
.split('\n')
.filter(Boolean);
const commitsWithoutLanguageScope: string[] = [];
const commitsWithUnknownLanguageScope: string[] = [];
const validCommits = latestCommits
.map((commitMessage) => {
const commit = parseCommit(commitMessage);
if ('error' in commit) {
// We don't do anything in that case, as we don't really care about
// those commits
if (commit.error === 'generation-commit') {
return undefined;
}
if (commit.error === 'missing-language-scope') {
commitsWithoutLanguageScope.push(commitMessage);
return undefined;
}
if (commit.error === 'unknown-language-scope') {
commitsWithUnknownLanguageScope.push(commitMessage);
return undefined;
}
}
return commit;
})
.filter(Boolean) as PassedCommit[];
if (validCommits.length === 0) {
console.log(
chalk.black.bgYellow('[INFO]'),
`Skipping release because no valid commit has been added since \`released\` tag.`
);
// eslint-disable-next-line no-process-exit
process.exit(0);
}
return {
validCommits,
skippedCommits: getSkippedCommitsText({
commitsWithoutLanguageScope,
commitsWithUnknownLanguageScope,
}),
};
}
async function createReleasePR(): Promise<void> {
ensureGitHubToken();
if (!process.env.LOCAL_TEST_DEV) {
if ((await run('git rev-parse --abbrev-ref HEAD')) !== MAIN_BRANCH) {
throw new Error(
`You can run this script only from \`${MAIN_BRANCH}\` branch.`
);
}
if (
(await getNbGitDiff({
head: null,
})) !== 0
) {
throw new Error(
'Working directory is not clean. Commit all the changes first.'
);
}
}
await run(`git rev-parse --verify refs/tags/${RELEASED_TAG}`, {
errorMessage: '`released` tag is missing in this repository.',
});
console.log('Pulling from origin...');
await run('git fetch origin');
await run('git pull');
// Remove the local tag, and fetch it from the remote.
// We move the `released` tag as we release, so we need to make it up-to-date.
await run(`git tag -d ${RELEASED_TAG}`);
await run(
`git fetch origin refs/tags/${RELEASED_TAG}:refs/tags/${RELEASED_TAG}`
);
console.log('Searching for commits since last release...');
const { validCommits, skippedCommits } = await getCommits();
const versions = decideReleaseStrategy({
versions: readVersions(),
commits: validCommits,
});
const versionChanges = getVersionChangesText(versions);
console.log('Creating changelogs for all languages...');
const changelog: Changelog = LANGUAGES.reduce((newChangelog, lang) => {
if (versions[lang].noCommit) {
return newChangelog;
}
return {
...newChangelog,
[lang]: validCommits
.filter(
(commit) =>
commit.scope === lang || COMMON_SCOPES.includes(commit.scope)
)
.map((commit) => `- ${commit.raw}`)
.join('\n'),
};
}, {} as Changelog);
const headBranch = `chore/prepare-release-${TODAY}`;
console.log('Updating config files...');
await updateAPIVersions(versions, changelog, headBranch);
console.log('Creating pull request...');
const octokit = getOctokit();
const {
data: { number, html_url: url },
} = await octokit.pulls.create({
owner: OWNER,
repo: REPO,
title: generationCommitText.commitPrepareReleaseMessage,
body: [
TEXT.header,
TEXT.summary,
TEXT.versionChangeHeader,
versionChanges,
TEXT.skippedCommitsHeader,
skippedCommits,
].join('\n\n'),
base: 'main',
head: headBranch,
});
console.log('Assigning team members to the PR...');
await octokit.pulls.requestReviewers({
owner: OWNER,
repo: REPO,
pull_number: number,
team_reviewers: ['api-clients-automation'],
});
console.log(`Release PR #${number} is ready for review.`);
console.log(` > ${url}`);
}
// JS version of `if __name__ == '__main__'`
if (require.main === module) {
createReleasePR();
}