@allons-y/actions-file-diff 0.3.0 → 0.4.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.
Files changed (3) hide show
  1. package/README.md +28 -6
  2. package/dist/index.js +159 -61
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -115,8 +115,9 @@ If `base-path` is omitted, or the directory does not exist, the action reports h
115
115
  | `rename-threshold` | no | `50` | Minimum similarity, as a percentage, for pairing a file only on base with a file only on head that has the same extension, the way git detects renames. `0` turns it off. |
116
116
  | `comment` | no | `"true"` | Whether to post or update the pull request comment. |
117
117
  | `comment-header` | no | `## File metrics` | First line of the comment. Also used to derive the hidden marker that keeps the comment sticky across runs, so use distinct headers if you run the action more than once per pull request. |
118
- | `visual-diff` | no | `summary` | Where the visual diff linked from the comment lives: `summary`, `branch` or `none`. See [Visual diff](#visual-diff). |
118
+ | `visual-diff` | no | `auto` | Where the visual diff linked from the comment lives: `auto`, `summary`, `branch` or `none`. See [Visual diff](#visual-diff). |
119
119
  | `report-branch` | no | `file-diff-reports` | Branch the HTML report is committed to when `visual-diff` is `branch`. Created as an orphan branch when missing. |
120
+ | `report-path` | no | — | Folder on `report-branch` for the reports, such as `file-diff` on a `gh-pages` branch that also serves a site. When set, reports are added as normal commits and the rest of the branch is left alone. See [Sharing a Pages branch](#sharing-a-pages-branch). |
120
121
  | `pages-url` | no | — | Base URL that serves `report-branch`. Defaults to the repository's GitHub Pages URL. |
121
122
  | `max-diff-size` | no | `262144` | Largest file, in bytes, that gets a line diff. Larger files are listed without one. |
122
123
  | `max-diff-lines` | no | `20000` | Most diff lines kept for the whole report. A diff that would go over is left out of the report, with its line counts kept. `0` leaves out every diff. |
@@ -125,7 +126,7 @@ If `base-path` is omitted, or the directory does not exist, the action reports h
125
126
 
126
127
  | Name | Description |
127
128
  | ------------- | ------------------------------------------------------------------------------------------------- |
128
- | `has-changed` | `"true"` when the head total differs from the base total. Always `"false"` when there is no base. |
129
+ | `has-changed` | `"true"` when any reported file was added, removed, or changed in content, after `ignore-patterns`. Always `"false"` when there is no base. |
129
130
  | `total-size` | Head total in bytes. |
130
131
  | `report-url` | Link to the visual diff (published page or workflow run). Empty when `visual-diff` is `none`. |
131
132
 
@@ -141,11 +142,18 @@ The visual diff opens with summary cards (total size, files changed, lines, imag
141
142
 
142
143
  The full page (cards, tabs, split view and image compare modes) needs `visual-diff: branch`. The job summary shows the same data as collapsible sections without the interactive controls.
143
144
 
144
- The pull request comment is shortened to fit GitHub's 65,536-character limit; when rows are left out it says so and links the full report.
145
+ The pull request comment lists only the files that changed, and says how many unchanged files it hid. The job summary and the log list every package and file. Both drop the Minified and Gzipped columns when no listed file has a minified or gzipped copy.
145
146
 
146
- ### `visual-diff: summary` (default)
147
+ The comment is also shortened to fit GitHub's 65,536-character limit; when rows are left out it says so and links the full report.
147
148
 
148
- - Writes the three parts as collapsible sections in the [job summary](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#adding-a-job-summary). The comment links to the workflow run.
149
+ ### `visual-diff: auto` (default)
150
+
151
+ - Acts as `branch` when GitHub Pages already serves `report-branch` from its root, and as `summary` otherwise. It never creates a branch, so a repository that isn't set up for Pages gets the job summary.
152
+ - The check reads the Pages settings with the workflow token. When the token can't read them, it acts as `summary`.
153
+
154
+ ### `visual-diff: summary`
155
+
156
+ - Writes the three parts as collapsible sections in the [job summary](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#adding-a-job-summary). The comment links to the workflow run, unless no files changed.
149
157
  - No extra permissions or setup.
150
158
  - Limits: the summary has no tabs and can't show images (only a list of changed images), and GitHub caps it at 1 MiB, so long diffs are cut off with a note. It is kept for as long as the run's logs.
151
159
 
@@ -187,6 +195,19 @@ jobs:
187
195
 
188
196
  On a `closed` event the action only removes the report, so the build steps can be skipped with `if: github.event.action != 'closed'`.
189
197
 
198
+ #### Sharing a Pages branch
199
+
200
+ A repository that already serves a site from `gh-pages` can keep the reports there, in a folder:
201
+
202
+ ```yaml
203
+ report-branch: gh-pages
204
+ report-path: file-diff
205
+ ```
206
+
207
+ - Reports go to `gh-pages/file-diff/pr-<number>/` as normal commits, and nothing outside that folder changes.
208
+ - With the default `auto`, no Pages setting changes: Pages already serves `gh-pages`.
209
+ - Whatever deploys the site must leave `file-diff/` in place. A deploy that replaces the whole branch, or syncs with `--delete`, removes the reports.
210
+
190
211
  ### Hashed and renamed files
191
212
 
192
213
  Bundlers often put a content hash in output filenames, so an edited file gets a new name. Before comparing, the action pairs each file that is only on base with one that is only on head, then reports the pair as one modified file, with its size change and a line diff against the old name:
@@ -214,8 +235,9 @@ ignore-patterns: |
214
235
  Each match is replaced with `[ignored]` on both sides before a text file is compared. A file that differs only in matches is left out of the changed files, and the line diff of a file with other changes shows `[ignored]` in place of each match.
215
236
 
216
237
  - It applies to text files up to `max-diff-size`. Larger and binary files compare byte for byte.
238
+ - Minified copies and source maps (`.min.*`, `.map`) are compared the same way, though they get no line diff of their own.
239
+ - Compressed copies (`.gz`, `.br`, `.zst`) count as changed only when the file they compress did, so recompression alone is not a change. One without an uncompressed copy compares byte for byte.
217
240
  - Sizes in the table still count the real bytes, so a match that changes length can still show a size change.
218
- - It needs `visual-diff` set to `summary` or `branch`, which is what lists the changed files.
219
241
 
220
242
  ### How sizes are counted
221
243
 
package/dist/index.js CHANGED
@@ -28399,12 +28399,24 @@ function buildFileRow({ readableFilename, files, hasBase, isMainFile = false })
28399
28399
  const gzipSize = removed ? " - " : siblingCell(gzippedName(readableFilename));
28400
28400
  return [isMainFile ? `**${readableFilename}**` : readableFilename, size, minSize, gzipSize, ...hasBase ? [delta] : []];
28401
28401
  }
28402
- function buildSections(packages, { hasBase, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
28402
+ var entryChanged = ({ path: path11, headByteSize, baseByteSize }, changed) => changed ? changed.has(path11) : headByteSize !== baseByteSize;
28403
+ function rowChanged(readableFilename, files, changed) {
28404
+ return [readableFilename, minifiedName(readableFilename), gzippedName(readableFilename)].some((name) => {
28405
+ const entry = name ? files.get(name) : void 0;
28406
+ return entry ? entryChanged(entry, changed) : false;
28407
+ });
28408
+ }
28409
+ var SIBLING_COLUMNS = [2, 3];
28410
+ function siblingColumns(rows) {
28411
+ const empty = SIBLING_COLUMNS.filter((index) => rows.every((row) => row[index].trim() === "-"));
28412
+ return (row) => row.filter((_, index) => !empty.includes(index));
28413
+ }
28414
+ function buildSections(packages, { hasBase, changed, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, includeUnchanged = false, core } = {}) {
28403
28415
  const sections = [];
28404
28416
  packages.forEach(({ name, packageDir, files }) => {
28405
28417
  if (files.size === 0) return;
28406
- const hasChange = [...files.values()].some(({ headByteSize, baseByteSize }) => headByteSize !== baseByteSize);
28407
- if (hasBase && !hasChange) return;
28418
+ const hasChange = [...files.values()].some((entry) => entryChanged(entry, changed));
28419
+ if (hasBase && !hasChange && !includeUnchanged) return;
28408
28420
  sections.push({
28409
28421
  name,
28410
28422
  packageDir,
@@ -28429,35 +28441,45 @@ function fitRows(rows, budget) {
28429
28441
  }
28430
28442
  return { kept, used };
28431
28443
  }
28432
- function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE__ */ new Map(), hasBase = baseMap.size > 0, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, extensions = [], maxLength = Infinity, core } = {}) {
28444
+ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE__ */ new Map(), hasBase = baseMap.size > 0, changed, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, extensions = [], maxLength = Infinity, full = false, core } = {}) {
28433
28445
  const allowed = normalizeExtensions(extensions);
28434
28446
  const head = filterByExtensions(headMap, allowed);
28435
28447
  const base = hasBase ? filterByExtensions(baseMap, allowed) : /* @__PURE__ */ new Map();
28436
28448
  const headTotal = totalSize(head);
28437
28449
  const baseTotal = hasBase ? totalSize(base) : 0;
28438
- const hasChanged = hasBase && headTotal !== baseTotal;
28439
- const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, rootPath, buildDir, mainFile, readPackageJson, core });
28450
+ const sizeChanged = hasBase && headTotal !== baseTotal;
28451
+ const listed = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, changed, rootPath, buildDir, mainFile, readPackageJson, includeUnchanged: full, core });
28452
+ const sections = listed.filter((section) => !hasBase || section.hasChange);
28453
+ const hasChanged = hasBase && (changed ? sections.length > 0 : sizeChanged);
28454
+ const shortList = hasBase && !full;
28440
28455
  const summary2 = ["### Summary", `**Total size**: ${bytesToSize(headTotal)}<sup>*</sup>`];
28441
28456
  const markdown = [];
28442
28457
  const omitted = { files: 0, packages: 0 };
28443
- if (sections.length === 0) {
28444
- summary2.push("", "\u{1F389} No changes detected in any packages");
28445
- } else {
28446
- const tableHead = ["Filename", "Head", "Minified", "Gzipped", ...hasBase ? ["Compared to base"] : []];
28458
+ let hidden = 0;
28459
+ if (sections.length === 0) summary2.push("", "\u{1F389} No changes detected in any packages");
28460
+ if (sections.length > 0 || full && listed.length > 0) {
28447
28461
  const summaryRows = [];
28448
- const tables = sections.map(({ name, mainFile: packageMain, files }) => {
28462
+ const tables = (shortList ? sections : listed).flatMap(({ name, mainFile: packageMain, files }) => {
28449
28463
  const rows = [];
28450
28464
  [...files.keys()].sort().forEach((readableFilename) => {
28451
28465
  if (!isReportedFile(readableFilename)) return;
28466
+ if (shortList && !rowChanged(readableFilename, files, changed)) {
28467
+ hidden++;
28468
+ return;
28469
+ }
28452
28470
  const isMainFile = readableFilename === packageMain;
28453
28471
  const row = buildFileRow({ readableFilename, files, hasBase, isMainFile });
28454
28472
  if (isMainFile) summaryRows.push([name, ...row.slice(1)]);
28455
28473
  rows.push(row);
28456
28474
  });
28457
- return { name, rows };
28475
+ return rows.length > 0 ? [{ name, rows }] : [];
28458
28476
  });
28477
+ const columns = siblingColumns([...summaryRows, ...tables.flatMap(({ rows }) => rows)]);
28478
+ const tableHead = columns(["Filename", "Head", "Minified", "Gzipped", ...hasBase ? ["Compared to base"] : []]);
28479
+ const summaryHead = columns(["Package", "Size", "Minified", "Gzipped", ...hasBase ? ["\u0394"] : []]);
28480
+ tables.forEach((table) => table.rows = table.rows.map(columns));
28481
+ summaryRows.forEach((row, index) => summaryRows[index] = columns(row));
28459
28482
  let budget = maxLength - FIXED_OVERHEAD;
28460
- const summaryHead = ["Package", "Size", "Minified", "Gzipped", ...hasBase ? ["\u0394"] : []];
28461
28483
  const summaryFit = fitRows(summaryRows, Math.max(0, budget * SUMMARY_SHARE));
28462
28484
  budget -= summaryFit.used;
28463
28485
  tables.forEach(({ name, rows }) => {
@@ -28480,13 +28502,15 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28480
28502
  if (omitted.packages > 0) markdown.push("", `<em>\u2026 ${omitted.packages} more ${omitted.packages === 1 ? "package" : "packages"} not shown.</em>`);
28481
28503
  if (!hasBase) {
28482
28504
  summary2.push("No base branch to compare against.", "");
28483
- } else if (hasChanged) {
28505
+ } else if (sections.length === 0) {
28506
+ summary2.push("");
28507
+ } else if (sizeChanged) {
28484
28508
  const percent = printPercentChange(headTotal, baseTotal);
28485
- summary2.push(`**Total change (\u0394)**: ${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>`, "");
28509
+ summary2.push(`**Total change (\u0394)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${tables.length > 1 ? ' Other changes can be found in the collapsed <a href="#details">Details</a> section below.' : ""}</em></small>`, "");
28486
28510
  } else {
28487
- summary2.push("\u2705 **No change in file sizes**", "");
28511
+ summary2.push(hasChanged ? "\u2705 **No change in total size**" : "\u2705 **No change in file sizes**", "");
28488
28512
  }
28489
- if (sections.length > 1) {
28513
+ if (tables.length > 1) {
28490
28514
  markdown.unshift('<a name="details"></a>', "<details>", "<summary><b>File change details</b></summary>", "");
28491
28515
  markdown.push("", "</details>");
28492
28516
  }
@@ -28503,7 +28527,8 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28503
28527
  hasBase,
28504
28528
  hasChanged,
28505
28529
  sections,
28506
- omitted
28530
+ omitted,
28531
+ hidden
28507
28532
  };
28508
28533
  }
28509
28534
 
@@ -28536,13 +28561,32 @@ function isBinaryFile(path11) {
28536
28561
  closeSync(fd);
28537
28562
  }
28538
28563
  }
28564
+ var COMPRESSED = /\.(gz|br|zst)$/i;
28565
+ var isCompressed = (file) => COMPRESSED.test(file);
28566
+ var stripCompression = (file) => file.replace(COMPRESSED, "");
28567
+ function contentDiffers({ headRoot, baseRoot, file, headByteSize, baseByteSize, ignorePatterns = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE }) {
28568
+ if (headByteSize == null || baseByteSize == null || !baseRoot) return headByteSize !== baseByteSize;
28569
+ const headPath = join6(headRoot, file);
28570
+ const basePath = join6(baseRoot, file);
28571
+ try {
28572
+ if (ignorePatterns.length === 0 || Math.max(headByteSize, baseByteSize) > maxDiffSize) return headByteSize !== baseByteSize || !sameContent(headPath, basePath);
28573
+ const headContent = readFileSync3(headPath);
28574
+ const baseContent = readFileSync3(basePath);
28575
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return false;
28576
+ if (isBinary(headContent) || isBinary(baseContent)) return true;
28577
+ return ignoreMatches(headContent.toString("utf8"), ignorePatterns) !== ignoreMatches(baseContent.toString("utf8"), ignorePatterns);
28578
+ } catch {
28579
+ return true;
28580
+ }
28581
+ }
28582
+ var compareBuffers = [Buffer.allocUnsafe(COMPARE_CHUNK), Buffer.allocUnsafe(COMPARE_CHUNK)];
28539
28583
  function sameContent(a, b) {
28540
28584
  const fa = openSync(a, "r");
28541
28585
  let fb;
28542
28586
  try {
28543
28587
  fb = openSync(b, "r");
28544
- const bufA = Buffer.alloc(COMPARE_CHUNK);
28545
- const bufB = Buffer.alloc(COMPARE_CHUNK);
28588
+ const bufA = compareBuffers[0];
28589
+ const bufB = compareBuffers[1];
28546
28590
  for (let position = 0; ; position += COMPARE_CHUNK) {
28547
28591
  const readA = readSync(fa, bufA, 0, COMPARE_CHUNK, position);
28548
28592
  const readB = readSync(fb, bufB, 0, COMPARE_CHUNK, position);
@@ -28603,16 +28647,21 @@ async function gitDiff({ basePath, headPath, git = "git", timeout = DIFF_TIMEOUT
28603
28647
  throw Object.assign(new Error(reason), { reason, cause: error2 });
28604
28648
  }
28605
28649
  }
28606
- async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, renames = /* @__PURE__ */ new Map(), ignorePatterns = [], extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, core }) {
28650
+ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, renames = /* @__PURE__ */ new Map(), ignorePatterns = [], extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, diffs = true, core }) {
28607
28651
  const allowed = normalizeExtensions(extensions);
28608
28652
  const head = filterByExtensions(headMap, allowed);
28609
28653
  const base = filterByExtensions(baseMap, allowed);
28610
28654
  const text = [];
28611
28655
  const images = [];
28612
28656
  const stats = { added: 0, removed: 0, modified: 0, additions: 0, deletions: 0 };
28657
+ const changed = /* @__PURE__ */ new Set();
28613
28658
  const pending = [];
28614
28659
  const unreadable = [];
28615
- const files = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].filter(isReportedFile).sort();
28660
+ const all = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].sort();
28661
+ const hasSource = (file) => isCompressed(file) && (head.has(stripCompression(file)) || base.has(stripCompression(file)));
28662
+ const files = all.filter((file) => isReportedFile(file) && !hasSource(file));
28663
+ const reported = new Set(files);
28664
+ const derived = all.filter((file) => !reported.has(file));
28616
28665
  files.forEach((file) => {
28617
28666
  const headByteSize = head.get(file);
28618
28667
  const baseByteSize = base.get(file);
@@ -28622,28 +28671,32 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28622
28671
  const from = renames.get(file);
28623
28672
  const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, from ?? file) : void 0;
28624
28673
  let failure;
28625
- if (status === "modified" && headByteSize === baseByteSize) {
28626
- try {
28627
- if (sameContent(headPath, basePath)) return;
28628
- } catch (error2) {
28629
- failure = error2;
28630
- }
28631
- }
28632
28674
  let ignored;
28675
+ let binary;
28633
28676
  const textFile = !isImage(file) || baseExtension(file) === "svg";
28634
- if (status === "modified" && !failure && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28677
+ if (status === "modified" && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28635
28678
  try {
28636
28679
  const headContent = readFileSync3(headPath);
28637
28680
  const baseContent = readFileSync3(basePath);
28638
- if (!isBinary(headContent) && !isBinary(baseContent)) {
28681
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return;
28682
+ binary = isBinary(headContent) || isBinary(baseContent);
28683
+ if (!binary) {
28639
28684
  ignored = { head: ignoreMatches(headContent.toString("utf8"), ignorePatterns), base: ignoreMatches(baseContent.toString("utf8"), ignorePatterns) };
28640
28685
  if (ignored.head === ignored.base) return;
28641
28686
  }
28642
28687
  } catch (error2) {
28643
28688
  failure = error2;
28644
28689
  }
28690
+ } else if (status === "modified" && headByteSize === baseByteSize) {
28691
+ try {
28692
+ if (sameContent(headPath, basePath)) return;
28693
+ } catch (error2) {
28694
+ failure = error2;
28695
+ }
28645
28696
  }
28646
28697
  stats[status]++;
28698
+ changed.add(file);
28699
+ if (!diffs) return;
28647
28700
  if (isImage(file)) {
28648
28701
  images.push({ file, status, headByteSize, baseByteSize, headPath, basePath, ...from ? { from } : {} });
28649
28702
  if (baseExtension(file) !== "svg") return;
@@ -28652,7 +28705,8 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28652
28705
  text.push(change);
28653
28706
  if (!failure) {
28654
28707
  try {
28655
- if (headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath)) {
28708
+ binary ??= Boolean(headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath));
28709
+ if (binary) {
28656
28710
  change.skipped = "binary file";
28657
28711
  return;
28658
28712
  }
@@ -28671,11 +28725,17 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28671
28725
  }
28672
28726
  pending.push({ change, headPath, basePath, ignored });
28673
28727
  });
28728
+ derived.filter((file) => !hasSource(file)).forEach((file) => {
28729
+ if (contentDiffers({ headRoot, baseRoot, file, headByteSize: head.get(file), baseByteSize: base.get(file), ignorePatterns, maxDiffSize })) changed.add(file);
28730
+ });
28731
+ derived.filter(hasSource).forEach((file) => {
28732
+ if (changed.has(stripCompression(file))) changed.add(file);
28733
+ });
28674
28734
  if (unreadable.length > 0) core?.warning?.(`Could not read ${unreadable.length} file${unreadable.length === 1 ? "" : "s"}; listed without a diff: ${unreadable.slice(0, 5).join(", ")}${unreadable.length > 5 ? ", \u2026" : ""}`);
28675
28735
  if (pending.length > 0 && !await hasGit(git)) {
28676
28736
  core?.warning?.("`git` was not found on the PATH, so line diffs are skipped. Install git (it is preinstalled on GitHub-hosted runners) to see them.");
28677
28737
  pending.forEach(({ change }) => change.skipped = "git is not available on PATH");
28678
- return { text, images, stats };
28738
+ return { text, images, stats, changed };
28679
28739
  }
28680
28740
  const started = Date.now();
28681
28741
  let retained = 0;
@@ -28718,7 +28778,7 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28718
28778
  } finally {
28719
28779
  if (scratch) rmSync(scratch, { recursive: true, force: true });
28720
28780
  }
28721
- return { text, images, stats };
28781
+ return { text, images, stats, changed };
28722
28782
  }
28723
28783
 
28724
28784
  // src/comment.js
@@ -28757,6 +28817,15 @@ async function reportUrl({ octokit, owner, repo, dir, pagesUrl }) {
28757
28817
  }
28758
28818
  return `${String(base).replace(/\/+$/, "")}/${dir}/`;
28759
28819
  }
28820
+ async function pagesServing({ octokit, owner, repo, branch }) {
28821
+ try {
28822
+ const { data } = await octokit.rest.repos.getPages({ owner, repo });
28823
+ const served = data.build_type !== "workflow" && data.source?.branch === branch && (data.source?.path ?? "/") === "/";
28824
+ return served ? data.html_url : void 0;
28825
+ } catch {
28826
+ return void 0;
28827
+ }
28828
+ }
28760
28829
  var isStatus = (error2, status) => error2?.status === status;
28761
28830
  var defaultDelay = (attempt) => new Promise((resolve2) => setTimeout(resolve2, 200 * attempt + Math.random() * 300));
28762
28831
  async function branchHead({ git, owner, repo, branch }) {
@@ -28768,15 +28837,19 @@ async function branchHead({ git, owner, repo, branch }) {
28768
28837
  }
28769
28838
  }
28770
28839
  async function staleEntries({ git, owner, repo, baseTree, dir, keep }) {
28771
- const root = (await git.getTree({ owner, repo, tree_sha: baseTree })).data;
28772
- if (root.truncated) throw new Error("The report branch has too many top-level entries to list.");
28773
- const entry = root.tree.find(({ path: path11, type }) => path11 === dir && type === "tree");
28774
- if (!entry) return [];
28775
- const listing = (await git.getTree({ owner, repo, tree_sha: entry.sha, recursive: "true" })).data;
28840
+ let sha = baseTree;
28841
+ for (const part of dir.split("/")) {
28842
+ const level = (await git.getTree({ owner, repo, tree_sha: sha })).data;
28843
+ if (level.truncated) throw new Error("The report branch has too many entries in one folder to list.");
28844
+ const entry = level.tree.find(({ path: path11, type }) => path11 === part && type === "tree");
28845
+ if (!entry) return [];
28846
+ sha = entry.sha;
28847
+ }
28848
+ const listing = (await git.getTree({ owner, repo, tree_sha: sha, recursive: "true" })).data;
28776
28849
  if (listing.truncated) throw new Error(`${dir}/ has too many files to list on the report branch.`);
28777
28850
  return listing.tree.filter(({ type }) => type === "blob").map(({ path: path11 }) => `${dir}/${path11}`).filter((path11) => !keep.has(path11)).map((path11) => ({ path: path11, mode: "100644", type: "blob", sha: null }));
28778
28851
  }
28779
- async function publishToBranch({ octokit, owner, repo, branch, dir, files, message, delay = defaultDelay }) {
28852
+ async function publishToBranch({ octokit, owner, repo, branch, dir, files, message, keepHistory = false, delay = defaultDelay }) {
28780
28853
  const { git } = octokit.rest;
28781
28854
  const target = { git, owner, repo, branch };
28782
28855
  const blobs = await mapLimit(files, UPLOAD_CONCURRENCY, async ({ path: path11, content }) => {
@@ -28798,11 +28871,11 @@ async function publishToBranch({ octokit, owner, repo, branch, dir, files, messa
28798
28871
  const nojekyll = (await git.createBlob({ owner, repo, content: "", encoding: "utf-8" })).data.sha;
28799
28872
  tree = (await git.createTree({ owner, repo, tree: [...blobs, { path: ".nojekyll", mode: "100644", type: "blob", sha: nojekyll }] })).data.sha;
28800
28873
  }
28801
- const commit = (await git.createCommit({ owner, repo, message, tree, parents: [] })).data.sha;
28874
+ const commit = (await git.createCommit({ owner, repo, message, tree, parents: keepHistory && parent ? [parent] : [] })).data.sha;
28802
28875
  const moved = await branchHead(target) !== parent;
28803
28876
  if (!moved) {
28804
28877
  try {
28805
- if (parent) await git.updateRef({ owner, repo, ref: `heads/${branch}`, sha: commit, force: true });
28878
+ if (parent) await git.updateRef({ owner, repo, ref: `heads/${branch}`, sha: commit, force: !keepHistory });
28806
28879
  else await git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha: commit });
28807
28880
  return commit;
28808
28881
  } catch (error2) {
@@ -28928,7 +29001,7 @@ function matchRenames({ headMap, baseMap, headRoot, baseRoot, normalizeNames = [
28928
29001
  }
28929
29002
 
28930
29003
  // src/inputs.js
28931
- var VISUAL_DIFF_MODES = ["summary", "branch", "none"];
29004
+ var VISUAL_DIFF_MODES = ["auto", "summary", "branch", "none"];
28932
29005
  var BRANCH_NAME = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
28933
29006
  function readInputs(core) {
28934
29007
  const text = (name, fallback = "") => core.getInput(name).trim() || fallback;
@@ -28940,10 +29013,12 @@ function readInputs(core) {
28940
29013
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid ${name} "${raw}"; expected a whole number of 0 or more.`);
28941
29014
  return value;
28942
29015
  };
28943
- const visualDiff = text("visual-diff", "summary").toLowerCase();
29016
+ const visualDiff = text("visual-diff", "auto").toLowerCase();
28944
29017
  if (!VISUAL_DIFF_MODES.includes(visualDiff)) throw new Error(`Invalid visual-diff "${visualDiff}"; expected one of: ${VISUAL_DIFF_MODES.join(", ")}.`);
28945
29018
  const reportBranch = text("report-branch", DEFAULT_REPORT_BRANCH);
28946
29019
  if (!BRANCH_NAME.test(reportBranch) || reportBranch.includes("..") || reportBranch.endsWith(".lock") || reportBranch.endsWith(".")) throw new Error(`Invalid report-branch "${reportBranch}"; use letters, digits, ".", "_", "-" and "/" in a valid git branch name.`);
29020
+ const reportPath = text("report-path").replace(/^\/+|\/+$/g, "");
29021
+ if (reportPath && (!BRANCH_NAME.test(reportPath) || reportPath.split("/").some((part) => part === "." || part === ".."))) throw new Error(`Invalid report-path "${reportPath}"; use folder names of letters, digits, ".", "_" and "-", separated by "/".`);
28947
29022
  const renameThreshold = count("rename-threshold", DEFAULT_RENAME_THRESHOLD);
28948
29023
  if (renameThreshold > 100) throw new Error(`Invalid rename-threshold "${renameThreshold}"; expected a percentage from 0 to 100.`);
28949
29024
  const pagesUrl = text("pages-url");
@@ -28969,6 +29044,7 @@ function readInputs(core) {
28969
29044
  extensions: core.getMultilineInput("extensions", { trimWhitespace: true }),
28970
29045
  visualDiff,
28971
29046
  reportBranch,
29047
+ reportPath,
28972
29048
  pagesUrl,
28973
29049
  maxDiffSize: count("max-diff-size", DEFAULT_MAX_DIFF_SIZE),
28974
29050
  maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES),
@@ -30970,12 +31046,21 @@ function runUrl(env) {
30970
31046
  async function run({ core, context: context3, getOctokit: getOctokit2, env = process.env }) {
30971
31047
  const inputs = readInputs(core);
30972
31048
  const pullRequest = context3.payload.pull_request;
30973
- const dir = reportDir({ pullNumber: pullRequest?.number, sha: pullRequest?.head?.sha ?? context3.sha });
31049
+ const dir = [inputs.reportPath, reportDir({ pullNumber: pullRequest?.number, sha: pullRequest?.head?.sha ?? context3.sha })].filter(Boolean).join("/");
31050
+ const keepHistory = Boolean(inputs.reportPath);
30974
31051
  let client;
30975
31052
  const octokit = () => client ??= getOctokit2(inputs.token);
30976
- if (inputs.visualDiff === "branch" && pullRequest && context3.payload.action === "closed") {
31053
+ let visualDiff = inputs.visualDiff;
31054
+ let pagesUrl = inputs.pagesUrl;
31055
+ if (visualDiff === "auto") {
31056
+ const served = await pagesServing({ octokit: octokit(), ...context3.repo, branch: inputs.reportBranch });
31057
+ visualDiff = served ? "branch" : "summary";
31058
+ pagesUrl ||= served ?? "";
31059
+ core.info(served ? `GitHub Pages serves ${inputs.reportBranch}; publishing the visual diff there.` : `GitHub Pages doesn't serve ${inputs.reportBranch}; writing the visual diff to the job summary.`);
31060
+ }
31061
+ if (visualDiff === "branch" && pullRequest && context3.payload.action === "closed") {
30977
31062
  const { owner, repo } = context3.repo;
30978
- const sha = await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files: [], message: `chore: remove file diff report for #${pullRequest.number}` });
31063
+ const sha = await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files: [], keepHistory, message: `chore: remove file diff report for #${pullRequest.number}` });
30979
31064
  core.info(sha ? `Removed ${dir}/ from ${inputs.reportBranch}.` : `Nothing to remove for ${dir}/ on ${inputs.reportBranch}.`);
30980
31065
  return;
30981
31066
  }
@@ -30984,37 +31069,50 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30984
31069
  const { baseMap, renames, timedOut } = hasBase ? matchRenames({ headMap, baseMap: measuredBase, headRoot: inputs.headPath, baseRoot: inputs.basePath, normalizeNames: inputs.normalizeNames, threshold: inputs.renameThreshold }) : { baseMap: measuredBase, renames: /* @__PURE__ */ new Map(), timedOut: false };
30985
31070
  if (timedOut) core.warning("Stopped matching renamed files after 30 seconds; some may show as added and removed. Add normalize-names patterns or narrow file-glob-pattern.");
30986
31071
  if (renames.size > 0) core.info(`Matched ${renames.size} renamed file${renames.size === 1 ? "" : "s"} between base and head.`);
30987
- const reportOptions = { headMap, baseMap, hasBase, rootPath: inputs.headPath, buildDir: inputs.buildDir, mainFile: inputs.mainFile, readPackageJson: inputs.readPackageJson, extensions: inputs.extensions, core };
31072
+ const visual = visualDiff !== "none";
31073
+ const changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, renames, ignorePatterns: inputs.ignorePatterns, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, diffs: visual, core });
31074
+ const reportOptions = { headMap, baseMap, hasBase, changed: changes.changed, rootPath: inputs.headPath, buildDir: inputs.buildDir, mainFile: inputs.mainFile, readPackageJson: inputs.readPackageJson, extensions: inputs.extensions, core };
30988
31075
  const report = buildReport(reportOptions);
30989
- const reportWithin = (limit) => report.text.length <= limit ? report : buildReport({ ...reportOptions, maxLength: limit });
30990
- let changes;
31076
+ const fullReport = buildReport({ ...reportOptions, full: true });
31077
+ const shortened = /* @__PURE__ */ new Map();
31078
+ const reportWithin = (limit, full = false) => {
31079
+ const whole = full ? fullReport : report;
31080
+ if (whole.text.length <= limit) return whole;
31081
+ const key = `${full}:${limit}`;
31082
+ if (!shortened.has(key)) shortened.set(key, buildReport({ ...reportOptions, full, maxLength: limit }));
31083
+ return shortened.get(key);
31084
+ };
30991
31085
  let link;
31086
+ let published = false;
30992
31087
  let summaryMarkdown = "";
30993
- if (inputs.visualDiff !== "none") {
30994
- changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, renames, ignorePatterns: inputs.ignorePatterns, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, core });
31088
+ if (visual) {
30995
31089
  const rows = sizeRows(report.sections);
30996
31090
  const totals = { headTotal: report.headTotal, baseTotal: report.baseTotal };
30997
- if (inputs.visualDiff === "branch") {
31091
+ if (visualDiff === "branch") {
30998
31092
  try {
30999
31093
  const { owner, repo } = context3.repo;
31000
31094
  const where = pullRequest ? `${owner}/${repo}#${pullRequest.number}` : `${owner}/${repo}`;
31001
31095
  const files = reportFiles({ title: inputs.commentHeader.replace(/^#+\s*/, "") || "File metrics", rows, hasBase, changes, totals, context: `${where} @ ${(pullRequest?.head?.sha ?? context3.sha ?? "").slice(0, 7)}` });
31002
- await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files, message: `chore: file diff report for ${pullRequest ? `#${pullRequest.number}` : dir}` });
31003
- link = await reportUrl({ octokit: octokit(), owner, repo, dir, pagesUrl: inputs.pagesUrl });
31096
+ await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files, keepHistory, message: `chore: file diff report for ${pullRequest ? `#${pullRequest.number}` : dir}` });
31097
+ link = await reportUrl({ octokit: octokit(), owner, repo, dir, pagesUrl });
31098
+ published = true;
31004
31099
  core.info(`Published the visual diff to ${inputs.reportBranch}/${dir}/ (${link}).`);
31005
31100
  } catch (error2) {
31006
31101
  core.warning(`Unable to publish the visual diff to "${inputs.reportBranch}" (${error2.message}). Falling back to the job summary; the token needs contents: write.`);
31007
31102
  }
31008
31103
  }
31009
- const summaryReport = reportWithin(SUMMARY_BUDGET / 2);
31104
+ const summaryReport = reportWithin(SUMMARY_BUDGET / 2, true);
31010
31105
  summaryMarkdown = renderSummaryMarkdown({ rows, hasBase, changes, budget: Math.max(0, SUMMARY_BUDGET - Buffer.byteLength(summaryReport.text)), reportUrl: link });
31011
31106
  link ??= runUrl(env);
31012
31107
  }
31013
31108
  const marker = commentMarker(inputs.commentHeader);
31014
- const stats = changes ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31109
+ const stats = visual ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31015
31110
  const commentReport = reportWithin(COMMENT_LIMIT - COMMENT_RESERVE);
31016
- const omittedNote = commentReport.omitted.files > 0 ? `<em>Some rows were left out to fit GitHub's comment limit.${link ? ` See the [full report](${link}).` : ""}</em>` : "";
31017
- const commentStats = [stats, link ? `\u{1F4CA} [View the visual diff](${link})` : ""].filter(Boolean).join("<br/>\n");
31111
+ const summaryUrl = env.GITHUB_STEP_SUMMARY ? runUrl(env) : void 0;
31112
+ const notes = [commentReport.omitted.files > 0 ? `Some rows were left out to fit GitHub's comment limit.${link ? ` See the [full report](${link}).` : ""}` : "", commentReport.hidden > 0 ? `${commentReport.hidden} unchanged ${commentReport.hidden === 1 ? "file is" : "files are"} hidden.${summaryUrl ? ` See every file in the [job summary](${summaryUrl}).` : ""}` : ""].filter(Boolean);
31113
+ const omittedNote = notes.length > 0 ? `<em>${notes.join(" ")}</em>` : "";
31114
+ const linkLine = !link || hasBase && !report.hasChanged ? "" : published ? `\u{1F4CA} [View the visual diff](${link})` : `\u{1F4DD} [Size and line diffs in the job summary](${link})`;
31115
+ const commentStats = [stats, linkLine].filter(Boolean).join("<br/>\n");
31018
31116
  const content = [marker, inputs.commentHeader, "", ...commentStats ? [commentStats, ""] : [], commentReport.text, ...omittedNote ? ["", omittedNote] : []].join("\n");
31019
31117
  if (inputs.comment) {
31020
31118
  if (!pullRequest) core.info("Not running on a pull request; skipping the comment.");
@@ -31029,10 +31127,10 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31029
31127
  }
31030
31128
  }
31031
31129
  core.startGroup(inputs.commentHeader);
31032
- core.info(report.text);
31130
+ core.info(fullReport.text);
31033
31131
  core.endGroup();
31034
31132
  if (env.GITHUB_STEP_SUMMARY) {
31035
- const summaryReport = reportWithin(SUMMARY_BUDGET / 2);
31133
+ const summaryReport = reportWithin(SUMMARY_BUDGET / 2, true);
31036
31134
  await core.summary.addRaw([inputs.commentHeader, "", ...stats ? [stats, ""] : [], summaryReport.text, "", summaryMarkdown].join("\n"), true).write();
31037
31135
  }
31038
31136
  core.setOutput("total-size", String(report.headTotal));
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "registry": "https://registry.npmjs.org/"
6
6
  },
7
7
  "name": "@allons-y/actions-file-diff",
8
- "version": "0.3.0",
8
+ "version": "0.4.0",
9
9
  "description": "Compare compiled assets between branches and report the diff back on the pull request.",
10
10
  "license": "MPL-2.0",
11
11
  "author": "Cassondra Roberts <castastrophe@users.noreply.github.com> (https://allons-y.studio)",