Skip to content

Commit

Permalink
Add support for snapshot reference recording (mitsuhiko#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko authored Oct 11, 2020
1 parent d1857e9 commit 9b3e054
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 25 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 1.1.0

* Added the `INSTA_SNAPSHOT_REFERENCES_FILE` environment variable to support
deletions of unreferenced snapshot files. (#136)

## 1.0.0

* Globs now follow links (#132)
Expand Down
17 changes: 17 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,23 @@
//! ```text
//! $ cargo insta test --accept --force-update-snapshots
//! ```
//!
//! # Deleting Unused Snapshots
//!
//! Insta cannot detect unused snapshot files. The reason for this is that
//! insta does not control the execution of the entirety of the tests so it
//! cannot spot which files are actually unreferenced. However you can use
//! the `INSTA_SNAPSHOT_REFERENCES_FILE` environment variable to
//! instruct insta to append all referenced files into a list. This can then
//! be used to delete all files not referenced. For instance one could use
//! [`ripgrep`](https://github.com/BurntSushi/ripgrep) like this:
//!
//! ```text
//! export INSTA_SNAPSHOT_REFERENCES_FILE="$(mktemp)"
//! cargo test
//! rg --files -lg '*.snap' "$(pwd)" | grep -vFf "$INSTA_SNAPSHOT_REFERENCES_FILE" | xargs rm
//! rm -f $INSTA_SNAPSHOT_REFERENCES_FILE
//! ```
#[macro_use]
mod macros;
mod content;
Expand Down
18 changes: 18 additions & 0 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ fn update_snapshot_behavior(unseen: bool) -> UpdateBehavior {
}
}

fn memoize_snapshot_file(snapshot_file: &Path) {
if let Ok(path) = env::var("INSTA_SNAPSHOT_REFERENCES_FILE") {
let mut f = fs::OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)
.unwrap();
f.write_all(format!("{}\n", snapshot_file.display()).as_bytes())
.unwrap();
}
}

fn output_snapshot_behavior() -> OutputBehavior {
match env::var("INSTA_OUTPUT").ok().as_deref() {
None | Some("") | Some("diff") => OutputBehavior::Diff,
Expand Down Expand Up @@ -921,6 +934,11 @@ pub fn assert_snapshot(
new_snapshot_contents,
);

// memoize the snapshot file if requested.
if let Some(ref snapshot_file) = snapshot_file {
memoize_snapshot_file(snapshot_file);
}

// if the snapshot matches we're done.
if let Some(ref old_snapshot) = old {
if old_snapshot.contents() == new.contents() {
Expand Down
25 changes: 0 additions & 25 deletions tests/snapshots/test_redaction__redaction_basics.snap

This file was deleted.

0 comments on commit 9b3e054

Please sign in to comment.