|
| 1 | +use similar::TextDiff; |
| 2 | +use std::path::Path; |
| 3 | + |
| 4 | +#[cfg(test)] |
| 5 | +mod tests; |
| 6 | + |
| 7 | +pub fn diff() -> Diff { |
| 8 | + Diff::new() |
| 9 | +} |
| 10 | + |
| 11 | +#[derive(Debug)] |
| 12 | +pub struct Diff { |
| 13 | + expected: Option<String>, |
| 14 | + actual: Option<String>, |
| 15 | +} |
| 16 | + |
| 17 | +impl Diff { |
| 18 | + /// Construct a bare `diff` invocation. |
| 19 | + pub fn new() -> Self { |
| 20 | + Self { expected: None, actual: None } |
| 21 | + } |
| 22 | + |
| 23 | + /// Specify the expected output for the diff from a file. |
| 24 | + pub fn expected_file<P: AsRef<Path>>(&mut self, path: P) -> &mut Self { |
| 25 | + let content = std::fs::read_to_string(path).expect("failed to read file"); |
| 26 | + self.expected = Some(content); |
| 27 | + self |
| 28 | + } |
| 29 | + |
| 30 | + /// Specify the expected output for the diff from a given text string. |
| 31 | + pub fn expected_text<T: AsRef<[u8]>>(&mut self, text: T) -> &mut Self { |
| 32 | + self.expected = Some(String::from_utf8_lossy(text.as_ref()).to_string()); |
| 33 | + self |
| 34 | + } |
| 35 | + |
| 36 | + /// Specify the actual output for the diff from a file. |
| 37 | + pub fn actual_file<P: AsRef<Path>>(&mut self, path: P) -> &mut Self { |
| 38 | + let content = std::fs::read_to_string(path).expect("failed to read file"); |
| 39 | + self.actual = Some(content); |
| 40 | + self |
| 41 | + } |
| 42 | + |
| 43 | + /// Specify the actual output for the diff from a given text string. |
| 44 | + pub fn actual_text<T: AsRef<[u8]>>(&mut self, text: T) -> &mut Self { |
| 45 | + self.actual = Some(String::from_utf8_lossy(text.as_ref()).to_string()); |
| 46 | + self |
| 47 | + } |
| 48 | + |
| 49 | + /// Executes the diff process, prints any differences to the standard error. |
| 50 | + pub fn run(&self) { |
| 51 | + let output = self.do_run(); |
| 52 | + if !output.is_empty() { |
| 53 | + panic!("{}", output) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// Compares the expected and actual texts and generates a diff output as a string. |
| 58 | + fn do_run(&self) -> String { |
| 59 | + let expected = self.expected.as_ref().expect("expected text not set"); |
| 60 | + let actual = self.actual.as_ref().expect("actual text not set"); |
| 61 | + |
| 62 | + TextDiff::from_lines(expected, actual).unified_diff().header("expect", "actual").to_string() |
| 63 | + } |
| 64 | +} |
0 commit comments