@allons-y/actions-file-diff 0.2.0 → 0.3.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/README.md +61 -27
- package/dist/index.js +208 -49
- package/package.json +16 -37
- package/action.yml +0 -80
- package/src/changes.js +0 -372
- package/src/index.js +0 -18
- package/src/page.js +0 -472
- package/src/publish.js +0 -171
- package/src/render.js +0 -191
- package/src/report-page.client.js +0 -398
- package/src/report-page.css +0 -1115
- package/src/report.js +0 -515
- package/src/utilities.js +0 -141
package/src/page.js
DELETED
|
@@ -1,472 +0,0 @@
|
|
|
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 { readFileSync } from "node:fs";
|
|
10
|
-
|
|
11
|
-
import { diffWordsWithSpace } from "diff";
|
|
12
|
-
|
|
13
|
-
import { MAX_IMAGE_SIZE } from "./changes.js";
|
|
14
|
-
import { barScale, escapeHtml as esc } from "./render.js";
|
|
15
|
-
import css from "./report-page.css";
|
|
16
|
-
import client from "./report-page.client.js";
|
|
17
|
-
import { bytesToSize } from "./utilities.js";
|
|
18
|
-
|
|
19
|
-
/** Longest line (chars) that gets word-level highlighting. */
|
|
20
|
-
const INTRALINE_LIMIT = 1000;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @typedef {object} PageOptions
|
|
24
|
-
* @property {string} title
|
|
25
|
-
* @property {import("./render.js").SizeRow[]} rows
|
|
26
|
-
* @property {boolean} hasBase
|
|
27
|
-
* @property {ReturnType<import("./changes.js").collectChanges>} changes
|
|
28
|
-
* @property {{ headTotal: number, baseTotal: number }} totals
|
|
29
|
-
* @property {Map<string, { head?: string, base?: string }>} [imageUrls] File → relative image URLs.
|
|
30
|
-
* @property {string} [context] Line under the title (e.g. PR and commit).
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
/** Inline SVG icons (decorative; always paired with text). */
|
|
34
|
-
const ICON = {
|
|
35
|
-
logo: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="12" height="12" rx="3" fill="currentColor" opacity=".35"/><rect x="9" y="9" width="12" height="12" rx="3" fill="currentColor"/></svg>',
|
|
36
|
-
side: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="8" height="14" rx="1.5"/><rect x="13" y="5" width="8" height="14" rx="1.5"/></svg>',
|
|
37
|
-
overlay: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="13" height="13" rx="1.5"/><rect x="8" y="8" width="13" height="13" rx="1.5"/></svg>',
|
|
38
|
-
swipe: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="1.5"/><path d="M12 3v18"/></svg>',
|
|
39
|
-
diff: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg>',
|
|
40
|
-
prev: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>',
|
|
41
|
-
next: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg>',
|
|
42
|
-
chevron: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg>',
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Splits a path into a muted directory part and the file name.
|
|
47
|
-
* @param {string} path
|
|
48
|
-
* @returns {string}
|
|
49
|
-
*/
|
|
50
|
-
const pathHtml = (path) => {
|
|
51
|
-
const i = path.lastIndexOf("/");
|
|
52
|
-
const inner = i === -1 ? `<span class="name">${esc(path)}</span>` : `<span class="dir">${esc(path.slice(0, i + 1))}</span><span class="name">${esc(path.slice(i + 1))}</span>`;
|
|
53
|
-
return `<bdi>${inner}</bdi>`;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Size change as a colored delta with percentage.
|
|
58
|
-
* @param {number|undefined} head
|
|
59
|
-
* @param {number|undefined} base
|
|
60
|
-
* @returns {string}
|
|
61
|
-
*/
|
|
62
|
-
export function deltaHtml(head, base) {
|
|
63
|
-
const d = (head ?? 0) - (base ?? 0);
|
|
64
|
-
if (d === 0) return '<span class="delta same">—</span>';
|
|
65
|
-
const percent = head != null && base ? ` <small>${d > 0 ? "+" : ""}${((d / base) * 100).toFixed(1)}%</small>` : "";
|
|
66
|
-
return `<span class="delta ${d > 0 ? "up" : "down"}">${d > 0 ? "+" : "−"}${esc(bytesToSize(Math.abs(d)))}${percent}</span>`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Change status for a pair of sizes.
|
|
71
|
-
* @param {number|undefined} head
|
|
72
|
-
* @param {number|undefined} base
|
|
73
|
-
* @param {boolean} hasBase
|
|
74
|
-
* @returns {"added"|"removed"|"modified"|"unchanged"}
|
|
75
|
-
*/
|
|
76
|
-
const rowStatus = (head, base, hasBase) => {
|
|
77
|
-
if (!hasBase) return "unchanged";
|
|
78
|
-
if (base == null) return "added";
|
|
79
|
-
if (head == null) return "removed";
|
|
80
|
-
return head === base ? "unchanged" : "modified";
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
/** Smallest similarity (0–1) at which a removed and an added line are shown as an edit of one another. */
|
|
84
|
-
const PAIR_THRESHOLD = 0.5;
|
|
85
|
-
|
|
86
|
-
/** Most removed × added line pairs compared when matching a run of changes. */
|
|
87
|
-
const PAIR_LIMIT = 400;
|
|
88
|
-
|
|
89
|
-
/** Non-whitespace characters in a string. */
|
|
90
|
-
const solid = (text) => text.replace(/\s+/g, "").length;
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Word-level comparison of two lines. Similarity is the share of non-whitespace
|
|
94
|
-
* characters the lines have in common, so indentation can't make unrelated
|
|
95
|
-
* lines look alike.
|
|
96
|
-
* @param {string} oldText
|
|
97
|
-
* @param {string} newText
|
|
98
|
-
* @returns {{ similarity: number, old: number[], new: number[] }} Changed ranges as flat `[start, end, …]` offsets.
|
|
99
|
-
*/
|
|
100
|
-
export function compareLines(oldText, newText) {
|
|
101
|
-
const none = { similarity: 0, old: [], new: [] };
|
|
102
|
-
if (oldText.length > INTRALINE_LIMIT || newText.length > INTRALINE_LIMIT) return none;
|
|
103
|
-
const longest = Math.max(1, solid(oldText), solid(newText));
|
|
104
|
-
// Common characters can't exceed the shorter line, which bounds the similarity cheaply.
|
|
105
|
-
if (Math.min(solid(oldText), solid(newText)) / longest < PAIR_THRESHOLD) return none;
|
|
106
|
-
|
|
107
|
-
const old = [];
|
|
108
|
-
const next = [];
|
|
109
|
-
let oldAt = 0;
|
|
110
|
-
let newAt = 0;
|
|
111
|
-
let common = 0;
|
|
112
|
-
const push = (ranges, start, end) => (ranges.length > 0 && ranges.at(-1) === start ? (ranges[ranges.length - 1] = end) : ranges.push(start, end));
|
|
113
|
-
|
|
114
|
-
diffWordsWithSpace(oldText, newText).forEach(({ added, removed, value }) => {
|
|
115
|
-
if (added) {
|
|
116
|
-
push(next, newAt, newAt + value.length);
|
|
117
|
-
newAt += value.length;
|
|
118
|
-
} else if (removed) {
|
|
119
|
-
push(old, oldAt, oldAt + value.length);
|
|
120
|
-
oldAt += value.length;
|
|
121
|
-
} else {
|
|
122
|
-
common += solid(value);
|
|
123
|
-
oldAt += value.length;
|
|
124
|
-
newAt += value.length;
|
|
125
|
-
}
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
return { similarity: common / longest, old, new: next };
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Matches removed lines to the added lines they were edited into. Chooses the
|
|
133
|
-
* order-preserving set of pairs with the highest total similarity, so an
|
|
134
|
-
* inserted or deleted line doesn't shift every pairing after it.
|
|
135
|
-
* @param {string[]} oldTexts
|
|
136
|
-
* @param {string[]} newTexts
|
|
137
|
-
* @returns {Array<{ del: number, add: number, old: number[], new: number[] }>} Indexes into the two arrays.
|
|
138
|
-
*/
|
|
139
|
-
export function pairLines(oldTexts, newTexts) {
|
|
140
|
-
if (oldTexts.length === 0 || newTexts.length === 0) return [];
|
|
141
|
-
|
|
142
|
-
const cells = new Map();
|
|
143
|
-
const score = (i, j) => {
|
|
144
|
-
const key = i * newTexts.length + j;
|
|
145
|
-
if (!cells.has(key)) cells.set(key, compareLines(oldTexts[i], newTexts[j]));
|
|
146
|
-
return cells.get(key);
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
// Too many combinations to compare all of them: pair line by line instead.
|
|
150
|
-
if (oldTexts.length * newTexts.length > PAIR_LIMIT) {
|
|
151
|
-
const pairs = [];
|
|
152
|
-
for (let k = 0; k < Math.min(oldTexts.length, newTexts.length); k++) {
|
|
153
|
-
const { similarity, old, new: next } = score(k, k);
|
|
154
|
-
if (similarity >= PAIR_THRESHOLD) pairs.push({ del: k, add: k, old, new: next });
|
|
155
|
-
}
|
|
156
|
-
return pairs;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
const rows = oldTexts.length + 1;
|
|
160
|
-
const cols = newTexts.length + 1;
|
|
161
|
-
const best = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
162
|
-
for (let i = 1; i < rows; i++) {
|
|
163
|
-
for (let j = 1; j < cols; j++) {
|
|
164
|
-
const { similarity } = score(i - 1, j - 1);
|
|
165
|
-
best[i][j] = Math.max(best[i - 1][j], best[i][j - 1], similarity >= PAIR_THRESHOLD ? best[i - 1][j - 1] + similarity : 0);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const pairs = [];
|
|
170
|
-
for (let i = rows - 1, j = cols - 1; i > 0 && j > 0; ) {
|
|
171
|
-
const { similarity, old, new: next } = score(i - 1, j - 1);
|
|
172
|
-
if (similarity >= PAIR_THRESHOLD && best[i][j] === best[i - 1][j - 1] + similarity) {
|
|
173
|
-
pairs.push({ del: i - 1, add: j - 1, old, new: next });
|
|
174
|
-
i--;
|
|
175
|
-
j--;
|
|
176
|
-
} else if (best[i][j] === best[i - 1][j]) i--;
|
|
177
|
-
else j--;
|
|
178
|
-
}
|
|
179
|
-
return pairs.reverse();
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Hunk data for the browser: the raw lines once, the matched removed/added
|
|
184
|
-
* pairs, and the changed word ranges. The page builds table rows from this when
|
|
185
|
-
* a file is opened, which keeps the HTML about as large as the diff itself.
|
|
186
|
-
* @param {import("./changes.js").Hunk} hunk
|
|
187
|
-
* @returns {{ h: string, o: number, n: number, l: string[], p: number[][], m: Record<number, number[]> }}
|
|
188
|
-
* `p` pairs `[removedLineIndex, addedLineIndex]`; `m` maps a line index to `[start, end, …]` offsets in its text (after the sign).
|
|
189
|
-
*/
|
|
190
|
-
export function hunkData({ oldStart, oldLines, newStart, newLines, lines }) {
|
|
191
|
-
const p = [];
|
|
192
|
-
const m = {};
|
|
193
|
-
|
|
194
|
-
for (let i = 0; i < lines.length; ) {
|
|
195
|
-
if (lines[i][0] !== "-" && lines[i][0] !== "+") {
|
|
196
|
-
i++;
|
|
197
|
-
continue;
|
|
198
|
-
}
|
|
199
|
-
const dels = [];
|
|
200
|
-
const adds = [];
|
|
201
|
-
while (lines[i]?.[0] === "-") dels.push(i++);
|
|
202
|
-
// A "\ No newline" marker can sit between the removed and added lines.
|
|
203
|
-
if (dels.length > 0 && lines[i]?.[0] === "\\") i++;
|
|
204
|
-
while (lines[i]?.[0] === "+") adds.push(i++);
|
|
205
|
-
|
|
206
|
-
pairLines(
|
|
207
|
-
dels.map((k) => lines[k].slice(1)),
|
|
208
|
-
adds.map((k) => lines[k].slice(1)),
|
|
209
|
-
).forEach((pair) => {
|
|
210
|
-
p.push([dels[pair.del], adds[pair.add]]);
|
|
211
|
-
if (pair.old.length) m[dels[pair.del]] = pair.old;
|
|
212
|
-
if (pair.new.length) m[adds[pair.add]] = pair.new;
|
|
213
|
-
});
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
return { h: `@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`, o: oldStart, n: newStart, l: lines, p, m };
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* JSON safe to place inside a `<script>` element.
|
|
221
|
-
* @param {unknown} value
|
|
222
|
-
* @returns {string}
|
|
223
|
-
*/
|
|
224
|
-
export const scriptJson = (value) =>
|
|
225
|
-
JSON.stringify(value)
|
|
226
|
-
.replace(/</g, "\\u003c")
|
|
227
|
-
.replace(/\u2028/g, "\\u2028")
|
|
228
|
-
.replace(/\u2029/g, "\\u2029");
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* Summary cards at the top of the page.
|
|
232
|
-
* @param {PageOptions} options
|
|
233
|
-
* @returns {string}
|
|
234
|
-
*/
|
|
235
|
-
function renderCards({ hasBase, changes, totals }) {
|
|
236
|
-
const { stats } = changes;
|
|
237
|
-
const files = stats.added + stats.removed + stats.modified;
|
|
238
|
-
const lines = stats.additions + stats.deletions;
|
|
239
|
-
const addShare = lines ? (stats.additions / lines) * 100 : 0;
|
|
240
|
-
const chip = (n, label, cls) => (n ? `<span class="chip ${cls}">${n} ${label}</span>` : "");
|
|
241
|
-
|
|
242
|
-
return `<section class="cards" aria-label="Summary">
|
|
243
|
-
<article class="card"><h2>Total size</h2><p class="metric">${esc(bytesToSize(totals.headTotal))}</p><p class="sub">${hasBase ? `${esc(bytesToSize(totals.baseTotal))} on base ${deltaHtml(totals.headTotal, totals.baseTotal)}` : "No base to compare"}</p></article>
|
|
244
|
-
<article class="card"><h2>Files changed</h2><p class="metric">${files}</p><p class="sub chips">${chip(stats.added, "added", "added") + chip(stats.removed, "removed", "removed") + chip(stats.modified, "modified", "modified") || "No changes"}</p></article>
|
|
245
|
-
<article class="card"><h2>Lines</h2><p class="metric"><span class="add">+${stats.additions}</span> <span class="del">−${stats.deletions}</span></p><p class="sub"><span class="ratio" role="img" aria-label="${stats.additions} added, ${stats.deletions} removed"><span style="inline-size:${addShare.toFixed(1)}%"></span></span></p></article>
|
|
246
|
-
<article class="card"><h2>Visual</h2><p class="metric">${changes.images.length}</p><p class="sub">${changes.images.length === 1 ? "image" : "images"} changed</p></article>
|
|
247
|
-
</section>`;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* Overview panel: sizes grouped by package.
|
|
252
|
-
* @param {PageOptions} options
|
|
253
|
-
* @param {Map<string, string>} anchors Change path → element id.
|
|
254
|
-
* @returns {string}
|
|
255
|
-
*/
|
|
256
|
-
function renderOverview({ rows, hasBase, changes }, anchors) {
|
|
257
|
-
if (rows.length === 0) {
|
|
258
|
-
const { added, removed, modified } = changes.stats;
|
|
259
|
-
const files = added + removed + modified;
|
|
260
|
-
return `<p class="empty-state">No size changes.${files > 0 ? ` ${files} ${files === 1 ? "file differs" : "files differ"} in content only. See the Code tab.` : ""}</p>`;
|
|
261
|
-
}
|
|
262
|
-
const max = Math.max(1, ...rows.flatMap(({ headByteSize, baseByteSize }) => [headByteSize ?? 0, baseByteSize ?? 0]));
|
|
263
|
-
const pct = (v) => `${(barScale(v, max) * 100).toFixed(1)}%`;
|
|
264
|
-
|
|
265
|
-
const groups = new Map();
|
|
266
|
-
rows.forEach((row) => {
|
|
267
|
-
const key = row.packageDir ?? row.packageName;
|
|
268
|
-
if (!groups.has(key)) groups.set(key, []);
|
|
269
|
-
groups.get(key).push(row);
|
|
270
|
-
});
|
|
271
|
-
|
|
272
|
-
const body = [...groups.values()]
|
|
273
|
-
.map((group) => {
|
|
274
|
-
const { packageName } = group[0];
|
|
275
|
-
const head = group.reduce((sum, r) => sum + (r.headByteSize ?? 0), 0);
|
|
276
|
-
const base = group.reduce((sum, r) => sum + (r.baseByteSize ?? 0), 0);
|
|
277
|
-
const header = `<tr class="pkg"><th scope="rowgroup" colspan="2">${esc(packageName)} <span class="muted">${group.length} ${group.length === 1 ? "file" : "files"}</span></th>${hasBase ? `<td class="num">${esc(bytesToSize(base))}</td>` : ""}<td class="num">${esc(bytesToSize(head))}</td>${hasBase ? `<td class="num">${deltaHtml(head, base)}</td>` : ""}<td></td></tr>`;
|
|
278
|
-
const items = group.map(({ file, path, headByteSize, baseByteSize }) => {
|
|
279
|
-
const status = rowStatus(headByteSize, baseByteSize, hasBase);
|
|
280
|
-
const name = anchors.has(path) ? `<a href="#${anchors.get(path)}">${esc(file)}</a>` : esc(file);
|
|
281
|
-
const bars = `${hasBase ? `<span class="bar base" style="inline-size:${pct(baseByteSize)}"></span>` : ""}<span class="bar head" style="inline-size:${pct(headByteSize)}"></span>`;
|
|
282
|
-
return `<tr><td><span class="dot ${status}" title="${status}"></span><span class="sr-only">${status}</span></td><td class="file-cell">${name}</td>${hasBase ? `<td class="num">${esc(bytesToSize(baseByteSize))}</td>` : ""}<td class="num">${esc(bytesToSize(headByteSize))}</td>${hasBase ? `<td class="num">${deltaHtml(headByteSize, baseByteSize)}</td>` : ""}<td class="chart" aria-hidden="true">${bars}</td></tr>`;
|
|
283
|
-
});
|
|
284
|
-
return `<tbody>${header}${items.join("")}</tbody>`;
|
|
285
|
-
})
|
|
286
|
-
.join("");
|
|
287
|
-
|
|
288
|
-
return `<div class="table-card"><table class="sizes">
|
|
289
|
-
<thead><tr><th scope="col"><span class="sr-only">Status</span></th><th scope="col">File</th>${hasBase ? '<th scope="col" class="num">Base</th>' : ""}<th scope="col" class="num">Head</th>${hasBase ? '<th scope="col" class="num">Change</th>' : ""}<th scope="col" class="chart">Size <span class="muted">(log)</span>${hasBase ? ' <span class="key base">base</span><span class="key head">head</span>' : ""}</th></tr></thead>
|
|
290
|
-
${body}</table></div>`;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Sticky file list shared by the code and visual panels.
|
|
295
|
-
* @param {Array<{ id: string, file: string, status: string, meta: string }>} items
|
|
296
|
-
* @param {string} label
|
|
297
|
-
* @param {boolean} [buttons] Render buttons (visual) instead of links (code).
|
|
298
|
-
* @returns {string}
|
|
299
|
-
*/
|
|
300
|
-
function renderFileList(items, label, buttons = false) {
|
|
301
|
-
const entries = items.map(({ id, file, status, meta }, i) => {
|
|
302
|
-
const inner = `<span class="dot ${status}" title="${status}"></span><span class="path">${pathHtml(file)}</span><span class="meta">${meta}</span>`;
|
|
303
|
-
return `<li>${buttons ? `<button type="button" data-target="${id}"${i === 0 ? ' aria-current="true"' : ""}>${inner}</button>` : `<a href="#${id}">${inner}</a>`}</li>`;
|
|
304
|
-
});
|
|
305
|
-
return `<nav class="filelist" aria-label="${esc(label)}"><ul>${entries.join("")}</ul></nav>`;
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/** Diff lines shown open on load, so small diffs are visible without a click. */
|
|
309
|
-
const OPEN_LINES = 800;
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Code panel: file list and per-file diffs with a unified/split toggle. Each
|
|
313
|
-
* diff ships as JSON and is turned into rows when its `<details>` opens.
|
|
314
|
-
* @param {PageOptions} options
|
|
315
|
-
* @param {Map<string, string>} anchors
|
|
316
|
-
* @returns {string}
|
|
317
|
-
*/
|
|
318
|
-
function renderCode({ changes }, anchors) {
|
|
319
|
-
if (changes.text.length === 0) return '<p class="empty-state">No text changes.</p>';
|
|
320
|
-
const counts = (c) => (c.skipped ? '<span class="muted">skipped</span>' : `<span class="add">+${c.additions}</span> <span class="del">−${c.deletions}</span>`);
|
|
321
|
-
|
|
322
|
-
const list = renderFileList(
|
|
323
|
-
changes.text.map((c) => ({ id: anchors.get(c.file), file: c.file, status: c.status, meta: counts(c) })),
|
|
324
|
-
"Changed files",
|
|
325
|
-
);
|
|
326
|
-
|
|
327
|
-
let shown = 0;
|
|
328
|
-
const files = changes.text
|
|
329
|
-
.map((c, i) => {
|
|
330
|
-
const size = c.hunks.reduce((sum, hunk) => sum + hunk.lines.length + 1, 0);
|
|
331
|
-
const open = c.hunks.length > 0 && (i === 0 || shown + size <= OPEN_LINES);
|
|
332
|
-
if (open) shown += size;
|
|
333
|
-
|
|
334
|
-
let body;
|
|
335
|
-
if (c.skipped) body = `<p class="note">Line diff skipped: ${esc(c.skipped)}.</p>`;
|
|
336
|
-
else if (c.omitted) body = `<p class="note">Diff left out because ${esc(c.omitted)}. Raise <code>max-diff-lines</code> to include it.</p>`;
|
|
337
|
-
else if (c.hunks.length === 0) body = '<p class="note">No line changes.</p>';
|
|
338
|
-
else body = `<div class="diff-scroll"><script type="application/json">${scriptJson(c.hunks.map(hunkData))}</script></div>`;
|
|
339
|
-
|
|
340
|
-
return `<section class="file" id="${anchors.get(c.file)}"><details${open ? " open" : ""}><summary><span class="chev">${ICON.chevron}</span><span class="pill ${c.status}">${c.status}</span><span class="path">${pathHtml(c.file)}</span><span class="meta">${counts(c)}</span></summary>${body}</details></section>`;
|
|
341
|
-
})
|
|
342
|
-
.join("");
|
|
343
|
-
|
|
344
|
-
return `<div class="layout">${list}<div class="main code-main" data-view="unified">
|
|
345
|
-
<div class="toolbar" role="toolbar" aria-label="Diff options">
|
|
346
|
-
<div class="segmented" role="group" aria-label="Diff layout"><button type="button" data-view="unified" aria-pressed="true">Unified</button><button type="button" data-view="split" aria-pressed="false">Split</button></div>
|
|
347
|
-
<span class="spacer"></span>
|
|
348
|
-
<button type="button" class="ghost" data-action="collapse">Collapse all</button>
|
|
349
|
-
</div>
|
|
350
|
-
<noscript><p class="note">Diffs are drawn by script. Enable JavaScript to see them.</p></noscript>
|
|
351
|
-
${files}</div></div>`;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Visual panel: image list and a compare viewer.
|
|
356
|
-
* @param {PageOptions} options
|
|
357
|
-
* @returns {string}
|
|
358
|
-
*/
|
|
359
|
-
function renderVisual({ changes, imageUrls = new Map() }) {
|
|
360
|
-
if (changes.images.length === 0) return "";
|
|
361
|
-
|
|
362
|
-
const items = changes.images.map((img, i) => ({ ...img, id: `img-${i}`, urls: imageUrls.get(img.file) ?? {} }));
|
|
363
|
-
const list = renderFileList(
|
|
364
|
-
items.map(({ id, file, status, baseByteSize, headByteSize }) => ({ id, file, status, meta: deltaHtml(headByteSize, baseByteSize) })),
|
|
365
|
-
"Changed images",
|
|
366
|
-
true,
|
|
367
|
-
);
|
|
368
|
-
|
|
369
|
-
const figure = (side, url) => (url ? `<figure class="layer ${side}"><img src="${esc(url)}" alt="${side === "base" ? "Base" : "Head"} version" decoding="async" data-side="${side}"><figcaption>${side === "base" ? "Base" : "Head"}</figcaption></figure>` : `<figure class="layer ${side} missing"><figcaption>${side === "base" ? "Base" : "Head"}: not available</figcaption></figure>`);
|
|
370
|
-
|
|
371
|
-
const viewers = items
|
|
372
|
-
.map(({ id, file, status, urls, baseByteSize, headByteSize }, i) => {
|
|
373
|
-
const single = !(urls.base && urls.head);
|
|
374
|
-
return `<section class="image-item" id="${id}"${i ? " hidden" : ""}${single ? " data-single" : ""} aria-label="${esc(file)}">
|
|
375
|
-
<header class="image-head"><span class="pill ${status}">${status}</span><span class="path">${pathHtml(file)}</span><span class="meta">${esc(bytesToSize(baseByteSize))} → ${esc(bytesToSize(headByteSize))} ${deltaHtml(headByteSize, baseByteSize)}</span><span class="meta dims"><span data-dims="base"></span><span data-dims="head"></span></span></header>
|
|
376
|
-
<div class="stage"><div class="layers">${figure("base", urls.base)}${figure("head", urls.head)}<span class="divider" aria-hidden="true"></span><span class="tag tag-base" aria-hidden="true">Base</span><span class="tag tag-head" aria-hidden="true">Head</span></div></div>
|
|
377
|
-
${single ? `<p class="note">${status === "added" ? "New image: there's no base version to compare." : status === "removed" ? "Removed image: there's no head version to compare." : "Only one version could be included."}</p>` : ""}
|
|
378
|
-
</section>`;
|
|
379
|
-
})
|
|
380
|
-
.join("");
|
|
381
|
-
|
|
382
|
-
const button = (attr, value, label, pressed, icon = "") => `<button type="button" data-${attr}="${value}" aria-pressed="${pressed}" title="${label}">${icon}<span>${label}</span></button>`;
|
|
383
|
-
|
|
384
|
-
return `<div class="layout">${list}<div class="main viewer" data-mode="side" data-bg="checker" data-zoom="fit" style="--opacity:0.5;--pos:50%">
|
|
385
|
-
<div class="toolbar" role="toolbar" aria-label="Compare options">
|
|
386
|
-
<div class="segmented modes" role="group" aria-label="Compare mode">${button("mode", "side", "Side by side", true, ICON.side)}${button("mode", "overlay", "Overlay", false, ICON.overlay)}${button("mode", "swipe", "Swipe", false, ICON.swipe)}${button("mode", "diff", "Difference", false, ICON.diff)}</div>
|
|
387
|
-
<span class="spacer"></span>
|
|
388
|
-
<div class="segmented" role="group" aria-label="Background">${button("bg", "checker", "Checker", true)}${button("bg", "light", "Light", false)}${button("bg", "dark", "Dark", false)}</div>
|
|
389
|
-
<div class="segmented" role="group" aria-label="Zoom">${button("zoom", "fit", "Fit", true)}${button("zoom", "1", "1×", false)}${button("zoom", "2", "2×", false)}${button("zoom", "4", "4×", false)}</div>
|
|
390
|
-
</div>
|
|
391
|
-
<div class="sliders">
|
|
392
|
-
<label class="slider-field opacity-field">Head opacity <input type="range" min="0" max="100" value="50" data-control="opacity"> <output>50%</output></label>
|
|
393
|
-
<label class="slider-field swipe-field">Swipe position <input type="range" min="0" max="100" value="50" data-control="pos"> <output>50%</output></label>
|
|
394
|
-
<p class="hint diff-hint">Matching pixels turn black; changes stay bright.</p>
|
|
395
|
-
<p class="hint side-hint">Use Overlay, Swipe or Difference to compare in place.</p>
|
|
396
|
-
</div>
|
|
397
|
-
${viewers}
|
|
398
|
-
<div class="pager"><button type="button" class="ghost" data-step="-1">${ICON.prev}<span>Previous</span></button><span class="pager-count" aria-live="polite">1 of ${items.length}</span><button type="button" class="ghost" data-step="1"><span>Next</span>${ICON.next}</button><span class="hint"><kbd>J</kbd> / <kbd>K</kbd> to switch images</span></div>
|
|
399
|
-
</div></div>`;
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Self-contained HTML report: summary cards, then Overview, Code and (when
|
|
404
|
-
* images changed) Visual tabs. Without JavaScript, the Overview tab shows.
|
|
405
|
-
* @param {PageOptions} options
|
|
406
|
-
* @returns {string}
|
|
407
|
-
*/
|
|
408
|
-
export function renderHtml(options) {
|
|
409
|
-
const { title, rows, changes, context = "" } = options;
|
|
410
|
-
const anchors = new Map(changes.text.map((c, i) => [c.file, `f-${i}`]));
|
|
411
|
-
|
|
412
|
-
const tabs = [["overview", "Overview", rows.length, renderOverview(options, anchors)], ["code", "Code", changes.text.length, renderCode(options, anchors)], ...(changes.images.length ? [["visual", "Visual", changes.images.length, renderVisual(options)]] : [])];
|
|
413
|
-
|
|
414
|
-
return `<!doctype html>
|
|
415
|
-
<html lang="en">
|
|
416
|
-
<head>
|
|
417
|
-
<meta charset="utf-8">
|
|
418
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
419
|
-
<meta name="color-scheme" content="light dark">
|
|
420
|
-
<meta name="robots" content="noindex">
|
|
421
|
-
<title>${esc(title)}</title>
|
|
422
|
-
<style>
|
|
423
|
-
${css}
|
|
424
|
-
</style>
|
|
425
|
-
</head>
|
|
426
|
-
<body>
|
|
427
|
-
<header class="topbar"><div class="wrap topbar-inner"><span class="brand">${ICON.logo}<span>${esc(title)}</span></span>${context ? `<span class="context">${esc(context)}</span>` : ""}</div></header>
|
|
428
|
-
<main class="wrap">
|
|
429
|
-
${renderCards(options)}
|
|
430
|
-
<div class="tabs">
|
|
431
|
-
<div class="tablist" role="tablist" aria-label="Report sections">${tabs.map(([id, label, count], i) => `<button type="button" role="tab" id="tab-${id}" aria-selected="${i === 0}" tabindex="${i === 0 ? 0 : -1}">${label}<span class="count">${count}</span></button>`).join("")}</div>
|
|
432
|
-
${tabs.map(([id, , , html], i) => `<div role="tabpanel" id="panel-${id}" aria-labelledby="tab-${id}"${i ? ' hidden="until-found"' : ""}><div class="panel">${html}</div></div>`).join("\n")}
|
|
433
|
-
</div>
|
|
434
|
-
</main>
|
|
435
|
-
<footer class="wrap footer">Generated by <a href="https://github.com/allonsy-studio/actions-file-diff">actions-file-diff</a></footer>
|
|
436
|
-
<script>
|
|
437
|
-
${client}
|
|
438
|
-
</script>
|
|
439
|
-
</body>
|
|
440
|
-
</html>
|
|
441
|
-
`;
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
/** Encodes each path segment for use in a relative URL. */
|
|
445
|
-
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
446
|
-
|
|
447
|
-
/**
|
|
448
|
-
* Files for a published report: `index.html` plus changed images (up to
|
|
449
|
-
* MAX_IMAGE_SIZE each) under `images/head/` and `images/base/`.
|
|
450
|
-
* @param {Omit<PageOptions, "imageUrls">} options
|
|
451
|
-
* @returns {import("./publish.js").ReportFile[]}
|
|
452
|
-
*/
|
|
453
|
-
export function reportFiles(options) {
|
|
454
|
-
const files = [];
|
|
455
|
-
const imageUrls = new Map();
|
|
456
|
-
|
|
457
|
-
options.changes.images.forEach((image) => {
|
|
458
|
-
const urls = {};
|
|
459
|
-
[
|
|
460
|
-
["head", image.headPath, image.headByteSize],
|
|
461
|
-
["base", image.basePath, image.baseByteSize],
|
|
462
|
-
].forEach(([side, path, size]) => {
|
|
463
|
-
if (!path || size > MAX_IMAGE_SIZE) return;
|
|
464
|
-
files.push({ path: `images/${side}/${image.file}`, content: readFileSync(path) });
|
|
465
|
-
urls[side] = `images/${side}/${encodePath(image.file)}`;
|
|
466
|
-
});
|
|
467
|
-
imageUrls.set(image.file, urls);
|
|
468
|
-
});
|
|
469
|
-
|
|
470
|
-
files.push({ path: "index.html", content: renderHtml({ ...options, imageUrls }) });
|
|
471
|
-
return files;
|
|
472
|
-
}
|
package/src/publish.js
DELETED
|
@@ -1,171 +0,0 @@
|
|
|
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 { mapLimit } from "./utilities.js";
|
|
10
|
-
|
|
11
|
-
/** Default branch the HTML report is committed to. */
|
|
12
|
-
export const DEFAULT_REPORT_BRANCH = "file-diff-reports";
|
|
13
|
-
|
|
14
|
-
/** Attempts when the branch moves under a concurrent run. */
|
|
15
|
-
const MAX_ATTEMPTS = 4;
|
|
16
|
-
|
|
17
|
-
/** Blob uploads in flight at once. GitHub asks clients not to hammer the API concurrently. */
|
|
18
|
-
const UPLOAD_CONCURRENCY = 6;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* @typedef {object} ReportFile
|
|
22
|
-
* @property {string} path Path relative to the report directory.
|
|
23
|
-
* @property {string|Buffer} content
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Directory for a run's report: `pr-<n>` on pull requests, else `sha-<short>`.
|
|
28
|
-
* @param {{ pullNumber?: number, sha?: string }} options
|
|
29
|
-
* @returns {string}
|
|
30
|
-
*/
|
|
31
|
-
export function reportDir({ pullNumber, sha = "" }) {
|
|
32
|
-
return pullNumber ? `pr-${pullNumber}` : `sha-${sha.slice(0, 12) || "unknown"}`;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Public URL of a report directory. Uses the repository's Pages URL when the
|
|
37
|
-
* API returns one, else the default `https://<owner>.github.io/<repo>/`.
|
|
38
|
-
* @param {object} options
|
|
39
|
-
* @param {object} options.octokit
|
|
40
|
-
* @param {string} options.owner
|
|
41
|
-
* @param {string} options.repo
|
|
42
|
-
* @param {string} options.dir
|
|
43
|
-
* @param {string} [options.pagesUrl] Explicit base URL; skips the API lookup.
|
|
44
|
-
* @returns {Promise<string>}
|
|
45
|
-
*/
|
|
46
|
-
export async function reportUrl({ octokit, owner, repo, dir, pagesUrl }) {
|
|
47
|
-
let base = pagesUrl;
|
|
48
|
-
if (!base) {
|
|
49
|
-
try {
|
|
50
|
-
base = (await octokit.rest.repos.getPages({ owner, repo })).data.html_url;
|
|
51
|
-
} catch {
|
|
52
|
-
base = repo.toLowerCase() === `${owner}.github.io`.toLowerCase() ? `https://${owner}.github.io/` : `https://${owner}.github.io/${repo}/`;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return `${String(base).replace(/\/+$/, "")}/${dir}/`;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Whether an Octokit error is an HTTP status.
|
|
60
|
-
* @param {unknown} error
|
|
61
|
-
* @param {number} status
|
|
62
|
-
* @returns {boolean}
|
|
63
|
-
*/
|
|
64
|
-
const isStatus = (error, status) => error?.status === status;
|
|
65
|
-
|
|
66
|
-
/** Waits before a retry, with jitter so competing runs don't collide again. */
|
|
67
|
-
const defaultDelay = (attempt) => new Promise((resolve) => setTimeout(resolve, 200 * attempt + Math.random() * 300));
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Current commit of a branch, or undefined when it doesn't exist.
|
|
71
|
-
* @returns {Promise<string|undefined>}
|
|
72
|
-
*/
|
|
73
|
-
async function branchHead({ git, owner, repo, branch }) {
|
|
74
|
-
try {
|
|
75
|
-
return (await git.getRef({ owner, repo, ref: `heads/${branch}` })).data.object.sha;
|
|
76
|
-
} catch (error) {
|
|
77
|
-
if (isStatus(error, 404)) return undefined;
|
|
78
|
-
throw error;
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Deletion entries for files already under `dir` that the new report doesn't
|
|
84
|
-
* contain. Reads only that directory's tree, never the whole branch.
|
|
85
|
-
* @returns {Promise<Array<{ path: string, mode: string, type: string, sha: null }>>}
|
|
86
|
-
* @throws {Error} When GitHub truncates a listing, since stale files would be missed.
|
|
87
|
-
*/
|
|
88
|
-
async function staleEntries({ git, owner, repo, baseTree, dir, keep }) {
|
|
89
|
-
const root = (await git.getTree({ owner, repo, tree_sha: baseTree })).data;
|
|
90
|
-
if (root.truncated) throw new Error("The report branch has too many top-level entries to list.");
|
|
91
|
-
const entry = root.tree.find(({ path, type }) => path === dir && type === "tree");
|
|
92
|
-
if (!entry) return [];
|
|
93
|
-
|
|
94
|
-
const listing = (await git.getTree({ owner, repo, tree_sha: entry.sha, recursive: "true" })).data;
|
|
95
|
-
if (listing.truncated) throw new Error(`${dir}/ has too many files to list on the report branch.`);
|
|
96
|
-
return listing.tree
|
|
97
|
-
.filter(({ type }) => type === "blob")
|
|
98
|
-
.map(({ path }) => `${dir}/${path}`)
|
|
99
|
-
.filter((path) => !keep.has(path))
|
|
100
|
-
.map((path) => ({ path, mode: "100644", type: "blob", sha: null }));
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Commits files under `dir` on `branch`, replacing whatever that directory held
|
|
105
|
-
* and leaving every other directory alone. With no files, the directory is removed.
|
|
106
|
-
*
|
|
107
|
-
* Each run writes a single parentless commit and moves the branch to it, so
|
|
108
|
-
* older versions of a report become unreachable instead of piling up in history.
|
|
109
|
-
* The branch is created (with `.nojekyll`) when missing.
|
|
110
|
-
*
|
|
111
|
-
* The branch is re-read just before it is moved, and the run starts over from
|
|
112
|
-
* the new tree if another run moved it first. A run that lands inside the few
|
|
113
|
-
* milliseconds between that check and the update can still overwrite the other
|
|
114
|
-
* run's directory; that report returns on the pull request's next push.
|
|
115
|
-
* @param {object} options
|
|
116
|
-
* @param {object} options.octokit
|
|
117
|
-
* @param {string} options.owner
|
|
118
|
-
* @param {string} options.repo
|
|
119
|
-
* @param {string} options.branch
|
|
120
|
-
* @param {string} options.dir
|
|
121
|
-
* @param {ReportFile[]} options.files
|
|
122
|
-
* @param {string} options.message
|
|
123
|
-
* @param {(attempt: number) => Promise<void>} [options.delay] Wait before a retry.
|
|
124
|
-
* @returns {Promise<string|undefined>} New commit SHA, or undefined when nothing changed.
|
|
125
|
-
*/
|
|
126
|
-
export async function publishToBranch({ octokit, owner, repo, branch, dir, files, message, delay = defaultDelay }) {
|
|
127
|
-
const { git } = octokit.rest;
|
|
128
|
-
const target = { git, owner, repo, branch };
|
|
129
|
-
|
|
130
|
-
// Uploading blobs doesn't touch the branch, so do it once, before any retry.
|
|
131
|
-
const blobs = await mapLimit(files, UPLOAD_CONCURRENCY, async ({ path, content }) => {
|
|
132
|
-
const { data } = await git.createBlob({ owner, repo, content: Buffer.from(content).toString("base64"), encoding: "base64" });
|
|
133
|
-
return { path: `${dir}/${path}`, mode: "100644", type: "blob", sha: data.sha };
|
|
134
|
-
});
|
|
135
|
-
const keep = new Set(blobs.map(({ path }) => path));
|
|
136
|
-
|
|
137
|
-
for (let attempt = 1; ; attempt++) {
|
|
138
|
-
const parent = await branchHead(target);
|
|
139
|
-
|
|
140
|
-
let tree;
|
|
141
|
-
if (parent) {
|
|
142
|
-
const baseTree = (await git.getCommit({ owner, repo, commit_sha: parent })).data.tree.sha;
|
|
143
|
-
const entries = [...blobs, ...(await staleEntries({ git, owner, repo, baseTree, dir, keep }))];
|
|
144
|
-
if (entries.length === 0) return undefined;
|
|
145
|
-
tree = (await git.createTree({ owner, repo, base_tree: baseTree, tree: entries })).data.sha;
|
|
146
|
-
if (tree === baseTree) return undefined;
|
|
147
|
-
} else {
|
|
148
|
-
if (blobs.length === 0) return undefined;
|
|
149
|
-
const nojekyll = (await git.createBlob({ owner, repo, content: "", encoding: "utf-8" })).data.sha;
|
|
150
|
-
tree = (await git.createTree({ owner, repo, tree: [...blobs, { path: ".nojekyll", mode: "100644", type: "blob", sha: nojekyll }] })).data.sha;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
const commit = (await git.createCommit({ owner, repo, message, tree, parents: [] })).data.sha;
|
|
154
|
-
|
|
155
|
-
// Another run moved the branch while this one worked: rebuild from its tree.
|
|
156
|
-
const moved = (await branchHead(target)) !== parent;
|
|
157
|
-
if (!moved) {
|
|
158
|
-
try {
|
|
159
|
-
if (parent) await git.updateRef({ owner, repo, ref: `heads/${branch}`, sha: commit, force: true });
|
|
160
|
-
else await git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha: commit });
|
|
161
|
-
return commit;
|
|
162
|
-
} catch (error) {
|
|
163
|
-
// createRef fails with 422 when a concurrent run created the branch first.
|
|
164
|
-
if (!isStatus(error, 422)) throw error;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
if (attempt >= MAX_ATTEMPTS) throw new Error(`The report branch "${branch}" kept changing underneath this run; gave up after ${MAX_ATTEMPTS} attempts.`);
|
|
169
|
-
await delay(attempt);
|
|
170
|
-
}
|
|
171
|
-
}
|