@allons-y/actions-file-diff 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +385 -0
- package/README.md +282 -2
- package/action.yml +80 -0
- package/dist/index.js +30888 -0
- package/package.json +97 -5
- package/src/changes.js +372 -0
- package/src/index.js +18 -0
- package/src/page.js +472 -0
- package/src/publish.js +171 -0
- package/src/render.js +191 -0
- package/src/report-page.client.js +398 -0
- package/src/report-page.css +1115 -0
- package/src/report.js +515 -0
- package/src/utilities.js +141 -0
package/src/report.js
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Copyright 2025 Allons-Y. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
6
|
+
* of the License at <http://www.apache.org/licenses/LICENSE-2.0>
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
import { bytesToSize } from "./utilities.js";
|
|
13
|
+
|
|
14
|
+
/** Default path segment separating a package from its built output. */
|
|
15
|
+
export const DEFAULT_BUILD_DIR = "dist";
|
|
16
|
+
|
|
17
|
+
/** Default main file (relative to the build dir) when package.json has none. */
|
|
18
|
+
export const DEFAULT_MAIN_FILE = "index.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {object} FileEntry
|
|
22
|
+
* @property {string} path Path relative to the measured roots (unique per file).
|
|
23
|
+
* @property {number|undefined} headByteSize Size on the head checkout, undefined when absent.
|
|
24
|
+
* @property {number|undefined} baseByteSize Size on the base checkout, undefined when absent.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @typedef {object} Package
|
|
29
|
+
* @property {string} name Display name (directory immediately before the build dir).
|
|
30
|
+
* @property {string} packageDir Directory containing the build dir, relative to the root path.
|
|
31
|
+
* @property {Map<string, FileEntry>} files Readable filename → sizes.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {object} Section
|
|
36
|
+
* @property {string} name Package display name.
|
|
37
|
+
* @property {string} packageDir Package directory relative to the root path.
|
|
38
|
+
* @property {string} mainFile Resolved main file, relative to the build dir.
|
|
39
|
+
* @property {boolean} hasChange Whether any file in the package differs from base.
|
|
40
|
+
* @property {Map<string, FileEntry>} files Readable filename → sizes.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** Splits a path into segments regardless of separator. */
|
|
44
|
+
const segments = (filepath) =>
|
|
45
|
+
String(filepath ?? "")
|
|
46
|
+
.split(/[\\/]+/)
|
|
47
|
+
.filter(Boolean);
|
|
48
|
+
|
|
49
|
+
/** Basename of a path (last segment). */
|
|
50
|
+
const basename = (filepath) => segments(filepath).at(-1) ?? "";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Escapes a string for literal use inside a RegExp.
|
|
54
|
+
* @param {string} value
|
|
55
|
+
* @returns {string}
|
|
56
|
+
*/
|
|
57
|
+
export function escapeRegExp(value) {
|
|
58
|
+
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Builds the hidden HTML marker that identifies this action's sticky comment.
|
|
63
|
+
* Different comment headers yield different markers so instances can coexist.
|
|
64
|
+
* @param {string} header Comment header text.
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function commentMarker(header) {
|
|
68
|
+
const slug =
|
|
69
|
+
String(header ?? "")
|
|
70
|
+
.replace(/[^a-z0-9]+/gi, "-")
|
|
71
|
+
.replace(/^-+|-+$/g, "")
|
|
72
|
+
.toLowerCase() || "default";
|
|
73
|
+
return `<!-- actions-file-diff:${slug} -->`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Normalizes an extensions input (multiline and/or comma-separated, with or
|
|
78
|
+
* without leading dots) into a set of lowercase extensions without dots.
|
|
79
|
+
* @param {string|string[]} input
|
|
80
|
+
* @returns {Set<string>}
|
|
81
|
+
*/
|
|
82
|
+
export function normalizeExtensions(input = []) {
|
|
83
|
+
const list = Array.isArray(input) ? input : [input];
|
|
84
|
+
return new Set(
|
|
85
|
+
list
|
|
86
|
+
.flatMap((entry) => String(entry ?? "").split(/[,\n]/))
|
|
87
|
+
.map((entry) => entry.trim().replace(/^\.+/, "").toLowerCase())
|
|
88
|
+
.filter(Boolean),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Returns the base extension of a file after stripping `.map`, `.gz` and
|
|
94
|
+
* `.min` layers, lowercase and without the leading dot.
|
|
95
|
+
* @example baseExtension("index.min.css.gz") // "css"
|
|
96
|
+
* @param {string} filepath
|
|
97
|
+
* @returns {string}
|
|
98
|
+
*/
|
|
99
|
+
export function baseExtension(filepath) {
|
|
100
|
+
let name = basename(filepath);
|
|
101
|
+
while (/\.(map|gz)$/i.test(name)) name = name.replace(/\.(map|gz)$/i, "");
|
|
102
|
+
name = name.replace(/\.min$/i, "");
|
|
103
|
+
const match = name.match(/\.([^.]+)$/);
|
|
104
|
+
return match ? match[1].toLowerCase() : "";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Whether a file is reported on its own row (not a map, gzip or minified sibling).
|
|
109
|
+
* @param {string} filepath
|
|
110
|
+
* @returns {boolean}
|
|
111
|
+
*/
|
|
112
|
+
export function isReportedFile(filepath) {
|
|
113
|
+
const name = basename(filepath);
|
|
114
|
+
return !/\.(map|gz)$/i.test(name) && !/\.min(\.|$)/i.test(name);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Name of the minified sibling for a file, or undefined when it has no extension.
|
|
119
|
+
* @param {string} filepath
|
|
120
|
+
* @returns {string|undefined}
|
|
121
|
+
*/
|
|
122
|
+
export function minifiedName(filepath) {
|
|
123
|
+
const match = String(filepath).match(/\.([^./\\]+)$/);
|
|
124
|
+
if (!match) return undefined;
|
|
125
|
+
return filepath.replace(/\.([^./\\]+)$/, ".min.$1");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Name of the gzipped, minified sibling for a file, or undefined when it has no extension.
|
|
130
|
+
* @param {string} filepath
|
|
131
|
+
* @returns {string|undefined}
|
|
132
|
+
*/
|
|
133
|
+
export function gzippedName(filepath) {
|
|
134
|
+
const minified = minifiedName(filepath);
|
|
135
|
+
return minified ? `${minified}.gz` : undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Filters a file map down to the files whose base extension is allowed.
|
|
140
|
+
* An empty allow-list keeps everything.
|
|
141
|
+
* @param {Map<string, number>} fileMap
|
|
142
|
+
* @param {Set<string>|string|string[]} extensions
|
|
143
|
+
* @returns {Map<string, number>}
|
|
144
|
+
*/
|
|
145
|
+
export function filterByExtensions(fileMap, extensions = []) {
|
|
146
|
+
const allowed = extensions instanceof Set ? extensions : normalizeExtensions(extensions);
|
|
147
|
+
if (allowed.size === 0) return new Map(fileMap);
|
|
148
|
+
return new Map([...fileMap].filter(([file]) => allowed.has(baseExtension(file))));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Size counted toward the total for a file: its `.min.<ext>` sibling when
|
|
153
|
+
* that sibling exists in the same map, otherwise its own size.
|
|
154
|
+
* @param {string} filepath
|
|
155
|
+
* @param {Map<string, number>} fileMap
|
|
156
|
+
* @returns {number}
|
|
157
|
+
*/
|
|
158
|
+
export function countedSize(filepath, fileMap) {
|
|
159
|
+
const minified = minifiedName(filepath);
|
|
160
|
+
if (minified && fileMap.has(minified)) return fileMap.get(minified) ?? 0;
|
|
161
|
+
return fileMap.get(filepath) ?? 0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Total size of a map: the sum of counted sizes over all reported files.
|
|
166
|
+
* @param {Map<string, number>} fileMap
|
|
167
|
+
* @returns {number}
|
|
168
|
+
*/
|
|
169
|
+
export function totalSize(fileMap) {
|
|
170
|
+
return [...fileMap.keys()].reduce((sum, file) => (isReportedFile(file) ? sum + countedSize(file, fileMap) : sum), 0);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Splits a relative file path into its package and readable filename using
|
|
175
|
+
* the build dir segment. Paths without the segment fall back to the parent
|
|
176
|
+
* directory as the package and the basename as the filename.
|
|
177
|
+
* @param {string} filepath
|
|
178
|
+
* @param {string} [buildDir]
|
|
179
|
+
* @returns {{ packageName: string, packageDir: string, readableFilename: string }}
|
|
180
|
+
*/
|
|
181
|
+
export function splitPath(filepath, buildDir = DEFAULT_BUILD_DIR) {
|
|
182
|
+
const parts = segments(filepath);
|
|
183
|
+
const idx = buildDir ? parts.indexOf(buildDir) : -1;
|
|
184
|
+
|
|
185
|
+
if (idx !== -1 && idx < parts.length - 1) {
|
|
186
|
+
const packagePath = parts.slice(0, idx);
|
|
187
|
+
return {
|
|
188
|
+
packageName: packagePath.at(-1) ?? ".",
|
|
189
|
+
packageDir: packagePath.join("/") || ".",
|
|
190
|
+
readableFilename: parts.slice(idx + 1).join("/"),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const dirParts = parts.slice(0, -1);
|
|
195
|
+
return {
|
|
196
|
+
packageName: dirParts.at(-1) ?? ".",
|
|
197
|
+
packageDir: dirParts.join("/") || ".",
|
|
198
|
+
readableFilename: parts.at(-1) ?? "",
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Groups head and base file maps into packages keyed by package directory.
|
|
204
|
+
* @param {Map<string, number>} headMap
|
|
205
|
+
* @param {Map<string, number>} [baseMap]
|
|
206
|
+
* @param {{ buildDir?: string }} [options]
|
|
207
|
+
* @returns {Map<string, Package>}
|
|
208
|
+
*/
|
|
209
|
+
export function groupByPackage(headMap, baseMap = new Map(), { buildDir = DEFAULT_BUILD_DIR } = {}) {
|
|
210
|
+
const packages = new Map();
|
|
211
|
+
|
|
212
|
+
const add = (filepath) => {
|
|
213
|
+
const { packageName, packageDir, readableFilename } = splitPath(filepath, buildDir);
|
|
214
|
+
if (!packages.has(packageDir)) packages.set(packageDir, { name: packageName, packageDir, files: new Map() });
|
|
215
|
+
const { files } = packages.get(packageDir);
|
|
216
|
+
if (files.has(readableFilename)) return;
|
|
217
|
+
files.set(readableFilename, { path: filepath, headByteSize: headMap.get(filepath), baseByteSize: baseMap.get(filepath) });
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
[...headMap.keys(), ...baseMap.keys()].forEach(add);
|
|
221
|
+
|
|
222
|
+
return new Map([...packages].sort(([a], [b]) => a.localeCompare(b)));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Resolves the main file for a package. When enabled and `<packageDir>/package.json`
|
|
227
|
+
* declares a string `main`, it is used (stripped of everything up to and including
|
|
228
|
+
* `<buildDir>/`); otherwise the fallback is returned. A malformed package.json
|
|
229
|
+
* logs a warning and falls back.
|
|
230
|
+
* @param {object} options
|
|
231
|
+
* @param {string} [options.rootPath]
|
|
232
|
+
* @param {string} [options.packageDir]
|
|
233
|
+
* @param {string} [options.buildDir]
|
|
234
|
+
* @param {string} [options.mainFile]
|
|
235
|
+
* @param {boolean} [options.readPackageJson]
|
|
236
|
+
* @param {{ warning?: Function }} [options.core]
|
|
237
|
+
* @returns {string}
|
|
238
|
+
*/
|
|
239
|
+
export function resolveMainFile({ rootPath = ".", packageDir = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
|
|
240
|
+
if (!readPackageJson) return mainFile;
|
|
241
|
+
|
|
242
|
+
const packagePath = join(rootPath, packageDir, "package.json");
|
|
243
|
+
if (!existsSync(packagePath)) return mainFile;
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const { main } = JSON.parse(readFileSync(packagePath, "utf8")) ?? {};
|
|
247
|
+
if (typeof main !== "string" || !main.trim()) return mainFile;
|
|
248
|
+
const stripper = new RegExp(`^(?:.*/)?${escapeRegExp(buildDir)}/`);
|
|
249
|
+
return main.trim().replace(/\\/g, "/").replace(stripper, "");
|
|
250
|
+
} catch (error) {
|
|
251
|
+
core?.warning?.(`Unable to read ${packagePath}: ${error.message}. Falling back to "${mainFile}".`);
|
|
252
|
+
return mainFile;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Byte difference between two sizes, treating missing values as zero.
|
|
258
|
+
* @param {number|undefined} v1
|
|
259
|
+
* @param {number|undefined} v0
|
|
260
|
+
* @returns {number}
|
|
261
|
+
*/
|
|
262
|
+
export const difference = (v1, v0) => (v1 ?? 0) - (v0 ?? 0);
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Whether a file exists on base but not on head.
|
|
266
|
+
* @param {number|undefined} head
|
|
267
|
+
* @param {number|undefined} base
|
|
268
|
+
* @returns {boolean}
|
|
269
|
+
*/
|
|
270
|
+
export const isRemoved = (head, base) => head == null && base != null;
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Whether a file exists on head but not on base.
|
|
274
|
+
* @param {number|undefined} head
|
|
275
|
+
* @param {number|undefined} base
|
|
276
|
+
* @returns {boolean}
|
|
277
|
+
*/
|
|
278
|
+
export const isNew = (head, base) => head != null && base == null;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Formats a size change with a direction indicator.
|
|
282
|
+
* @param {number|undefined} v1 Head size.
|
|
283
|
+
* @param {number|undefined} v0 Base size.
|
|
284
|
+
* @returns {string}
|
|
285
|
+
*/
|
|
286
|
+
export function printChange(v1, v0) {
|
|
287
|
+
const d = difference(v1, v0);
|
|
288
|
+
if (d === 0) return "-";
|
|
289
|
+
return `${d > 0 ? "🔴 ⬆" : "🟢 ⬇"} ${bytesToSize(Math.abs(d))}`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Formats a percentage change; empty when there is no base value or no head value.
|
|
294
|
+
* @param {number|undefined} v1 Head size.
|
|
295
|
+
* @param {number|undefined} v0 Base size.
|
|
296
|
+
* @returns {string}
|
|
297
|
+
*/
|
|
298
|
+
export function printPercentChange(v1, v0) {
|
|
299
|
+
if (!v0 || v1 == null) return "";
|
|
300
|
+
const delta = ((v1 - v0) / v0) * 100;
|
|
301
|
+
if (delta === 0) return "no change";
|
|
302
|
+
return `${delta.toFixed(2)}%`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Builds the table row cells for a reported file. The "Compared to base"
|
|
307
|
+
* cell is only present when there is a base.
|
|
308
|
+
* @param {object} options
|
|
309
|
+
* @param {string} options.readableFilename
|
|
310
|
+
* @param {Map<string, FileEntry>} options.files Package file map.
|
|
311
|
+
* @param {boolean} options.hasBase
|
|
312
|
+
* @param {boolean} [options.isMainFile]
|
|
313
|
+
* @returns {string[]}
|
|
314
|
+
*/
|
|
315
|
+
export function buildFileRow({ readableFilename, files, hasBase, isMainFile = false }) {
|
|
316
|
+
const { headByteSize, baseByteSize } = files.get(readableFilename) ?? {};
|
|
317
|
+
const removed = hasBase && isRemoved(headByteSize, baseByteSize);
|
|
318
|
+
const added = hasBase && isNew(headByteSize, baseByteSize);
|
|
319
|
+
|
|
320
|
+
const siblingCell = (name) => {
|
|
321
|
+
const sibling = name ? files.get(name) : undefined;
|
|
322
|
+
if (!sibling) return " - ";
|
|
323
|
+
if (hasBase && isRemoved(sibling.headByteSize, sibling.baseByteSize)) return "🚨 deleted/moved";
|
|
324
|
+
if (sibling.headByteSize == null) return " - ";
|
|
325
|
+
if (hasBase && isNew(sibling.headByteSize, sibling.baseByteSize)) return `🆕 ${bytesToSize(sibling.headByteSize)}`;
|
|
326
|
+
return bytesToSize(sibling.headByteSize);
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
let size;
|
|
330
|
+
let delta;
|
|
331
|
+
if (removed) {
|
|
332
|
+
size = "🚨 deleted/moved";
|
|
333
|
+
delta = `⬇ ${bytesToSize(baseByteSize)}`;
|
|
334
|
+
} else {
|
|
335
|
+
size = bytesToSize(headByteSize);
|
|
336
|
+
if (added) delta = `🆕 ${bytesToSize(headByteSize)}`;
|
|
337
|
+
else {
|
|
338
|
+
delta = printChange(headByteSize, baseByteSize);
|
|
339
|
+
const percent = printPercentChange(headByteSize, baseByteSize);
|
|
340
|
+
if (delta !== "-" && percent) delta += ` (${percent})`;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const minSize = removed ? " - " : siblingCell(minifiedName(readableFilename));
|
|
345
|
+
const gzipSize = removed ? " - " : siblingCell(gzippedName(readableFilename));
|
|
346
|
+
|
|
347
|
+
return [isMainFile ? `**${readableFilename}**` : readableFilename, size, minSize, gzipSize, ...(hasBase ? [delta] : [])];
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Turns packages into report sections. A section is included when any file
|
|
352
|
+
* differs between head and base, or always when there is no base.
|
|
353
|
+
* @param {Map<string, Package>} packages
|
|
354
|
+
* @param {object} options
|
|
355
|
+
* @param {boolean} options.hasBase
|
|
356
|
+
* @param {string} [options.rootPath]
|
|
357
|
+
* @param {string} [options.buildDir]
|
|
358
|
+
* @param {string} [options.mainFile]
|
|
359
|
+
* @param {boolean} [options.readPackageJson]
|
|
360
|
+
* @param {{ warning?: Function }} [options.core]
|
|
361
|
+
* @returns {Section[]}
|
|
362
|
+
*/
|
|
363
|
+
export function buildSections(packages, { hasBase, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
|
|
364
|
+
const sections = [];
|
|
365
|
+
|
|
366
|
+
packages.forEach(({ name, packageDir, files }) => {
|
|
367
|
+
if (files.size === 0) return;
|
|
368
|
+
const hasChange = [...files.values()].some(({ headByteSize, baseByteSize }) => headByteSize !== baseByteSize);
|
|
369
|
+
if (hasBase && !hasChange) return;
|
|
370
|
+
|
|
371
|
+
sections.push({
|
|
372
|
+
name,
|
|
373
|
+
packageDir,
|
|
374
|
+
hasChange,
|
|
375
|
+
mainFile: resolveMainFile({ rootPath, packageDir, buildDir, mainFile, readPackageJson, core }),
|
|
376
|
+
files,
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
return sections;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Renders a header and rows as markdown table lines. */
|
|
384
|
+
const toTable = (header, rows) => [header, header.map(() => "-"), ...rows].map((row) => `| ${row.join(" | ")} |`);
|
|
385
|
+
|
|
386
|
+
/** Characters reserved for the fixed parts of the report (summary lines, footer, wrappers). */
|
|
387
|
+
const FIXED_OVERHEAD = 1500;
|
|
388
|
+
|
|
389
|
+
/** Share of the length budget the main-file summary table may use. */
|
|
390
|
+
const SUMMARY_SHARE = 0.25;
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Takes table rows while their rendered length fits in the budget.
|
|
394
|
+
* @param {string[][]} rows
|
|
395
|
+
* @param {number} budget Characters available.
|
|
396
|
+
* @returns {{ kept: string[][], used: number }}
|
|
397
|
+
*/
|
|
398
|
+
export function fitRows(rows, budget) {
|
|
399
|
+
const kept = [];
|
|
400
|
+
let used = 0;
|
|
401
|
+
for (const row of rows) {
|
|
402
|
+
const length = row.join(" | ").length + 6;
|
|
403
|
+
if (used + length > budget) break;
|
|
404
|
+
used += length;
|
|
405
|
+
kept.push(row);
|
|
406
|
+
}
|
|
407
|
+
return { kept, used };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Builds the full report: summary lines, detail markdown lines, totals and
|
|
412
|
+
* the has-changed flag. Totals use the same formula as the `total-size` and
|
|
413
|
+
* `has-changed` outputs so the two can never disagree.
|
|
414
|
+
* @param {object} options
|
|
415
|
+
* @param {Map<string, number>} options.headMap Relative path → size on head.
|
|
416
|
+
* @param {Map<string, number>} [options.baseMap] Relative path → size on base.
|
|
417
|
+
* @param {boolean} [options.hasBase] Defaults to whether baseMap has entries.
|
|
418
|
+
* @param {string} [options.rootPath] Head root, used to locate package.json files.
|
|
419
|
+
* @param {string} [options.buildDir]
|
|
420
|
+
* @param {string} [options.mainFile]
|
|
421
|
+
* @param {boolean} [options.readPackageJson]
|
|
422
|
+
* @param {string|string[]} [options.extensions]
|
|
423
|
+
* @param {number} [options.maxLength] Soft cap on `text` length in characters. Rows past it are replaced by a note, so the report fits in a pull request comment.
|
|
424
|
+
* @param {{ warning?: Function }} [options.core]
|
|
425
|
+
* @returns {{ summary: string[], markdown: string[], text: string, headTotal: number, baseTotal: number, hasBase: boolean, hasChanged: boolean, sections: Section[], omitted: { files: number, packages: number } }}
|
|
426
|
+
*/
|
|
427
|
+
export function buildReport({ headMap = new Map(), baseMap = new Map(), hasBase = baseMap.size > 0, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, extensions = [], maxLength = Infinity, core } = {}) {
|
|
428
|
+
const allowed = normalizeExtensions(extensions);
|
|
429
|
+
const head = filterByExtensions(headMap, allowed);
|
|
430
|
+
const base = hasBase ? filterByExtensions(baseMap, allowed) : new Map();
|
|
431
|
+
|
|
432
|
+
const headTotal = totalSize(head);
|
|
433
|
+
const baseTotal = hasBase ? totalSize(base) : 0;
|
|
434
|
+
const hasChanged = hasBase && headTotal !== baseTotal;
|
|
435
|
+
|
|
436
|
+
const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, rootPath, buildDir, mainFile, readPackageJson, core });
|
|
437
|
+
|
|
438
|
+
const summary = ["### Summary", `**Total size**: ${bytesToSize(headTotal)}<sup>*</sup>`];
|
|
439
|
+
const markdown = [];
|
|
440
|
+
const omitted = { files: 0, packages: 0 };
|
|
441
|
+
|
|
442
|
+
if (sections.length === 0) {
|
|
443
|
+
summary.push("", "🎉 No changes detected in any packages");
|
|
444
|
+
} else {
|
|
445
|
+
const tableHead = ["Filename", "Head", "Minified", "Gzipped", ...(hasBase ? ["Compared to base"] : [])];
|
|
446
|
+
|
|
447
|
+
const summaryRows = [];
|
|
448
|
+
const tables = sections.map(({ name, mainFile: packageMain, files }) => {
|
|
449
|
+
const rows = [];
|
|
450
|
+
[...files.keys()].sort().forEach((readableFilename) => {
|
|
451
|
+
if (!isReportedFile(readableFilename)) return;
|
|
452
|
+
const isMainFile = readableFilename === packageMain;
|
|
453
|
+
const row = buildFileRow({ readableFilename, files, hasBase, isMainFile });
|
|
454
|
+
if (isMainFile) summaryRows.push([name, ...row.slice(1)]);
|
|
455
|
+
rows.push(row);
|
|
456
|
+
});
|
|
457
|
+
return { name, rows };
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
let budget = maxLength - FIXED_OVERHEAD;
|
|
461
|
+
const summaryHead = ["Package", "Size", "Minified", "Gzipped", ...(hasBase ? ["Δ"] : [])];
|
|
462
|
+
const summaryFit = fitRows(summaryRows, Math.max(0, budget * SUMMARY_SHARE));
|
|
463
|
+
budget -= summaryFit.used;
|
|
464
|
+
|
|
465
|
+
tables.forEach(({ name, rows }) => {
|
|
466
|
+
const header = ["", `#### ${name}`, "", ...toTable(tableHead, [])];
|
|
467
|
+
const headerLength = header.join("\n").length + 1;
|
|
468
|
+
if (budget < headerLength + 200) {
|
|
469
|
+
omitted.packages++;
|
|
470
|
+
omitted.files += rows.length;
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
budget -= headerLength;
|
|
474
|
+
const { kept, used } = fitRows(rows, budget);
|
|
475
|
+
budget -= used;
|
|
476
|
+
markdown.push("", `#### ${name}`, "", ...toTable(tableHead, kept));
|
|
477
|
+
if (kept.length < rows.length) {
|
|
478
|
+
omitted.files += rows.length - kept.length;
|
|
479
|
+
markdown.push("", `<em>… ${rows.length - kept.length} more ${rows.length - kept.length === 1 ? "file" : "files"} not shown.</em>`);
|
|
480
|
+
}
|
|
481
|
+
});
|
|
482
|
+
if (omitted.packages > 0) markdown.push("", `<em>… ${omitted.packages} more ${omitted.packages === 1 ? "package" : "packages"} not shown.</em>`);
|
|
483
|
+
|
|
484
|
+
if (!hasBase) {
|
|
485
|
+
summary.push("No base branch to compare against.", "");
|
|
486
|
+
} else if (hasChanged) {
|
|
487
|
+
const percent = printPercentChange(headTotal, baseTotal);
|
|
488
|
+
summary.push(`**Total change (Δ)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${sections.length > 1 ? ` Other changes can be found in the collapsed <a href="#details">Details</a> section below.` : ""}</em></small>`, "");
|
|
489
|
+
} else {
|
|
490
|
+
summary.push("✅ **No change in file sizes**", "");
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (sections.length > 1) {
|
|
494
|
+
markdown.unshift('<a name="details"></a>', "<details>", "<summary><b>File change details</b></summary>", "");
|
|
495
|
+
markdown.push("", "</details>");
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (summaryFit.kept.length > 0) summary.push(...toTable(summaryHead, summaryFit.kept));
|
|
499
|
+
if (summaryFit.kept.length < summaryRows.length) summary.push("", `<em>… ${summaryRows.length - summaryFit.kept.length} more packages not shown.</em>`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
markdown.push("", "<small>", "* <em>Size is the sum of all reported files, using the minified size where one exists.</em><br/>", "* <em>An ASCII character in UTF-8 is 8 bits or 1 byte.</em>", "</small>");
|
|
503
|
+
|
|
504
|
+
return {
|
|
505
|
+
summary,
|
|
506
|
+
markdown,
|
|
507
|
+
text: [summary.join("\n"), markdown.join("\n")].join("\n\n"),
|
|
508
|
+
headTotal,
|
|
509
|
+
baseTotal,
|
|
510
|
+
hasBase,
|
|
511
|
+
hasChanged,
|
|
512
|
+
sections,
|
|
513
|
+
omitted,
|
|
514
|
+
};
|
|
515
|
+
}
|
package/src/utilities.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Copyright 2025 Allons-Y. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
6
|
+
* of the License at <http://www.apache.org/licenses/LICENSE-2.0>
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, lstatSync, readdirSync, statSync } from "node:fs";
|
|
10
|
+
import { join, relative } from "node:path";
|
|
11
|
+
|
|
12
|
+
import { create } from "@actions/glob";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Lists every file under a path (for debugging an empty glob) and then throws.
|
|
16
|
+
* @param {string} path
|
|
17
|
+
* @param {string[]} pattern
|
|
18
|
+
* @param {{ core: object }} options
|
|
19
|
+
* @throws {Error} Always, describing the unmatched glob.
|
|
20
|
+
*/
|
|
21
|
+
function debugEmptyDirectory(path, pattern, { core }) {
|
|
22
|
+
function reportOnDirectoryFiles(p, { rootDir = p }) {
|
|
23
|
+
readdirSync(p, { withFileTypes: true }).forEach((dirent) => {
|
|
24
|
+
if (dirent.name.startsWith(".")) return;
|
|
25
|
+
if (dirent.isFile()) {
|
|
26
|
+
const file = join(p, dirent.name);
|
|
27
|
+
core.info(`- ${relative(rootDir, file)} | ${bytesToSize(statSync(file).size)}`);
|
|
28
|
+
} else if (dirent.isDirectory()) {
|
|
29
|
+
if (dirent.name === "node_modules") return;
|
|
30
|
+
const dir = join(p, dirent.name);
|
|
31
|
+
core.info(`${relative(rootDir, dir)}/`);
|
|
32
|
+
reportOnDirectoryFiles(dir, { rootDir });
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
core.startGroup(`All files in ${path}`);
|
|
38
|
+
reportOnDirectoryFiles(path, {});
|
|
39
|
+
core.endGroup();
|
|
40
|
+
|
|
41
|
+
throw new Error(`No files found matching the glob pattern: ${pattern.map((p) => join(path, p)).join(", ")}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Prefixes each glob line with the root path, preserving `!` negations and
|
|
46
|
+
* dropping empty lines.
|
|
47
|
+
* @param {string} rootPath
|
|
48
|
+
* @param {string[]} patterns
|
|
49
|
+
* @returns {string[]}
|
|
50
|
+
*/
|
|
51
|
+
export function globPatterns(rootPath, patterns = []) {
|
|
52
|
+
return patterns
|
|
53
|
+
.map((pattern) => String(pattern ?? "").trim())
|
|
54
|
+
.filter(Boolean)
|
|
55
|
+
.map((pattern) => (pattern.startsWith("!") ? `!${join(rootPath, pattern.slice(1))}` : join(rootPath, pattern)));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Units above bytes; sub-KB sizes are shown in KB too. */
|
|
59
|
+
const UNITS = ["KB", "MB", "GB", "TB"];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Formats a byte count as a human readable size using 1024-based units. The
|
|
63
|
+
* unit is chosen after rounding, so 1,048,575 bytes reads "1.00 MB", not "1024.00 KB".
|
|
64
|
+
* @param {number|undefined|null} bytes
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function bytesToSize(bytes) {
|
|
68
|
+
if (bytes === 0) return "0";
|
|
69
|
+
if (!bytes) return "-";
|
|
70
|
+
|
|
71
|
+
let value = bytes / 1024;
|
|
72
|
+
if (bytes < 1024) return value.toFixed(2) === "0.00" ? "< 0.01 KB" : `${value.toFixed(2)} KB`;
|
|
73
|
+
|
|
74
|
+
let unit = 0;
|
|
75
|
+
while (unit < UNITS.length - 1 && Number(value.toFixed(2)) >= 1024) {
|
|
76
|
+
value /= 1024;
|
|
77
|
+
unit++;
|
|
78
|
+
}
|
|
79
|
+
return `${value.toFixed(2)} ${UNITS[unit]}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Maps over items with at most `limit` calls in flight, preserving order.
|
|
84
|
+
* @template T, R
|
|
85
|
+
* @param {T[]} items
|
|
86
|
+
* @param {number} limit
|
|
87
|
+
* @param {(item: T, index: number) => Promise<R>} fn
|
|
88
|
+
* @returns {Promise<R[]>}
|
|
89
|
+
*/
|
|
90
|
+
export async function mapLimit(items, limit, fn) {
|
|
91
|
+
const results = new Array(items.length);
|
|
92
|
+
let next = 0;
|
|
93
|
+
const worker = async () => {
|
|
94
|
+
while (next < items.length) {
|
|
95
|
+
const index = next++;
|
|
96
|
+
results[index] = await fn(items[index], index);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));
|
|
100
|
+
return results;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Globs a root path and returns a map of relative file path → size in bytes.
|
|
105
|
+
* Only regular files are returned: symbolic links are never followed, because
|
|
106
|
+
* the tree may come from an untrusted pull request and a link could point at
|
|
107
|
+
* files outside the checkout. A required root must exist and match at least
|
|
108
|
+
* one file (otherwise throws); an optional root that is missing or unmatched
|
|
109
|
+
* yields an empty map.
|
|
110
|
+
* @param {string} rootPath
|
|
111
|
+
* @param {string[]} [patterns]
|
|
112
|
+
* @param {{ core: object, required?: boolean }} options
|
|
113
|
+
* @returns {Promise<Map<string, number>>}
|
|
114
|
+
*/
|
|
115
|
+
export async function fetchFilesAndSizes(rootPath, patterns = [], { core, required = true }) {
|
|
116
|
+
if (!rootPath || !existsSync(rootPath)) {
|
|
117
|
+
if (required) throw new Error(`The provided path does not exist in the workspace: "${rootPath}"`);
|
|
118
|
+
return new Map();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const globber = await create(globPatterns(rootPath, patterns).join("\n"), { matchDirectories: false, followSymbolicLinks: false });
|
|
122
|
+
|
|
123
|
+
const files = new Map();
|
|
124
|
+
let links = 0;
|
|
125
|
+
(await globber.glob()).forEach((f) => {
|
|
126
|
+
const stat = lstatSync(f, { throwIfNoEntry: false });
|
|
127
|
+
if (stat?.isFile()) files.set(relative(rootPath, f), stat.size);
|
|
128
|
+
else if (stat?.isSymbolicLink()) links++;
|
|
129
|
+
});
|
|
130
|
+
if (links > 0) core.warning(`From ${rootPath}, ignored ${links} symbolic link${links === 1 ? "" : "s"}; only regular files are measured.`);
|
|
131
|
+
|
|
132
|
+
if (files.size === 0) {
|
|
133
|
+
if (required) debugEmptyDirectory(rootPath, patterns, { core });
|
|
134
|
+
core.warning(`From ${rootPath}, no files matched the glob pattern ${patterns.join(", ")}; continuing without a base.`);
|
|
135
|
+
return new Map();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
core.info(`From ${rootPath}, found ${files.size} files matching the glob pattern ${patterns.join(", ")}.`);
|
|
139
|
+
|
|
140
|
+
return files;
|
|
141
|
+
}
|