@allons-y/actions-file-diff 0.3.1 → 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 +24 -3
  2. package/dist/index.js +94 -40
  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. |
@@ -141,9 +142,16 @@ 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.
148
+
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`
147
155
 
148
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.
@@ -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:
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, changed, 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(({ path: path11, headByteSize, baseByteSize }) => changed ? changed.has(path11) : 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,36 +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, changed, 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
28450
  const sizeChanged = hasBase && headTotal !== baseTotal;
28439
- const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, changed, rootPath, buildDir, mainFile, readPackageJson, core });
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);
28440
28453
  const hasChanged = hasBase && (changed ? sections.length > 0 : sizeChanged);
28454
+ const shortList = hasBase && !full;
28441
28455
  const summary2 = ["### Summary", `**Total size**: ${bytesToSize(headTotal)}<sup>*</sup>`];
28442
28456
  const markdown = [];
28443
28457
  const omitted = { files: 0, packages: 0 };
28444
- if (sections.length === 0) {
28445
- summary2.push("", "\u{1F389} No changes detected in any packages");
28446
- } else {
28447
- 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) {
28448
28461
  const summaryRows = [];
28449
- const tables = sections.map(({ name, mainFile: packageMain, files }) => {
28462
+ const tables = (shortList ? sections : listed).flatMap(({ name, mainFile: packageMain, files }) => {
28450
28463
  const rows = [];
28451
28464
  [...files.keys()].sort().forEach((readableFilename) => {
28452
28465
  if (!isReportedFile(readableFilename)) return;
28466
+ if (shortList && !rowChanged(readableFilename, files, changed)) {
28467
+ hidden++;
28468
+ return;
28469
+ }
28453
28470
  const isMainFile = readableFilename === packageMain;
28454
28471
  const row = buildFileRow({ readableFilename, files, hasBase, isMainFile });
28455
28472
  if (isMainFile) summaryRows.push([name, ...row.slice(1)]);
28456
28473
  rows.push(row);
28457
28474
  });
28458
- return { name, rows };
28475
+ return rows.length > 0 ? [{ name, rows }] : [];
28459
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));
28460
28482
  let budget = maxLength - FIXED_OVERHEAD;
28461
- const summaryHead = ["Package", "Size", "Minified", "Gzipped", ...hasBase ? ["\u0394"] : []];
28462
28483
  const summaryFit = fitRows(summaryRows, Math.max(0, budget * SUMMARY_SHARE));
28463
28484
  budget -= summaryFit.used;
28464
28485
  tables.forEach(({ name, rows }) => {
@@ -28481,13 +28502,15 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28481
28502
  if (omitted.packages > 0) markdown.push("", `<em>\u2026 ${omitted.packages} more ${omitted.packages === 1 ? "package" : "packages"} not shown.</em>`);
28482
28503
  if (!hasBase) {
28483
28504
  summary2.push("No base branch to compare against.", "");
28505
+ } else if (sections.length === 0) {
28506
+ summary2.push("");
28484
28507
  } else if (sizeChanged) {
28485
28508
  const percent = printPercentChange(headTotal, baseTotal);
28486
- 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>`, "");
28487
28510
  } else {
28488
28511
  summary2.push(hasChanged ? "\u2705 **No change in total size**" : "\u2705 **No change in file sizes**", "");
28489
28512
  }
28490
- if (sections.length > 1) {
28513
+ if (tables.length > 1) {
28491
28514
  markdown.unshift('<a name="details"></a>', "<details>", "<summary><b>File change details</b></summary>", "");
28492
28515
  markdown.push("", "</details>");
28493
28516
  }
@@ -28504,7 +28527,8 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28504
28527
  hasBase,
28505
28528
  hasChanged,
28506
28529
  sections,
28507
- omitted
28530
+ omitted,
28531
+ hidden
28508
28532
  };
28509
28533
  }
28510
28534
 
@@ -28793,6 +28817,15 @@ async function reportUrl({ octokit, owner, repo, dir, pagesUrl }) {
28793
28817
  }
28794
28818
  return `${String(base).replace(/\/+$/, "")}/${dir}/`;
28795
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
+ }
28796
28829
  var isStatus = (error2, status) => error2?.status === status;
28797
28830
  var defaultDelay = (attempt) => new Promise((resolve2) => setTimeout(resolve2, 200 * attempt + Math.random() * 300));
28798
28831
  async function branchHead({ git, owner, repo, branch }) {
@@ -28804,15 +28837,19 @@ async function branchHead({ git, owner, repo, branch }) {
28804
28837
  }
28805
28838
  }
28806
28839
  async function staleEntries({ git, owner, repo, baseTree, dir, keep }) {
28807
- const root = (await git.getTree({ owner, repo, tree_sha: baseTree })).data;
28808
- if (root.truncated) throw new Error("The report branch has too many top-level entries to list.");
28809
- const entry = root.tree.find(({ path: path11, type }) => path11 === dir && type === "tree");
28810
- if (!entry) return [];
28811
- 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;
28812
28849
  if (listing.truncated) throw new Error(`${dir}/ has too many files to list on the report branch.`);
28813
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 }));
28814
28851
  }
28815
- 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 }) {
28816
28853
  const { git } = octokit.rest;
28817
28854
  const target = { git, owner, repo, branch };
28818
28855
  const blobs = await mapLimit(files, UPLOAD_CONCURRENCY, async ({ path: path11, content }) => {
@@ -28834,11 +28871,11 @@ async function publishToBranch({ octokit, owner, repo, branch, dir, files, messa
28834
28871
  const nojekyll = (await git.createBlob({ owner, repo, content: "", encoding: "utf-8" })).data.sha;
28835
28872
  tree = (await git.createTree({ owner, repo, tree: [...blobs, { path: ".nojekyll", mode: "100644", type: "blob", sha: nojekyll }] })).data.sha;
28836
28873
  }
28837
- 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;
28838
28875
  const moved = await branchHead(target) !== parent;
28839
28876
  if (!moved) {
28840
28877
  try {
28841
- 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 });
28842
28879
  else await git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha: commit });
28843
28880
  return commit;
28844
28881
  } catch (error2) {
@@ -28964,7 +29001,7 @@ function matchRenames({ headMap, baseMap, headRoot, baseRoot, normalizeNames = [
28964
29001
  }
28965
29002
 
28966
29003
  // src/inputs.js
28967
- var VISUAL_DIFF_MODES = ["summary", "branch", "none"];
29004
+ var VISUAL_DIFF_MODES = ["auto", "summary", "branch", "none"];
28968
29005
  var BRANCH_NAME = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
28969
29006
  function readInputs(core) {
28970
29007
  const text = (name, fallback = "") => core.getInput(name).trim() || fallback;
@@ -28976,10 +29013,12 @@ function readInputs(core) {
28976
29013
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid ${name} "${raw}"; expected a whole number of 0 or more.`);
28977
29014
  return value;
28978
29015
  };
28979
- const visualDiff = text("visual-diff", "summary").toLowerCase();
29016
+ const visualDiff = text("visual-diff", "auto").toLowerCase();
28980
29017
  if (!VISUAL_DIFF_MODES.includes(visualDiff)) throw new Error(`Invalid visual-diff "${visualDiff}"; expected one of: ${VISUAL_DIFF_MODES.join(", ")}.`);
28981
29018
  const reportBranch = text("report-branch", DEFAULT_REPORT_BRANCH);
28982
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 "/".`);
28983
29022
  const renameThreshold = count("rename-threshold", DEFAULT_RENAME_THRESHOLD);
28984
29023
  if (renameThreshold > 100) throw new Error(`Invalid rename-threshold "${renameThreshold}"; expected a percentage from 0 to 100.`);
28985
29024
  const pagesUrl = text("pages-url");
@@ -29005,6 +29044,7 @@ function readInputs(core) {
29005
29044
  extensions: core.getMultilineInput("extensions", { trimWhitespace: true }),
29006
29045
  visualDiff,
29007
29046
  reportBranch,
29047
+ reportPath,
29008
29048
  pagesUrl,
29009
29049
  maxDiffSize: count("max-diff-size", DEFAULT_MAX_DIFF_SIZE),
29010
29050
  maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES),
@@ -31006,12 +31046,21 @@ function runUrl(env) {
31006
31046
  async function run({ core, context: context3, getOctokit: getOctokit2, env = process.env }) {
31007
31047
  const inputs = readInputs(core);
31008
31048
  const pullRequest = context3.payload.pull_request;
31009
- 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);
31010
31051
  let client;
31011
31052
  const octokit = () => client ??= getOctokit2(inputs.token);
31012
- 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") {
31013
31062
  const { owner, repo } = context3.repo;
31014
- 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}` });
31015
31064
  core.info(sha ? `Removed ${dir}/ from ${inputs.reportBranch}.` : `Nothing to remove for ${dir}/ on ${inputs.reportBranch}.`);
31016
31065
  return;
31017
31066
  }
@@ -31020,15 +31069,18 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31020
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 };
31021
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.");
31022
31071
  if (renames.size > 0) core.info(`Matched ${renames.size} renamed file${renames.size === 1 ? "" : "s"} between base and head.`);
31023
- const visual = inputs.visualDiff !== "none";
31072
+ const visual = visualDiff !== "none";
31024
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 });
31025
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 };
31026
31075
  const report = buildReport(reportOptions);
31076
+ const fullReport = buildReport({ ...reportOptions, full: true });
31027
31077
  const shortened = /* @__PURE__ */ new Map();
31028
- const reportWithin = (limit) => {
31029
- if (report.text.length <= limit) return report;
31030
- if (!shortened.has(limit)) shortened.set(limit, buildReport({ ...reportOptions, maxLength: limit }));
31031
- return shortened.get(limit);
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);
31032
31084
  };
31033
31085
  let link;
31034
31086
  let published = false;
@@ -31036,27 +31088,29 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31036
31088
  if (visual) {
31037
31089
  const rows = sizeRows(report.sections);
31038
31090
  const totals = { headTotal: report.headTotal, baseTotal: report.baseTotal };
31039
- if (inputs.visualDiff === "branch") {
31091
+ if (visualDiff === "branch") {
31040
31092
  try {
31041
31093
  const { owner, repo } = context3.repo;
31042
31094
  const where = pullRequest ? `${owner}/${repo}#${pullRequest.number}` : `${owner}/${repo}`;
31043
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)}` });
31044
- await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files, message: `chore: file diff report for ${pullRequest ? `#${pullRequest.number}` : dir}` });
31045
- 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 });
31046
31098
  published = true;
31047
31099
  core.info(`Published the visual diff to ${inputs.reportBranch}/${dir}/ (${link}).`);
31048
31100
  } catch (error2) {
31049
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.`);
31050
31102
  }
31051
31103
  }
31052
- const summaryReport = reportWithin(SUMMARY_BUDGET / 2);
31104
+ const summaryReport = reportWithin(SUMMARY_BUDGET / 2, true);
31053
31105
  summaryMarkdown = renderSummaryMarkdown({ rows, hasBase, changes, budget: Math.max(0, SUMMARY_BUDGET - Buffer.byteLength(summaryReport.text)), reportUrl: link });
31054
31106
  link ??= runUrl(env);
31055
31107
  }
31056
31108
  const marker = commentMarker(inputs.commentHeader);
31057
31109
  const stats = visual ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31058
31110
  const commentReport = reportWithin(COMMENT_LIMIT - COMMENT_RESERVE);
31059
- 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>` : "";
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>` : "";
31060
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})`;
31061
31115
  const commentStats = [stats, linkLine].filter(Boolean).join("<br/>\n");
31062
31116
  const content = [marker, inputs.commentHeader, "", ...commentStats ? [commentStats, ""] : [], commentReport.text, ...omittedNote ? ["", omittedNote] : []].join("\n");
@@ -31073,10 +31127,10 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31073
31127
  }
31074
31128
  }
31075
31129
  core.startGroup(inputs.commentHeader);
31076
- core.info(report.text);
31130
+ core.info(fullReport.text);
31077
31131
  core.endGroup();
31078
31132
  if (env.GITHUB_STEP_SUMMARY) {
31079
- const summaryReport = reportWithin(SUMMARY_BUDGET / 2);
31133
+ const summaryReport = reportWithin(SUMMARY_BUDGET / 2, true);
31080
31134
  await core.summary.addRaw([inputs.commentHeader, "", ...stats ? [stats, ""] : [], summaryReport.text, "", summaryMarkdown].join("\n"), true).write();
31081
31135
  }
31082
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.1",
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)",