/
index.ts
316 lines (265 loc) · 8.67 KB
/
index.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
import { RestEndpointMethodTypes } from "@octokit/rest";
import {
Auto,
getPrNumberFromEnv,
IPlugin,
validatePluginConfiguration,
} from "@auto-it/core";
import endent from "endent";
import * as FileType from "file-type";
import fs from "fs";
import glob from "fast-glob";
import path from "path";
import { promisify } from "util";
import link from "terminal-link";
import * as t from "io-ts";
type AssetResponse = RestEndpointMethodTypes["repos"]["uploadReleaseAsset"]["response"]["data"];
type GitHubRelease = RestEndpointMethodTypes["repos"]["getReleaseByTag"]["response"]["data"];
const stat = promisify(fs.stat);
const readFile = promisify(fs.readFile);
const canaryTag = "0.0.0-canary";
const requiredPluginOptions = t.interface({
/** Paths to assets to upload */
assets: t.array(t.string),
});
const optionalPluginOptions = t.partial({
/** Max number of assets to keep in the canary release */
maxCanaryAssets: t.number,
});
const pluginOptions = t.intersection([
requiredPluginOptions,
optionalPluginOptions,
]);
/** Convert shorthand options to noraml shape */
const normalizeOptions = (options: IUploadAssetsPluginOptions | string[]) =>
Array.isArray(options) ? { assets: options } : options;
export type IUploadAssetsPluginOptions = t.TypeOf<typeof pluginOptions>;
interface Release {
/** The response data */
data: {
/** the release id */
id: number;
};
}
/** Attach extra assets to a GitHub Release */
export default class UploadAssetsPlugin implements IPlugin {
/** The name of the plugin */
name = "upload-assets";
/** The options of the plugin */
readonly options: Required<IUploadAssetsPluginOptions>;
/** Initialize the plugin with it's options */
constructor(options: IUploadAssetsPluginOptions | string[]) {
const normalizedOptions = normalizeOptions(options);
this.options = {
...normalizedOptions,
maxCanaryAssets: normalizedOptions.maxCanaryAssets || 300,
};
}
/** Tap into auto plugin points. */
apply(auto: Auto) {
auto.hooks.validateConfig.tapPromise(this.name, async (name, options) => {
if (name === this.name || name === `@auto-it/${this.name}`) {
return validatePluginConfiguration(
this.name,
pluginOptions,
normalizeOptions(options)
);
}
});
auto.hooks.canary.tapPromise(
this.name,
async ({ canaryIdentifier, dryRun }) => {
const canaryRelease = await this.getCanaryGitHubRelease(auto, true);
auto.logger.log.info(endent`${
dryRun ? "Would update" : "Updating"
} Canary Release:
${canaryRelease.html_url}
`);
const assets = await this.uploadAssets(
auto,
{ data: canaryRelease },
dryRun,
canaryIdentifier
);
if (!assets.length) {
return;
}
auto.logger.log.success(endent`
Download canary assets:
${assets
.map((asset) => link(asset.name, asset.browser_download_url))
.join(" \n")}
`);
const prNumber = getPrNumberFromEnv();
if (!prNumber) {
return;
}
const assetList = assets
.map((asset) => `[${asset.name}](${asset.browser_download_url}) `)
.join("\n");
await auto.git?.addToPrBody(
endent`
:baby_chick: Download canary assets:
${assetList}
`,
prNumber,
"canary-assets"
);
}
);
auto.hooks.afterRelease.tapPromise(this.name, async ({ response }) => {
if (!response) {
return;
}
await this.uploadAssets(auto, response);
await this.cleanupCanaryAssets(auto);
});
}
/** Upload the configured asset to a release */
private async uploadAssets(
auto: Auto,
release: Release | Release[],
dryRun = false,
id?: string
) {
const assets = await glob(this.options.assets);
auto.logger.log.info(endent`
${dryRun ? "Would upload" : "Uploading"}:
${assets.map((asset) => ` - ${asset}`).join("\n")}
`);
console.log("");
if (dryRun) {
return [];
}
const responses = await Promise.all(
assets.map(async (asset) => {
if (!auto.git) {
return;
}
const file = await readFile(asset);
const stats = await stat(asset);
const type = await FileType.fromBuffer(file);
const DEFAULT_BASE_URL = "https://api.github.com";
const baseUrl = auto.git.options.baseUrl || DEFAULT_BASE_URL;
const fileName = path.basename(asset);
const extension = path.extname(fileName);
const options: RestEndpointMethodTypes["repos"]["uploadReleaseAsset"]["parameters"] = {
// placeholder to appease typescript
release_id: -1,
data: (file as unknown) as string,
name: id
? extension
? fileName.replace(extension, `-${id}${extension}`)
: `${fileName}-${id}`
: fileName,
owner: auto.git.options.owner,
repo: auto.git.options.repo,
headers: {
"content-length": stats.size,
"content-type": type ? type.mime : "application/octet-stream",
},
};
if (baseUrl !== DEFAULT_BASE_URL) {
const { origin } = new URL(baseUrl);
options.baseUrl = `${origin}/api/uploads`;
}
const assetResponses: AssetResponse[] = [];
// Multiple releases were made
if (Array.isArray(release)) {
await Promise.all(
release.map(async (r) => {
const {
data: releaseAsset,
} = await auto.git!.github.repos.uploadReleaseAsset({
...options,
release_id: r.data.id,
});
assetResponses.push(releaseAsset);
})
);
} else {
const {
data: releaseAsset,
} = await auto.git.github.repos.uploadReleaseAsset({
...options,
release_id: release.data.id,
});
assetResponses.push(releaseAsset);
}
auto.logger.log.success(`Uploaded asset: ${asset}`);
return assetResponses;
})
);
return responses
.filter((r): r is AssetResponse[] => Boolean(r))
.reduce((acc, item) => [...acc, ...item], []);
}
// prettier-ignore
private async getCanaryGitHubRelease(auto: Auto): Promise<GitHubRelease | undefined>
// prettier-ignore
private async getCanaryGitHubRelease(auto: Auto, create: true): Promise<GitHubRelease>
// prettier-ignore
/** Get the release all the canaries are stored in */
private async getCanaryGitHubRelease(auto: Auto, create = false): Promise<GitHubRelease | undefined> {
try {
const canaryRelease = await auto.git!.github.repos.getReleaseByTag({
repo: auto.git!.options.repo,
owner: auto.git!.options.owner,
tag: auto.prefixRelease(canaryTag),
});
return canaryRelease.data;
} catch (error) {
if (!create) {
return;
}
const canaryRelease = await auto.git!.github.repos.createRelease({
repo: auto.git!.options.repo,
owner: auto.git!.options.owner,
tag_name: auto.prefixRelease(canaryTag),
name: "Canary Assets",
prerelease: true,
body: `This release contains preview assets of Pull Requests.`,
target_commitish: await auto.git?.getFirstCommit()
});
return canaryRelease.data;
}
}
/** Delete old canary asset */
private async cleanupCanaryAssets(auto: Auto) {
const canaryRelease = await this.getCanaryGitHubRelease(auto);
if (!canaryRelease) {
return;
}
const canaryReleaseAssets = await auto.git!.github.paginate(
auto.git!.github.repos.listReleaseAssets,
{
repo: auto.git!.options.repo,
owner: auto.git!.options.owner,
release_id: canaryRelease.id,
}
);
const assetsToDelete = canaryReleaseAssets
.sort(
(a, b) =>
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
)
.slice(0, canaryReleaseAssets.length - this.options.maxCanaryAssets);
if (!assetsToDelete.length) {
return;
}
auto.logger.log.info(endent`
Deleting old canary assets:
${assetsToDelete.map((asset) => ` - ${asset}`).join("\n")}
`);
await Promise.all(
assetsToDelete.map(async (assetToDelete) => {
await auto.git!.github.repos.deleteReleaseAsset({
repo: auto.git!.options.repo,
owner: auto.git!.options.owner,
release_id: canaryRelease.id,
asset_id: assetToDelete.id,
});
})
);
}
}