diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 50b601c6..598049e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,8 @@ jobs: - run: rustup show active-toolchain || rustup toolchain install - run: cargo fmt --all --check - run: cargo clippy --locked --workspace --all-targets -- -D warnings + # snapshot-diff goes on crates.io: it builds without its schemars feature too. + - run: cargo clippy --locked -p snapshot-diff --no-default-features --all-targets -- -D warnings # The CLI changed since its last release without a version bump: the docs would describe a CLI nobody can download. # Not needed by deploy, so it never holds back the server. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d0202614..6e936480 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,5 @@ -# Release the visualci CLI: static binaries for Linux (musl) and macOS, attached to a GitHub release v. +# Release the visualci CLI: static binaries for Linux (musl) and macOS, attached to a GitHub release v; and +# publish the snapshot-diff crate (crates/snapshot-diff) to crates.io when its version isn't there yet. # A release happens by itself once CI passes on main with a workspace version (Cargo.toml) that has no release yet, so # a version bump is all it takes and the docs never describe a CLI nobody can download. The cli-version job in ci.yml # fails when the CLI changed since its last release without a bump. Pushing a v* tag by hand still works too. @@ -95,3 +96,26 @@ jobs: run: | gh release create "${{ needs.version.outputs.tag }}" visualci-*.tar.gz* -R "${{ github.repository }}" \ --target "${{ needs.version.outputs.sha }}" --generate-notes + + # snapshot-diff on crates.io (https://crates.io/crates/snapshot-diff), once per version in its Cargo.toml. Needs the + # CARGO_REGISTRY_TOKEN secret (a crates.io token for snapshot-diff, 1Password crates-io-snapshot-diff-token). + snapshot-diff: + if: github.event_name == 'push' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + - env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + version=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/snapshot-diff/Cargo.toml | head -1) + code=$(curl -s -o /dev/null -w '%{http_code}' -A 'snapshot-diff release (github.com/DocSpring/visualci)' \ + "https://crates.io/api/v1/crates/snapshot-diff/$version") + if [ "$code" = 200 ]; then + echo "snapshot-diff $version is already on crates.io" + elif [ -z "$CARGO_REGISTRY_TOKEN" ]; then + echo "::warning::snapshot-diff $version isn't on crates.io, and there's no CARGO_REGISTRY_TOKEN secret to publish it with" + else + cargo publish --locked -p snapshot-diff + fi diff --git a/Cargo.lock b/Cargo.lock index a020bf7d..63b1df62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4260,6 +4260,17 @@ dependencies = [ "serde", ] +[[package]] +name = "snapshot-diff" +version = "0.1.0" +dependencies = [ + "regex", + "schemars", + "serde", + "serde_json", + "similar", +] + [[package]] name = "socket2" version = "0.6.5" @@ -5195,7 +5206,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "visualci-cli" -version = "0.2.10" +version = "0.2.11" dependencies = [ "anyhow", "base64 0.22.1", @@ -5212,24 +5223,24 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.10" +version = "0.2.11" dependencies = [ "globset", "hex", "image", "lopdf", - "regex", "schemars", "serde", "serde_json", "sha2 0.10.9", "similar", + "snapshot-diff", "thiserror 2.0.21", ] [[package]] name = "visualci-renderer" -version = "0.2.10" +version = "0.2.11" dependencies = [ "anyhow", "image", @@ -5243,7 +5254,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.10" +version = "0.2.11" dependencies = [ "image", "serde", @@ -5253,7 +5264,7 @@ dependencies = [ [[package]] name = "visualci_server" -version = "0.2.10" +version = "0.2.11" dependencies = [ "aes-gcm", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 35fe60a2..7dd7576f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*", "server", "server/migration"] [workspace.package] -version = "0.2.10" +version = "0.2.11" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" @@ -32,3 +32,4 @@ sha2 = "0.10" similar = "2" thiserror = "2" visualci-core = { path = "crates/visualci-core" } +snapshot-diff = { path = "crates/snapshot-diff", version = "0.1.0" } diff --git a/crates/snapshot-diff/Cargo.toml b/crates/snapshot-diff/Cargo.toml new file mode 100644 index 00000000..3091a3af --- /dev/null +++ b/crates/snapshot-diff/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "snapshot-diff" +description = "Normalized diffs for text, JSON and HTML snapshots: canonical forms, ignore rules for volatile values, JSON changes by path, and unified diffs" +version = "0.1.0" +edition.workspace = true +license.workspace = true +repository.workspace = true +documentation = "https://docs.rs/snapshot-diff" +readme = "README.md" +keywords = ["snapshot", "testing", "diff", "json", "html"] +categories = ["development-tools::testing", "text-processing"] + +[features] +# `IgnoreRules` derives schemars' JsonSchema, for configuration files that embed it. +schemars = ["dep:schemars"] + +[dependencies] +regex.workspace = true +schemars = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +similar.workspace = true + +[package.metadata.docs.rs] +all-features = true diff --git a/crates/snapshot-diff/README.md b/crates/snapshot-diff/README.md new file mode 100644 index 00000000..00204617 --- /dev/null +++ b/crates/snapshot-diff/README.md @@ -0,0 +1,27 @@ +# snapshot-diff + +Normalized diffs for text snapshots: plain text, JSON, HTML and serialized component trees. Snapshot tests compare a +value with the one saved last time; this crate makes that comparison ignore what doesn't matter and say clearly what +does. + +- **Normalization:** JSON with sorted keys and two-space indents, HTML with sorted attributes and collapsed whitespace, + text with normalized line endings. A change in key order, attribute order or whitespace isn't a change. +- **Ignore rules:** JSON paths (`$.generated_at`, `$.items[*].id`, `$..request_id`) and regular expressions whose values + are replaced with `[ignored]` before comparing, for timestamps, IDs and other values that change on every run. +- **JSON changes by path:** `items[3].price: 10 → 12`, `items[4]: added`. +- **Unified diffs** of the normalized text, for a failing test's message. + +```rust +use snapshot_diff::{normalize, unified, Format, IgnoreRules}; + +let rules = IgnoreRules { json_paths: vec!["$.created_at".into()], ..Default::default() }.compile().unwrap(); +let base = normalize(Format::Json, r#"{"total": 65, "created_at": "2026-01-01"}"#, &rules); +let head = normalize(Format::Json, r#"{"created_at": "2026-12-02", "total": 71}"#, &rules); +println!("{}", unified(&base.text, &head.text, 3)); +``` + +The `schemars` feature derives `JsonSchema` for `IgnoreRules`, for configuration files that embed the rules. + +Used by [VisualCI](https://visualci.com). For image diffs, see [blazediff](https://crates.io/crates/blazediff). + +Licensed under Apache-2.0. diff --git a/crates/visualci-core/src/snapshot_text.rs b/crates/snapshot-diff/src/lib.rs similarity index 96% rename from crates/visualci-core/src/snapshot_text.rs rename to crates/snapshot-diff/src/lib.rs index ef985dcd..aa65f151 100644 --- a/crates/visualci-core/src/snapshot_text.rs +++ b/crates/snapshot-diff/src/lib.rs @@ -1,6 +1,24 @@ -//! Text snapshots: plain text, JSON, HTML and serialized component trees. Each format is normalized before it's -//! compared, so a change in key order, attribute order or whitespace isn't a change, and a project's ignore rules -//! blank out volatile values (timestamps, IDs) first. +//! Normalized diffs for text snapshots: plain text, JSON, HTML and serialized component trees. +//! +//! Each format is normalized before it's compared, so a change in key order, attribute order or whitespace isn't a +//! change, and ignore rules blank out volatile values (timestamps, IDs) first: +//! +//! - [`normalize`]: a snapshot in its canonical form (JSON with sorted keys and two-space indents, HTML with sorted +//! attributes and collapsed whitespace, text with normalized line endings), after the [`IgnoreRules`]. +//! - [`json_changes`]: what changed between two JSON values, by path (`items[3].price: 10 → 12`). +//! - [`unified`]: a unified diff of two normalized snapshots, for a test failure's message. +//! +//! ``` +//! use snapshot_diff::{normalize, unified, CompiledRules, Format, IgnoreRules}; +//! +//! let rules = IgnoreRules { json_paths: vec!["$.created_at".into()], ..Default::default() }.compile().unwrap(); +//! let base = normalize(Format::Json, r#"{"total": 65, "created_at": "2026-01-01"}"#, &rules); +//! let head = normalize(Format::Json, r#"{"created_at": "2026-12-02", "total": 71}"#, &rules); +//! assert!(unified(&base.text, &head.text, 3).contains("- \"total\": 65")); +//! # let _: CompiledRules = rules; +//! ``` +//! +//! Used by [VisualCI](https://visualci.com). use std::fmt::Write as _; @@ -74,7 +92,8 @@ impl Format { } /// Rules for values that change on every run. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub struct IgnoreRules { /// JSON paths whose values are ignored: `$.generated_at`, `$.items[*].id`, `$..request_id`, `$["odd key"]`. diff --git a/crates/visualci-core/Cargo.toml b/crates/visualci-core/Cargo.toml index 1eb5a043..d1e73e78 100644 --- a/crates/visualci-core/Cargo.toml +++ b/crates/visualci-core/Cargo.toml @@ -11,10 +11,10 @@ globset.workspace = true hex.workspace = true image.workspace = true lopdf.workspace = true -regex.workspace = true schemars.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true similar.workspace = true +snapshot-diff = { workspace = true, features = ["schemars"] } thiserror.workspace = true diff --git a/crates/visualci-core/src/lib.rs b/crates/visualci-core/src/lib.rs index 3bd95b6c..b40e8eaf 100644 --- a/crates/visualci-core/src/lib.rs +++ b/crates/visualci-core/src/lib.rs @@ -10,7 +10,10 @@ pub mod config; pub mod diff; pub mod image_hash; pub mod pdf; -pub mod snapshot_text; +/// Text snapshots: the `snapshot-diff` crate. +pub mod snapshot_text { + pub use snapshot_diff::*; +} pub mod text; /// Hex SHA-256 of some bytes.