-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmain.js
301 lines (263 loc) · 8.79 KB
/
main.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
const http = require('http');
const https = require('https');
const utils = require('./utils');
const Environment = require('./environment');
const UserAgent = require('./user-agent');
const retry = require('bluebird-retry');
const requestPromise = require('request-promise');
const PromisePool = require('es6-promise-pool');
const regeneratorRuntime = require('regenerator-runtime'); // eslint-disable-line no-unused-vars
const fs = require('fs');
require('./dotenv').config();
const RETRY_ERROR_CODES = ['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'EHOSTUNREACH', 'EAI_AGAIN'];
const JSON_API_CONTENT_TYPE = 'application/vnd.api+json';
const CONCURRENCY = 2;
function retryPredicate(err) {
if (err.statusCode) {
return err.statusCode >= 500 && err.statusCode < 600;
} else if (err.error && !!err.error.code) {
return RETRY_ERROR_CODES.includes(err.error.code);
} else {
return false;
}
}
class Resource {
constructor(options) {
if (!options.resourceUrl) {
throw new Error('"resourceUrl" arg is required to create a Resource.');
}
if (!options.sha && !options.content) {
throw new Error('Either "sha" or "content" is required to create a Resource.');
}
if (/\s/.test(options.resourceUrl)) {
throw new Error('"resourceUrl" arg includes whitespace. It needs to be encoded.');
}
this.resourceUrl = options.resourceUrl;
this.content = options.content;
this.sha = options.sha || utils.sha256hash(options.content);
this.mimetype = options.mimetype;
this.isRoot = options.isRoot;
// Temporary convenience attributes, will not be serialized. These are used, for example,
// to hold the local path so reading file contents can be deferred.
this.localPath = options.localPath;
}
serialize() {
return {
type: 'resources',
id: this.sha,
attributes: {
'resource-url': this.resourceUrl,
mimetype: this.mimetype || null,
'is-root': this.isRoot || null,
},
};
}
}
class PercyClient {
constructor(options) {
options = options || {};
this.token = options.token;
this.apiUrl = options.apiUrl || 'https://percy.io/api/v1';
this.environment = options.environment || new Environment(process.env);
this._httpClient = requestPromise;
this._httpModule = this.apiUrl.indexOf('http://') === 0 ? http : https;
// A custom HttpAgent with pooling and keepalive.
this._httpAgent = new this._httpModule.Agent({
maxSockets: 5,
keepAlive: true,
});
this._clientInfo = options.clientInfo;
this._environmentInfo = options.environmentInfo;
this._sdkClientInfo = null;
this._sdkEnvironmentInfo = null;
}
_headers(headers) {
return Object.assign(
{
Authorization: `Token token=${this.token}`,
'User-Agent': new UserAgent(this).toString(),
},
headers,
);
}
_httpGet(uri) {
let requestOptions = {
method: 'GET',
uri: uri,
headers: this._headers(),
json: true,
resolveWithFullResponse: true,
agent: this._httpAgent,
};
return retry(this._httpClient, {
context: this,
args: [uri, requestOptions],
interval: 50,
max_tries: 5,
throw_original: true,
predicate: retryPredicate,
});
}
_httpPost(uri, data) {
let requestOptions = {
method: 'POST',
uri: uri,
body: data,
headers: this._headers({'Content-Type': JSON_API_CONTENT_TYPE}),
json: true,
resolveWithFullResponse: true,
agent: this._httpAgent,
};
return retry(this._httpClient, {
context: this,
args: [uri, requestOptions],
interval: 50,
max_tries: 5,
throw_original: true,
predicate: retryPredicate,
});
}
createBuild(options) {
let parallelNonce = this.environment.parallelNonce;
let parallelTotalShards = this.environment.parallelTotalShards;
// Only pass parallelism data if it all exists.
if (!parallelNonce || !parallelTotalShards) {
parallelNonce = null;
parallelTotalShards = null;
}
options = options || {};
const commitData = options['commitData'] || this.environment.commitData;
let data = {
data: {
type: 'builds',
attributes: {
branch: commitData.branch,
'target-branch': this.environment.targetBranch,
'target-commit-sha': this.environment.targetCommitSha,
'commit-sha': commitData.sha,
'commit-committed-at': commitData.committedAt,
'commit-author-name': commitData.authorName,
'commit-author-email': commitData.authorEmail,
'commit-committer-name': commitData.committerName,
'commit-committer-email': commitData.committerEmail,
'commit-message': commitData.message,
'pull-request-number': this.environment.pullRequestNumber,
'parallel-nonce': parallelNonce,
'parallel-total-shards': parallelTotalShards,
partial: this.environment.partialBuild,
},
},
};
if (options.resources) {
data['data']['relationships'] = {
resources: {
data: options.resources.map(function(resource) {
return resource.serialize();
}),
},
};
}
return this._httpPost(`${this.apiUrl}/builds/`, data);
}
// This method is unavailable to normal write-only project tokens.
getBuild(buildId) {
return this._httpGet(`${this.apiUrl}/builds/${buildId}`);
}
// This method is unavailable to normal write-only project tokens.
getBuilds(project, filter) {
filter = filter || {};
let queryString = Object.keys(filter)
.map(key => {
if (Array.isArray(filter[key])) {
// If filter value is an array, match Percy API's format expectations of:
// filter[key][]=value1&filter[key][]=value2
return filter[key].map(array_value => `filter[${key}][]=${array_value}`).join('&');
} else {
return 'filter[' + key + ']=' + filter[key];
}
})
.join('&');
if (queryString.length > 0) {
queryString = '?' + queryString;
}
return this._httpGet(`${this.apiUrl}/projects/${project}/builds${queryString}`);
}
makeResource(options) {
return new Resource(options);
}
// Synchronously walks a directory of compiled assets and returns an array of Resource objects.
gatherBuildResources(rootDir, options) {
return utils.gatherBuildResources(this, rootDir, options);
}
uploadResource(buildId, content) {
let sha = utils.sha256hash(content);
let data = {
data: {
type: 'resources',
id: sha,
attributes: {
'base64-content': utils.base64encode(content),
},
},
};
return this._httpPost(`${this.apiUrl}/builds/${buildId}/resources/`, data);
}
uploadResources(buildId, resources) {
const _this = this;
function* generatePromises() {
for (const resource of resources) {
const content = resource.localPath ? fs.readFileSync(resource.localPath) : resource.content;
yield _this.uploadResource(buildId, content);
}
}
const pool = new PromisePool(generatePromises(), CONCURRENCY);
return pool.start();
}
uploadMissingResources(buildId, response, resources) {
const missingResourceShas = utils.getMissingResources(response);
if (!missingResourceShas.length) {
return Promise.resolve();
}
const resourcesBySha = resources.reduce((map, resource) => {
map[resource.sha] = resource;
return map;
}, {});
const missingResources = missingResourceShas.map(resource => resourcesBySha[resource.id]);
return this.uploadResources(buildId, missingResources);
}
createSnapshot(buildId, resources, options) {
options = options || {};
resources = resources || [];
let data = {
data: {
type: 'snapshots',
attributes: {
name: options.name || null,
'enable-javascript': options.enableJavaScript || null,
widths: options.widths || null,
'minimum-height': options.minimumHeight || null,
},
relationships: {
resources: {
data: resources.map(function(resource) {
return resource.serialize();
}),
},
},
},
};
this._sdkClientInfo = options.clientInfo;
this._sdkEnvironmentInfo = options.environmentInfo;
return this._httpPost(`${this.apiUrl}/builds/${buildId}/snapshots/`, data);
}
finalizeSnapshot(snapshotId) {
return this._httpPost(`${this.apiUrl}/snapshots/${snapshotId}/finalize`, {});
}
finalizeBuild(buildId, options) {
options = options || {};
let allShards = options.allShards || false;
let query = allShards ? '?all-shards=true' : '';
return this._httpPost(`${this.apiUrl}/builds/${buildId}/finalize${query}`, {});
}
}
module.exports = PercyClient;