Skip to content

Commit

Permalink
Write inline snapshots with atomic rename (#373)
Browse files Browse the repository at this point in the history
  • Loading branch information
max-sixty committed Jun 3, 2023
1 parent 2658173 commit 3dcb42b
Show file tree
Hide file tree
Showing 3 changed files with 232 additions and 27 deletions.
243 changes: 219 additions & 24 deletions cargo-insta/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 @@ -21,3 +21,4 @@ proc-macro2 = { version = "1.0.24", features = ["span-locations"] }
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"
15 changes: 12 additions & 3 deletions cargo-insta/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};

use insta::_cargo_insta_support::SnapshotContents;
use proc_macro2::TokenTree;
use syn;

use syn::spanned::Spanned;

#[derive(Debug)]
Expand Down Expand Up @@ -47,10 +47,19 @@ impl FilePatcher {
}

pub fn save(&self) -> Result<(), Box<dyn Error>> {
let mut f = fs::File::create(&self.filename)?;
// We use a temp file and then atomically rename to prevent a
// file watcher restarting the process midway through the write.
let mut temp_file = tempfile::Builder::new()
.suffix(".snap.tmp")
.tempfile_in(self.filename.parent().ok_or("Parent directory not found")?)?;

for line in &self.lines {
writeln!(&mut f, "{}", line)?;
writeln!(temp_file, "{}", line)?;
}

temp_file.flush()?;
fs::rename(temp_file.path(), &self.filename)?;

Ok(())
}

Expand Down

0 comments on commit 3dcb42b

Please sign in to comment.