-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
257 lines (226 loc) · 7.75 KB
/
index.js
File metadata and controls
257 lines (226 loc) · 7.75 KB
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
const debugLog = require('debug')('log');
const debugError = require('debug')('error');
// const debugInfo = require('debug')('info');
const dotenvFlow = require('dotenv-flow');
const fs = require('fs');
const HttpCors = require('http-cors');
const WebhooksApi = require('@octokit/webhooks');
const octokit = require('@octokit/rest')();
const { spawn } = require('child_process');
const rimraf = require('rimraf');
const S3 = require('aws-sdk/clients/s3');
const perfReportTemplate = require('./perfReportTemplate');
const compareAssets = require('./compareAssets');
if (process.env.NODE_ENV !== 'production') {
dotenvFlow.config();
}
const kBSize = size => `${Math.round(size / 1e3)}kB`;
const cors = new HttpCors();
const options = {
GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_PERSONAL_ACCESS_TOKEN,
GITHUB_SECRET: process.env.GITHUB_SECRET,
DIST_FOLDER: process.env.DIST_FOLDER || 'dist',
DOWNLOAD_FOLDER: process.env.DOWNLOAD_FOLDER || '/tmp',
BUILD_AND_ANALYZE_SCRIPT: process.env.BUILD_AND_ANALYZE_SCRIPT || 'webpack-bundle-analyzer',
CHANGE_LIMIT: Number(process.env.CHANGE_LIMIT || '2000'),
};
octokit.authenticate({
type: 'token',
token: options.GITHUB_PERSONAL_ACCESS_TOKEN,
});
const repoFolderLocation = ({ branch, repo }) => `${options.DOWNLOAD_FOLDER}/${repo}-${branch}`;
const deleteBranchFolder = ({ branch, repo }) =>
new Promise((resolve, reject) => {
rimraf(repoFolderLocation({ branch, repo }), (error) => {
if (error) {
debugError("couldn't delete a repo", error);
reject();
return;
}
resolve();
});
});
const logProcessOutput = (logPrefix, spawnedProcess) => {
spawnedProcess.stdout.on('data', (data) => {
debugLog(`"${logPrefix}" stdout: ${data}`);
});
spawnedProcess.stderr.on('data', (data) => {
debugError(`"${logPrefix}" stderr: ${data}`);
});
};
const runShellCommand = shellCommand =>
new Promise((resolve, reject) => {
const [command, ...commandArguments] = shellCommand.split(' ');
const shellCommandProcess = spawn(command, commandArguments);
logProcessOutput(shellCommand, shellCommandProcess);
shellCommandProcess.on('close', (code) => {
// yarn analyze exits with 1 as the exit code even though it's successful
if (code !== 0) {
reject(new Error(`"${shellCommand}" failed with error code ${code}`));
return;
}
resolve();
});
});
const yarnInstall = ({ branch, repo }) =>
runShellCommand(`yarn install --production=false --cwd=${repoFolderLocation({ branch, repo })}`);
const downloadBranch = ({ branch, owner, repo }) =>
runShellCommand(`git clone --branch ${branch} --single-branch --depth=1 git@github.com:${owner}/${repo} ${repoFolderLocation({ branch, repo })}`);
const yarnRunAnalyze = ({ branch, repo }) =>
runShellCommand(`yarn --cwd=${repoFolderLocation({ branch, repo })} ${options.BUILD_AND_ANALYZE_SCRIPT}`);
const getFileSizes = ({ branch, repo }) =>
new Promise((resolve) => {
const branchStats = JSON.parse(fs.readFileSync(`${repoFolderLocation({ branch, repo })}/${options.DIST_FOLDER}/stats.json`));
const masterStats = JSON.parse(fs.readFileSync(`${repoFolderLocation({ branch: 'master', repo })}/${options.DIST_FOLDER}/stats.json`));
resolve(compareAssets(masterStats.chunks, branchStats.chunks));
});
const setStatus = ({
description, owner, repo, sha, state, targetUrl,
}) => {
octokit.repos
.createStatus({
owner,
repo,
sha,
state,
description,
target_url: targetUrl,
context: 'Perf',
})
.catch(debugError);
};
const webhooks = new WebhooksApi({
secret: options.GITHUB_SECRET,
});
const s3Region = process.env.AWS_S3_REGION;
const s3 = () =>
new S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
region: s3Region,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
const s3BucketName = process.env.AWS_S3_BUCKET_NAME;
const s3BucketUrl = `https://s3-${s3Region}.amazonaws.com/${s3BucketName}`;
const getS3Url = ({ branch, fileName, repo }) => `${s3BucketUrl}/${repo}-${branch}-${fileName}`;
const uploadCoverageFile = ({ branch, fileName, repo }) =>
new Promise((fileResolve, fileReject) => {
const filePath = `${repoFolderLocation({ branch, repo })}/${options.DIST_FOLDER}/${fileName}`;
const stream = fs.createReadStream(`${filePath}`);
s3().upload(
{
ACL: 'public-read',
Bucket: s3BucketName,
ContentType: fileName.match(/\.json$/) ? 'application/json' : 'text/html',
Body: stream,
Key: `${repo}-${branch}-${fileName}`,
},
{ partSize: 100 * 1024 ** 2 },
(error, data) => {
if (error) {
fileReject(new Error(error));
} else {
fileResolve(data.Location);
}
},
);
});
const uploadFiles = ({ branch, repo }) =>
new Promise((resolve, reject) => {
Promise.all([
...['stats.json', 'report.html'].map(fileName =>
uploadCoverageFile({ branch: 'master', fileName, repo })),
...['stats.json', 'report.html', 'index.html'].map(fileName =>
uploadCoverageFile({ branch, fileName, repo })),
])
.then(([reportUrl, statsUrl]) => {
resolve({
reportUrl,
statsUrl,
});
})
.catch(reject);
});
webhooks.on('pull_request', ({ payload }) => {
debugLog('PULL REQUEST event received:\n', JSON.stringify({ payload }, null, 2));
const {
action,
pull_request: {
head: { sha, ref: branch },
},
repository: {
name: repo,
owner: { login: owner },
},
} = payload;
if (!['opened', 'synchronize'].includes(action)) {
debugLog("exiting since the action wasn't opened or synchronize");
return;
}
setStatus({
owner,
repo,
sha,
state: 'pending',
});
const tasks = [
() => deleteBranchFolder({ branch: 'master', owner, repo }),
() => downloadBranch({ branch: 'master', owner, repo }),
() => yarnInstall({ branch: 'master', owner, repo }),
() => yarnRunAnalyze({ branch: 'master', owner, repo }),
() => deleteBranchFolder({ branch, owner, repo }),
() => downloadBranch({ branch, owner, repo }),
() => yarnInstall({ branch, owner, repo }),
() => yarnRunAnalyze({ branch, owner, repo }),
getFileSizes.bind(null, { branch, owner, repo }),
(fileSizes) => {
const changeLimit = options.CHANGE_LIMIT;
const change = fileSizes.reduce((sum, fileSize) => sum + fileSize.change, 0);
const description =
change > changeLimit
? `Size increase > ${kBSize(changeLimit)} (${kBSize(change)}) double check details`
: `Size changed with: ${kBSize(change)}`;
fs.writeFileSync(
`${repoFolderLocation({ branch, repo })}/${options.DIST_FOLDER}/index.html`,
perfReportTemplate({
branch,
fileSizes,
getS3Url,
repo,
}),
(error) => {
if (error) {
throw new Error(error);
}
},
);
uploadFiles({ branch, repo })
.then(() => {
setStatus({
owner,
repo,
sha,
state: change < changeLimit ? 'success' : 'failure',
description,
targetUrl: getS3Url({ branch, fileName: 'index.html', repo }),
});
})
.catch(debugError);
},
];
tasks
.reduce((previousPromise, task) => previousPromise.then(task), Promise.resolve())
.catch(debugError);
});
const server = require('http').createServer((request, response) => {
if (cors.apply(request, response)) {
response.end();
return;
}
webhooks.middleware(request, response);
});
if (require.main === module) {
const port = process.env.PORT || 3000;
debugLog(`Starting server on http://localhost:${port}`);
server.listen(port);
}
exports.server = server;