1#![doc = include_str!("../README.md")]
2
3#[track_caller]
10pub fn assert_eq_or_update(value: impl AsRef<str>, snapshot_path: impl AsRef<std::path::Path>) {
11 let snapshot_path = snapshot_path.as_ref();
12
13 if update_snapshot() {
14 ensure_parent_dir_exists(snapshot_path);
15
16 std::fs::write(snapshot_path, value.as_ref())
17 .unwrap_or_else(|e| panic!("Error writing {snapshot_path:?}: {e}"));
18 } else {
19 let snapshot = std::fs::read_to_string(snapshot_path)
20 .unwrap_or_else(|e| panic!("Error reading {snapshot_path:?}: {e}"));
21
22 maybe_enable_colors();
23
24 similar_asserts::assert_eq!(
25 value.as_ref(),
26 snapshot,
27 "\n\n{}: run with env var `UPDATE_SNAPSHOTS=yes` to update snapshots\n",
28 console::style("help").cyan()
29 );
30 }
31}
32
33fn maybe_enable_colors() {
42 if let Ok(color) = std::env::var("CARGO_TERM_COLOR") {
45 if color == "always" {
46 console::set_colors_enabled(true);
47 }
48 }
49}
50
51fn ensure_parent_dir_exists(snapshot_path: &std::path::Path) {
52 if !snapshot_path.exists() {
53 std::fs::create_dir_all(snapshot_path.parent().unwrap())
54 .unwrap_or_else(|e| panic!("Error creating directory for {snapshot_path:?}: {e}"));
55 }
56}
57
58fn update_snapshot() -> bool {
59 std::env::var("UPDATE_SNAPSHOTS")
60 .map(|s| s.to_lowercase())
61 .is_ok_and(|s| s == "1" || s == "yes" || s == "true")
62}