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