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