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

Write inline snapshots with atomic rename #373

Merged
merged 2 commits into from
Jun 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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