forked from ColinPitrat/update-release
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.ts
509 lines (435 loc) · 15.5 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
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
import * as core from '@actions/core';
import { getOctokitOptions, GitHub } from '@actions/github/lib/utils';
import { Context } from '@actions/github/lib/context';
import { retry } from '@octokit/plugin-retry';
import { throttling } from '@octokit/plugin-throttling';
import { } from '@octokit/types';
import { config } from 'dotenv';
import { readFileSync, statSync, existsSync } from 'fs';
import { resolve, isAbsolute, basename } from 'path';
import { lookup } from 'mime-types';
const context = new Context();
class Tagger {
public name: string;
public email: string;
public date: string;
constructor() {
this.name = 'update-existing-release github action';
this.email = 'none'
let now = new Date();
this.date = now.toISOString();
}
}
/**
* A nexus for keeping track of, and managing the state of, the connection to Github.
*/
class Connection {
/**
* The Octokit Github object, used for most interactions with the server.
*/
protected github: InstanceType<typeof GitHub>;
/**
* The secret token used to authenticate with the server.
*/
protected token: string = 'unknown-token'
/**
* The name of the owner whose repo we are building on.
*/
protected owner: string = 'unknown-owner';
/**
* The name of the repo we are building on.
*/
protected repo: string = 'unknown-repo';
/**
* The git ref that triggered this build.
*/
protected ref: string = 'unknown-ref';
/**
* The friendly, autogenerated name of the release, derived from the git tag that triggered
* this build.
*/
protected release: string = 'unknown-release';
/**
* The SHA associated with this build.
*/
protected sha: string = 'unknown-sha';
/** The tag for the release. If it does not exist, it will be created. If it does exist,
* it will be deleted and recreated. If not given, it will be set to the same as the
* name of the release.
*/
protected tag: string = 'unknown-tag';
/**
* The default single-line message for tags created by update-existing-release.
*/
protected message: string = '';
/**
* The default description body for any created release.
*/
protected body: string = '';
/**
* Is this a draft release?
*/
protected draft: boolean = false;
/**
* Is this a prerelease?
*/
protected prerelease: boolean = false;
/**
* The path to the file to be released.
*/
protected files: Array<string> = [];
/**
* The Github context, useful for establishing the current user and project.
*/
protected context: Object;
/**
* The Github repo ID.
*/
protected id: number = -1;
/**
* The Github repo ID.
*/
protected uploadUrl: string = null;
constructor() {
config();
this.token = core.getInput('token', { required: true });
core.setSecret(this.token);
this.github = new GitHub(getOctokitOptions(
this.token,
{
throttling,
retry
}
));
this.context = context;
[this.owner, this.repo] = process.env.GITHUB_REPOSITORY.split('/')
this.ref = process.env.GITHUB_REF;
this.sha = process.env.GITHUB_SHA;
this.setRelease();
this.setDraft();
this.setPrerelease();
this.setFiles();
this.setMessage();
this.setBody();
}
protected async createLightweightTag(tagger: Tagger) {
return await this.github.rest.git.createTag({
...context.repo,
tag: this.tag,
message: this.message,
object: this.sha,
type: 'commit',
tagger: tagger
});
}
protected async createRelease() {
core.startGroup('Creating release ' + this.release + '...')
let release = await this.github.rest.repos.createRelease(
{
...context.repo,
tag_name: this.tag,
name: this.release,
body: this.body,
draft: this.draft,
prerelease: this.prerelease
}
);
core.endGroup();
this.id = release.data.id;
this.uploadUrl = release.data.upload_url;
}
protected async updateRelease() {
core.startGroup('Updating release ' + this.release + ' (' + this.id + ') ...')
// Update release
await this.github.rest.repos.updateRelease(
{
...context.repo,
release_id: this.id,
name: this.release,
body: this.body,
draft: this.draft,
prerelease: this.prerelease
}
);
core.endGroup();
}
protected async createTag() {
console.log(`Creating tag '${this.tag}'`)
let tagger = new Tagger();
let tagObject = await this.createLightweightTag(tagger);
await this.github.rest.git.createRef(
{
...context.repo,
ref: 'refs/tags/' + this.tag,
sha: tagObject.data.sha
}
)
console.log(`Successfully created tag '${this.tag}'`)
}
protected async deleteAssetsIfTheyExist(shouldDeleteAllExisting: boolean): Promise<boolean> {
let assets = await this.getReleaseAssets();
let result: boolean = false;
for (let asset of assets) {
let shouldDelete: boolean = shouldDeleteAllExisting;
if (!shouldDeleteAllExisting) {
for (let oneFile of this.files) {
if (asset.name === basename(oneFile)) {
shouldDelete = true;
}
}
}
if (shouldDelete) {
core.startGroup('Deleting old release asset id ' + asset.id + '...');
await this.github.rest.repos.deleteReleaseAsset(
{
...context.repo,
asset_id: asset.id
}
)
result = true;
core.endGroup();
}
}
return result;
}
protected async doesReleaseExist(): Promise<boolean> {
let releases = await this.getReleases();
return releases.includes(this.release);
}
dump(name: string, thing: Object): void {
console.debug(name + ':' + JSON.stringify(thing));
}
protected async getReleaseAssets() {
core.startGroup('Getting assets for the release...')
console.debug('Release id: ' + this.id);
if (this.id < 0)
return;
let assets = [];
let page = 1;
while(true){
let response = await this.github.rest.repos.listReleaseAssets({
...context.repo,
release_id: this.id,
per_page: 100,
page: page++,
});
let pageOfAssets = response.data;
let count = 0;
for(let asset of pageOfAssets){
assets.push(asset);
count++;
}
if(count < 100){
break;
}
}
this.dump('assets', assets);
core.endGroup();
return assets;
}
protected async useExistingRelease() {
core.startGroup('Finding ID of release...')
if(this.id >= 0){
this.dump('Using cached', this.id);
core.endGroup();
return;
}
let releasesObject = await this.github.rest.repos.listReleases({
...context.repo,
});
for (let release of releasesObject.data) {
if (release.name == this.release) {
this.id = release.id;
this.uploadUrl = release.upload_url;
return;
}
}
this.dump('releasesObjectData', releasesObject.data);
core.endGroup();
throw new Error('could not find id corresponding to release ' + this.release);
}
protected async getReleases(): Promise<Array<string>> {
core.startGroup('Getting list of releases...')
let releasesObject = await this.github.rest.repos.listReleases({
...context.repo,
});
let releases: Array<string> = [];
for (let release of releasesObject.data) {
releases.push(release.name);
}
this.dump('releases', releases);
core.endGroup();
return releases;
}
protected async getReleaseUploadURL(): Promise<string> {
return this.uploadUrl;
}
protected async getRepos() {
core.startGroup('Getting list of repositories...');
const allReleases = await this.github.rest.repos.listReleases({
...context.repo
});
const repos = allReleases.data;
this.dump('repos', repos);
core.endGroup();
return repos;
}
/**
* Returns details on the current tag, or false if it cannot be found.
*/
protected async getTag() {
core.startGroup('Getting list of repo tags...')
let tagsQuery = await this.github.rest.repos.listTags({ ...context.repo });
let tags = tagsQuery.data;
core.endGroup();
for (let tag of tags) {
if (tag.name === this.tag) {
console.log(`Successfully found tag '${this.tag}'`)
return tag;
}
}
console.log(`Could not find tag '${this.tag}'`)
return null;
}
public async run() {
let tag = await this.getTag();
// Create the tag if necessary
if (tag === null) {
await this.createTag();
tag = await this.getTag();
}
if (await this.doesReleaseExist()) {
await this.useExistingRelease();
} else {
await this.createRelease();
}
console.debug('Release id: ' + this.id);
if (this.id >= 0) {
await this.updateRelease();
await this.deleteAssetsIfTheyExist(isTruthyString(core.getInput('replace')));
await this.uploadAssets();
if (!isFalsyString(core.getInput('updateTag'))) {
await this.updateTag();
}
}
}
protected async setBody() {
this.body = core.getInput('body');
if (this.body !== '')
return;
const commitObject = await this.github.rest.git.getCommit({
...context.repo,
commit_sha: this.sha
});
this.body = commitObject.data.message;
}
protected setDraft() {
this.draft = isTruthyString(core.getInput('draft'));
core.setOutput('draft', this.draft ? 'true' : 'false');
}
protected setFiles() {
let inputFileString: string = core.getInput('files', { required: true });
let inputFiles: Array<string> = inputFileString.split(/[ ,\r\n\t]+/);
for (let oneFile of inputFiles) {
let tryPath: string = oneFile;
if (!existsSync(tryPath) || !isAbsolute(tryPath)) {
// go on a path hunt
tryPath = resolve(process.env.GITHUB_WORKSPACE, oneFile);
if (!existsSync(tryPath)) {
throw new Error(`could not find ${oneFile} as either absolute path or path relative to workspace`);
}
}
if (!existsSync(tryPath)) {
throw new Error(`could not find file ${tryPath} for release; please provide a full path or path relative to workspace`);
}
// Although Windows uses backslashes as separators, Windows can also use forward slashes as separators
// and this choice is more compatible with cross-platform scripts
this.files.push(tryPath.replace(/\\/g, '/'));
}
core.setOutput('files', JSON.stringify(this.files));
}
protected setMessage() {
let message = core.getInput('message');
if (message === '') {
this.message = this.release + ' (automatically created)';
}
}
protected setPrerelease() {
this.prerelease = !isFalsyString(core.getInput('prerelease'));
core.setOutput('prerelease', this.prerelease ? 'true' : 'false');
}
protected setRelease() {
this.release = core.getInput('release');
if (this.release === '') {
this.release = this.ref;
/* Convert a git ref to a friendlier looking name */
this.release = this.release.replace(/refs\//, '');
this.release = this.release.replace(/heads\//, '');
this.release = this.release.replace(/tags\//, '');
this.release = this.release.replace(/\//g, '-');
}
this.tag = core.getInput('tag');
if (this.tag === '') {
this.tag = this.release;
}
if (/[\\?~^:*\[@\s]|^\/.*$|\/$|\/\/|\.\.|\.$/.test(this.tag)) {
throw new Error("Unsuitable tag name");
}
core.setOutput('release', this.release);
core.setOutput('tag', this.tag);
}
protected async updateTag() {
// Update tag
console.debug('Updating tag ' + this.tag + ' to ' + this.sha);
await this.github.rest.git.updateRef({
...context.repo,
ref: `tags/${this.tag}`,
sha: process.env.GITHUB_SHA
});
}
protected async uploadAssets() {
// if we can't figure out what file type you have, we'll assign it this unknown type
// https://www.iana.org/assignments/media-types/application/octet-stream
const defaultAssetContentType = 'application/octet-stream';
core.startGroup('Uploading release asset ' + this.files + '...')
for (let oneFile of this.files) {
let contentType: any = lookup(oneFile);
if (contentType == false) {
console.warn('content type for file ' + oneFile +
' could not be automatically determined from extension; going with ' +
defaultAssetContentType);
contentType = defaultAssetContentType;
}
// Determine content-length for header to upload asset
const contentLength = statSync(oneFile).size;
// Setup headers for API call, see Octokit Documentation: https://octokit.github.io/rest.js/#octokit-routes-repos-upload-release-asset for more information
const headers = {
'content-type': contentType,
'content-length': contentLength
};
// Upload a release asset
// API Documentation: https://developer.github.com/v3/repos/releases/#upload-a-release-asset
// Octokit Documentation: https://octokit.github.io/rest.js/#octokit-routes-repos-upload-release-asset
console.debug('Uploading release asset ' + oneFile);
await this.github.rest.repos.uploadReleaseAsset({
...context.repo,
release_id: this.id,
url: await this.getReleaseUploadURL(),
headers,
name: basename(oneFile),
data: readFileSync(oneFile) as any
});
}
core.endGroup();
}
}
function isTruthyString(string: String) {
return string === 'true' || string == 'yes';
}
function isFalsyString(string: String) {
return string === 'false' || string == 'no';
}
core.startGroup('Updating release...');
let connection = new Connection();
connection.run();
core.endGroup();