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