-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
278 lines (234 loc) · 8.51 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
import * as fs from 'node:fs';
import * as zlib from 'node:zlib';
import * as util from 'node:util';
import {getInput, setFailed, info} from '@actions/core';
import * as github from '@actions/github';
import {exec} from '@actions/exec';
import {globby} from 'globby';
import prettyBytes from 'pretty-bytes';
const gzip = util.promisify(zlib.gzip);
const brotliCompress = util.promisify(zlib.brotliCompress);
type BranchStats = {
totalSize: number;
totalGzip: number;
totalBrotli: number;
files: {
[key: string]: {
size: number;
gzip: number;
brotli: number;
};
};
};
const commentHash = '<!-- @alex-page was here -->';
const getFileStats = async (
file: string,
branch: string,
branchStats: BranchStats,
) => {
const stats = await fs.promises.stat(file);
const fileContents = await fs.promises.readFile(file);
const gzipFile = await gzip(fileContents);
const gzipSize = Buffer.byteLength(gzipFile);
const brotliFile = await brotliCompress(fileContents);
const brotliSize = Buffer.byteLength(brotliFile);
// Remove the GitHub file path from the repo file path
const filePath = file.split(`${branch}/`).slice(1)[0]!;
branchStats.totalSize += stats.size;
branchStats.totalGzip += gzipSize;
branchStats.totalBrotli += brotliSize;
branchStats.files[filePath] = {
size: stats.size,
gzip: gzipSize,
brotli: brotliSize,
};
};
const getBranchStats = async (
branch: string,
dirGlob: string,
script?: string,
): Promise<BranchStats> => {
info(`[${branch}] copy repo and git checkout `);
const tempDir = '.filediff';
const cwd = `../${tempDir}/${branch}`;
await fs.promises.cp('.', cwd, {recursive: true});
await exec('git', ['fetch', 'origin', branch], {cwd});
await exec('git', ['checkout', branch], {cwd});
if (script) {
info(`[${branch}] Running ${script}`);
const commands = script.split('&&').map((cmd) => cmd.trim());
for (const cmd of commands) {
const [cmdName, ...cmdArgs] = cmd.split(/\s+/);
await exec(cmdName!, cmdArgs, {cwd});
}
}
const files = await globby(dirGlob.split(','), {cwd, absolute: true});
info(`[${branch}] Getting file stats for ${files.length} files`);
const branchStats: BranchStats = {
totalSize: 0,
totalBrotli: 0,
totalGzip: 0,
files: {},
};
await Promise.all(
files.map((file) => getFileStats(file, branch, branchStats)),
);
info(`[${branch}] Completed file stats`);
return branchStats;
};
const getCommonStringStart = (strings: string[]): string => {
if (strings.length < 2) return '';
const sortedStrings = strings.slice().sort();
// The first and last strings are the most different
const first = sortedStrings[0]!;
const last = sortedStrings[sortedStrings.length - 1]!;
for (let i = 0; i < first.length; i++) {
if (first[i] !== last[i]) return first.slice(0, i);
}
return first;
};
export const getStatComment = (
targetStats: BranchStats,
prStats: BranchStats,
fileDetailsOpen: Boolean,
): string => {
const fileTotals = {
changed: 0,
removed: 0,
added: 0,
};
const getDiff = (a: number, b: number) => prettyBytes(a - b, {signed: true});
const totalDiff = {
size: getDiff(prStats.totalSize, targetStats.totalSize),
gzip: getDiff(prStats.totalGzip, targetStats.totalGzip),
brotli: getDiff(prStats.totalBrotli, targetStats.totalBrotli),
};
const allFilePaths = new Set([
...Object.keys(prStats.files),
...Object.keys(targetStats.files),
]);
const commonStart = getCommonStringStart([...allFilePaths]);
const commonFilePath = commonStart.slice(0, commonStart.lastIndexOf('/') + 1);
let fileColumns: string[] = [];
Object.entries(prStats.files).forEach(([filePath, {size, brotli, gzip}]) => {
const targetFile = targetStats.files[filePath];
if (!targetFile) {
// File in PR is not in target branch (added)
fileTotals.added = fileTotals.added + 1;
fileColumns.push(
`| <sub>${filePath.slice(commonFilePath.length)}</sub> | <sub>${prettyBytes(size)} \`${prettyBytes(size, {signed: true})}\`</sub> | <sub>${prettyBytes(gzip)} \`${prettyBytes(gzip, {signed: true})}\`</sub> | <sub>${prettyBytes(brotli)} \`${prettyBytes(brotli, {signed: true})}\`</sub> |`,
);
} else if (size !== targetFile.size) {
// File in PR is in target branch
fileTotals.changed = fileTotals.changed + 1;
fileColumns.push(
`| <sub>${filePath.slice(commonFilePath.length)}</sub> | <sub>${prettyBytes(size)} \`${getDiff(size, targetFile.size)}\`</sub> | <sub>${prettyBytes(gzip)} \`${getDiff(gzip, targetFile.gzip)}\`</sub> | <sub>${prettyBytes(brotli)} \`${getDiff(brotli, targetFile.brotli)}\`</sub> |`,
);
}
});
Object.entries(targetStats.files).forEach(
([filePath, {size, brotli, gzip}]) => {
const prFile = prStats.files[filePath];
if (prFile === undefined) {
fileTotals.removed = fileTotals.removed + 1;
fileColumns.push(
`| <sub>~${filePath.slice(commonFilePath.length)}~</sub> | <sub>0 B \`${prettyBytes(-1 * size, {signed: true})}\`</sub> | <sub>0 B \`${prettyBytes(-1 * gzip, {signed: true})}\`</sub> | <sub>0 B \`${prettyBytes(-1 * brotli, {signed: true})}\`</sub> |`,
);
}
},
);
const pluralize = (count: number, single: string, plural: string) =>
count === 1 ? single : plural;
const detailsSummaryText = [];
if (fileTotals.changed !== 0)
detailsSummaryText.push(
`${fileTotals.changed} ${pluralize(
fileTotals.changed,
'file changed',
'files changed',
)}`,
);
if (fileTotals.added !== 0)
detailsSummaryText.push(
`${fileTotals.added} ${pluralize(fileTotals.added, 'file added', 'files added')}`,
);
if (fileTotals.removed !== 0)
detailsSummaryText.push(
`${fileTotals.removed} ${pluralize(
fileTotals.removed,
'file removed',
'files removed',
)}`,
);
return `${commentHash}\n<sub>**[[filediff]](https://github.com/shopify/filediff)** The total bytes ${totalDiff.size.startsWith('+') ? 'added' : 'removed'} are:</sub>
| uncompressed | gzip | brotli |
|:--- |:--- |:--- |
| <sub>${prettyBytes(prStats.totalSize)} \`${totalDiff.size}\`</sub> | <sub>${prettyBytes(prStats.totalGzip)} \`${totalDiff.gzip}\`</sub> | <sub>${prettyBytes(prStats.totalBrotli)} \`${totalDiff.brotli}\`</sub> |
<details${fileDetailsOpen ? ' open' : ''}>
<summary><sub>${detailsSummaryText.join(', ')}</sub></summary>
${commonFilePath ? `<sub>All changed files are in ${commonFilePath}</sub>` : ''}
| Filename | size | gzip | brotli |
|:--- | ---:| ---:| ---:|
${fileColumns.join('\n')}
</details>
`;
};
const run = async () => {
try {
info('Creating filediff comment');
if (!process.env.GITHUB_TOKEN) {
throw new Error(`Missing required environment variables: GITHUB_TOKEN`);
}
const octokit = github.getOctokit(process.env.GITHUB_TOKEN);
const {payload} = github.context;
if (!payload.repository || !payload.pull_request) return;
const prBranch = payload.pull_request.head.ref;
const prNumber = payload.pull_request.number;
const owner = payload.repository.owner.login;
const repo = payload.repository.name;
const targetBranch = getInput('target_branch', {required: true});
const dirGlob = getInput('dir_glob', {required: true});
const script = getInput('pre_diff_script');
const fileDetailsOpen = getInput('file_details_open');
const replaceComment = getInput('replace_comment');
const [targetStats, prStats] = await Promise.all([
getBranchStats(targetBranch, dirGlob, script),
getBranchStats(prBranch, dirGlob, script),
]);
// No changes found, exit early
if (targetStats.totalSize === prStats.totalSize) return;
if (replaceComment === 'true') {
// Replace existing filediff comment
const comments = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: prNumber,
});
for (let comment of comments.data) {
if (comment.body?.startsWith(commentHash)) {
await octokit.rest.issues.deleteComment({
owner,
repo,
comment_id: comment.id,
});
}
}
}
const commentBody = getStatComment(
targetStats,
prStats,
fileDetailsOpen === 'true',
);
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body: commentBody,
});
} catch (error) {
setFailed(
error instanceof Error ? error.message : 'An unexpected error occurred',
);
}
};
run();