@allons-y/actions-file-diff 0.3.0 → 0.3.1

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 +4 -3
  2. package/dist/index.js +74 -30
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -125,7 +125,7 @@ If `base-path` is omitted, or the directory does not exist, the action reports h
125
125
 
126
126
  | Name | Description |
127
127
  | ------------- | ------------------------------------------------------------------------------------------------- |
128
- | `has-changed` | `"true"` when the head total differs from the base total. Always `"false"` when there is no base. |
128
+ | `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
129
  | `total-size` | Head total in bytes. |
130
130
  | `report-url` | Link to the visual diff (published page or workflow run). Empty when `visual-diff` is `none`. |
131
131
 
@@ -145,7 +145,7 @@ The pull request comment is shortened to fit GitHub's 65,536-character limit; wh
145
145
 
146
146
  ### `visual-diff: summary` (default)
147
147
 
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.
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, unless no files changed.
149
149
  - No extra permissions or setup.
150
150
  - 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
151
 
@@ -214,8 +214,9 @@ ignore-patterns: |
214
214
  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
215
 
216
216
  - It applies to text files up to `max-diff-size`. Larger and binary files compare byte for byte.
217
+ - Minified copies and source maps (`.min.*`, `.map`) are compared the same way, though they get no line diff of their own.
218
+ - 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
219
  - 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
220
 
220
221
  ### How sizes are counted
221
222
 
package/dist/index.js CHANGED
@@ -28399,11 +28399,11 @@ 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
+ function buildSections(packages, { hasBase, changed, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
28403
28403
  const sections = [];
28404
28404
  packages.forEach(({ name, packageDir, files }) => {
28405
28405
  if (files.size === 0) return;
28406
- const hasChange = [...files.values()].some(({ headByteSize, baseByteSize }) => headByteSize !== baseByteSize);
28406
+ const hasChange = [...files.values()].some(({ path: path11, headByteSize, baseByteSize }) => changed ? changed.has(path11) : headByteSize !== baseByteSize);
28407
28407
  if (hasBase && !hasChange) return;
28408
28408
  sections.push({
28409
28409
  name,
@@ -28429,14 +28429,15 @@ function fitRows(rows, budget) {
28429
28429
  }
28430
28430
  return { kept, used };
28431
28431
  }
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 } = {}) {
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 } = {}) {
28433
28433
  const allowed = normalizeExtensions(extensions);
28434
28434
  const head = filterByExtensions(headMap, allowed);
28435
28435
  const base = hasBase ? filterByExtensions(baseMap, allowed) : /* @__PURE__ */ new Map();
28436
28436
  const headTotal = totalSize(head);
28437
28437
  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 });
28438
+ const sizeChanged = hasBase && headTotal !== baseTotal;
28439
+ const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, changed, rootPath, buildDir, mainFile, readPackageJson, core });
28440
+ const hasChanged = hasBase && (changed ? sections.length > 0 : sizeChanged);
28440
28441
  const summary2 = ["### Summary", `**Total size**: ${bytesToSize(headTotal)}<sup>*</sup>`];
28441
28442
  const markdown = [];
28442
28443
  const omitted = { files: 0, packages: 0 };
@@ -28480,11 +28481,11 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28480
28481
  if (omitted.packages > 0) markdown.push("", `<em>\u2026 ${omitted.packages} more ${omitted.packages === 1 ? "package" : "packages"} not shown.</em>`);
28481
28482
  if (!hasBase) {
28482
28483
  summary2.push("No base branch to compare against.", "");
28483
- } else if (hasChanged) {
28484
+ } else if (sizeChanged) {
28484
28485
  const percent = printPercentChange(headTotal, baseTotal);
28485
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>`, "");
28486
28487
  } else {
28487
- summary2.push("\u2705 **No change in file sizes**", "");
28488
+ summary2.push(hasChanged ? "\u2705 **No change in total size**" : "\u2705 **No change in file sizes**", "");
28488
28489
  }
28489
28490
  if (sections.length > 1) {
28490
28491
  markdown.unshift('<a name="details"></a>', "<details>", "<summary><b>File change details</b></summary>", "");
@@ -28536,13 +28537,32 @@ function isBinaryFile(path11) {
28536
28537
  closeSync(fd);
28537
28538
  }
28538
28539
  }
28540
+ var COMPRESSED = /\.(gz|br|zst)$/i;
28541
+ var isCompressed = (file) => COMPRESSED.test(file);
28542
+ var stripCompression = (file) => file.replace(COMPRESSED, "");
28543
+ function contentDiffers({ headRoot, baseRoot, file, headByteSize, baseByteSize, ignorePatterns = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE }) {
28544
+ if (headByteSize == null || baseByteSize == null || !baseRoot) return headByteSize !== baseByteSize;
28545
+ const headPath = join6(headRoot, file);
28546
+ const basePath = join6(baseRoot, file);
28547
+ try {
28548
+ if (ignorePatterns.length === 0 || Math.max(headByteSize, baseByteSize) > maxDiffSize) return headByteSize !== baseByteSize || !sameContent(headPath, basePath);
28549
+ const headContent = readFileSync3(headPath);
28550
+ const baseContent = readFileSync3(basePath);
28551
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return false;
28552
+ if (isBinary(headContent) || isBinary(baseContent)) return true;
28553
+ return ignoreMatches(headContent.toString("utf8"), ignorePatterns) !== ignoreMatches(baseContent.toString("utf8"), ignorePatterns);
28554
+ } catch {
28555
+ return true;
28556
+ }
28557
+ }
28558
+ var compareBuffers = [Buffer.allocUnsafe(COMPARE_CHUNK), Buffer.allocUnsafe(COMPARE_CHUNK)];
28539
28559
  function sameContent(a, b) {
28540
28560
  const fa = openSync(a, "r");
28541
28561
  let fb;
28542
28562
  try {
28543
28563
  fb = openSync(b, "r");
28544
- const bufA = Buffer.alloc(COMPARE_CHUNK);
28545
- const bufB = Buffer.alloc(COMPARE_CHUNK);
28564
+ const bufA = compareBuffers[0];
28565
+ const bufB = compareBuffers[1];
28546
28566
  for (let position = 0; ; position += COMPARE_CHUNK) {
28547
28567
  const readA = readSync(fa, bufA, 0, COMPARE_CHUNK, position);
28548
28568
  const readB = readSync(fb, bufB, 0, COMPARE_CHUNK, position);
@@ -28603,16 +28623,21 @@ async function gitDiff({ basePath, headPath, git = "git", timeout = DIFF_TIMEOUT
28603
28623
  throw Object.assign(new Error(reason), { reason, cause: error2 });
28604
28624
  }
28605
28625
  }
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 }) {
28626
+ 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
28627
  const allowed = normalizeExtensions(extensions);
28608
28628
  const head = filterByExtensions(headMap, allowed);
28609
28629
  const base = filterByExtensions(baseMap, allowed);
28610
28630
  const text = [];
28611
28631
  const images = [];
28612
28632
  const stats = { added: 0, removed: 0, modified: 0, additions: 0, deletions: 0 };
28633
+ const changed = /* @__PURE__ */ new Set();
28613
28634
  const pending = [];
28614
28635
  const unreadable = [];
28615
- const files = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].filter(isReportedFile).sort();
28636
+ const all = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].sort();
28637
+ const hasSource = (file) => isCompressed(file) && (head.has(stripCompression(file)) || base.has(stripCompression(file)));
28638
+ const files = all.filter((file) => isReportedFile(file) && !hasSource(file));
28639
+ const reported = new Set(files);
28640
+ const derived = all.filter((file) => !reported.has(file));
28616
28641
  files.forEach((file) => {
28617
28642
  const headByteSize = head.get(file);
28618
28643
  const baseByteSize = base.get(file);
@@ -28622,28 +28647,32 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28622
28647
  const from = renames.get(file);
28623
28648
  const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, from ?? file) : void 0;
28624
28649
  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
28650
  let ignored;
28651
+ let binary;
28633
28652
  const textFile = !isImage(file) || baseExtension(file) === "svg";
28634
- if (status === "modified" && !failure && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28653
+ if (status === "modified" && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28635
28654
  try {
28636
28655
  const headContent = readFileSync3(headPath);
28637
28656
  const baseContent = readFileSync3(basePath);
28638
- if (!isBinary(headContent) && !isBinary(baseContent)) {
28657
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return;
28658
+ binary = isBinary(headContent) || isBinary(baseContent);
28659
+ if (!binary) {
28639
28660
  ignored = { head: ignoreMatches(headContent.toString("utf8"), ignorePatterns), base: ignoreMatches(baseContent.toString("utf8"), ignorePatterns) };
28640
28661
  if (ignored.head === ignored.base) return;
28641
28662
  }
28642
28663
  } catch (error2) {
28643
28664
  failure = error2;
28644
28665
  }
28666
+ } else if (status === "modified" && headByteSize === baseByteSize) {
28667
+ try {
28668
+ if (sameContent(headPath, basePath)) return;
28669
+ } catch (error2) {
28670
+ failure = error2;
28671
+ }
28645
28672
  }
28646
28673
  stats[status]++;
28674
+ changed.add(file);
28675
+ if (!diffs) return;
28647
28676
  if (isImage(file)) {
28648
28677
  images.push({ file, status, headByteSize, baseByteSize, headPath, basePath, ...from ? { from } : {} });
28649
28678
  if (baseExtension(file) !== "svg") return;
@@ -28652,7 +28681,8 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28652
28681
  text.push(change);
28653
28682
  if (!failure) {
28654
28683
  try {
28655
- if (headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath)) {
28684
+ binary ??= Boolean(headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath));
28685
+ if (binary) {
28656
28686
  change.skipped = "binary file";
28657
28687
  return;
28658
28688
  }
@@ -28671,11 +28701,17 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28671
28701
  }
28672
28702
  pending.push({ change, headPath, basePath, ignored });
28673
28703
  });
28704
+ derived.filter((file) => !hasSource(file)).forEach((file) => {
28705
+ if (contentDiffers({ headRoot, baseRoot, file, headByteSize: head.get(file), baseByteSize: base.get(file), ignorePatterns, maxDiffSize })) changed.add(file);
28706
+ });
28707
+ derived.filter(hasSource).forEach((file) => {
28708
+ if (changed.has(stripCompression(file))) changed.add(file);
28709
+ });
28674
28710
  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
28711
  if (pending.length > 0 && !await hasGit(git)) {
28676
28712
  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
28713
  pending.forEach(({ change }) => change.skipped = "git is not available on PATH");
28678
- return { text, images, stats };
28714
+ return { text, images, stats, changed };
28679
28715
  }
28680
28716
  const started = Date.now();
28681
28717
  let retained = 0;
@@ -28718,7 +28754,7 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28718
28754
  } finally {
28719
28755
  if (scratch) rmSync(scratch, { recursive: true, force: true });
28720
28756
  }
28721
- return { text, images, stats };
28757
+ return { text, images, stats, changed };
28722
28758
  }
28723
28759
 
28724
28760
  // src/comment.js
@@ -30984,14 +31020,20 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30984
31020
  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
31021
  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
31022
  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 };
31023
+ const visual = inputs.visualDiff !== "none";
31024
+ 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
+ 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
31026
  const report = buildReport(reportOptions);
30989
- const reportWithin = (limit) => report.text.length <= limit ? report : buildReport({ ...reportOptions, maxLength: limit });
30990
- let changes;
31027
+ 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);
31032
+ };
30991
31033
  let link;
31034
+ let published = false;
30992
31035
  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 });
31036
+ if (visual) {
30995
31037
  const rows = sizeRows(report.sections);
30996
31038
  const totals = { headTotal: report.headTotal, baseTotal: report.baseTotal };
30997
31039
  if (inputs.visualDiff === "branch") {
@@ -31001,6 +31043,7 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31001
31043
  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
31044
  await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files, message: `chore: file diff report for ${pullRequest ? `#${pullRequest.number}` : dir}` });
31003
31045
  link = await reportUrl({ octokit: octokit(), owner, repo, dir, pagesUrl: inputs.pagesUrl });
31046
+ published = true;
31004
31047
  core.info(`Published the visual diff to ${inputs.reportBranch}/${dir}/ (${link}).`);
31005
31048
  } catch (error2) {
31006
31049
  core.warning(`Unable to publish the visual diff to "${inputs.reportBranch}" (${error2.message}). Falling back to the job summary; the token needs contents: write.`);
@@ -31011,10 +31054,11 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
31011
31054
  link ??= runUrl(env);
31012
31055
  }
31013
31056
  const marker = commentMarker(inputs.commentHeader);
31014
- const stats = changes ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31057
+ const stats = visual ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31015
31058
  const commentReport = reportWithin(COMMENT_LIMIT - COMMENT_RESERVE);
31016
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>` : "";
31017
- const commentStats = [stats, link ? `\u{1F4CA} [View the visual diff](${link})` : ""].filter(Boolean).join("<br/>\n");
31060
+ 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
+ const commentStats = [stats, linkLine].filter(Boolean).join("<br/>\n");
31018
31062
  const content = [marker, inputs.commentHeader, "", ...commentStats ? [commentStats, ""] : [], commentReport.text, ...omittedNote ? ["", omittedNote] : []].join("\n");
31019
31063
  if (inputs.comment) {
31020
31064
  if (!pullRequest) core.info("Not running on a pull request; skipping the comment.");
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.3.1",
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)",