1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use regex::Regex;
use similar::TextDiff;
use std::path::{Path, PathBuf};

use crate::drop_bomb::DropBomb;
use crate::fs_wrapper;

#[cfg(test)]
mod tests;

#[track_caller]
pub fn diff() -> Diff {
    Diff::new()
}

#[derive(Debug)]
#[must_use]
pub struct Diff {
    expected: Option<String>,
    expected_name: Option<String>,
    expected_file: Option<PathBuf>,
    actual: Option<String>,
    actual_name: Option<String>,
    normalizers: Vec<(String, String)>,
    drop_bomb: DropBomb,
}

impl Diff {
    /// Construct a bare `diff` invocation.
    #[track_caller]
    pub fn new() -> Self {
        Self {
            expected: None,
            expected_name: None,
            expected_file: None,
            actual: None,
            actual_name: None,
            normalizers: Vec::new(),
            drop_bomb: DropBomb::arm("diff"),
        }
    }

    /// Specify the expected output for the diff from a file.
    pub fn expected_file<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
        let path = path.as_ref();
        let content = fs_wrapper::read_to_string(path);
        let name = path.to_string_lossy().to_string();

        self.expected_file = Some(path.into());
        self.expected = Some(content);
        self.expected_name = Some(name);
        self
    }

    /// Specify the expected output for the diff from a given text string.
    pub fn expected_text<T: AsRef<[u8]>>(&mut self, name: &str, text: T) -> &mut Self {
        self.expected = Some(String::from_utf8_lossy(text.as_ref()).to_string());
        self.expected_name = Some(name.to_string());
        self
    }

    /// Specify the actual output for the diff from a file.
    pub fn actual_file<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
        let path = path.as_ref();
        let content = fs_wrapper::read_to_string(path);
        let name = path.to_string_lossy().to_string();

        self.actual = Some(content);
        self.actual_name = Some(name);
        self
    }

    /// Specify the actual output for the diff from a given text string.
    pub fn actual_text<T: AsRef<[u8]>>(&mut self, name: &str, text: T) -> &mut Self {
        self.actual = Some(String::from_utf8_lossy(text.as_ref()).to_string());
        self.actual_name = Some(name.to_string());
        self
    }

    /// Specify a regex that should replace text in the "actual" text that will be compared.
    pub fn normalize<R: Into<String>, I: Into<String>>(
        &mut self,
        regex: R,
        replacement: I,
    ) -> &mut Self {
        self.normalizers.push((regex.into(), replacement.into()));
        self
    }

    fn run_common(&self) -> (&str, &str, String, String) {
        let expected = self.expected.as_ref().expect("expected text not set");
        let mut actual = self.actual.as_ref().expect("actual text not set").to_string();
        let expected_name = self.expected_name.as_ref().unwrap();
        let actual_name = self.actual_name.as_ref().unwrap();
        for (regex, replacement) in &self.normalizers {
            let re = Regex::new(regex).expect("bad regex in custom normalization rule");
            actual = re.replace_all(&actual, replacement).into_owned();
        }

        let output = TextDiff::from_lines(expected, &actual)
            .unified_diff()
            .header(expected_name, actual_name)
            .to_string();

        (expected_name, actual_name, output, actual)
    }

    #[track_caller]
    pub fn run(&mut self) {
        self.drop_bomb.defuse();
        let (expected_name, actual_name, output, actual) = self.run_common();

        if !output.is_empty() {
            // If we can bless (meaning we have a file to write into and the `RUSTC_BLESS_TEST`
            // environment variable set), then we write into the file and return.
            if let Some(ref expected_file) = self.expected_file {
                if std::env::var("RUSTC_BLESS_TEST").is_ok() {
                    println!("Blessing `{}`", expected_file.display());
                    fs_wrapper::write(expected_file, actual);
                    return;
                }
            }
            panic!(
                "test failed: `{}` is different from `{}`\n\n{}",
                expected_name, actual_name, output
            )
        }
    }

    #[track_caller]
    pub fn run_fail(&mut self) {
        self.drop_bomb.defuse();
        let (expected_name, actual_name, output, actual) = self.run_common();

        if output.is_empty() {
            // If we can bless (meaning we have a file to write into and the `RUSTC_BLESS_TEST`
            // environment variable set), then we write into the file and return.
            if let Some(ref expected_file) = self.expected_file {
                if std::env::var("RUSTC_BLESS_TEST").is_ok() {
                    println!("Blessing `{}`", expected_file.display());
                    fs_wrapper::write(expected_file, actual);
                    return;
                }
            }
            panic!(
                "test failed: `{}` is not different from `{}`\n\n{}",
                expected_name, actual_name, output
            )
        }
    }
}