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