| 1 |
use crate::snapshot::ast; |
| 2 |
use crate::snapshot::source_code; |
| 3 |
use crate::snapshot::source_code::Range; |
| 4 |
use crate::types; |
| 5 |
use anyhow::{Context, Result}; |
| 6 |
use colored::*; |
| 7 |
use lazy_static::lazy_static; |
| 8 |
use std::collections::HashMap; |
| 9 |
use std::fmt::Debug; |
| 10 |
use std::path::PathBuf; |
| 11 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 12 |
use std::sync::Mutex; |
| 13 |
|
| 14 |
lazy_static! { |
| 15 |
static ref SOURCE_FILES: Mutex<Option<HashMap<types::FilePath, SourceFile>>> = |
| 16 |
Mutex::new(Some(HashMap::new())); |
| 17 |
static ref ATEXIT_HOOK_REGISTERED: AtomicBool = AtomicBool::new(false); |
| 18 |
} |
| 19 |
|
| 20 |
extern "C" fn libc_atexit_hook() { |
| 21 |
let files = SOURCE_FILES.lock().expect("poisoned lock").take().unwrap(); |
| 22 |
|
| 23 |
for (_path, file) in files { |
| 24 |
update_inline_snapshots(file).expect("Failed to update snapshots"); |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
fn maybe_register_atexit_hook() { |
| 29 |
if !ATEXIT_HOOK_REGISTERED.swap(true, Ordering::SeqCst) { |
| 30 |
unsafe { |
| 31 |
libc::atexit(libc_atexit_hook); |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
pub fn snapshot<V: Debug>( |
| 37 |
value: V, |
| 38 |
snapshot: Option<&str>, |
| 39 |
line: u32, |
| 40 |
_column: u32, |
| 41 |
file: &str, |
| 42 |
) -> Option<String> { |
| 43 |
snapshot_internal(value, snapshot, line, file) |
| 44 |
.context("snapshot!() macro failed") |
| 45 |
.unwrap() |
| 46 |
} |
| 47 |
|
| 48 |
pub fn snapshot_internal<V: Debug>( |
| 49 |
value: V, |
| 50 |
snapshot: Option<&str>, |
| 51 |
line: u32, |
| 52 |
file: &str, |
| 53 |
) -> Result<Option<String>> { |
| 54 |
let value_str = value_to_string(value); |
| 55 |
match (snapshot, crate::config::CONFIG.update_mode) { |
| 56 |
(Some(snapshot), false) => Ok(snapshot_matching_message(&value_str, snapshot)), |
| 57 |
(None, false) => Ok(Some(empty_snapshot_message(&value_str))), |
| 58 |
(_, true) => { |
| 59 |
let line = line as usize; |
| 60 |
|
| 61 |
let crate_root = |
| 62 |
crate::paths::find_crate_root(file).context("Failed to find crate root")?; |
| 63 |
|
| 64 |
let mut this_file_path = crate_root; |
| 65 |
this_file_path.push(file); |
| 66 |
|
| 67 |
if let Some(snapshot) = snapshot { |
| 68 |
let need_updating = snapshot_matching_message(&value_str, snapshot).is_some(); |
| 69 |
|
| 70 |
if need_updating { |
| 71 |
let mode = UpdateInlineSnapshotMode::Replace; |
| 72 |
schedule_snapshot_update(this_file_path, line, &value_str, mode).unwrap(); |
| 73 |
} |
| 74 |
} else { |
| 75 |
let mode = UpdateInlineSnapshotMode::Create; |
| 76 |
schedule_snapshot_update(this_file_path, line, &value_str, mode).unwrap(); |
| 77 |
}; |
| 78 |
|
| 79 |
Ok(None) |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 85 |
enum UpdateInlineSnapshotMode { |
| 86 |
Create, |
| 87 |
Replace, |
| 88 |
} |
| 89 |
#[derive(Debug)] |
| 90 |
pub struct InlineSnapshotUpdate { |
| 91 |
range: Range, |
| 92 |
new_value: String, |
| 93 |
mode: UpdateInlineSnapshotMode, |
| 94 |
} |
| 95 |
|
| 96 |
#[derive(Debug)] |
| 97 |
pub struct SourceFile { |
| 98 |
pub content: String, |
| 99 |
pub updates: Vec<InlineSnapshotUpdate>, |
| 100 |
pub path: types::FilePath, |
| 101 |
} |
| 102 |
|
| 103 |
impl SourceFile { |
| 104 |
fn new(path: types::FilePath) -> Result<Self> { |
| 105 |
let content = Self::read(&path)?; |
| 106 |
Ok(Self { |
| 107 |
path, |
| 108 |
content, |
| 109 |
updates: vec![], |
| 110 |
}) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
pub fn read_and_compare(&self) -> Result<()> { |
| 115 |
let read_content = Self::read(&self.path)?; |
| 116 |
|
| 117 |
if read_content != self.content { |
| 118 |
anyhow::bail!("File content was modified during test run"); |
| 119 |
} |
| 120 |
Ok(()) |
| 121 |
} |
| 122 |
|
| 123 |
pub fn read(absolute_path: &str) -> Result<String> { |
| 124 |
std::fs::read_to_string(absolute_path) |
| 125 |
.with_context(|| format!("Can't read source file. File path: {}", absolute_path)) |
| 126 |
} |
| 127 |
|
| 128 |
pub fn write(&self) { |
| 129 |
std::fs::write(&self.path, &self.content).unwrap(); |
| 130 |
} |
| 131 |
|
| 132 |
pub fn format(&mut self) { |
| 133 |
use std::process::Command; |
| 134 |
|
| 135 |
|
| 136 |
let _output = Command::new("rustfmt").arg(&self.path).output(); |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
pub fn with_source_file<F, T>(absolute_path: &str, f: F) -> Result<T> |
| 141 |
where |
| 142 |
F: FnOnce(&mut SourceFile) -> Result<T>, |
| 143 |
{ |
| 144 |
let mut map = SOURCE_FILES.lock().expect("poisoned lock"); |
| 145 |
let source_file = map |
| 146 |
.as_mut() |
| 147 |
.context("Missing source file")? |
| 148 |
.entry(absolute_path.to_string()) |
| 149 |
.or_insert_with(|| SourceFile::new(absolute_path.to_string()).unwrap()); |
| 150 |
|
| 151 |
f(source_file) |
| 152 |
} |
| 153 |
|
| 154 |
fn snapshot_matching_message(s: &str, snapshot: &str) -> Option<String> { |
| 155 |
let diff = crate::string_diff::colored_diff(snapshot, s); |
| 156 |
|
| 157 |
diff.map(|diff| { |
| 158 |
format!( |
| 159 |
"Expected {string_desc} to match {snapshot_desc} |
| 160 |
|
| 161 |
Difference: |
| 162 |
{diff} |
| 163 |
|
| 164 |
{update_instructions} |
| 165 |
", |
| 166 |
string_desc = "string".red(), |
| 167 |
snapshot_desc = "inline snapshot".green(), |
| 168 |
diff = diff, |
| 169 |
update_instructions = crate::config::update_instructions(), |
| 170 |
) |
| 171 |
}) |
| 172 |
} |
| 173 |
|
| 174 |
fn empty_snapshot_message(s: &str) -> String { |
| 175 |
format!( |
| 176 |
"Expected {string_desc} to match {snapshot_desc} |
| 177 |
|
| 178 |
but that assertion did not have any inline snapshots. |
| 179 |
|
| 180 |
Received value: |
| 181 |
{received_value} |
| 182 |
|
| 183 |
{update_instructions} |
| 184 |
", |
| 185 |
string_desc = "string".red(), |
| 186 |
snapshot_desc = "inline snapshot".green(), |
| 187 |
update_instructions = crate::config::update_instructions(), |
| 188 |
received_value = s.green(), |
| 189 |
) |
| 190 |
} |
| 191 |
|
| 192 |
fn schedule_snapshot_update( |
| 193 |
file_path: PathBuf, |
| 194 |
original_line_num: usize, |
| 195 |
to_add: &str, |
| 196 |
mode: UpdateInlineSnapshotMode, |
| 197 |
) -> Result<()> { |
| 198 |
maybe_register_atexit_hook(); |
| 199 |
|
| 200 |
with_source_file(&file_path.display().to_string(), |file| { |
| 201 |
let range = ast::find_snapshot_literal_range( |
| 202 |
&file.content, |
| 203 |
"snapshot", |
| 204 |
original_line_num, |
| 205 |
mode == UpdateInlineSnapshotMode::Replace, |
| 206 |
) |
| 207 |
.with_context(|| { |
| 208 |
format!( |
| 209 |
"Failed to find the origin of snapshot macro call in `{}`", |
| 210 |
&file_path.display() |
| 211 |
) |
| 212 |
})?; |
| 213 |
|
| 214 |
file.updates.push(InlineSnapshotUpdate { |
| 215 |
range, |
| 216 |
new_value: to_add.to_string(), |
| 217 |
mode, |
| 218 |
}); |
| 219 |
|
| 220 |
Ok(()) |
| 221 |
}) |
| 222 |
} |
| 223 |
|
| 224 |
fn update_inline_snapshots(mut file: SourceFile) -> Result<()> { |
| 225 |
file.read_and_compare()?; |
| 226 |
let content = file.content.clone(); |
| 227 |
|
| 228 |
let mut updates = file.updates.iter().collect::<Vec<_>>(); |
| 229 |
updates.sort_by(|a, b| a.range.start.line.cmp(&b.range.start.line)); |
| 230 |
|
| 231 |
let parts = source_code::split_by_ranges(content, updates.iter().map(|u| &u.range).collect()); |
| 232 |
|
| 233 |
assert_eq!(parts.len(), updates.len() + 1); |
| 234 |
|
| 235 |
let mut parts_iter = parts.into_iter(); |
| 236 |
let mut updates_iter = updates.into_iter(); |
| 237 |
let mut result = String::new(); |
| 238 |
|
| 239 |
loop { |
| 240 |
match (parts_iter.next(), updates_iter.next()) { |
| 241 |
(Some(part), Some(update)) => { |
| 242 |
result.push_str(&part); |
| 243 |
|
| 244 |
let comma_separator = match update.mode { |
| 245 |
UpdateInlineSnapshotMode::Create => ", ", |
| 246 |
UpdateInlineSnapshotMode::Replace => "", |
| 247 |
}; |
| 248 |
|
| 249 |
let literal = make_literal(&update.new_value); |
| 250 |
|
| 251 |
let update_string = format!( |
| 252 |
"{comma_separator}{to_add}", |
| 253 |
comma_separator = comma_separator, |
| 254 |
to_add = literal |
| 255 |
); |
| 256 |
|
| 257 |
result.push_str(&update_string); |
| 258 |
} |
| 259 |
(Some(part), None) => { |
| 260 |
result.push_str(&part); |
| 261 |
} |
| 262 |
(None, None) => { |
| 263 |
break; |
| 264 |
} |
| 265 |
_ => panic!("unreachable"), |
| 266 |
} |
| 267 |
} |
| 268 |
file.content = result; |
| 269 |
file.write(); |
| 270 |
file.format(); |
| 271 |
Ok(()) |
| 272 |
} |
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
fn value_to_string<V: Debug>(value: V) -> String { |
| 278 |
let mut s = format!("{:#?}", value); |
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
s = s.replace(r#"\n"#, "\n"); |
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
s = s.replace(r#"\""#, r#"""#); |
| 290 |
s = s.replace(r#"\'"#, r#"'"#); |
| 291 |
|
| 292 |
let mut chars = s.chars(); |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
if let (Some('"'), Some('"')) = (chars.next(), chars.next_back()) { |
| 299 |
s = chars.collect(); |
| 300 |
} |
| 301 |
|
| 302 |
if s.contains('\n') { |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
s = format!("\n{}\n", s); |
| 308 |
} |
| 309 |
s |
| 310 |
} |
| 311 |
|
| 312 |
fn make_literal(s: &str) -> String { |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
if !s.contains('"') && !s.contains('\'') && !s.contains('\\') { |
| 317 |
return format!(r#""{}""#, s); |
| 318 |
} |
| 319 |
|
| 320 |
|
| 321 |
let mut max = 0; |
| 322 |
let mut chars = s.chars(); |
| 323 |
while let Some(c) = chars.next() { |
| 324 |
if c == '\"' { |
| 325 |
max = max.max(chars.by_ref().take_while(|c| *c == '#').count()) |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
let esc = "#".repeat(max + 1); |
| 330 |
format!(r#"r{}"{}"{}"#, esc, s, esc) |
| 331 |
} |