-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
index.js
263 lines (248 loc) · 7.35 KB
/
index.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
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const argv = require('minimist')(process.argv.slice(2));
const globby = require('globby');
const path = require('path');
const url = require('url');
const util = require('util');
const {
gitCommitHash,
gitCiMasterBaseline,
shortSha,
} = require('../../common/git');
const {
isPullRequestBuild,
isPushBuild,
ciPushBranch,
ciRepoSlug,
} = require('../../common/ci');
const {
VERSION: internalRuntimeVersion,
} = require('../../compile/internal-version');
const {cyan, red, yellow} = require('kleur/colors');
const {log, logWithoutTimestamp} = require('../../common/logging');
const {report, NoTTYReport} = require('@ampproject/filesize');
const requestPost = util.promisify(require('request').post);
const filesizeConfigPath = require.resolve('./filesize.json');
const fileGlobs = require(filesizeConfigPath).filesize.track;
const normalizedRtvNumber = '1234567890123';
const expectedGitHubRepoSlug = 'ampproject/amphtml';
const bundleSizeAppBaseUrl = 'https://amp-bundle-size-bot.appspot.com/v0/';
const replacementExpression = new RegExp(internalRuntimeVersion, 'g');
/**
* Get the brotli bundle sizes of the current build after normalizing the RTV number.
*
* @return {Map<string, number>} the bundle size in KB rounded to 2 decimal
* points.
*/
async function getBrotliBundleSizes() {
const bundleSizes = {};
const sizes = await report(
filesizeConfigPath,
(content) => content.replace(replacementExpression, normalizedRtvNumber),
NoTTYReport,
/* silent */ false
);
for (const size of sizes) {
const [filePath, sizeMap] = size;
const relativePath = path.relative('.', filePath);
const reportedSize = parseFloat((sizeMap[0][0] / 1024).toFixed(2));
bundleSizes[relativePath] = reportedSize;
}
return bundleSizes;
}
/**
* Checks the response of an operation. Throws if there's an error, and prints
* success messages if not.
* @param {!Object} response
* @param {...string} successMessages
*/
function checkResponse(response, ...successMessages) {
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(
`${response.statusCode} ${response.statusMessage}: ` + response.body
);
} else {
log(...successMessages);
}
}
/**
* Store the bundle sizes for a commit hash in the build artifacts storage
* repository to the passed value.
*/
async function storeBundleSize() {
if (!isPushBuild() || ciPushBranch() !== 'master') {
log(
yellow('Skipping'),
cyan('--on_push_build') + ':',
'this action can only be performed on `master` push builds during CI'
);
return;
}
if (ciRepoSlug() !== expectedGitHubRepoSlug) {
log(
yellow('Skipping'),
cyan('--on_push_build') + ':',
'this action can only be performed during CI builds on the',
cyan(expectedGitHubRepoSlug),
'repository'
);
return;
}
const commitHash = gitCommitHash();
log('Storing bundle sizes for commit', cyan(shortSha(commitHash)) + '...');
try {
const response = await requestPost({
uri: url.resolve(
bundleSizeAppBaseUrl,
path.join('commit', commitHash, 'store')
),
json: true,
body: {
token: process.env.BUNDLE_SIZE_TOKEN,
bundleSizes: await getBrotliBundleSizes(),
},
});
checkResponse(response, 'Successfully stored bundle sizes.');
} catch (error) {
log(yellow('WARNING:'), 'Could not store bundle sizes');
logWithoutTimestamp(error);
return;
}
}
/**
* Mark a pull request as skipped, via the AMP bundle-size GitHub App.
*/
async function skipBundleSize() {
if (isPullRequestBuild()) {
const commitHash = gitCommitHash();
log(
'Skipping bundle size reporting for commit',
cyan(shortSha(commitHash)) + '...'
);
try {
const response = await requestPost(
url.resolve(
bundleSizeAppBaseUrl,
path.join('commit', commitHash, 'skip')
)
);
checkResponse(response, 'Successfully skipped bundle size reporting.');
} catch (error) {
log(yellow('WARNING:'), 'Could not skip bundle size reporting');
logWithoutTimestamp(error);
return;
}
} else {
log(
yellow('WARNING'),
'Pull requests can be marked as skipped only during CI builds'
);
}
}
/**
* Report the size to the bundle-size GitHub App, to determine size changes.
*/
async function reportBundleSize() {
if (isPullRequestBuild()) {
const baseSha = gitCiMasterBaseline();
const commitHash = gitCommitHash();
log(
'Reporting bundle sizes for commit',
cyan(shortSha(commitHash)),
'using baseline commit',
cyan(shortSha(baseSha)) + '...'
);
try {
const response = await requestPost({
uri: url.resolve(
bundleSizeAppBaseUrl,
path.join('commit', commitHash, 'report')
),
json: true,
body: {
baseSha,
bundleSizes: await getBrotliBundleSizes(),
},
});
checkResponse(response, 'Successfully reported bundle sizes.');
} catch (error) {
log(
yellow('WARNING:'),
'Could not report the bundle sizes for this pull request'
);
logWithoutTimestamp(error);
return;
}
} else {
log(
yellow('WARNING:'),
'Bundle sizes from pull requests can be reported only during CI builds'
);
}
}
/**
* @return {Promise<void>}
*/
async function getLocalBundleSize() {
if (globby.sync(fileGlobs).length === 0) {
log('Could not find runtime files.');
log('Run', cyan('gulp dist --noextensions'), 'and re-run this task.');
process.exitCode = 1;
return;
} else {
log(
'Computing bundle sizes for version',
cyan(internalRuntimeVersion),
'at commit',
cyan(shortSha(gitCommitHash())) + '.'
);
}
await getBrotliBundleSizes();
}
/**
* @return {Promise<void>}
*/
async function bundleSize() {
if (argv.on_skipped_build) {
return skipBundleSize();
} else if (argv.on_push_build) {
return storeBundleSize();
} else if (argv.on_pr_build) {
return reportBundleSize();
} else if (argv.on_local_build) {
return getLocalBundleSize();
} else {
log(red('Called'), cyan('gulp bundle-size'), red('with no task.'));
process.exitCode = 1;
}
}
module.exports = {
bundleSize,
};
bundleSize.description =
'Checks if the minified AMP binary has exceeded its size cap';
bundleSize.flags = {
'on_push_build':
' Store bundle sizes in the AMP build artifacts repo ' +
'(also implies --on_pr_build)',
'on_pr_build': ' Report the bundle sizes for this pull request to GitHub',
'on_skipped_build':
" Set the status of this pull request's bundle " +
'size check in GitHub to `skipped`',
'on_local_build': ' Compute bundle sizes for the locally built runtime',
};