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.
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.
11 #![feature(rustc_private)]
16 extern crate rustfmt_nightly as rustfmt;
19 use std::collections::HashMap;
21 use std::io::{self, BufRead, BufReader, Read};
22 use std::iter::Peekable;
23 use std::path::{Path, PathBuf};
27 use rustfmt::filemap::{write_system_newlines, FileMap};
28 use rustfmt::config::{Color, Config, ReportTactic};
29 use rustfmt::rustfmt_diff::*;
31 const DIFF_CONTEXT_SIZE: usize = 3;
33 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> PathBuf {
34 dir_entry.expect("Couldn't get DirEntry").path().to_owned()
37 // Integration tests. The files in the tests/source are formatted and compared
38 // to their equivalent in tests/target. The target file and config can be
39 // overridden by annotations in the source file. The input and output must match
43 // Get all files in the tests/source directory.
44 let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
45 // Turn a DirEntry into a String that represents the relative path to the
47 let files = files.map(get_path_string);
48 let (_reports, count, fails) = check_files(files);
51 println!("Ran {} system tests.", count);
52 assert_eq!(fails, 0, "{} system tests failed", fails);
55 // Do the same for tests/coverage-source directory
56 // the only difference is the coverage mode
59 let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
60 let files = files.map(get_path_string);
61 let (_reports, count, fails) = check_files(files);
63 println!("Ran {} tests in coverage mode.", count);
64 assert_eq!(fails, 0, "{} tests failed", fails);
68 fn checkstyle_test() {
69 let filename = "tests/writemode/source/fn-single-line.rs";
70 let expected_filename = "tests/writemode/target/checkstyle.xml";
71 assert_output(Path::new(filename), Path::new(expected_filename));
74 // Helper function for comparing the results of rustfmt
75 // to a known output file generated by one of the write modes.
76 fn assert_output(source: &Path, expected_filename: &Path) {
77 let config = read_config(source);
78 let (_error_summary, file_map, _report) = format_file(source, &config);
80 // Populate output by writing to a vec.
82 let _ = filemap::write_all_files(&file_map, &mut out, &config);
83 let output = String::from_utf8(out).unwrap();
85 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
86 let mut expected_text = String::new();
88 .read_to_string(&mut expected_text)
89 .expect("Failed reading target");
91 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
92 if !compare.is_empty() {
93 let mut failures = HashMap::new();
94 failures.insert(source.to_owned(), compare);
95 print_mismatches(failures);
96 assert!(false, "Text does not match expected output");
100 // Idempotence tests. Files in tests/target are checked to be unaltered by
103 fn idempotence_tests() {
104 // Get all files in the tests/target directory.
105 let files = fs::read_dir("tests/target")
106 .expect("Couldn't read target dir")
107 .map(get_path_string);
108 let (_reports, count, fails) = check_files(files);
111 println!("Ran {} idempotent tests.", count);
112 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
115 // Run rustfmt on itself. This operation must be idempotent. We also check that
116 // no warnings are emitted.
119 let files = fs::read_dir("src/bin")
120 .expect("Couldn't read src dir")
121 .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
122 .map(get_path_string);
123 // Hack because there's no `IntoIterator` impl for `[T; N]`.
124 let files = files.chain(Some(PathBuf::from("src/lib.rs")).into_iter());
125 let files = files.chain(Some(PathBuf::from("build.rs")).into_iter());
127 let (reports, count, fails) = check_files(files);
128 let mut warnings = 0;
131 println!("Ran {} self tests.", count);
132 assert_eq!(fails, 0, "{} self tests failed", fails);
134 for format_report in reports {
135 println!("{}", format_report);
136 warnings += format_report.warning_count();
142 "Rustfmt's code generated {} warnings",
148 fn stdin_formatting_smoke_test() {
149 let input = Input::Text("fn main () {}".to_owned());
150 let config = Config::default();
151 let (error_summary, file_map, _report) =
152 format_input::<io::Stdout>(input, &config, None).unwrap();
153 assert!(error_summary.has_no_errors());
154 for &(ref file_name, ref text) in &file_map {
155 if let FileName::Custom(ref file_name) = *file_name {
156 if file_name == "stdin" {
157 assert_eq!(text.to_string(), "fn main() {}\n");
165 // FIXME(#1990) restore this test
167 // fn stdin_disable_all_formatting_test() {
168 // let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
169 // let mut child = Command::new("./target/debug/rustfmt")
170 // .stdin(Stdio::piped())
171 // .stdout(Stdio::piped())
172 // .arg("--config-path=./tests/config/disable_all_formatting.toml")
174 // .expect("failed to execute child");
177 // let stdin = child.stdin.as_mut().expect("failed to get stdin");
179 // .write_all(input.as_bytes())
180 // .expect("failed to write stdin");
182 // let output = child.wait_with_output().expect("failed to wait on child");
183 // assert!(output.status.success());
184 // assert!(output.stderr.is_empty());
185 // assert_eq!(input, String::from_utf8(output.stdout).unwrap());
189 fn format_lines_errors_are_reported() {
190 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
191 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
192 let config = Config::default();
193 let (error_summary, _file_map, _report) =
194 format_input::<io::Stdout>(input, &config, None).unwrap();
195 assert!(error_summary.has_formatting_errors());
198 // For each file, run rustfmt and collect the output.
199 // Returns the number of files checked and the number of failures.
200 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
202 I: Iterator<Item = PathBuf>,
206 let mut reports = vec![];
208 for file_name in files.filter(|f| f.extension().map_or(false, |f| f == "rs")) {
209 debug!("Testing '{}'...", file_name.display());
211 match idempotent_check(file_name) {
212 Ok(ref report) if report.has_warnings() => {
213 print!("{}", report);
216 Ok(report) => reports.push(report),
218 if let IdempotentCheckError::Mismatch(msg) = err {
219 print_mismatches(msg);
228 (reports, count, fails)
231 fn print_mismatches(result: HashMap<PathBuf, Vec<Mismatch>>) {
232 let mut t = term::stdout().unwrap();
234 for (file_name, diff) in result {
237 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num),
245 fn read_config(filename: &Path) -> Config {
246 let sig_comments = read_significant_comments(filename);
247 // Look for a config file... If there is a 'config' property in the significant comments, use
248 // that. Otherwise, if there are no significant comments at all, look for a config file with
249 // the same name as the test file.
250 let mut config = if !sig_comments.is_empty() {
251 get_config(sig_comments.get("config").map(Path::new))
253 get_config(filename.with_extension("toml").file_name().map(Path::new))
256 for (key, val) in &sig_comments {
257 if key != "target" && key != "config" {
258 config.override_value(key, val);
262 // Don't generate warnings for to-do items.
263 config.set().report_todo(ReportTactic::Never);
268 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
269 let filepath = filepath.into();
270 let input = Input::File(filepath);
271 format_input::<io::Stdout>(input, config, None).unwrap()
274 pub enum IdempotentCheckError {
275 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
279 pub fn idempotent_check(filename: PathBuf) -> Result<FormatReport, IdempotentCheckError> {
280 let sig_comments = read_significant_comments(&filename);
281 let config = read_config(&filename);
282 let (error_summary, file_map, format_report) = format_file(filename, &config);
283 if error_summary.has_parsing_errors() {
284 return Err(IdempotentCheckError::Parse);
287 let mut write_result = HashMap::new();
288 for &(ref filename, ref text) in &file_map {
289 let mut v = Vec::new();
290 // Won't panic, as we're not doing any IO.
291 write_system_newlines(&mut v, text, &config).unwrap();
292 // Won't panic, we are writing correct utf8.
293 let one_result = String::from_utf8(v).unwrap();
294 if let FileName::Real(ref filename) = *filename {
295 write_result.insert(filename.to_owned(), one_result);
299 let target = sig_comments.get("target").map(|x| &(*x)[..]);
301 handle_result(write_result, target).map(|_| format_report)
304 // Reads test config file using the supplied (optional) file name. If there's no file name or the
305 // file doesn't exist, just return the default config. Otherwise, the file must be read
307 fn get_config(config_file: Option<&Path>) -> Config {
308 let config_file_name = match config_file {
309 None => return Default::default(),
311 let mut full_path = PathBuf::from("tests/config/");
312 full_path.push(file_name);
313 if !full_path.exists() {
314 return Default::default();
320 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
321 let mut def_config = String::new();
323 .read_to_string(&mut def_config)
324 .expect("Couldn't read config");
326 Config::from_toml(&def_config).expect("Invalid toml")
329 // Reads significant comments of the form: // rustfmt-key: value
331 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
333 fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
334 let reader = BufReader::new(file);
335 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
336 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
338 // Matches lines containing significant comments or whitespace.
339 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
340 .expect("Failed creating pattern 2");
344 .map(|line| line.expect("Failed getting line"))
345 .take_while(|line| line_regex.is_match(line))
347 regex.captures_iter(&line).next().map(|capture| {
351 .expect("Couldn't unwrap capture")
356 .expect("Couldn't unwrap capture")
365 // Compare output to input.
366 // TODO: needs a better name, more explanation.
368 result: HashMap<PathBuf, String>,
369 target: Option<&str>,
370 ) -> Result<(), IdempotentCheckError> {
371 let mut failures = HashMap::new();
373 for (file_name, fmt_text) in result {
374 // If file is in tests/source, compare to file with same name in tests/target.
375 let target = get_target(&file_name, target);
376 let open_error = format!("Couldn't open target {:?}", &target);
377 let mut f = fs::File::open(&target).expect(&open_error);
379 let mut text = String::new();
380 let read_error = format!("Failed reading target {:?}", &target);
381 f.read_to_string(&mut text).expect(&read_error);
383 // Ignore LF and CRLF difference for Windows.
384 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
385 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
388 "Empty diff? Maybe due to a missing a newline at the end of a file?"
390 failures.insert(file_name, diff);
394 if failures.is_empty() {
397 Err(IdempotentCheckError::Mismatch(failures))
401 // Map source file paths to their target paths.
402 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
403 if let Some(n) = file_name
405 .position(|c| c.as_os_str() == "source")
407 let mut target_file_name = PathBuf::new();
408 for (i, c) in file_name.components().enumerate() {
410 target_file_name.push("target");
412 target_file_name.push(c.as_os_str());
415 if let Some(replace_name) = target {
416 target_file_name.with_file_name(replace_name)
421 // This is either and idempotence check or a self check
427 fn rustfmt_diff_make_diff_tests() {
428 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
435 DiffLine::Context("a".into()),
436 DiffLine::Resulting("b".into()),
437 DiffLine::Expected("e".into()),
438 DiffLine::Context("c".into()),
439 DiffLine::Context("d".into()),
447 fn rustfmt_diff_no_diff_test() {
448 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
449 assert_eq!(diff, vec![]);
452 // Compare strings without distinguishing between CRLF and LF
453 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
454 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
455 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
459 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
461 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
463 fn next(&mut self) -> Option<char> {
464 self.0.next().map(|c| {
466 if *self.0.peek().unwrap_or(&'\0') == '\n' {
480 fn string_eq_ignore_newline_repr_test() {
481 assert!(string_eq_ignore_newline_repr("", ""));
482 assert!(!string_eq_ignore_newline_repr("", "abc"));
483 assert!(!string_eq_ignore_newline_repr("abc", ""));
484 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
485 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
486 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));