This repository has been archived by the owner on May 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
main.ts
326 lines (284 loc) · 10.4 KB
/
main.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
import * as core from '@actions/core';
import * as github from '@actions/github';
import {Context} from '@actions/github/lib/context';
import * as Octokit from '@octokit/rest';
import {sync as commitParser} from 'conventional-commits-parser';
import {getChangelogOptions, dumpGitHubEventPayload} from './utils';
import {isBreakingChange, generateChangelogFromParsedCommits, parseGitTag, ParsedCommits, octokitLogger} from './utils';
import semverValid from 'semver/functions/valid';
import semverRcompare from 'semver/functions/rcompare';
import semverLt from 'semver/functions/lt';
import {uploadReleaseArtifacts} from './uploadReleaseArtifacts';
type Args = {
repoToken: string;
automaticReleaseTag: string;
draftRelease: boolean;
preRelease: boolean;
releaseTitle: string;
files: string[];
};
const getAndValidateArgs = (): Args => {
const args = {
repoToken: core.getInput('repo_token', {required: true}),
automaticReleaseTag: core.getInput('automatic_release_tag', {
required: false,
}),
draftRelease: JSON.parse(core.getInput('draft', {required: true})),
preRelease: JSON.parse(core.getInput('prerelease', {required: true})),
releaseTitle: core.getInput('title', {required: false}),
files: [] as string[],
};
const inputFilesStr = core.getInput('files', {required: false});
if (inputFilesStr) {
args.files = inputFilesStr.split(/\r?\n/);
}
return args;
};
const createReleaseTag = async (client: github.GitHub, refInfo: Octokit.GitCreateRefParams) => {
core.startGroup('Generating release tag');
const friendlyTagName = refInfo.ref.substring(10); // 'refs/tags/latest' => 'latest'
core.info(`Attempting to create or update release tag "${friendlyTagName}"`);
try {
await client.git.createRef(refInfo);
} catch (err: any) {
const existingTag = refInfo.ref.substring(5); // 'refs/tags/latest' => 'tags/latest'
core.info(
`Could not create new tag "${refInfo.ref}" (${err.message}) therefore updating existing tag "${existingTag}"`,
);
await client.git.updateRef({
...refInfo,
ref: existingTag,
force: true,
});
}
core.info(`Successfully created or updated the release tag "${friendlyTagName}"`);
core.endGroup();
};
const deletePreviousGitHubRelease = async (client: github.GitHub, releaseInfo: Octokit.ReposGetReleaseByTagParams) => {
core.startGroup(`Deleting GitHub releases associated with the tag "${releaseInfo.tag}"`);
try {
core.info(`Searching for releases corresponding to the "${releaseInfo.tag}" tag`);
const resp = await client.repos.getReleaseByTag(releaseInfo);
core.info(`Deleting release: ${resp.data.id}`);
await client.repos.deleteRelease({
owner: releaseInfo.owner,
repo: releaseInfo.repo,
release_id: resp.data.id,
});
} catch (err: any) {
core.info(`Could not find release associated with tag "${releaseInfo.tag}" (${err.message})`);
}
core.endGroup();
};
const generateNewGitHubRelease = async (
client: github.GitHub,
releaseInfo: Octokit.ReposCreateReleaseParams,
): Promise<string> => {
core.startGroup(`Generating new GitHub release for the "${releaseInfo.tag_name}" tag`);
core.info('Creating new release');
const resp = await client.repos.createRelease(releaseInfo);
core.endGroup();
return resp.data.upload_url;
};
const searchForPreviousReleaseTag = async (
client: github.GitHub,
currentReleaseTag: string,
tagInfo: Octokit.ReposListTagsParams,
): Promise<string> => {
const validSemver = semverValid(currentReleaseTag);
if (!validSemver) {
throw new Error(
`The parameter "automatic_release_tag" was not set and the current tag "${currentReleaseTag}" does not appear to conform to semantic versioning.`,
);
}
const listTagsOptions = client.repos.listTags.endpoint.merge(tagInfo);
const tl = await client.paginate(listTagsOptions);
const tagList = tl
.map((tag) => {
core.debug(`Currently processing tag ${tag.name}`);
const t = semverValid(tag.name);
return {
...tag,
semverTag: t,
};
})
.filter((tag) => tag.semverTag !== null)
.sort((a, b) => semverRcompare(a.semverTag, b.semverTag));
let previousReleaseTag = '';
for (const tag of tagList) {
if (semverLt(tag.semverTag, currentReleaseTag)) {
previousReleaseTag = tag.name;
break;
}
}
return previousReleaseTag;
};
const getCommitsSinceRelease = async (
client: github.GitHub,
tagInfo: Octokit.GitGetRefParams,
currentSha: string,
): Promise<Octokit.ReposCompareCommitsResponseCommitsItem[]> => {
core.startGroup('Retrieving commit history');
let resp;
core.info('Determining state of the previous release');
let previousReleaseRef = '' as string;
core.info(`Searching for SHA corresponding to previous "${tagInfo.ref}" release tag`);
try {
resp = await client.git.getRef(tagInfo);
previousReleaseRef = parseGitTag(tagInfo.ref);
} catch (err: any) {
core.info(
`Could not find SHA corresponding to tag "${tagInfo.ref}" (${err.message}). Assuming this is the first release.`,
);
previousReleaseRef = 'HEAD';
}
core.info(`Retrieving commits between ${previousReleaseRef} and ${currentSha}`);
try {
resp = await client.repos.compareCommits({
owner: tagInfo.owner,
repo: tagInfo.repo,
base: previousReleaseRef,
head: currentSha,
});
core.info(
`Successfully retrieved ${resp.data.commits.length} commits between ${previousReleaseRef} and ${currentSha}`,
);
} catch (_err) {
// istanbul ignore next
core.warning(`Could not find any commits between ${previousReleaseRef} and ${currentSha}`);
}
let commits = [];
if (resp?.data?.commits) {
commits = resp.data.commits;
}
core.debug(`Currently ${commits.length} number of commits between ${previousReleaseRef} and ${currentSha}`);
core.endGroup();
return commits;
};
export const getChangelog = async (
client: github.GitHub,
owner: string,
repo: string,
commits: Octokit.ReposCompareCommitsResponseCommitsItem[],
): Promise<string> => {
const parsedCommits: ParsedCommits[] = [];
core.startGroup('Generating changelog');
for (const commit of commits) {
core.debug(`Processing commit: ${JSON.stringify(commit)}`);
core.debug(`Searching for pull requests associated with commit ${commit.sha}`);
const pulls = await client.repos.listPullRequestsAssociatedWithCommit({
owner: owner,
repo: repo,
commit_sha: commit.sha,
});
if (pulls.data.length) {
core.info(`Found ${pulls.data.length} pull request(s) associated with commit ${commit.sha}`);
}
const clOptions = await getChangelogOptions();
const parsedCommitMsg = commitParser(commit.commit.message, clOptions);
// istanbul ignore next
if (parsedCommitMsg.merge) {
core.debug(`Ignoring merge commit: ${parsedCommitMsg.merge}`);
continue;
}
parsedCommitMsg.extra = {
commit: commit,
pullRequests: [],
breakingChange: false,
};
parsedCommitMsg.extra.pullRequests = pulls.data.map((pr) => {
return {
number: pr.number,
url: pr.html_url,
};
});
parsedCommitMsg.extra.breakingChange = isBreakingChange({
body: parsedCommitMsg.body,
footer: parsedCommitMsg.footer,
});
core.debug(`Parsed commit: ${JSON.stringify(parsedCommitMsg)}`);
parsedCommits.push(parsedCommitMsg);
core.info(`Adding commit "${parsedCommitMsg.header}" to the changelog`);
}
const changelog = generateChangelogFromParsedCommits(parsedCommits);
core.debug('Changelog:');
core.debug(changelog);
core.endGroup();
return changelog;
};
export const main = async (): Promise<void> => {
try {
const args = getAndValidateArgs();
const context = new Context();
// istanbul ignore next
const client = new github.GitHub(args.repoToken, {
baseUrl: process.env['JEST_MOCK_HTTP_PORT']
? `http://localhost:${process.env['JEST_MOCK_HTTP_PORT']}`
: undefined,
log: {
debug: (...logArgs) => core.debug(octokitLogger(...logArgs)),
info: (...logArgs) => core.debug(octokitLogger(...logArgs)),
warn: (...logArgs) => core.warning(octokitLogger(...logArgs)),
error: (...logArgs) => core.error(octokitLogger(...logArgs)),
},
});
core.startGroup('Initializing the Automatic Releases action');
dumpGitHubEventPayload();
core.debug(`Github context: ${JSON.stringify(context)}`);
core.endGroup();
core.startGroup('Determining release tags');
const releaseTag = args.automaticReleaseTag ? args.automaticReleaseTag : parseGitTag(context.ref);
if (!releaseTag) {
throw new Error(
`The parameter "automatic_release_tag" was not set and this does not appear to be a GitHub tag event. (Event: ${context.ref})`,
);
}
const previousReleaseTag = args.automaticReleaseTag
? args.automaticReleaseTag
: await searchForPreviousReleaseTag(client, releaseTag, {
owner: context.repo.owner,
repo: context.repo.repo,
});
core.endGroup();
const commitsSinceRelease = await getCommitsSinceRelease(
client,
{
owner: context.repo.owner,
repo: context.repo.repo,
ref: `tags/${previousReleaseTag}`,
},
context.sha,
);
const changelog = await getChangelog(client, context.repo.owner, context.repo.repo, commitsSinceRelease);
if (args.automaticReleaseTag) {
await createReleaseTag(client, {
owner: context.repo.owner,
ref: `refs/tags/${args.automaticReleaseTag}`,
repo: context.repo.repo,
sha: context.sha,
});
await deletePreviousGitHubRelease(client, {
owner: context.repo.owner,
repo: context.repo.repo,
tag: args.automaticReleaseTag,
});
}
const releaseUploadUrl = await generateNewGitHubRelease(client, {
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: releaseTag,
name: args.releaseTitle ? args.releaseTitle : releaseTag,
draft: args.draftRelease,
prerelease: args.preRelease,
body: changelog,
});
await uploadReleaseArtifacts(client, releaseUploadUrl, args.files);
core.debug(`Exporting environment variable AUTOMATIC_RELEASES_TAG with value ${releaseTag}`);
core.exportVariable('AUTOMATIC_RELEASES_TAG', releaseTag);
core.setOutput('automatic_releases_tag', releaseTag);
core.setOutput('upload_url', releaseUploadUrl);
} catch (error: any) {
core.setFailed(error.message);
throw error;
}
};