/
GitHub.js
312 lines (269 loc) Β· 9.43 KB
/
GitHub.js
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
import fs from 'fs';
import path from 'path';
import { Octokit } from '@octokit/rest';
import globby from 'globby';
import mime from 'mime-types';
import _ from 'lodash';
import retry from 'async-retry';
import { format, parseVersion, readJSON, e } from '../../util.js';
import Release from '../GitRelease.js';
import prompts from './prompts.js';
const pkg = readJSON(new URL('../../../package.json', import.meta.url));
const docs = 'https://git.io/release-it-github';
const RETRY_CODES = [408, 413, 429, 500, 502, 503, 504, 521, 522, 524];
const DEFAULT_RETRY_MIN_TIMEOUT = 1000;
const parseErrormsg = err => {
let msg = err;
if (err instanceof Error) {
const { status, message } = err;
const { headers } = err.response;
msg = `${_.get(headers, 'status', status)} (${message})`;
}
return msg;
};
class GitHub extends Release {
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
}
async init() {
await super.init();
const { skipChecks, tokenRef, update } = this.options;
if (!skipChecks) {
if (!this.token) {
throw e(`Environment variable "${tokenRef}" is required for GitHub releases.`, docs);
}
// If we're running on GitHub Actions, we can skip the authentication and
// collaborator checks. Ref: https://bit.ly/2vsyRzu
if (process.env.GITHUB_ACTIONS) {
this.setContext({ username: process.env.GITHUB_ACTOR });
} else {
if (!(await this.isAuthenticated())) {
throw e(`Could not authenticate with GitHub using environment variable "${tokenRef}".`, docs);
}
if (!(await this.isCollaborator())) {
const { repository } = this.getContext('repo');
const { username } = this.getContext();
throw e(`User ${username} is not a collaborator for ${repository}.`, docs);
}
}
}
if (update) {
const { latestTag } = this.config.getContext();
try {
const { id, upload_url, tag_name } = await this.getLatestRelease();
if (latestTag === tag_name) {
this.setContext({ isUpdate: true, isReleased: true, releaseId: id, upload_url });
} else {
this.setContext({ isUpdate: false });
}
} catch (error) {
this.setContext({ isUpdate: false });
}
if (!this.getContext('isUpdate')) {
this.log.warn(`GitHub release for tag ${latestTag} was not found. Creating new release.`);
}
}
}
async isAuthenticated() {
if (this.config.isDryRun) return true;
try {
this.log.verbose('octokit users#getAuthenticated');
const { data } = await this.client.users.getAuthenticated();
this.setContext({ username: data.login });
return true;
} catch (error) {
this.debug(error);
return false;
}
}
async isCollaborator() {
if (this.config.isDryRun) return true;
const { owner, project: repo } = this.getContext('repo');
const { username } = this.getContext();
try {
const options = { owner, repo, username };
this.log.verbose(`octokit repos#checkCollaborator (${username})`);
await this.client.repos.checkCollaborator(options);
return true;
} catch (error) {
this.debug(error);
return false;
}
}
async release() {
const { assets } = this.options;
const { isUpdate } = this.getContext();
const { isCI } = this.config;
const type = isUpdate ? 'update' : 'create';
const publishMethod = `${type}Release`;
if (isCI) {
await this.step({ task: () => this[publishMethod](), label: `GitHub ${type} release` });
return this.step({ enabled: assets, task: () => this.uploadAssets(), label: 'GitHub upload assets' });
} else {
const release = async () => {
await this[publishMethod]();
return this.uploadAssets();
};
return this.step({ task: release, label: `GitHub ${type} release`, prompt: 'release' });
}
}
handleError(err, bail) {
const message = parseErrormsg(err);
const githubError = new Error(message);
this.log.verbose(err.errors);
this.debug(err);
if (!_.includes(RETRY_CODES, err.status)) {
return bail(githubError);
}
throw githubError;
}
get client() {
if (this._client) return this._client;
const { proxy, timeout } = this.options;
const host = this.options.host || this.getContext('repo.host');
const isGitHub = host === 'github.com';
const baseUrl = `https://${isGitHub ? 'api.github.com' : host}${isGitHub ? '' : '/api/v3'}`;
const options = {
baseUrl,
auth: `token ${this.token}`,
userAgent: `release-it/${pkg.version}`,
log: this.config.isDebug ? console : null,
request: {
timeout
}
};
if (proxy) {
options.proxy = proxy;
}
const client = new Octokit(options);
this._client = client;
return client;
}
async getLatestRelease() {
const { owner, project: repo } = this.getContext('repo');
try {
const options = { owner, repo };
this.debug(options);
const response = await this.client.repos.listReleases({ owner, repo, per_page: 1, page: 1 });
this.debug(response.data[0]);
return response.data[0];
} catch (err) {
return this.handleError(err, () => {});
}
}
getOctokitReleaseOptions(options = {}) {
const { owner, project: repo } = this.getContext('repo');
const { releaseName, draft = false, preRelease = false } = this.options;
const { tagName } = this.config.getContext();
const { version, releaseNotes } = this.getContext();
const { isPreRelease } = parseVersion(version);
const name = format(releaseName, this.config.getContext());
const body = releaseNotes;
return Object.assign(options, {
owner,
repo,
tag_name: tagName,
name,
body,
draft,
prerelease: isPreRelease || preRelease
});
}
retry(fn) {
const { retryMinTimeout } = this.options;
return retry(fn, {
retries: 2,
minTimeout: typeof retryMinTimeout === 'number' ? retryMinTimeout : DEFAULT_RETRY_MIN_TIMEOUT
});
}
async createRelease() {
const options = this.getOctokitReleaseOptions();
const { isDryRun } = this.config;
this.log.exec(`octokit repos.createRelease "${options.name}" (${options.tag_name})`, { isDryRun });
if (isDryRun) {
this.setContext({ isReleased: true, releaseUrl: this.getReleaseUrlFallback(options.tag_name) });
return true;
}
return this.retry(async bail => {
try {
this.debug(options);
const response = await this.client.repos.createRelease(options);
this.debug(response.data);
const { html_url, upload_url, id } = response.data;
this.setContext({ isReleased: true, releaseId: id, releaseUrl: html_url, upload_url });
this.log.verbose(`octokit repos.createRelease: done (${response.headers.location})`);
return response.data;
} catch (err) {
return this.handleError(err, bail);
}
});
}
uploadAsset(filePath) {
const url = this.getContext('upload_url');
const name = path.basename(filePath);
const contentType = mime.contentType(name) || 'application/octet-stream';
const contentLength = fs.statSync(filePath).size;
return this.retry(async bail => {
try {
const options = {
url,
data: fs.createReadStream(filePath),
name,
headers: {
'content-type': contentType,
'content-length': contentLength
}
};
this.debug(options);
const response = await this.client.repos.uploadReleaseAsset(options);
this.debug(response.data);
this.log.verbose(`octokit repos.uploadReleaseAsset: done (${response.data.browser_download_url})`);
return response.data;
} catch (err) {
return this.handleError(err, bail);
}
});
}
uploadAssets() {
const { assets } = this.options;
const { isReleased } = this.getContext();
const context = this.config.getContext();
const { isDryRun } = this.config;
this.log.exec('octokit repos.uploadReleaseAssets', assets, { isDryRun });
if (!assets || !isReleased || isDryRun) {
return true;
}
const patterns = _.castArray(assets).map(pattern => format(pattern, context));
return globby(patterns).then(files => {
if (!files.length) {
this.log.warn(`octokit repos.uploadReleaseAssets: did not find "${assets}" relative to ${process.cwd()}`);
}
return Promise.all(files.map(filePath => this.uploadAsset(filePath)));
});
}
getReleaseUrlFallback(tagName) {
const { host, repository } = this.getContext('repo');
return `https://${host}/${repository}/releases/tag/${tagName}`;
}
updateRelease() {
const { isDryRun } = this.config;
const release_id = this.getContext('releaseId');
const options = this.getOctokitReleaseOptions({ release_id });
this.log.exec(`octokit repos.updateRelease (${options.tag_name})`, { isDryRun });
if (isDryRun) return true;
return this.retry(async bail => {
try {
this.debug(options);
const response = await this.client.repos.updateRelease(options);
this.setContext({ releaseUrl: response.data.html_url });
this.debug(response.data);
this.log.verbose(`octokit repos.updateRelease: done (${response.headers.location})`);
return true;
} catch (err) {
return this.handleError(err, bail);
}
});
}
}
export default GitHub;