]> git.lizzy.rs Git - rust.git/blob - src/test/mod.rs
Merge pull request #3334 from rchaser53/issue-3227
[rust.git] / src / test / mod.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::collections::{HashMap, HashSet};
12 use std::env;
13 use std::fs;
14 use std::io::{self, BufRead, BufReader, Read, Write};
15 use std::iter::{Enumerate, Peekable};
16 use std::mem;
17 use std::path::{Path, PathBuf};
18 use std::process::{Command, Stdio};
19 use std::str::Chars;
20
21 use crate::config::{Color, Config, EmitMode, FileName, ReportTactic};
22 use crate::formatting::{ModifiedChunk, SourceFile};
23 use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, OutputWriter};
24 use crate::source_file;
25 use crate::{FormatReport, Input, Session};
26
27 const DIFF_CONTEXT_SIZE: usize = 3;
28 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
29
30 // Returns a `Vec` containing `PathBuf`s of files with a rs extension in the
31 // given path. The `recursive` argument controls if files from subdirectories
32 // are also returned.
33 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
34     let mut files = vec![];
35     if path.is_dir() {
36         for entry in fs::read_dir(path).expect(&format!(
37             "Couldn't read directory {}",
38             path.to_str().unwrap()
39         )) {
40             let entry = entry.expect("Couldn't get DirEntry");
41             let path = entry.path();
42             if path.is_dir() && recursive {
43                 files.append(&mut get_test_files(&path, recursive));
44             } else if path.extension().map_or(false, |f| f == "rs") {
45                 files.push(path);
46             }
47         }
48     }
49     files
50 }
51
52 fn verify_config_used(path: &Path, config_name: &str) {
53     for entry in fs::read_dir(path).expect(&format!(
54         "Couldn't read {} directory",
55         path.to_str().unwrap()
56     )) {
57         let entry = entry.expect("Couldn't get directory entry");
58         let path = entry.path();
59         if path.extension().map_or(false, |f| f == "rs") {
60             // check if "// rustfmt-<config_name>:" appears in the file.
61             let filebuf = BufReader::new(
62                 fs::File::open(&path).expect(&format!("Couldn't read file {}", path.display())),
63             );
64             assert!(
65                 filebuf
66                     .lines()
67                     .map(|l| l.unwrap())
68                     .take_while(|l| l.starts_with("//"))
69                     .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
70                 format!(
71                     "config option file {} does not contain expected config name",
72                     path.display()
73                 )
74             );
75         }
76     }
77 }
78
79 #[test]
80 fn verify_config_test_names() {
81     for path in &[
82         Path::new("tests/source/configs"),
83         Path::new("tests/target/configs"),
84     ] {
85         for entry in fs::read_dir(path).expect("Couldn't read configs directory") {
86             let entry = entry.expect("Couldn't get directory entry");
87             let path = entry.path();
88             if path.is_dir() {
89                 let config_name = path.file_name().unwrap().to_str().unwrap();
90
91                 // Make sure that config name is used in the files in the directory.
92                 verify_config_used(&path, config_name);
93             }
94         }
95     }
96 }
97
98 // This writes to the terminal using the same approach (via term::stdout or
99 // println!) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
100 // using only one or the other will cause the output order to differ when
101 // `print_diff` selects the approach not used.
102 fn write_message(msg: &str) {
103     let mut writer = OutputWriter::new(Color::Auto);
104     writer.writeln(msg, None);
105 }
106
107 // Integration tests. The files in the tests/source are formatted and compared
108 // to their equivalent in tests/target. The target file and config can be
109 // overridden by annotations in the source file. The input and output must match
110 // exactly.
111 #[test]
112 fn system_tests() {
113     // Get all files in the tests/source directory.
114     let files = get_test_files(Path::new("tests/source"), true);
115     let (_reports, count, fails) = check_files(files, &None);
116
117     // Display results.
118     println!("Ran {} system tests.", count);
119     assert_eq!(fails, 0, "{} system tests failed", fails);
120 }
121
122 // Do the same for tests/coverage-source directory
123 // the only difference is the coverage mode
124 #[test]
125 fn coverage_tests() {
126     let files = get_test_files(Path::new("tests/coverage/source"), true);
127     let (_reports, count, fails) = check_files(files, &None);
128
129     println!("Ran {} tests in coverage mode.", count);
130     assert_eq!(fails, 0, "{} tests failed", fails);
131 }
132
133 #[test]
134 fn checkstyle_test() {
135     let filename = "tests/writemode/source/fn-single-line.rs";
136     let expected_filename = "tests/writemode/target/checkstyle.xml";
137     assert_output(Path::new(filename), Path::new(expected_filename));
138 }
139
140 #[test]
141 fn modified_test() {
142     use std::io::BufRead;
143
144     // Test "modified" output
145     let filename = "tests/writemode/source/modified.rs";
146     let mut data = Vec::new();
147     let mut config = Config::default();
148     config
149         .set()
150         .emit_mode(crate::config::EmitMode::ModifiedLines);
151
152     {
153         let mut session = Session::new(config, Some(&mut data));
154         session.format(Input::File(filename.into())).unwrap();
155     }
156
157     let mut lines = data.lines();
158     let mut chunks = Vec::new();
159     while let Some(Ok(header)) = lines.next() {
160         // Parse the header line
161         let values: Vec<_> = header
162             .split(' ')
163             .map(|s| s.parse::<u32>().unwrap())
164             .collect();
165         assert_eq!(values.len(), 3);
166         let line_number_orig = values[0];
167         let lines_removed = values[1];
168         let num_added = values[2];
169         let mut added_lines = Vec::new();
170         for _ in 0..num_added {
171             added_lines.push(lines.next().unwrap().unwrap());
172         }
173         chunks.push(ModifiedChunk {
174             line_number_orig,
175             lines_removed,
176             lines: added_lines,
177         });
178     }
179
180     assert_eq!(
181         chunks,
182         vec![
183             ModifiedChunk {
184                 line_number_orig: 4,
185                 lines_removed: 4,
186                 lines: vec!["fn blah() {}".into()],
187             },
188             ModifiedChunk {
189                 line_number_orig: 9,
190                 lines_removed: 6,
191                 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
192             },
193         ],
194     );
195 }
196
197 // Helper function for comparing the results of rustfmt
198 // to a known output file generated by one of the write modes.
199 fn assert_output(source: &Path, expected_filename: &Path) {
200     let config = read_config(source);
201     let (_, source_file, _) = format_file(source, config.clone());
202
203     // Populate output by writing to a vec.
204     let mut out = vec![];
205     let _ = source_file::write_all_files(&source_file, &mut out, &config);
206     let output = String::from_utf8(out).unwrap();
207
208     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
209     let mut expected_text = String::new();
210     expected_file
211         .read_to_string(&mut expected_text)
212         .expect("Failed reading target");
213
214     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
215     if !compare.is_empty() {
216         let mut failures = HashMap::new();
217         failures.insert(source.to_owned(), compare);
218         print_mismatches_default_message(failures);
219         assert!(false, "Text does not match expected output");
220     }
221 }
222
223 // Idempotence tests. Files in tests/target are checked to be unaltered by
224 // rustfmt.
225 #[test]
226 fn idempotence_tests() {
227     match option_env!("CFG_RELEASE_CHANNEL") {
228         None | Some("nightly") => {}
229         _ => return, // these tests require nightly
230     }
231     // Get all files in the tests/target directory.
232     let files = get_test_files(Path::new("tests/target"), true);
233     let (_reports, count, fails) = check_files(files, &None);
234
235     // Display results.
236     println!("Ran {} idempotent tests.", count);
237     assert_eq!(fails, 0, "{} idempotent tests failed", fails);
238 }
239
240 // Run rustfmt on itself. This operation must be idempotent. We also check that
241 // no warnings are emitted.
242 #[test]
243 fn self_tests() {
244     let mut files = get_test_files(Path::new("tests"), false);
245     let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
246     for dir in bin_directories {
247         let mut path = PathBuf::from("src");
248         path.push(dir);
249         path.push("main.rs");
250         files.push(path);
251     }
252     files.push(PathBuf::from("src/lib.rs"));
253
254     let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
255     let mut warnings = 0;
256
257     // Display results.
258     println!("Ran {} self tests.", count);
259     assert_eq!(fails, 0, "{} self tests failed", fails);
260
261     for format_report in reports {
262         println!("{}", format_report);
263         warnings += format_report.warning_count();
264     }
265
266     assert_eq!(
267         warnings, 0,
268         "Rustfmt's code generated {} warnings",
269         warnings
270     );
271 }
272
273 #[test]
274 fn stdin_formatting_smoke_test() {
275     let input = Input::Text("fn main () {}".to_owned());
276     let mut config = Config::default();
277     config.set().emit_mode(EmitMode::Stdout);
278     let mut buf: Vec<u8> = vec![];
279     {
280         let mut session = Session::new(config, Some(&mut buf));
281         session.format(input).unwrap();
282         assert!(session.has_no_errors());
283     }
284
285     #[cfg(not(windows))]
286     assert_eq!(buf, "fn main() {}\n".as_bytes());
287     #[cfg(windows)]
288     assert_eq!(buf, "fn main() {}\r\n".as_bytes());
289 }
290
291 #[test]
292 fn stdin_parser_panic_caught() {
293     // https://github.com/rust-lang/rustfmt/issues/3239
294     for text in ["{", "}"].iter().cloned().map(String::from) {
295         let mut buf = vec![];
296         let mut session = Session::new(Default::default(), Some(&mut buf));
297         let _ = session.format(Input::Text(text));
298
299         assert!(session.has_parsing_errors());
300     }
301 }
302
303 #[test]
304 fn stdin_disable_all_formatting_test() {
305     match option_env!("CFG_RELEASE_CHANNEL") {
306         None | Some("nightly") => {}
307         _ => return, // these tests require nightly
308     }
309     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
310     let mut child = Command::new(rustfmt().to_str().unwrap())
311         .stdin(Stdio::piped())
312         .stdout(Stdio::piped())
313         .arg("--config-path=./tests/config/disable_all_formatting.toml")
314         .spawn()
315         .expect("failed to execute child");
316
317     {
318         let stdin = child.stdin.as_mut().expect("failed to get stdin");
319         stdin
320             .write_all(input.as_bytes())
321             .expect("failed to write stdin");
322     }
323
324     let output = child.wait_with_output().expect("failed to wait on child");
325     assert!(output.status.success());
326     assert!(output.stderr.is_empty());
327     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
328 }
329
330 #[test]
331 fn format_lines_errors_are_reported() {
332     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
333     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
334     let mut config = Config::default();
335     config.set().error_on_line_overflow(true);
336     let mut session = Session::<io::Stdout>::new(config, None);
337     session.format(input).unwrap();
338     assert!(session.has_formatting_errors());
339 }
340
341 #[test]
342 fn format_lines_errors_are_reported_with_tabs() {
343     let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
344     let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
345     let mut config = Config::default();
346     config.set().error_on_line_overflow(true);
347     config.set().hard_tabs(true);
348     let mut session = Session::<io::Stdout>::new(config, None);
349     session.format(input).unwrap();
350     assert!(session.has_formatting_errors());
351 }
352
353 // For each file, run rustfmt and collect the output.
354 // Returns the number of files checked and the number of failures.
355 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
356     let mut count = 0;
357     let mut fails = 0;
358     let mut reports = vec![];
359
360     for file_name in files {
361         debug!("Testing '{}'...", file_name.display());
362
363         match idempotent_check(&file_name, &opt_config) {
364             Ok(ref report) if report.has_warnings() => {
365                 print!("{}", report);
366                 fails += 1;
367             }
368             Ok(report) => reports.push(report),
369             Err(err) => {
370                 if let IdempotentCheckError::Mismatch(msg) = err {
371                     print_mismatches_default_message(msg);
372                 }
373                 fails += 1;
374             }
375         }
376
377         count += 1;
378     }
379
380     (reports, count, fails)
381 }
382
383 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
384     for (file_name, diff) in result {
385         let mismatch_msg_formatter =
386             |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
387         print_diff(diff, &mismatch_msg_formatter, &Default::default());
388     }
389
390     if let Some(mut t) = term::stdout() {
391         t.reset().unwrap_or(());
392     }
393 }
394
395 fn print_mismatches<T: Fn(u32) -> String>(
396     result: HashMap<PathBuf, Vec<Mismatch>>,
397     mismatch_msg_formatter: T,
398 ) {
399     for (_file_name, diff) in result {
400         print_diff(diff, &mismatch_msg_formatter, &Default::default());
401     }
402
403     if let Some(mut t) = term::stdout() {
404         t.reset().unwrap_or(());
405     }
406 }
407
408 fn read_config(filename: &Path) -> Config {
409     let sig_comments = read_significant_comments(filename);
410     // Look for a config file... If there is a 'config' property in the significant comments, use
411     // that. Otherwise, if there are no significant comments at all, look for a config file with
412     // the same name as the test file.
413     let mut config = if !sig_comments.is_empty() {
414         get_config(sig_comments.get("config").map(Path::new))
415     } else {
416         get_config(filename.with_extension("toml").file_name().map(Path::new))
417     };
418
419     for (key, val) in &sig_comments {
420         if key != "target" && key != "config" {
421             config.override_value(key, val);
422             if config.is_default(key) {
423                 warn!("Default value {} used explicitly for {}", val, key);
424             }
425         }
426     }
427
428     // Don't generate warnings for to-do items.
429     config.set().report_todo(ReportTactic::Never);
430
431     config
432 }
433
434 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
435     let filepath = filepath.into();
436     let input = Input::File(filepath);
437     let mut session = Session::<io::Stdout>::new(config, None);
438     let result = session.format(input).unwrap();
439     let parsing_errors = session.has_parsing_errors();
440     let mut source_file = SourceFile::new();
441     mem::swap(&mut session.source_file, &mut source_file);
442     (parsing_errors, source_file, result)
443 }
444
445 enum IdempotentCheckError {
446     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
447     Parse,
448 }
449
450 fn idempotent_check(
451     filename: &PathBuf,
452     opt_config: &Option<PathBuf>,
453 ) -> Result<FormatReport, IdempotentCheckError> {
454     let sig_comments = read_significant_comments(filename);
455     let config = if let Some(ref config_file_path) = opt_config {
456         Config::from_toml_path(config_file_path).expect("rustfmt.toml not found")
457     } else {
458         read_config(filename)
459     };
460     let (parsing_errors, source_file, format_report) = format_file(filename, config);
461     if parsing_errors {
462         return Err(IdempotentCheckError::Parse);
463     }
464
465     let mut write_result = HashMap::new();
466     for (filename, text) in source_file {
467         if let FileName::Real(ref filename) = filename {
468             write_result.insert(filename.to_owned(), text);
469         }
470     }
471
472     let target = sig_comments.get("target").map(|x| &(*x)[..]);
473
474     handle_result(write_result, target).map(|_| format_report)
475 }
476
477 // Reads test config file using the supplied (optional) file name. If there's no file name or the
478 // file doesn't exist, just return the default config. Otherwise, the file must be read
479 // successfully.
480 fn get_config(config_file: Option<&Path>) -> Config {
481     let config_file_name = match config_file {
482         None => return Default::default(),
483         Some(file_name) => {
484             let mut full_path = PathBuf::from("tests/config/");
485             full_path.push(file_name);
486             if !full_path.exists() {
487                 return Default::default();
488             };
489             full_path
490         }
491     };
492
493     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
494     let mut def_config = String::new();
495     def_config_file
496         .read_to_string(&mut def_config)
497         .expect("Couldn't read config");
498
499     Config::from_toml(&def_config, Path::new("tests/config/")).expect("Invalid toml")
500 }
501
502 // Reads significant comments of the form: // rustfmt-key: value
503 // into a hash map.
504 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
505     let file =
506         fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
507     let reader = BufReader::new(file);
508     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
509     let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
510
511     // Matches lines containing significant comments or whitespace.
512     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
513         .expect("Failed creating pattern 2");
514
515     reader
516         .lines()
517         .map(|line| line.expect("Failed getting line"))
518         .take_while(|line| line_regex.is_match(line))
519         .filter_map(|line| {
520             regex.captures_iter(&line).next().map(|capture| {
521                 (
522                     capture
523                         .get(1)
524                         .expect("Couldn't unwrap capture")
525                         .as_str()
526                         .to_owned(),
527                     capture
528                         .get(2)
529                         .expect("Couldn't unwrap capture")
530                         .as_str()
531                         .to_owned(),
532                 )
533             })
534         })
535         .collect()
536 }
537
538 // Compare output to input.
539 // TODO: needs a better name, more explanation.
540 fn handle_result(
541     result: HashMap<PathBuf, String>,
542     target: Option<&str>,
543 ) -> Result<(), IdempotentCheckError> {
544     let mut failures = HashMap::new();
545
546     for (file_name, fmt_text) in result {
547         // If file is in tests/source, compare to file with same name in tests/target.
548         let target = get_target(&file_name, target);
549         let open_error = format!("Couldn't open target {:?}", &target);
550         let mut f = fs::File::open(&target).expect(&open_error);
551
552         let mut text = String::new();
553         let read_error = format!("Failed reading target {:?}", &target);
554         f.read_to_string(&mut text).expect(&read_error);
555
556         // Ignore LF and CRLF difference for Windows.
557         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
558             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
559             assert!(
560                 !diff.is_empty(),
561                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
562             );
563             failures.insert(file_name, diff);
564         }
565     }
566
567     if failures.is_empty() {
568         Ok(())
569     } else {
570         Err(IdempotentCheckError::Mismatch(failures))
571     }
572 }
573
574 // Map source file paths to their target paths.
575 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
576     if let Some(n) = file_name
577         .components()
578         .position(|c| c.as_os_str() == "source")
579     {
580         let mut target_file_name = PathBuf::new();
581         for (i, c) in file_name.components().enumerate() {
582             if i == n {
583                 target_file_name.push("target");
584             } else {
585                 target_file_name.push(c.as_os_str());
586             }
587         }
588         if let Some(replace_name) = target {
589             target_file_name.with_file_name(replace_name)
590         } else {
591             target_file_name
592         }
593     } else {
594         // This is either and idempotence check or a self check
595         file_name.to_owned()
596     }
597 }
598
599 #[test]
600 fn rustfmt_diff_make_diff_tests() {
601     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
602     assert_eq!(
603         diff,
604         vec![Mismatch {
605             line_number: 1,
606             line_number_orig: 1,
607             lines: vec![
608                 DiffLine::Context("a".into()),
609                 DiffLine::Resulting("b".into()),
610                 DiffLine::Expected("e".into()),
611                 DiffLine::Context("c".into()),
612                 DiffLine::Context("d".into()),
613             ],
614         }]
615     );
616 }
617
618 #[test]
619 fn rustfmt_diff_no_diff_test() {
620     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
621     assert_eq!(diff, vec![]);
622 }
623
624 // Compare strings without distinguishing between CRLF and LF
625 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
626     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
627     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
628     left.eq(right)
629 }
630
631 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
632
633 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
634     type Item = char;
635
636     fn next(&mut self) -> Option<char> {
637         self.0.next().map(|c| {
638             if c == '\r' {
639                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
640                     self.0.next();
641                     '\n'
642                 } else {
643                     '\r'
644                 }
645             } else {
646                 c
647             }
648         })
649     }
650 }
651
652 #[test]
653 fn string_eq_ignore_newline_repr_test() {
654     assert!(string_eq_ignore_newline_repr("", ""));
655     assert!(!string_eq_ignore_newline_repr("", "abc"));
656     assert!(!string_eq_ignore_newline_repr("abc", ""));
657     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
658     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
659     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
660 }
661
662 // This enum is used to represent one of three text features in Configurations.md: a block of code
663 // with its starting line number, the name of a rustfmt configuration option, or the value of a
664 // rustfmt configuration option.
665 enum ConfigurationSection {
666     CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
667     ConfigName(String),
668     ConfigValue(String),
669 }
670
671 impl ConfigurationSection {
672     fn get_section<I: Iterator<Item = String>>(
673         file: &mut Enumerate<I>,
674     ) -> Option<ConfigurationSection> {
675         lazy_static! {
676             static ref CONFIG_NAME_REGEX: regex::Regex =
677                 regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
678             static ref CONFIG_VALUE_REGEX: regex::Regex =
679                 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
680                     .expect("Failed creating configuration value pattern");
681         }
682
683         loop {
684             match file.next() {
685                 Some((i, line)) => {
686                     if line.starts_with("```rust") {
687                         // Get the lines of the code block.
688                         let lines: Vec<String> = file
689                             .map(|(_i, l)| l)
690                             .take_while(|l| !l.starts_with("```"))
691                             .collect();
692                         let block = format!("{}\n", lines.join("\n"));
693
694                         // +1 to translate to one-based indexing
695                         // +1 to get to first line of code (line after "```")
696                         let start_line = (i + 2) as u32;
697
698                         return Some(ConfigurationSection::CodeBlock((block, start_line)));
699                     } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
700                         return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
701                     } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
702                         return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
703                     }
704                 }
705                 None => return None, // reached the end of the file
706             }
707         }
708     }
709 }
710
711 // This struct stores the information about code blocks in the configurations
712 // file, formats the code blocks, and prints formatting errors.
713 struct ConfigCodeBlock {
714     config_name: Option<String>,
715     config_value: Option<String>,
716     code_block: Option<String>,
717     code_block_start: Option<u32>,
718 }
719
720 impl ConfigCodeBlock {
721     fn new() -> ConfigCodeBlock {
722         ConfigCodeBlock {
723             config_name: None,
724             config_value: None,
725             code_block: None,
726             code_block_start: None,
727         }
728     }
729
730     fn set_config_name(&mut self, name: Option<String>) {
731         self.config_name = name;
732         self.config_value = None;
733     }
734
735     fn set_config_value(&mut self, value: Option<String>) {
736         self.config_value = value;
737     }
738
739     fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
740         self.code_block = Some(code_block);
741         self.code_block_start = Some(code_block_start);
742     }
743
744     fn get_block_config(&self) -> Config {
745         let mut config = Config::default();
746         if self.config_value.is_some() && self.config_value.is_some() {
747             config.override_value(
748                 self.config_name.as_ref().unwrap(),
749                 self.config_value.as_ref().unwrap(),
750             );
751         }
752         config
753     }
754
755     fn code_block_valid(&self) -> bool {
756         // We never expect to not have a code block.
757         assert!(self.code_block.is_some() && self.code_block_start.is_some());
758
759         // See if code block begins with #![rustfmt::skip].
760         let fmt_skip = self
761             .code_block
762             .as_ref()
763             .unwrap()
764             .lines()
765             .nth(0)
766             .unwrap_or("")
767             == "#![rustfmt::skip]";
768
769         if self.config_name.is_none() && !fmt_skip {
770             write_message(&format!(
771                 "No configuration name for {}:{}",
772                 CONFIGURATIONS_FILE_NAME,
773                 self.code_block_start.unwrap()
774             ));
775             return false;
776         }
777         if self.config_value.is_none() && !fmt_skip {
778             write_message(&format!(
779                 "No configuration value for {}:{}",
780                 CONFIGURATIONS_FILE_NAME,
781                 self.code_block_start.unwrap()
782             ));
783             return false;
784         }
785         true
786     }
787
788     fn has_parsing_errors<T: Write>(&self, session: &Session<'_, T>) -> bool {
789         if session.has_parsing_errors() {
790             write_message(&format!(
791                 "\u{261d}\u{1f3fd} Cannot format {}:{}",
792                 CONFIGURATIONS_FILE_NAME,
793                 self.code_block_start.unwrap()
794             ));
795             return true;
796         }
797
798         false
799     }
800
801     fn print_diff(&self, compare: Vec<Mismatch>) {
802         let mut mismatches = HashMap::new();
803         mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
804         print_mismatches(mismatches, |line_num| {
805             format!(
806                 "\nMismatch at {}:{}:",
807                 CONFIGURATIONS_FILE_NAME,
808                 line_num + self.code_block_start.unwrap() - 1
809             )
810         });
811     }
812
813     fn formatted_has_diff(&self, text: &str) -> bool {
814         let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
815         if !compare.is_empty() {
816             self.print_diff(compare);
817             return true;
818         }
819
820         false
821     }
822
823     // Return a bool indicating if formatting this code block is an idempotent
824     // operation. This function also triggers printing any formatting failure
825     // messages.
826     fn formatted_is_idempotent(&self) -> bool {
827         // Verify that we have all of the expected information.
828         if !self.code_block_valid() {
829             return false;
830         }
831
832         let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
833         let mut config = self.get_block_config();
834         config.set().emit_mode(EmitMode::Stdout);
835         let mut buf: Vec<u8> = vec![];
836
837         {
838             let mut session = Session::new(config, Some(&mut buf));
839             session.format(input).unwrap();
840             if self.has_parsing_errors(&session) {
841                 return false;
842             }
843         }
844
845         !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
846     }
847
848     // Extract a code block from the iterator. Behavior:
849     // - Rust code blocks are identifed by lines beginning with "```rust".
850     // - One explicit configuration setting is supported per code block.
851     // - Rust code blocks with no configuration setting are illegal and cause an
852     //   assertion failure, unless the snippet begins with #![rustfmt::skip].
853     // - Configuration names in Configurations.md must be in the form of
854     //   "## `NAME`".
855     // - Configuration values in Configurations.md must be in the form of
856     //   "#### `VALUE`".
857     fn extract<I: Iterator<Item = String>>(
858         file: &mut Enumerate<I>,
859         prev: Option<&ConfigCodeBlock>,
860         hash_set: &mut HashSet<String>,
861     ) -> Option<ConfigCodeBlock> {
862         let mut code_block = ConfigCodeBlock::new();
863         code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
864
865         loop {
866             match ConfigurationSection::get_section(file) {
867                 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
868                     code_block.set_code_block(block, start_line);
869                     break;
870                 }
871                 Some(ConfigurationSection::ConfigName(name)) => {
872                     assert!(
873                         Config::is_valid_name(&name),
874                         "an unknown configuration option was found: {}",
875                         name
876                     );
877                     assert!(
878                         hash_set.remove(&name),
879                         "multiple configuration guides found for option {}",
880                         name
881                     );
882                     code_block.set_config_name(Some(name));
883                 }
884                 Some(ConfigurationSection::ConfigValue(value)) => {
885                     code_block.set_config_value(Some(value));
886                 }
887                 None => return None, // end of file was reached
888             }
889         }
890
891         Some(code_block)
892     }
893 }
894
895 #[test]
896 fn configuration_snippet_tests() {
897     // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
898     // entry for each Rust code block found.
899     fn get_code_blocks() -> Vec<ConfigCodeBlock> {
900         let mut file_iter = BufReader::new(
901             fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
902                 .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
903         )
904         .lines()
905         .map(|l| l.unwrap())
906         .enumerate();
907         let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
908         let mut hash_set = Config::hash_set();
909
910         while let Some(cb) =
911             ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
912         {
913             code_blocks.push(cb);
914         }
915
916         for name in hash_set {
917             if !Config::is_hidden_option(&name) {
918                 panic!("{} does not have a configuration guide", name);
919             }
920         }
921
922         code_blocks
923     }
924
925     let blocks = get_code_blocks();
926     let failures = blocks
927         .iter()
928         .map(|b| b.formatted_is_idempotent())
929         .fold(0, |acc, r| acc + (!r as u32));
930
931     // Display results.
932     println!("Ran {} configurations tests.", blocks.len());
933     assert_eq!(failures, 0, "{} configurations tests failed", failures);
934 }
935
936 struct TempFile {
937     path: PathBuf,
938 }
939
940 fn make_temp_file(file_name: &'static str) -> TempFile {
941     use std::env::var;
942     use std::fs::File;
943
944     // Used in the Rust build system.
945     let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
946     let path = Path::new(&target_dir).join(file_name);
947
948     let mut file = File::create(&path).expect("Couldn't create temp file");
949     let content = "fn main() {}\n";
950     file.write_all(content.as_bytes())
951         .expect("Couldn't write temp file");
952     TempFile { path }
953 }
954
955 impl Drop for TempFile {
956     fn drop(&mut self) {
957         use std::fs::remove_file;
958         remove_file(&self.path).expect("Couldn't delete temp file");
959     }
960 }
961
962 fn rustfmt() -> PathBuf {
963     let mut me = env::current_exe().expect("failed to get current executable");
964     me.pop(); // chop of the test name
965     me.pop(); // chop off `deps`
966
967     // if we run `cargo test --release` we might only have a release build
968     if cfg!(release) {
969         // ../release/
970         me.pop();
971         me.push("release");
972     }
973     me.push("rustfmt");
974     assert!(
975         me.is_file() || me.with_extension("exe").is_file(),
976         if cfg!(release) {
977             "no rustfmt bin, try running `cargo build --release` before testing"
978         } else {
979             "no rustfmt bin, try running `cargo build` before testing"
980         }
981     );
982     me
983 }
984
985 #[test]
986 fn verify_check_works() {
987     let temp_file = make_temp_file("temp_check.rs");
988
989     Command::new(rustfmt().to_str().unwrap())
990         .arg("--check")
991         .arg(temp_file.path.to_str().unwrap())
992         .status()
993         .expect("run with check option failed");
994 }