mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5c1c2ee4d |
No files matched your search
@@ -226,10 +226,22 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
|
||||
|
||||
- name: 🖼️ Check the corpus renders against its references
|
||||
id: check
|
||||
run: cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
|
||||
|
||||
# The `comment-regression-renders.yml` workflow reads these to post the mismatches on the PR, since fork PRs can't be given the permission here
|
||||
- name: 📝 Record the PR and outcome for the render comment
|
||||
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
OUTCOME: ${{ steps.check.outcome }}
|
||||
run: |
|
||||
mkdir -p target/regression
|
||||
echo "$PR_NUMBER" > target/regression/pr-number
|
||||
echo "$OUTCOME" > target/regression/outcome
|
||||
|
||||
- name: 📤 Upload the renders and diffs of mismatches
|
||||
if: ${{ failure() }}
|
||||
if: ${{ !cancelled() && (failure() || github.event_name == 'pull_request') }}
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: regression-mismatches
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
name: "Regression Render Comment"
|
||||
|
||||
# Runs after the Check workflow in the base repository's context, which fork PRs can't reach themselves.
|
||||
# It never checks out or runs PR code, and everything read from the artifact is treated as untrusted data.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Check"]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
if: github.event.workflow_run.event == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Download the artifact of the Check run
|
||||
actions: read
|
||||
# Post and update the render comment
|
||||
pull-requests: write
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
||||
RUN_URL: ${{ github.event.workflow_run.html_url }}
|
||||
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
MARKER: "<!-- regression-renders -->"
|
||||
steps:
|
||||
- name: 📥 Download the renders of mismatches
|
||||
id: download
|
||||
run: |
|
||||
if ! gh run download "$RUN_ID" --repo "$REPOSITORY" --name regression-mismatches --dir mismatches; then
|
||||
echo "The Check run has no render artifact (the regression job was skipped or didn't get that far)"
|
||||
echo "found=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
echo "found=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 🔍 Validate the PR and outcome
|
||||
id: validate
|
||||
if: steps.download.outputs.found == 'true'
|
||||
run: |
|
||||
PR_NUMBER=$(head -c 32 mismatches/pr-number 2>/dev/null | tr -d '[:space:]')
|
||||
OUTCOME=$(head -c 32 mismatches/outcome 2>/dev/null | tr -d '[:space:]')
|
||||
if ! [[ "$PR_NUMBER" =~ ^[0-9]+$ ]]; then
|
||||
echo "The artifact names no valid PR number"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$OUTCOME" != "success" && "$OUTCOME" != "failure" ]]; then
|
||||
echo "The corpus check didn't finish (outcome '$OUTCOME'), so there is nothing to report"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The artifact could claim any PR, so only accept the one whose head is the commit that was checked. A newer push gets its own run.
|
||||
PR_HEAD=$(gh api "repos/$REPOSITORY/pulls/$PR_NUMBER" --jq '.head.sha')
|
||||
if [ "$PR_HEAD" != "$HEAD_SHA" ]; then
|
||||
echo "PR #$PR_NUMBER has moved on from $HEAD_SHA, skipping"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
|
||||
echo "outcome=$OUTCOME" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 🗂️ Collect the side-by-side images
|
||||
id: collect
|
||||
if: steps.validate.outputs.outcome == 'failure'
|
||||
run: |
|
||||
# Only PNGs from documents with plain names are published, so the artifact can't place pages or markup on the site or in the comment
|
||||
mkdir -p site
|
||||
COUNT=0
|
||||
while IFS= read -r -d '' IMAGE; do
|
||||
RELATIVE="${IMAGE#mismatches/}"
|
||||
DOCUMENT="${RELATIVE%/*}"
|
||||
FILE="${RELATIVE##*/}"
|
||||
if ! [[ "$DOCUMENT" =~ ^[A-Za-z0-9\ ._-]+$ && "$FILE" =~ ^[0-9]+\.[0-9]+s\.side-by-side\.png$ ]]; then
|
||||
echo "Skipping unexpected file '$RELATIVE'"
|
||||
continue
|
||||
fi
|
||||
if [ "$(head -c 8 "$IMAGE" | od -An -tx1 | tr -d ' \n')" != "89504e470d0a1a0a" ]; then
|
||||
echo "Skipping '$RELATIVE', which isn't a PNG"
|
||||
continue
|
||||
fi
|
||||
mkdir -p "site/$DOCUMENT"
|
||||
cp "$IMAGE" "site/$DOCUMENT/$FILE"
|
||||
COUNT=$((COUNT + 1))
|
||||
done < <(find mismatches -mindepth 2 -maxdepth 2 -type f -name '*.side-by-side.png' -print0 | sort -z)
|
||||
echo "count=$COUNT" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 📤 Publish the images to Cloudflare Pages
|
||||
id: cloudflare
|
||||
if: steps.collect.outputs.count > 0
|
||||
continue-on-error: true
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
PROJECT: ${{ vars.REGRESSION_PAGES_PROJECT || 'graphite-regression' }}
|
||||
PR_NUMBER: ${{ steps.validate.outputs.pr_number }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available, so the comment lists the mismatches without images"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Creating the project fails harmlessly once it exists
|
||||
npx wrangler@3 pages project create "$PROJECT" --production-branch=master || true
|
||||
|
||||
MAX_ATTEMPTS=5
|
||||
DELAY=15
|
||||
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
|
||||
echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..."
|
||||
npx wrangler@3 pages deploy site --project-name="$PROJECT" --branch="pr-$PR_NUMBER" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
|
||||
if [ ${PIPESTATUS[0]} -eq 0 ]; then
|
||||
# The deployment's own URL rather than the branch alias, so GitHub's image cache never shows an older push's images
|
||||
URL=$(grep -oP 'https://[^\s]+\.pages\.dev' /tmp/wrangler_output | head -1)
|
||||
echo "url=$URL" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$ATTEMPT" -lt "$MAX_ATTEMPTS" ]; then
|
||||
sleep "$DELAY"
|
||||
DELAY=$((DELAY * 2))
|
||||
fi
|
||||
done
|
||||
echo "All $MAX_ATTEMPTS Cloudflare Pages publish attempts failed"
|
||||
exit 1
|
||||
|
||||
- name: 💬 Post or update the render comment
|
||||
if: steps.validate.outputs.outcome != ''
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.validate.outputs.pr_number }}
|
||||
OUTCOME: ${{ steps.validate.outputs.outcome }}
|
||||
IMAGE_COUNT: ${{ steps.collect.outputs.count || 0 }}
|
||||
SITE_URL: ${{ steps.cloudflare.outputs.url }}
|
||||
run: |
|
||||
EXISTING=$(gh api --paginate "repos/$REPOSITORY/issues/$PR_NUMBER/comments" \
|
||||
--jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(env.MARKER))) | .id' | head -1)
|
||||
|
||||
if [ "$OUTCOME" = "success" ]; then
|
||||
if [ -z "$EXISTING" ]; then
|
||||
echo "Every render matches and there is no earlier comment to update"
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n### Corpus renders\n\nEvery corpus render matches its reference again.\n' "$MARKER" > body.md
|
||||
else
|
||||
{
|
||||
echo "$MARKER"
|
||||
echo "### Corpus render changes"
|
||||
echo
|
||||
if [ "$IMAGE_COUNT" -eq 0 ]; then
|
||||
echo "The corpus check failed without differing images, so a document failed to render or changed size. See the [Check run]($RUN_URL)."
|
||||
else
|
||||
echo "Each image shows the reference, this PR's render, and the differing pixels in red, cropped to where they differ. If the change is intended, bless the affected documents in the corpus."
|
||||
echo
|
||||
MAX_IMAGES=20
|
||||
SHOWN=0
|
||||
while IFS= read -r -d '' IMAGE; do
|
||||
if [ "$SHOWN" -ge "$MAX_IMAGES" ]; then
|
||||
echo "And $((IMAGE_COUNT - MAX_IMAGES)) more, see the [Check run]($RUN_URL)."
|
||||
break
|
||||
fi
|
||||
RELATIVE="${IMAGE#site/}"
|
||||
DOCUMENT="${RELATIVE%/*}"
|
||||
TIME="${RELATIVE##*/}"
|
||||
TIME="${TIME%.side-by-side.png}"
|
||||
echo "<details open><summary>$DOCUMENT at $TIME</summary>"
|
||||
echo
|
||||
if [ -n "$SITE_URL" ]; then
|
||||
echo "<img src=\"$SITE_URL/$(jq -rn --arg path "$RELATIVE" '$path | @uri | gsub("%2F"; "/")')\" alt=\"$DOCUMENT at $TIME\">"
|
||||
else
|
||||
echo "Images couldn't be published, see the \`regression-mismatches\` artifact of the [Check run]($RUN_URL)."
|
||||
fi
|
||||
echo
|
||||
echo "</details>"
|
||||
SHOWN=$((SHOWN + 1))
|
||||
done < <(find site -type f -name '*.side-by-side.png' -print0 | sort -z)
|
||||
echo
|
||||
echo "The full renders and diffs are in the \`regression-mismatches\` artifact of the [Check run]($RUN_URL)."
|
||||
fi
|
||||
} > body.md
|
||||
fi
|
||||
|
||||
if [ -n "$EXISTING" ]; then
|
||||
gh api -X PATCH "repos/$REPOSITORY/issues/comments/$EXISTING" -F [email protected] > /dev/null
|
||||
else
|
||||
gh api "repos/$REPOSITORY/issues/$PR_NUMBER/comments" -F [email protected] > /dev/null
|
||||
fi
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
use crate::corpus::Tolerance;
|
||||
use image::RgbaImage;
|
||||
use image::imageops::{self, FilterType};
|
||||
use image::math::Rect;
|
||||
|
||||
/// Pixels of unchanged surroundings kept around the differing region in a side-by-side image.
|
||||
const CONTEXT_MARGIN: u32 = 32;
|
||||
/// The widest a side-by-side image gets before it is scaled down.
|
||||
const MAX_SIDE_BY_SIDE_WIDTH: u32 = 1800;
|
||||
const PANEL_GAP: u32 = 8;
|
||||
|
||||
pub(crate) enum Comparison {
|
||||
Matches,
|
||||
@@ -9,11 +17,12 @@ pub(crate) enum Comparison {
|
||||
reference: (u32, u32),
|
||||
actual: (u32, u32),
|
||||
},
|
||||
/// More pixels than the tolerance allows differ, highlighted in `diff`.
|
||||
/// More pixels than the tolerance allows differ, highlighted in `diff` and all within `region`.
|
||||
Differs {
|
||||
differing: usize,
|
||||
total: usize,
|
||||
diff: RgbaImage,
|
||||
region: Rect,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -29,10 +38,13 @@ pub(crate) fn compare(reference: &RgbaImage, actual: &RgbaImage, tolerance: Tole
|
||||
// Differing pixels show red over a faded copy of the reference, so they stand out in context
|
||||
let mut diff = RgbaImage::new(actual.width(), actual.height());
|
||||
let mut differing = 0;
|
||||
for ((expected, rendered), marked) in reference.pixels().zip(actual.pixels()).zip(diff.pixels_mut()) {
|
||||
let (mut min, mut max) = ((u32::MAX, u32::MAX), (0, 0));
|
||||
for ((expected, rendered), (x, y, marked)) in reference.pixels().zip(actual.pixels()).zip(diff.enumerate_pixels_mut()) {
|
||||
let largest_difference = expected.0.iter().zip(rendered.0).map(|(a, b)| a.abs_diff(b)).max().unwrap_or_default();
|
||||
if largest_difference > tolerance.channel {
|
||||
differing += 1;
|
||||
min = (min.0.min(x), min.1.min(y));
|
||||
max = (max.0.max(x), max.1.max(y));
|
||||
*marked = image::Rgba([255, 0, 0, 255]);
|
||||
} else {
|
||||
let [red, green, blue, alpha] = expected.0;
|
||||
@@ -43,12 +55,39 @@ pub(crate) fn compare(reference: &RgbaImage, actual: &RgbaImage, tolerance: Tole
|
||||
|
||||
let total = (actual.width() * actual.height()) as usize;
|
||||
if differing as f64 > tolerance.pixels * total as f64 {
|
||||
Comparison::Differs { differing, total, diff }
|
||||
let region = Rect {
|
||||
x: min.0,
|
||||
y: min.1,
|
||||
width: max.0 - min.0 + 1,
|
||||
height: max.1 - min.1 + 1,
|
||||
};
|
||||
Comparison::Differs { differing, total, diff, region }
|
||||
} else {
|
||||
Comparison::Matches
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference, render, and diff next to each other, cropped to `region` with some context and scaled down to fit a review comment.
|
||||
pub(crate) fn side_by_side(reference: &RgbaImage, actual: &RgbaImage, diff: &RgbaImage, region: Rect) -> RgbaImage {
|
||||
let x = region.x.saturating_sub(CONTEXT_MARGIN);
|
||||
let y = region.y.saturating_sub(CONTEXT_MARGIN);
|
||||
let width = (region.x + region.width + CONTEXT_MARGIN).min(reference.width()) - x;
|
||||
let height = (region.y + region.height + CONTEXT_MARGIN).min(reference.height()) - y;
|
||||
|
||||
let panels = [reference, actual, diff];
|
||||
let mut combined = RgbaImage::new(width * 3 + PANEL_GAP * 2, height);
|
||||
for (index, panel) in panels.into_iter().enumerate() {
|
||||
let cropped = imageops::crop_imm(panel, x, y, width, height).to_image();
|
||||
imageops::overlay(&mut combined, &cropped, (index as u32 * (width + PANEL_GAP)) as i64, 0);
|
||||
}
|
||||
|
||||
if combined.width() <= MAX_SIDE_BY_SIDE_WIDTH {
|
||||
return combined;
|
||||
}
|
||||
let scaled_height = (combined.height() as u64 * MAX_SIDE_BY_SIDE_WIDTH as u64 / combined.width() as u64).max(1) as u32;
|
||||
imageops::resize(&combined, MAX_SIDE_BY_SIDE_WIDTH, scaled_height, FilterType::Triangle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -67,11 +106,29 @@ mod tests {
|
||||
let lenient = Tolerance { channel: 2, pixels: 0.25 };
|
||||
assert!(matches!(compare(&reference, &one_off, lenient), Comparison::Matches));
|
||||
|
||||
let Comparison::Differs { differing, total, diff } = compare(&reference, &one_off, Tolerance::default()) else {
|
||||
let Comparison::Differs { differing, total, diff, region } = compare(&reference, &one_off, Tolerance::default()) else {
|
||||
panic!("one pixel in four exceeds the default tolerance");
|
||||
};
|
||||
assert_eq!((differing, total), (1, 4));
|
||||
assert_eq!(diff.get_pixel(3, 0).0, [255, 0, 0, 255]);
|
||||
assert_eq!((region.x, region.y, region.width, region.height), (3, 0, 1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_by_side_crops_each_panel_to_the_differing_region() {
|
||||
let reference = RgbaImage::from_pixel(200, 100, image::Rgba([0, 0, 0, 255]));
|
||||
let mut actual = reference.clone();
|
||||
actual.put_pixel(100, 50, image::Rgba([255, 255, 255, 255]));
|
||||
|
||||
let exact = Tolerance { channel: 0, pixels: 0. };
|
||||
let Comparison::Differs { diff, region, .. } = compare(&reference, &actual, exact) else {
|
||||
panic!("any changed pixel exceeds an exact tolerance");
|
||||
};
|
||||
let combined = side_by_side(&reference, &actual, &diff, region);
|
||||
|
||||
let panel_width = CONTEXT_MARGIN * 2 + 1;
|
||||
assert_eq!(combined.dimensions(), (panel_width * 3 + PANEL_GAP * 2, CONTEXT_MARGIN * 2 + 1));
|
||||
assert_eq!(combined.get_pixel(CONTEXT_MARGIN + panel_width + PANEL_GAP, CONTEXT_MARGIN).0, [255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,6 +8,7 @@ mod upgrade;
|
||||
use clap::{Parser, Subcommand};
|
||||
use compare::Comparison;
|
||||
use corpus::{Corpus, Entry};
|
||||
use image::math::Rect;
|
||||
use std::error::Error;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
@@ -209,23 +210,24 @@ async fn check(corpus: &Corpus, entry: &Entry, output: &Path) -> bool {
|
||||
continue;
|
||||
}
|
||||
Comparison::SizeChanged { reference, actual } => (format!("the size changed from {reference:?} to {actual:?}"), None),
|
||||
Comparison::Differs { differing, total, diff } => (format!("{differing} of {total} pixels differ"), Some(diff)),
|
||||
Comparison::Differs { differing, total, diff, region } => (format!("{differing} of {total} pixels differ"), Some((diff, region))),
|
||||
};
|
||||
passed = false;
|
||||
|
||||
let written = save_mismatch(output, &entry.name, *time, &actual, diff.as_ref());
|
||||
let written = save_mismatch(output, &entry.name, *time, &reference, &actual, diff.as_ref());
|
||||
let location = written.map_or_else(|error| format!("writing the mismatch failed: {error}"), |directory| format!("see {}", directory.display()));
|
||||
println!("FAIL {label}: {reason}, {location}");
|
||||
}
|
||||
passed
|
||||
}
|
||||
|
||||
fn save_mismatch(output: &Path, name: &str, time: f64, actual: &image::RgbaImage, diff: Option<&image::RgbaImage>) -> Result<PathBuf, Box<dyn Error>> {
|
||||
fn save_mismatch(output: &Path, name: &str, time: f64, reference: &image::RgbaImage, actual: &image::RgbaImage, diff: Option<&(image::RgbaImage, Rect)>) -> Result<PathBuf, Box<dyn Error>> {
|
||||
let directory = output.join(name);
|
||||
std::fs::create_dir_all(&directory)?;
|
||||
actual.save(directory.join(format!("{time:.3}s.actual.png")))?;
|
||||
if let Some(diff) = diff {
|
||||
if let Some((diff, region)) = diff {
|
||||
diff.save(directory.join(format!("{time:.3}s.diff.png")))?;
|
||||
compare::side_by_side(reference, actual, diff, *region).save(directory.join(format!("{time:.3}s.side-by-side.png")))?;
|
||||
}
|
||||
Ok(directory)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user