Skip to main content

rustfmt_nightly/emitter/
diff.rs

1use super::*;
2use crate::config::Config;
3use crate::rustfmt_diff::{make_diff, print_diff};
4
5pub(crate) struct DiffEmitter {
6    config: Config,
7}
8
9impl DiffEmitter {
10    pub(crate) fn new(config: Config) -> Self {
11        Self { config }
12    }
13}
14
15impl Emitter for DiffEmitter {
16    fn emit_formatted_file(
17        &mut self,
18        output: &mut dyn Write,
19        FormattedFile {
20            filename,
21            original_text,
22            formatted_text,
23        }: FormattedFile<'_>,
24    ) -> Result<EmitterResult, io::Error> {
25        const CONTEXT_SIZE: usize = 3;
26        let mismatch = make_diff(original_text, formatted_text, CONTEXT_SIZE);
27        let has_diff = !mismatch.is_empty();
28
29        if has_diff {
30            if self.config.print_misformatted_file_names() {
31                writeln!(output, "{filename}")?;
32            } else {
33                print_diff(
34                    mismatch,
35                    |line_num| format!("Diff in {}:{}:", filename, line_num),
36                    &self.config,
37                );
38            }
39        } else if original_text != formatted_text {
40            // This occurs when the only difference between the original and formatted values
41            // is the newline style. This happens because The make_diff function compares the
42            // original and formatted values line by line, independent of line endings.
43            writeln!(output, "Incorrect newline style in {filename}")?;
44            return Ok(EmitterResult { has_diff: true });
45        }
46
47        Ok(EmitterResult { has_diff })
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use indoc::{formatdoc, indoc};
55    use std::path::PathBuf;
56
57    #[test]
58    fn does_not_print_when_no_files_reformatted() {
59        let mut writer = Vec::new();
60        let config = Config::default();
61        let mut emitter = DiffEmitter::new(config);
62        let result = emitter
63            .emit_formatted_file(
64                &mut writer,
65                FormattedFile {
66                    filename: &FileName::Real(PathBuf::from("src/lib.rs")),
67                    original_text: "fn empty() {}\n",
68                    formatted_text: "fn empty() {}\n",
69                },
70            )
71            .unwrap();
72        assert_eq!(result.has_diff, false);
73        assert_eq!(writer.len(), 0);
74    }
75
76    #[test]
77    fn prints_file_names_when_config_is_enabled() {
78        let bin_file = "src/bin.rs";
79        let bin_original = indoc! {r#"
80            fn main() {
81            println!("Hello, world!");
82            }
83        "#};
84        let bin_formatted = indoc! {r#"
85            fn main() {
86                println!("Hello, world!");
87            }
88        "#};
89        let lib_file = "src/lib.rs";
90        let lib_original = indoc! {r#"
91            fn greet() {
92            println!("Greetings!");
93            }
94        "#};
95        let lib_formatted = indoc! {r#"
96            fn greet() {
97                println!("Greetings!");
98            }
99        "#};
100
101        let mut writer = Vec::new();
102        let mut config = Config::default();
103        config.set().print_misformatted_file_names(true);
104        let mut emitter = DiffEmitter::new(config);
105        let _ = emitter
106            .emit_formatted_file(
107                &mut writer,
108                FormattedFile {
109                    filename: &FileName::Real(PathBuf::from(bin_file)),
110                    original_text: bin_original,
111                    formatted_text: bin_formatted,
112                },
113            )
114            .unwrap();
115        let _ = emitter
116            .emit_formatted_file(
117                &mut writer,
118                FormattedFile {
119                    filename: &FileName::Real(PathBuf::from(lib_file)),
120                    original_text: lib_original,
121                    formatted_text: lib_formatted,
122                },
123            )
124            .unwrap();
125
126        assert_eq!(
127            String::from_utf8(writer).unwrap(),
128            formatdoc! {"
129                {bin_file}
130                {lib_file}
131            "},
132        )
133    }
134
135    #[test]
136    fn prints_newline_message_with_only_newline_style_diff() {
137        let mut writer = Vec::new();
138        let config = Config::default();
139        let mut emitter = DiffEmitter::new(config);
140        let _ = emitter
141            .emit_formatted_file(
142                &mut writer,
143                FormattedFile {
144                    filename: &FileName::Real(PathBuf::from("src/lib.rs")),
145                    original_text: "fn empty() {}\n",
146                    formatted_text: "fn empty() {}\r\n",
147                },
148            )
149            .unwrap();
150        assert_eq!(
151            String::from_utf8(writer).unwrap(),
152            String::from("Incorrect newline style in src/lib.rs\n")
153        );
154    }
155}