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