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