Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary snapshots (in-memory) #610

Merged
merged 55 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from 48 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
e0612ae
Add binary snapshots
lasernoises Sep 18, 2024
c6161ac
Merge remote-tracking branch 'upstream/master' into in-memory-binary-…
lasernoises Sep 20, 2024
7ce931a
Merge remote-tracking branch 'upstream/master' into in-memory-binary-…
lasernoises Sep 22, 2024
4aaf10e
Clean up merge related issues
lasernoises Sep 22, 2024
4989161
Fix error when trying to clean up files in non-existent directory
lasernoises Sep 22, 2024
a970400
Rename some types for clarity
lasernoises Sep 22, 2024
43398a7
Merge remote-tracking branch 'upstream/master' into in-memory-binary-…
lasernoises Sep 22, 2024
85dd8f9
Add more basic tests for binary snapshots
lasernoises Sep 22, 2024
d3bad2a
Add integration tests for binary snapshots
lasernoises Sep 23, 2024
5bb0f70
Use `Self` type as parameter for matches* methods
lasernoises Sep 23, 2024
7607518
Improve panic message for forbidden `.new` binary snapshot file exten…
lasernoises Sep 23, 2024
58f459c
Fix MSRV related issues
lasernoises Sep 23, 2024
5aa7a13
Add docstrings and rename `Text` to `FileText` in SnapshotValue enum
lasernoises Sep 23, 2024
9a714ba
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Sep 24, 2024
5bab3b7
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Sep 24, 2024
907dd63
Improve error message for integration tests
lasernoises Sep 24, 2024
931016e
Update docstrings
lasernoises Sep 24, 2024
645576b
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Sep 25, 2024
7d82e10
Fix named binary snapshots
lasernoises Sep 25, 2024
4727fb1
Add integration test for removal of pending binary snapshot
lasernoises Sep 25, 2024
654e1a6
Add integration tests for changing between binary and text snapshots
lasernoises Sep 25, 2024
1c7f546
Update cleanup of binary snapshot files
lasernoises Sep 26, 2024
091b1a4
Add a couple comments (#617)
max-sixty Sep 26, 2024
2d08233
Add colors to integration test output to discriminate between inner &…
max-sixty Sep 26, 2024
851b16f
chore: fixed `warn(elided_named_lifetimes)` (#620)
CommanderStorm Sep 26, 2024
c8beea3
Move a few functions onto context object
max-sixty Sep 27, 2024
43d90bb
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Sep 27, 2024
6aaae63
Add docstrings to integration tests for binary snapshots
lasernoises Sep 27, 2024
1b4f7ec
Remove redundant extension and extra struct for binary snapshots
lasernoises Sep 27, 2024
1a84853
Merge branch 'master' into in-memory-binary-snapshots
lasernoises Sep 30, 2024
bd24f02
Change binary snapshot macro syntax
lasernoises Sep 30, 2024
7409c98
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Oct 1, 2024
2721aaf
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Oct 1, 2024
9a80d87
max-sixty Oct 1, 2024
d015be1
Fix clippy warning
lasernoises Oct 1, 2024
a501dfb
Change back snapshot macro internals
lasernoises Oct 1, 2024
ae70db9
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Oct 1, 2024
070471b
max-sixty Oct 1, 2024
7fd63d0
Merge branch 'master' into in-memory-binary-snapshots
lasernoises Oct 3, 2024
08be264
Change snapshot_type to snapshot_kind in metadata
lasernoises Oct 3, 2024
7d8f02e
Merge branch 'master' into in-memory-binary-snapshots
max-sixty Oct 4, 2024
d70c4cd
Merge branch 'master' into in-memory-binary-snapshots
lasernoises Oct 4, 2024
644b491
Add doc comment for assert_binary_snapshot macro
lasernoises Oct 4, 2024
966242f
Add changelog entry for binary snapshots
lasernoises Oct 4, 2024
ae0dba6
Improve error message for wrong name format for binary snapshots
lasernoises Oct 4, 2024
dc2fcd1
Improve assert_snapshot paramter naming
lasernoises Oct 4, 2024
988aed1
Improve error message for wrong name format for binary snapshots
lasernoises Oct 4, 2024
4cd477b
Call matches in matches_fully for binary snapshots
lasernoises Oct 4, 2024
090fe5c
Update CHANGELOG.md
lasernoises Oct 4, 2024
102010f
Update insta/src/runtime.rs
lasernoises Oct 4, 2024
f59925e
Update insta/src/runtime.rs
max-sixty Oct 4, 2024
0a639ae
Fix deletion of unreferenced binary snapshots
lasernoises Oct 4, 2024
f437077
Fix snapshot printing bug when changing between binary and text
lasernoises Oct 4, 2024
e0a61c9
Add examples to assert_binary_snapshot doc comment
lasernoises Oct 4, 2024
62637b2
Improve error handling for deletion of unreferenced snapshots
lasernoises Oct 4, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ All notable changes to insta and cargo-insta are documented here.

- Inline snapshots only use `#` characters as delimiters when required. #603

- Experimental support for binary snapshots
lasernoises marked this conversation as resolved.
Show resolved Hide resolved

## 1.40.0

- `cargo-insta` no longer panics when running `cargo insta test --accept --workspace`
Expand Down
41 changes: 39 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cargo-insta/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ tempfile = "3.5.0"
semver = {version = "1.0.7", features = ["serde"]}
lazy_static = "1.4.0"
clap = { workspace=true }
open = "5.3.0"
itertools = "0.10.0"

[dev-dependencies]
Expand Down
40 changes: 38 additions & 2 deletions cargo-insta/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,24 @@ fn query_snapshot(
style("toggle snapshot diff").dim()
);

let new_is_binary = new.contents().is_binary();
let old_is_binary = old.map(|o| o.contents().is_binary()).unwrap_or(false);

if new_is_binary || old_is_binary {
println!(
" {} open {}",
style("o").cyan().bold(),
style(if new_is_binary && old_is_binary {
"open snapshot files in external tool"
} else if new_is_binary {
"open new snapshot file in external tool"
} else {
"open old snapshot file in external tool"
})
.dim()
);
}

loop {
match term.read_key()? {
Key::Char('a') | Key::Enter => return Ok(Operation::Accept),
Expand All @@ -334,6 +352,21 @@ fn query_snapshot(
*show_diff = !*show_diff;
break;
}
Key::Char('o') => {
if let Some(old) = old {
if let Some(path) = old.build_binary_path(snapshot_file.unwrap()) {
open::that_detached(path)?;
}
}

if let Some(path) =
new.build_binary_path(snapshot_file.unwrap().with_extension("snap.new"))
{
open::that_detached(path)?;
}

// there's no break here because there's no need to re-output anything
}
_ => {}
}
}
Expand Down Expand Up @@ -1085,8 +1118,11 @@ fn pending_snapshots_cmd(cmd: PendingSnapshotsCommand) -> Result<(), Box<dyn Err
let is_inline = snapshot_container.snapshot_file().is_none();
for snapshot_ref in snapshot_container.iter_snapshots() {
if cmd.as_json {
let old_snapshot = snapshot_ref.old.as_ref().map(|x| x.contents_string());
let new_snapshot = snapshot_ref.new.contents_string();
let old_snapshot = snapshot_ref
.old
.as_ref()
.map(|x| x.contents_string().unwrap());
let new_snapshot = snapshot_ref.new.contents_string().unwrap();
let info = if is_inline {
SnapshotKey::InlineSnapshot {
path: &target_file,
Expand Down
51 changes: 30 additions & 21 deletions cargo-insta/src/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fs;
use std::path::{Path, PathBuf};

use insta::Snapshot;
pub(crate) use insta::SnapshotKind;
pub(crate) use insta::TextSnapshotKind;
use insta::_cargo_insta_support::{ContentError, PendingInlineSnapshot};

use crate::inline::FilePatcher;
Expand Down Expand Up @@ -51,7 +51,7 @@ pub(crate) struct SnapshotContainer {
pending_path: PathBuf,
// Path of the target snapshot file (generally a `.snap` file)
target_path: PathBuf,
kind: SnapshotKind,
kind: TextSnapshotKind,
snapshots: Vec<PendingSnapshot>,
patcher: Option<FilePatcher>,
}
Expand All @@ -60,11 +60,11 @@ impl SnapshotContainer {
pub(crate) fn load(
pending_path: PathBuf,
target_path: PathBuf,
kind: SnapshotKind,
kind: TextSnapshotKind,
) -> Result<SnapshotContainer, Box<dyn Error>> {
let mut snapshots = Vec::new();
let patcher = match kind {
SnapshotKind::File => {
TextSnapshotKind::File => {
let old = if fs::metadata(&target_path).is_err() {
None
} else {
Expand All @@ -80,7 +80,7 @@ impl SnapshotContainer {
});
None
}
SnapshotKind::Inline => {
TextSnapshotKind::Inline => {
let mut pending_vec = PendingInlineSnapshot::load_batch(&pending_path)?;
let mut have_new = false;

Expand Down Expand Up @@ -136,8 +136,8 @@ impl SnapshotContainer {

pub(crate) fn snapshot_file(&self) -> Option<&Path> {
match self.kind {
SnapshotKind::File => Some(&self.target_path),
SnapshotKind::Inline => None,
TextSnapshotKind::File => Some(&self.target_path),
TextSnapshotKind::Inline => None,
}
}

Expand Down Expand Up @@ -167,7 +167,7 @@ impl SnapshotContainer {
// Try removing the snapshot file. If it fails, it's
// likely because it another process removed it; which
// is fine — print a message and continue.
let try_removing_snapshot = |p| {
let try_removing_snapshot = |p: &Path| {
fs::remove_file(p).unwrap_or_else(|_| {
eprintln!(
"Pending snapshot file at {:?} couldn't be removed. It was likely removed by another process.",
Expand All @@ -184,7 +184,10 @@ impl SnapshotContainer {
for (idx, snapshot) in self.snapshots.iter().enumerate() {
match snapshot.op {
Operation::Accept => {
patcher.set_new_content(idx, snapshot.new.contents());
patcher.set_new_content(
idx,
snapshot.new.contents().as_string_contents().unwrap(),
);
did_accept = true;
}
Operation::Reject => {}
Expand Down Expand Up @@ -213,22 +216,28 @@ impl SnapshotContainer {
for snapshot in self.snapshots.iter() {
match snapshot.op {
Operation::Accept => {
let snapshot = Snapshot::from_file(&self.pending_path).map_err(|e| {
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
// If it's an IO error, pass a ContentError back so
// we get a slightly clearer error message
match e.downcast::<std::io::Error>() {
Ok(io_error) => Box::new(ContentError::FileIo(
*io_error,
self.pending_path.to_path_buf(),
)),
Err(other_error) => other_error,
}
})?;
snapshot.save(&self.target_path)?;
try_removing_snapshot(&self.pending_path);

if let Some(ref old) = snapshot.old {
if let Some(path) = old.build_binary_path(&self.target_path) {
try_removing_snapshot(&path);
}
}

if let Some(path) = snapshot.new.build_binary_path(&self.pending_path) {
try_removing_snapshot(&path);
}

// We save at the end because we might write a binary file into the same
// path again.
snapshot.new.save(&self.target_path)?;
}
Operation::Reject => {
try_removing_snapshot(&self.pending_path);

if let Some(path) = snapshot.new.build_binary_path(&self.pending_path) {
try_removing_snapshot(&path);
}
}
Operation::Skip => {}
}
Expand Down
4 changes: 2 additions & 2 deletions cargo-insta/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use insta::_cargo_insta_support::SnapshotContents;
use insta::_cargo_insta_support::TextSnapshotContents;
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
use proc_macro2::TokenTree;

use syn::__private::ToTokens;
Expand Down Expand Up @@ -90,7 +90,7 @@ impl FilePatcher {
self.inline_snapshots[id].start.0 + 1
}

pub(crate) fn set_new_content(&mut self, id: usize, snapshot: &SnapshotContents) {
pub(crate) fn set_new_content(&mut self, id: usize, snapshot: &TextSnapshotContents) {
let inline = &mut self.inline_snapshots[id];

// find prefix and suffix on the first and last lines
Expand Down
6 changes: 3 additions & 3 deletions cargo-insta/src/walk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::Path;
use ignore::overrides::OverrideBuilder;
use ignore::{DirEntry, Walk, WalkBuilder};

use crate::container::{SnapshotContainer, SnapshotKind};
use crate::container::{SnapshotContainer, TextSnapshotKind};

#[derive(Debug, Copy, Clone)]
pub(crate) struct FindFlags {
Expand Down Expand Up @@ -38,7 +38,7 @@ pub(crate) fn find_pending_snapshots<'a>(
Some(SnapshotContainer::load(
path.clone(),
path.with_file_name(new_fname),
SnapshotKind::File,
TextSnapshotKind::File,
))
} else if let Some(new_fname) = fname
.strip_prefix('.')
Expand All @@ -47,7 +47,7 @@ pub(crate) fn find_pending_snapshots<'a>(
Some(SnapshotContainer::load(
path.clone(),
path.with_file_name(new_fname),
SnapshotKind::Inline,
TextSnapshotKind::Inline,
))
} else {
None
Expand Down
Loading