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 #489

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6e66262
Add support for binary snapshots
lasernoises Apr 26, 2024
0f9a08d
Move file_eq function to utils
lasernoises Apr 29, 2024
0f08023
Fix snapshot comparison whitespace handling
lasernoises Apr 30, 2024
f193ca8
Add basic test for binary snapshots
lasernoises May 2, 2024
5f8de35
Add more tests for file extension of binary snapshots
lasernoises May 2, 2024
6b9884a
Fix file extension change behavior for binary snapshots
lasernoises May 8, 2024
51cb04b
Move &mut for binary snapshot closure into macro
lasernoises May 8, 2024
13fea4a
Merge branch 'master' into binary-snapshots
lasernoises May 27, 2024
c4aad15
Use try_removing_snapshot closure for binary deletion
lasernoises May 27, 2024
6ec72dc
Switch to a temporary .snap._ for binary snapshots before saving
lasernoises May 29, 2024
831427a
Fix handling of binary snapshot paths
lasernoises Jun 5, 2024
fdb9eca
Add cleanup for binary snapshots
lasernoises Jun 5, 2024
4865e6d
Change file content to ascii for binary snapshot tests
lasernoises Jun 5, 2024
36b1cc0
Forbid binary snapshot extensions that could cause conflicts
lasernoises Jun 5, 2024
87306da
Reduce binary snapshot code duplication
lasernoises Jun 6, 2024
ebbd335
Make binary snapshot error handling more constistent with the rest of…
lasernoises Jun 7, 2024
edfabf3
Add doc comment for encode_file_link_escape
lasernoises Jun 13, 2024
86a56d7
Merge remote-tracking branch 'upstream/master' into binary-snapshots
lasernoises Sep 16, 2024
a27eed1
Fix some issues after merge
lasernoises Sep 16, 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
1 change: 1 addition & 0 deletions cargo-insta/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ syn = { version = "1.0.50", features = ["full", "visit", "extra-traits"] }
ignore = "0.4.17"
uuid = { version = "1.0.0", features = ["v4"] }
tempfile = "3.5.0"
open = "5.1.2"

[dev-dependencies]
walkdir = "2.3.1"
34 changes: 32 additions & 2 deletions cargo-insta/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{env, fs};
use std::{io, process};

use console::{set_colors_enabled, style, Key, Term};
use insta::internals::SnapshotContents;
use insta::Snapshot;
use insta::_cargo_insta_support::{
is_ci, SnapshotPrinter, SnapshotUpdate, TestRunner, ToolConfig, UnreferencedSnapshots,
Expand Down Expand Up @@ -306,6 +307,24 @@ fn query_snapshot(
style("toggle snapshot diff").dim()
);

let new_is_binary = new.contents().is_binary();
let old_is_binary = old.is_some_and(|o| o.contents().is_binary());

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 @@ -319,6 +338,17 @@ fn query_snapshot(
*show_diff = !*show_diff;
break;
}
Key::Char('o') => {
if let Some(SnapshotContents::Binary { path, .. }) = old.map(|o| o.contents()) {
open::that_detached(path)?;
}

if let SnapshotContents::Binary { path, .. } = new.contents() {
open::that_detached(path)?;
}

// there's no break here because there's no need to re-output anything
}
_ => {}
}
}
Expand Down Expand Up @@ -1004,8 +1034,8 @@ fn pending_snapshots_cmd(cmd: PendingSnapshotsCommand) -> Result<(), Box<dyn Err
path: &target_file,
line: snapshot_ref.line.unwrap(),
name: snapshot_ref.new.snapshot_name(),
old_snapshot: snapshot_ref.old.as_ref().map(|x| x.contents_str()),
new_snapshot: snapshot_ref.new.contents_str(),
old_snapshot: snapshot_ref.old.as_ref().map(|x| x.contents_str().unwrap()),
new_snapshot: snapshot_ref.new.contents_str().unwrap(),
expression: snapshot_ref.new.metadata().expression(),
}
} else {
Expand Down
16 changes: 14 additions & 2 deletions cargo-insta/src/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,15 +212,27 @@ impl SnapshotContainer {
for snapshot in self.snapshots.iter() {
match snapshot.op {
Operation::Accept => {
let snapshot = Snapshot::from_file(&self.snapshot_path)?;
snapshot.save(&self.target_path)?;
let mut new_snapshot = Snapshot::from_file(&self.snapshot_path)?;
new_snapshot.save(&self.target_path)?;
try_removing_snapshot(&self.snapshot_path);
}
Operation::Reject => {
try_removing_snapshot(&self.snapshot_path);

if let insta::internals::SnapshotContents::Binary { path, .. } =
snapshot.new.contents()
{
try_removing_snapshot(path);
}
}
Operation::Skip => {}
}

if let Operation::Accept | Operation::Reject = snapshot.op {
let snapshot = Snapshot::from_file(&self.target_path).ok();

Snapshot::cleanup_extra_files(snapshot.as_ref(), &self.snapshot_path)?;
}
}
}
Ok(())
Expand Down
8 changes: 6 additions & 2 deletions cargo-insta/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,12 @@ impl FilePatcher {
.collect();

// replace lines
let snapshot_line_contents =
[prefix, snapshot.to_inline(inline.indentation), suffix].join("");
let snapshot_line_contents = [
prefix,
snapshot.to_inline(inline.indentation).unwrap(),
suffix,
]
.join("");

self.lines.splice(
inline.start.0..=inline.end.0,
Expand Down
2 changes: 0 additions & 2 deletions insta/src/content/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use std::fmt;
pub enum Error {
FailedParsingYaml(std::path::PathBuf),
UnexpectedDataType,
#[cfg(feature = "_cargo_insta_internal")]
MissingField,
#[cfg(feature = "_cargo_insta_internal")]
FileIo(std::io::Error, std::path::PathBuf),
Expand All @@ -37,7 +36,6 @@ impl fmt::Display for Error {
Error::UnexpectedDataType => {
f.write_str("The present data type wasn't what was expected")
}
#[cfg(feature = "_cargo_insta_internal")]
Error::MissingField => f.write_str("A required field was missing"),
#[cfg(feature = "_cargo_insta_internal")]
Error::FileIo(e, p) => {
Expand Down
4 changes: 3 additions & 1 deletion insta/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,9 @@ pub use crate::redaction::{dynamic_redaction, rounded_redaction, sorted_redactio
pub mod _macro_support {
pub use crate::content::Content;
pub use crate::env::get_cargo_workspace;
pub use crate::runtime::{assert_snapshot, with_allow_duplicates, AutoName, ReferenceValue};
pub use crate::runtime::{
assert_snapshot, with_allow_duplicates, AutoName, ReferenceValue, SnapshotValue,
};

#[cfg(feature = "serde")]
pub use crate::serialization::{serialize_value, SerializationFormat, SnapshotLocation};
Expand Down
30 changes: 29 additions & 1 deletion insta/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,35 @@ macro_rules! _assert_snapshot_base {
$crate::_macro_support::assert_snapshot(
$name.into(),
#[allow(clippy::redundant_closure_call)]
&$transform(&$value),
$crate::_macro_support::SnapshotValue::String(&$transform(&$value)),
env!("CARGO_MANIFEST_DIR"),
$crate::_function_name!(),
module_path!(),
file!(),
line!(),
$debug_expr,
)
.unwrap()
};
}

#[macro_export]
macro_rules! assert_binary_snapshot {
($extension:expr, $value:expr $(,)?) => {
$crate::assert_binary_snapshot!($extension, $crate::_macro_support::AutoName, $value);
};

($extension:expr, $name:expr, $value:expr $(,)?) => {
$crate::assert_binary_snapshot!($extension, $name, $value, stringify!($value));
};

($extension:expr, $name:expr, $value:expr, $debug_expr:expr $(,)?) => {
$crate::_macro_support::assert_snapshot(
$name.into(),
$crate::_macro_support::SnapshotValue::Binary {
write: &mut $value,
extension: $extension,
},
env!("CARGO_MANIFEST_DIR"),
$crate::_function_name!(),
module_path!(),
Expand Down
Loading