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 extern crate assert_cli;
13 use std::collections::{HashMap, HashSet};
16 use std::io::{self, BufRead, BufReader, Read};
17 use std::iter::{Enumerate, Peekable};
18 use std::path::{Path, PathBuf};
21 use config::summary::Summary;
22 use config::{Color, Config, ReportTactic};
23 use filemap::write_system_newlines;
27 const DIFF_CONTEXT_SIZE: usize = 3;
28 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
30 // Returns a `Vec` containing `PathBuf`s of files with a rs extension in the
31 // given path. The `recursive` argument controls if files from subdirectories
33 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
34 let mut files = vec![];
36 for entry in fs::read_dir(path).expect(&format!(
37 "Couldn't read directory {}",
38 path.to_str().unwrap()
40 let entry = entry.expect("Couldn't get DirEntry");
41 let path = entry.path();
42 if path.is_dir() && recursive {
43 files.append(&mut get_test_files(&path, recursive));
44 } else if path.extension().map_or(false, |f| f == "rs") {
52 fn verify_config_used(path: &Path, config_name: &str) {
53 for entry in fs::read_dir(path).expect(&format!(
54 "Couldn't read {} directory",
55 path.to_str().unwrap()
57 let entry = entry.expect("Couldn't get directory entry");
58 let path = entry.path();
59 if path.extension().map_or(false, |f| f == "rs") {
60 // check if "// rustfmt-<config_name>:" appears in the file.
61 let filebuf = BufReader::new(
62 fs::File::open(&path).expect(&format!("Couldn't read file {}", path.display())),
68 .take_while(|l| l.starts_with("//"))
69 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
71 "config option file {} does not contain expected config name",
80 fn verify_config_test_names() {
82 Path::new("tests/source/configs"),
83 Path::new("tests/target/configs"),
85 for entry in fs::read_dir(path).expect("Couldn't read configs directory") {
86 let entry = entry.expect("Couldn't get directory entry");
87 let path = entry.path();
89 let config_name = path.file_name().unwrap().to_str().unwrap();
91 // Make sure that config name is used in the files in the directory.
92 verify_config_used(&path, config_name);
98 // This writes to the terminal using the same approach (via term::stdout or
99 // println!) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
100 // using only one or the other will cause the output order to differ when
101 // `print_diff` selects the approach not used.
102 fn write_message(msg: &str) {
103 let mut writer = OutputWriter::new(Color::Auto);
104 writer.writeln(&format!("{}", msg), None);
107 // Integration tests. The files in the tests/source are formatted and compared
108 // to their equivalent in tests/target. The target file and config can be
109 // overridden by annotations in the source file. The input and output must match
113 // Get all files in the tests/source directory.
114 let files = get_test_files(Path::new("tests/source"), true);
115 let (_reports, count, fails) = check_files(files, None);
118 println!("Ran {} system tests.", count);
119 assert_eq!(fails, 0, "{} system tests failed", fails);
122 // Do the same for tests/coverage-source directory
123 // the only difference is the coverage mode
125 fn coverage_tests() {
126 let files = get_test_files(Path::new("tests/coverage/source"), true);
127 let (_reports, count, fails) = check_files(files, None);
129 println!("Ran {} tests in coverage mode.", count);
130 assert_eq!(fails, 0, "{} tests failed", fails);
134 fn checkstyle_test() {
135 let filename = "tests/writemode/source/fn-single-line.rs";
136 let expected_filename = "tests/writemode/target/checkstyle.xml";
137 assert_output(Path::new(filename), Path::new(expected_filename));
142 // Test "modified" output
143 let filename = "tests/writemode/source/modified.rs";
144 let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap();
146 result.modified_lines,
152 lines: vec!["fn blah() {}".into()],
157 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
164 // Helper function for comparing the results of rustfmt
165 // to a known output file generated by one of the write modes.
166 fn assert_output(source: &Path, expected_filename: &Path) {
167 let config = read_config(source);
168 let (_error_summary, file_map, _report) = format_file(source, &config);
170 // Populate output by writing to a vec.
171 let mut out = vec![];
172 let _ = filemap::write_all_files(&file_map, &mut out, &config);
173 let output = String::from_utf8(out).unwrap();
175 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
176 let mut expected_text = String::new();
178 .read_to_string(&mut expected_text)
179 .expect("Failed reading target");
181 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
182 if !compare.is_empty() {
183 let mut failures = HashMap::new();
184 failures.insert(source.to_owned(), compare);
185 print_mismatches_default_message(failures);
186 assert!(false, "Text does not match expected output");
190 // Idempotence tests. Files in tests/target are checked to be unaltered by
193 fn idempotence_tests() {
194 match option_env!("CFG_RELEASE_CHANNEL") {
195 None | Some("nightly") => {}
196 _ => return, // these tests require nightly
198 // Get all files in the tests/target directory.
199 let files = get_test_files(Path::new("tests/target"), true);
200 let (_reports, count, fails) = check_files(files, None);
203 println!("Ran {} idempotent tests.", count);
204 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
207 // Run rustfmt on itself. This operation must be idempotent. We also check that
208 // no warnings are emitted.
211 let mut files = get_test_files(Path::new("tests"), false);
212 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
213 for dir in bin_directories {
214 let mut path = PathBuf::from("src");
216 path.push("main.rs");
219 files.push(PathBuf::from("src/lib.rs"));
221 let (reports, count, fails) = check_files(files, Some(PathBuf::from("rustfmt.toml")));
222 let mut warnings = 0;
225 println!("Ran {} self tests.", count);
226 assert_eq!(fails, 0, "{} self tests failed", fails);
228 for format_report in reports {
229 println!("{}", format_report);
230 warnings += format_report.warning_count();
235 "Rustfmt's code generated {} warnings",
241 fn stdin_formatting_smoke_test() {
242 let input = Input::Text("fn main () {}".to_owned());
243 let config = Config::default();
244 let (error_summary, file_map, _report) =
245 format_input::<io::Stdout>(input, &config, None).unwrap();
246 assert!(error_summary.has_no_errors());
247 for &(ref file_name, ref text) in &file_map {
248 if let FileName::Custom(ref file_name) = *file_name {
249 if file_name == "stdin" {
250 assert_eq!(text.to_string(), "fn main() {}\n");
258 // FIXME(#1990) restore this test
260 // fn stdin_disable_all_formatting_test() {
261 // let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
262 // let mut child = Command::new("./target/debug/rustfmt")
263 // .stdin(Stdio::piped())
264 // .stdout(Stdio::piped())
265 // .arg("--config-path=./tests/config/disable_all_formatting.toml")
267 // .expect("failed to execute child");
270 // let stdin = child.stdin.as_mut().expect("failed to get stdin");
272 // .write_all(input.as_bytes())
273 // .expect("failed to write stdin");
275 // let output = child.wait_with_output().expect("failed to wait on child");
276 // assert!(output.status.success());
277 // assert!(output.stderr.is_empty());
278 // assert_eq!(input, String::from_utf8(output.stdout).unwrap());
282 fn format_lines_errors_are_reported() {
283 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
284 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
285 let mut config = Config::default();
286 config.set().error_on_line_overflow(true);
287 let (error_summary, _file_map, _report) =
288 format_input::<io::Stdout>(input, &config, None).unwrap();
289 assert!(error_summary.has_formatting_errors());
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 mut config = Config::default();
297 config.set().error_on_line_overflow(true);
298 config.set().hard_tabs(true);
299 let (error_summary, _file_map, _report) =
300 format_input::<io::Stdout>(input, &config, None).unwrap();
301 assert!(error_summary.has_formatting_errors());
304 // For each file, run rustfmt and collect the output.
305 // Returns the number of files checked and the number of failures.
306 fn check_files(files: Vec<PathBuf>, opt_config: Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
309 let mut reports = vec![];
311 for file_name in files {
312 debug!("Testing '{}'...", file_name.display());
314 match idempotent_check(&file_name, &opt_config) {
315 Ok(ref report) if report.has_warnings() => {
316 print!("{}", report);
319 Ok(report) => reports.push(report),
321 if let IdempotentCheckError::Mismatch(msg) = err {
322 print_mismatches_default_message(msg);
331 (reports, count, fails)
334 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
335 for (file_name, diff) in result {
336 let mismatch_msg_formatter =
337 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
338 print_diff(diff, &mismatch_msg_formatter, &Default::default());
341 if let Some(mut t) = term::stdout() {
342 t.reset().unwrap_or(());
346 fn print_mismatches<T: Fn(u32) -> String>(
347 result: HashMap<PathBuf, Vec<Mismatch>>,
348 mismatch_msg_formatter: T,
350 for (_file_name, diff) in result {
351 print_diff(diff, &mismatch_msg_formatter, &Default::default());
354 if let Some(mut t) = term::stdout() {
355 t.reset().unwrap_or(());
359 fn read_config(filename: &Path) -> Config {
360 let sig_comments = read_significant_comments(filename);
361 // Look for a config file... If there is a 'config' property in the significant comments, use
362 // that. Otherwise, if there are no significant comments at all, look for a config file with
363 // the same name as the test file.
364 let mut config = if !sig_comments.is_empty() {
365 get_config(sig_comments.get("config").map(Path::new))
367 get_config(filename.with_extension("toml").file_name().map(Path::new))
370 for (key, val) in &sig_comments {
371 if key != "target" && key != "config" {
372 config.override_value(key, val);
376 // Don't generate warnings for to-do items.
377 config.set().report_todo(ReportTactic::Never);
382 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
383 let filepath = filepath.into();
384 let input = Input::File(filepath);
385 format_input::<io::Stdout>(input, config, None).unwrap()
388 pub enum IdempotentCheckError {
389 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
393 pub fn idempotent_check(
395 opt_config: &Option<PathBuf>,
396 ) -> Result<FormatReport, IdempotentCheckError> {
397 let sig_comments = read_significant_comments(filename);
398 let config = if let Some(ref config_file_path) = opt_config {
399 Config::from_toml_path(config_file_path).expect("rustfmt.toml not found")
401 read_config(filename)
403 let (error_summary, file_map, format_report) = format_file(filename, &config);
404 if error_summary.has_parsing_errors() {
405 return Err(IdempotentCheckError::Parse);
408 let mut write_result = HashMap::new();
409 for &(ref filename, ref text) in &file_map {
410 let mut v = Vec::new();
411 // Won't panic, as we're not doing any IO.
412 write_system_newlines(&mut v, text, &config).unwrap();
413 // Won't panic, we are writing correct utf8.
414 let one_result = String::from_utf8(v).unwrap();
415 if let FileName::Real(ref filename) = *filename {
416 write_result.insert(filename.to_owned(), one_result);
420 let target = sig_comments.get("target").map(|x| &(*x)[..]);
422 handle_result(write_result, target).map(|_| format_report)
425 // Reads test config file using the supplied (optional) file name. If there's no file name or the
426 // file doesn't exist, just return the default config. Otherwise, the file must be read
428 fn get_config(config_file: Option<&Path>) -> Config {
429 let config_file_name = match config_file {
430 None => return Default::default(),
432 let mut full_path = PathBuf::from("tests/config/");
433 full_path.push(file_name);
434 if !full_path.exists() {
435 return Default::default();
441 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
442 let mut def_config = String::new();
444 .read_to_string(&mut def_config)
445 .expect("Couldn't read config");
447 Config::from_toml(&def_config, Path::new("tests/config/")).expect("Invalid toml")
450 // Reads significant comments of the form: // rustfmt-key: value
452 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
454 fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
455 let reader = BufReader::new(file);
456 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
457 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
459 // Matches lines containing significant comments or whitespace.
460 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
461 .expect("Failed creating pattern 2");
465 .map(|line| line.expect("Failed getting line"))
466 .take_while(|line| line_regex.is_match(line))
468 regex.captures_iter(&line).next().map(|capture| {
472 .expect("Couldn't unwrap capture")
477 .expect("Couldn't unwrap capture")
486 // Compare output to input.
487 // TODO: needs a better name, more explanation.
489 result: HashMap<PathBuf, String>,
490 target: Option<&str>,
491 ) -> Result<(), IdempotentCheckError> {
492 let mut failures = HashMap::new();
494 for (file_name, fmt_text) in result {
495 // If file is in tests/source, compare to file with same name in tests/target.
496 let target = get_target(&file_name, target);
497 let open_error = format!("Couldn't open target {:?}", &target);
498 let mut f = fs::File::open(&target).expect(&open_error);
500 let mut text = String::new();
501 let read_error = format!("Failed reading target {:?}", &target);
502 f.read_to_string(&mut text).expect(&read_error);
504 // Ignore LF and CRLF difference for Windows.
505 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
506 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
509 "Empty diff? Maybe due to a missing a newline at the end of a file?"
511 failures.insert(file_name, diff);
515 if failures.is_empty() {
518 Err(IdempotentCheckError::Mismatch(failures))
522 // Map source file paths to their target paths.
523 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
524 if let Some(n) = file_name
526 .position(|c| c.as_os_str() == "source")
528 let mut target_file_name = PathBuf::new();
529 for (i, c) in file_name.components().enumerate() {
531 target_file_name.push("target");
533 target_file_name.push(c.as_os_str());
536 if let Some(replace_name) = target {
537 target_file_name.with_file_name(replace_name)
542 // This is either and idempotence check or a self check
548 fn rustfmt_diff_make_diff_tests() {
549 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
556 DiffLine::Context("a".into()),
557 DiffLine::Resulting("b".into()),
558 DiffLine::Expected("e".into()),
559 DiffLine::Context("c".into()),
560 DiffLine::Context("d".into()),
567 fn rustfmt_diff_no_diff_test() {
568 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
569 assert_eq!(diff, vec![]);
572 // Compare strings without distinguishing between CRLF and LF
573 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
574 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
575 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
579 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
581 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
584 fn next(&mut self) -> Option<char> {
585 self.0.next().map(|c| {
587 if *self.0.peek().unwrap_or(&'\0') == '\n' {
601 fn string_eq_ignore_newline_repr_test() {
602 assert!(string_eq_ignore_newline_repr("", ""));
603 assert!(!string_eq_ignore_newline_repr("", "abc"));
604 assert!(!string_eq_ignore_newline_repr("abc", ""));
605 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
606 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
607 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
610 // This enum is used to represent one of three text features in Configurations.md: a block of code
611 // with its starting line number, the name of a rustfmt configuration option, or the value of a
612 // rustfmt configuration option.
613 enum ConfigurationSection {
614 CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
619 impl ConfigurationSection {
620 fn get_section<I: Iterator<Item = String>>(
621 file: &mut Enumerate<I>,
622 ) -> Option<ConfigurationSection> {
624 static ref CONFIG_NAME_REGEX: regex::Regex =
625 regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
626 static ref CONFIG_VALUE_REGEX: regex::Regex =
627 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
628 .expect("Failed creating configuration value pattern");
634 if line.starts_with("```rust") {
635 // Get the lines of the code block.
636 let lines: Vec<String> = file
638 .take_while(|l| !l.starts_with("```"))
640 let block = format!("{}\n", lines.join("\n"));
642 // +1 to translate to one-based indexing
643 // +1 to get to first line of code (line after "```")
644 let start_line = (i + 2) as u32;
646 return Some(ConfigurationSection::CodeBlock((block, start_line)));
647 } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
648 return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
649 } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
650 return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
653 None => return None, // reached the end of the file
659 // This struct stores the information about code blocks in the configurations
660 // file, formats the code blocks, and prints formatting errors.
661 struct ConfigCodeBlock {
662 config_name: Option<String>,
663 config_value: Option<String>,
664 code_block: Option<String>,
665 code_block_start: Option<u32>,
668 impl ConfigCodeBlock {
669 fn new() -> ConfigCodeBlock {
674 code_block_start: None,
678 fn set_config_name(&mut self, name: Option<String>) {
679 self.config_name = name;
680 self.config_value = None;
683 fn set_config_value(&mut self, value: Option<String>) {
684 self.config_value = value;
687 fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
688 self.code_block = Some(code_block);
689 self.code_block_start = Some(code_block_start);
692 fn get_block_config(&self) -> Config {
693 let mut config = Config::default();
694 if self.config_value.is_some() && self.config_value.is_some() {
695 config.override_value(
696 self.config_name.as_ref().unwrap(),
697 self.config_value.as_ref().unwrap(),
703 fn code_block_valid(&self) -> bool {
704 // We never expect to not have a code block.
705 assert!(self.code_block.is_some() && self.code_block_start.is_some());
707 // See if code block begins with #![rustfmt_skip].
714 .unwrap_or("") == "#![rustfmt_skip]";
716 if self.config_name.is_none() && !fmt_skip {
717 write_message(&format!(
718 "No configuration name for {}:{}",
719 CONFIGURATIONS_FILE_NAME,
720 self.code_block_start.unwrap()
724 if self.config_value.is_none() && !fmt_skip {
725 write_message(&format!(
726 "No configuration value for {}:{}",
727 CONFIGURATIONS_FILE_NAME,
728 self.code_block_start.unwrap()
735 fn has_parsing_errors(&self, error_summary: Summary) -> bool {
736 if error_summary.has_parsing_errors() {
737 write_message(&format!(
738 "\u{261d}\u{1f3fd} Cannot format {}:{}",
739 CONFIGURATIONS_FILE_NAME,
740 self.code_block_start.unwrap()
748 fn print_diff(&self, compare: Vec<Mismatch>) {
749 let mut mismatches = HashMap::new();
750 mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
751 print_mismatches(mismatches, |line_num| {
753 "\nMismatch at {}:{}:",
754 CONFIGURATIONS_FILE_NAME,
755 line_num + self.code_block_start.unwrap() - 1
760 fn formatted_has_diff(&self, file_map: &FileMap) -> bool {
761 let &(ref _file_name, ref text) = file_map.first().unwrap();
762 let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
763 if !compare.is_empty() {
764 self.print_diff(compare);
771 // Return a bool indicating if formatting this code block is an idempotent
772 // operation. This function also triggers printing any formatting failure
774 fn formatted_is_idempotent(&self) -> bool {
775 // Verify that we have all of the expected information.
776 if !self.code_block_valid() {
780 let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
781 let config = self.get_block_config();
783 let (error_summary, file_map, _report) =
784 format_input::<io::Stdout>(input, &config, None).unwrap();
786 !self.has_parsing_errors(error_summary) && !self.formatted_has_diff(&file_map)
789 // Extract a code block from the iterator. Behavior:
790 // - Rust code blocks are identifed by lines beginning with "```rust".
791 // - One explicit configuration setting is supported per code block.
792 // - Rust code blocks with no configuration setting are illegal and cause an
793 // assertion failure, unless the snippet begins with #![rustfmt_skip].
794 // - Configuration names in Configurations.md must be in the form of
796 // - Configuration values in Configurations.md must be in the form of
798 fn extract<I: Iterator<Item = String>>(
799 file: &mut Enumerate<I>,
800 prev: Option<&ConfigCodeBlock>,
801 hash_set: &mut HashSet<String>,
802 ) -> Option<ConfigCodeBlock> {
803 let mut code_block = ConfigCodeBlock::new();
804 code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
807 match ConfigurationSection::get_section(file) {
808 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
809 code_block.set_code_block(block, start_line);
812 Some(ConfigurationSection::ConfigName(name)) => {
814 Config::is_valid_name(&name),
815 "an unknown configuration option was found: {}",
819 hash_set.remove(&name),
820 "multiple configuration guides found for option {}",
823 code_block.set_config_name(Some(name));
825 Some(ConfigurationSection::ConfigValue(value)) => {
826 code_block.set_config_value(Some(value));
828 None => return None, // end of file was reached
837 fn configuration_snippet_tests() {
838 // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
839 // entry for each Rust code block found.
840 fn get_code_blocks() -> Vec<ConfigCodeBlock> {
841 let mut file_iter = BufReader::new(
842 fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
843 .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
847 let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
848 let mut hash_set = Config::hash_set();
851 ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
853 code_blocks.push(cb);
856 for name in hash_set {
857 if !Config::is_hidden_option(&name) {
858 panic!("{} does not have a configuration guide", name);
865 let blocks = get_code_blocks();
866 let failures = blocks
868 .map(|b| b.formatted_is_idempotent())
869 .fold(0, |acc, r| acc + (!r as u32));
872 println!("Ran {} configurations tests.", blocks.len());
873 assert_eq!(failures, 0, "{} configurations tests failed", failures);
880 fn make_temp_file(file_name: &'static str) -> TempFile {
884 // Used in the Rust build system.
885 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
886 let path = Path::new(&target_dir).join(file_name);
888 let mut file = File::create(&path).expect("Couldn't create temp file");
889 let content = "fn main() {}\n";
890 file.write_all(content.as_bytes())
891 .expect("Couldn't write temp file");
895 impl Drop for TempFile {
897 use std::fs::remove_file;
898 remove_file(&self.path).expect("Couldn't delete temp file");
902 fn rustfmt() -> PathBuf {
903 let mut me = env::current_exe().expect("failed to get current executable");
904 me.pop(); // chop of the test name
905 me.pop(); // chop off `deps`
911 fn verify_check_works() {
912 let temp_file = make_temp_file("temp_check.rs");
913 assert_cli::Assert::command(&[
914 rustfmt().to_str().unwrap(),
916 temp_file.path.to_str().unwrap(),