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