-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-extern crate assert_cli;
-
use std::collections::{HashMap, HashSet};
+use std::env;
use std::fs;
-use std::io::{self, BufRead, BufReader, Read};
+use std::io::{self, BufRead, BufReader, Read, Write};
use std::iter::{Enumerate, Peekable};
+use std::mem;
use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
use std::str::Chars;
-use config::summary::Summary;
-use config::{Color, Config, ReportTactic};
-use filemap::write_system_newlines;
-use rustfmt_diff::*;
-use *;
+use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle, ReportTactic};
+use crate::formatting::{ReportedErrors, SourceFile};
+use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
+use crate::source_file;
+use crate::{FormatReport, Input, Session};
const DIFF_CONTEXT_SIZE: usize = 3;
const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
-// Returns a `Vec` containing `PathBuf`s of files with a rs extension in the
+// A list of files on which we want to skip testing.
+const SKIP_FILE_WHITE_LIST: &[&str] = &[
+ // We want to make sure that the `skip_children` is correctly working,
+ // so we do not want to test this file directly.
+ "configs/skip_children/foo/mod.rs",
+ "issue-3434/no_entry.rs",
+];
+
+fn is_file_skip(path: &Path) -> bool {
+ SKIP_FILE_WHITE_LIST
+ .iter()
+ .any(|file_path| path.ends_with(file_path))
+}
+
+// Returns a `Vec` containing `PathBuf`s of files with an `rs` extension in the
// given path. The `recursive` argument controls if files from subdirectories
// are also returned.
fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
let mut files = vec![];
if path.is_dir() {
for entry in fs::read_dir(path).expect(&format!(
- "Couldn't read directory {}",
+ "couldn't read directory {}",
path.to_str().unwrap()
)) {
- let entry = entry.expect("Couldn't get DirEntry");
+ let entry = entry.expect("couldn't get `DirEntry`");
let path = entry.path();
if path.is_dir() && recursive {
files.append(&mut get_test_files(&path, recursive));
- } else if path.extension().map_or(false, |f| f == "rs") {
+ } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
files.push(path);
}
}
fn verify_config_used(path: &Path, config_name: &str) {
for entry in fs::read_dir(path).expect(&format!(
- "Couldn't read {} directory",
+ "couldn't read {} directory",
path.to_str().unwrap()
)) {
- let entry = entry.expect("Couldn't get directory entry");
+ let entry = entry.expect("couldn't get directory entry");
let path = entry.path();
if path.extension().map_or(false, |f| f == "rs") {
// check if "// rustfmt-<config_name>:" appears in the file.
let filebuf = BufReader::new(
- fs::File::open(&path).expect(&format!("Couldn't read file {}", path.display())),
+ fs::File::open(&path).expect(&format!("couldn't read file {}", path.display())),
);
assert!(
filebuf
Path::new("tests/source/configs"),
Path::new("tests/target/configs"),
] {
- for entry in fs::read_dir(path).expect("Couldn't read configs directory") {
- let entry = entry.expect("Couldn't get directory entry");
+ for entry in fs::read_dir(path).expect("couldn't read configs directory") {
+ let entry = entry.expect("couldn't get directory entry");
let path = entry.path();
if path.is_dir() {
let config_name = path.file_name().unwrap().to_str().unwrap();
}
}
-// This writes to the terminal using the same approach (via term::stdout or
-// println!) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
+// This writes to the terminal using the same approach (via `term::stdout` or
+// `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
// using only one or the other will cause the output order to differ when
// `print_diff` selects the approach not used.
fn write_message(msg: &str) {
let mut writer = OutputWriter::new(Color::Auto);
- writer.writeln(&format!("{}", msg), None);
+ writer.writeln(msg, None);
}
-// Integration tests. The files in the tests/source are formatted and compared
-// to their equivalent in tests/target. The target file and config can be
+// Integration tests. The files in `tests/source` are formatted and compared
+// to their equivalent in `tests/target`. The target file and config can be
// overridden by annotations in the source file. The input and output must match
// exactly.
#[test]
fn system_tests() {
// Get all files in the tests/source directory.
let files = get_test_files(Path::new("tests/source"), true);
- let (_reports, count, fails) = check_files(files);
+ let (_reports, count, fails) = check_files(files, &None);
// Display results.
println!("Ran {} system tests.", count);
assert_eq!(fails, 0, "{} system tests failed", fails);
}
-// Do the same for tests/coverage-source directory
-// the only difference is the coverage mode
+// Do the same for tests/coverage-source directory.
+// The only difference is the coverage mode.
#[test]
fn coverage_tests() {
let files = get_test_files(Path::new("tests/coverage/source"), true);
- let (_reports, count, fails) = check_files(files);
+ let (_reports, count, fails) = check_files(files, &None);
println!("Ran {} tests in coverage mode.", count);
assert_eq!(fails, 0, "{} tests failed", fails);
#[test]
fn modified_test() {
+ use std::io::BufRead;
+
// Test "modified" output
let filename = "tests/writemode/source/modified.rs";
- let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap();
- assert_eq!(
- result.modified_lines,
- ModifiedLines {
- chunks: vec![
- ModifiedChunk {
- line_number_orig: 4,
- lines_removed: 4,
- lines: vec!["fn blah() {}".into()],
- },
- ModifiedChunk {
- line_number_orig: 9,
- lines_removed: 6,
- lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
- },
- ],
+ let mut data = Vec::new();
+ let mut config = Config::default();
+ config
+ .set()
+ .emit_mode(crate::config::EmitMode::ModifiedLines);
+
+ {
+ let mut session = Session::new(config, Some(&mut data));
+ session.format(Input::File(filename.into())).unwrap();
+ }
+
+ let mut lines = data.lines();
+ let mut chunks = Vec::new();
+ while let Some(Ok(header)) = lines.next() {
+ // Parse the header line
+ let values: Vec<_> = header
+ .split(' ')
+ .map(|s| s.parse::<u32>().unwrap())
+ .collect();
+ assert_eq!(values.len(), 3);
+ let line_number_orig = values[0];
+ let lines_removed = values[1];
+ let num_added = values[2];
+ let mut added_lines = Vec::new();
+ for _ in 0..num_added {
+ added_lines.push(lines.next().unwrap().unwrap());
}
+ chunks.push(ModifiedChunk {
+ line_number_orig,
+ lines_removed,
+ lines: added_lines,
+ });
+ }
+
+ assert_eq!(
+ chunks,
+ vec![
+ ModifiedChunk {
+ line_number_orig: 4,
+ lines_removed: 4,
+ lines: vec!["fn blah() {}".into()],
+ },
+ ModifiedChunk {
+ line_number_orig: 9,
+ lines_removed: 6,
+ lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
+ },
+ ],
);
}
// to a known output file generated by one of the write modes.
fn assert_output(source: &Path, expected_filename: &Path) {
let config = read_config(source);
- let (_error_summary, file_map, _report) = format_file(source, &config);
+ let (_, source_file, _) = format_file(source, config.clone());
// Populate output by writing to a vec.
let mut out = vec![];
- let _ = filemap::write_all_files(&file_map, &mut out, &config);
+ let _ = source_file::write_all_files(&source_file, &mut out, &config);
let output = String::from_utf8(out).unwrap();
- let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
+ let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
let mut expected_text = String::new();
expected_file
.read_to_string(&mut expected_text)
// rustfmt.
#[test]
fn idempotence_tests() {
+ match option_env!("CFG_RELEASE_CHANNEL") {
+ None | Some("nightly") => {}
+ _ => return, // these tests require nightly
+ }
// Get all files in the tests/target directory.
let files = get_test_files(Path::new("tests/target"), true);
- let (_reports, count, fails) = check_files(files);
+ let (_reports, count, fails) = check_files(files, &None);
// Display results.
println!("Ran {} idempotent tests.", count);
// no warnings are emitted.
#[test]
fn self_tests() {
+ match option_env!("CFG_RELEASE_CHANNEL") {
+ None | Some("nightly") => {}
+ _ => return, // Issue-3443: these tests require nightly
+ }
let mut files = get_test_files(Path::new("tests"), false);
let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
for dir in bin_directories {
}
files.push(PathBuf::from("src/lib.rs"));
- let (reports, count, fails) = check_files(files);
+ let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
let mut warnings = 0;
// Display results.
#[test]
fn stdin_formatting_smoke_test() {
let input = Input::Text("fn main () {}".to_owned());
- let config = Config::default();
- let (error_summary, file_map, _report) =
- format_input::<io::Stdout>(input, &config, None).unwrap();
- assert!(error_summary.has_no_errors());
- for &(ref file_name, ref text) in &file_map {
- if let FileName::Custom(ref file_name) = *file_name {
- if file_name == "stdin" {
- assert_eq!(text.to_string(), "fn main() {}\n");
- return;
- }
- }
+ let mut config = Config::default();
+ config.set().emit_mode(EmitMode::Stdout);
+ let mut buf: Vec<u8> = vec![];
+ {
+ let mut session = Session::new(config, Some(&mut buf));
+ session.format(input).unwrap();
+ assert!(session.has_no_errors());
+ }
+
+ #[cfg(not(windows))]
+ assert_eq!(buf, "fn main() {}\n".as_bytes());
+ #[cfg(windows)]
+ assert_eq!(buf, "fn main() {}\r\n".as_bytes());
+}
+
+#[test]
+fn stdin_parser_panic_caught() {
+ // See issue #3239.
+ for text in ["{", "}"].iter().cloned().map(String::from) {
+ let mut buf = vec![];
+ let mut session = Session::new(Default::default(), Some(&mut buf));
+ let _ = session.format(Input::Text(text));
+
+ assert!(session.has_parsing_errors());
+ }
+}
+
+/// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
+/// when embedding Rustfmt (e.g. inside RLS).
+#[test]
+fn stdin_works_with_modified_lines() {
+ let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
+ let output = "1 6 2\nfn some() {}\nfn main() {}\n";
+
+ let input = Input::Text(input.to_owned());
+ let mut config = Config::default();
+ config.set().newline_style(NewlineStyle::Unix);
+ config.set().emit_mode(EmitMode::ModifiedLines);
+ let mut buf: Vec<u8> = vec![];
+ {
+ let mut session = Session::new(config, Some(&mut buf));
+ session.format(input).unwrap();
+ let errors = ReportedErrors {
+ has_diff: true,
+ ..Default::default()
+ };
+ assert_eq!(session.errors, errors);
}
- panic!("no stdin");
-}
-
-// FIXME(#1990) restore this test
-// #[test]
-// fn stdin_disable_all_formatting_test() {
-// let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
-// let mut child = Command::new("./target/debug/rustfmt")
-// .stdin(Stdio::piped())
-// .stdout(Stdio::piped())
-// .arg("--config-path=./tests/config/disable_all_formatting.toml")
-// .spawn()
-// .expect("failed to execute child");
-
-// {
-// let stdin = child.stdin.as_mut().expect("failed to get stdin");
-// stdin
-// .write_all(input.as_bytes())
-// .expect("failed to write stdin");
-// }
-// let output = child.wait_with_output().expect("failed to wait on child");
-// assert!(output.status.success());
-// assert!(output.stderr.is_empty());
-// assert_eq!(input, String::from_utf8(output.stdout).unwrap());
-// }
+ assert_eq!(buf, output.as_bytes());
+}
+
+#[test]
+fn stdin_disable_all_formatting_test() {
+ match option_env!("CFG_RELEASE_CHANNEL") {
+ None | Some("nightly") => {}
+ // These tests require nightly.
+ _ => return,
+ }
+ let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
+ let mut child = Command::new(rustfmt().to_str().unwrap())
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .arg("--config-path=./tests/config/disable_all_formatting.toml")
+ .spawn()
+ .expect("failed to execute child");
+
+ {
+ let stdin = child.stdin.as_mut().expect("failed to get stdin");
+ stdin
+ .write_all(input.as_bytes())
+ .expect("failed to write stdin");
+ }
+
+ let output = child.wait_with_output().expect("failed to wait on child");
+ assert!(output.status.success());
+ assert!(output.stderr.is_empty());
+ assert_eq!(input, String::from_utf8(output.stdout).unwrap());
+}
#[test]
fn format_lines_errors_are_reported() {
let input = Input::Text(format!("fn {}() {{}}", long_identifier));
let mut config = Config::default();
config.set().error_on_line_overflow(true);
- let (error_summary, _file_map, _report) =
- format_input::<io::Stdout>(input, &config, None).unwrap();
- assert!(error_summary.has_formatting_errors());
+ let mut session = Session::<io::Stdout>::new(config, None);
+ session.format(input).unwrap();
+ assert!(session.has_formatting_errors());
}
#[test]
let mut config = Config::default();
config.set().error_on_line_overflow(true);
config.set().hard_tabs(true);
- let (error_summary, _file_map, _report) =
- format_input::<io::Stdout>(input, &config, None).unwrap();
- assert!(error_summary.has_formatting_errors());
+ let mut session = Session::<io::Stdout>::new(config, None);
+ session.format(input).unwrap();
+ assert!(session.has_formatting_errors());
}
// For each file, run rustfmt and collect the output.
// Returns the number of files checked and the number of failures.
-fn check_files(files: Vec<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
+fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
let mut count = 0;
let mut fails = 0;
let mut reports = vec![];
for file_name in files {
debug!("Testing '{}'...", file_name.display());
- match idempotent_check(&file_name) {
+ match idempotent_check(&file_name, &opt_config) {
Ok(ref report) if report.has_warnings() => {
print!("{}", report);
fails += 1;
fn read_config(filename: &Path) -> Config {
let sig_comments = read_significant_comments(filename);
- // Look for a config file... If there is a 'config' property in the significant comments, use
+ // Look for a config file. If there is a 'config' property in the significant comments, use
// that. Otherwise, if there are no significant comments at all, look for a config file with
// the same name as the test file.
let mut config = if !sig_comments.is_empty() {
for (key, val) in &sig_comments {
if key != "target" && key != "config" {
config.override_value(key, val);
+ if config.is_default(key) {
+ warn!("Default value {} used explicitly for {}", val, key);
+ }
}
}
config
}
-fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
+fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
let filepath = filepath.into();
let input = Input::File(filepath);
- format_input::<io::Stdout>(input, config, None).unwrap()
+ let mut session = Session::<io::Stdout>::new(config, None);
+ let result = session.format(input).unwrap();
+ let parsing_errors = session.has_parsing_errors();
+ let mut source_file = SourceFile::new();
+ mem::swap(&mut session.source_file, &mut source_file);
+ (parsing_errors, source_file, result)
}
-pub enum IdempotentCheckError {
+enum IdempotentCheckError {
Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
Parse,
}
-pub fn idempotent_check(filename: &PathBuf) -> Result<FormatReport, IdempotentCheckError> {
+fn idempotent_check(
+ filename: &PathBuf,
+ opt_config: &Option<PathBuf>,
+) -> Result<FormatReport, IdempotentCheckError> {
let sig_comments = read_significant_comments(filename);
- let config = read_config(filename);
- let (error_summary, file_map, format_report) = format_file(filename, &config);
- if error_summary.has_parsing_errors() {
+ let config = if let Some(ref config_file_path) = opt_config {
+ Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
+ } else {
+ read_config(filename)
+ };
+ let (parsing_errors, source_file, format_report) = format_file(filename, config);
+ if parsing_errors {
return Err(IdempotentCheckError::Parse);
}
let mut write_result = HashMap::new();
- for &(ref filename, ref text) in &file_map {
- let mut v = Vec::new();
- // Won't panic, as we're not doing any IO.
- write_system_newlines(&mut v, text, &config).unwrap();
- // Won't panic, we are writing correct utf8.
- let one_result = String::from_utf8(v).unwrap();
- if let FileName::Real(ref filename) = *filename {
- write_result.insert(filename.to_owned(), one_result);
+ for (filename, text) in source_file {
+ if let FileName::Real(ref filename) = filename {
+ write_result.insert(filename.to_owned(), text);
}
}
}
};
- let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
+ let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
let mut def_config = String::new();
def_config_file
.read_to_string(&mut def_config)
.expect("Couldn't read config");
- Config::from_toml(&def_config, Path::new("tests/config/")).expect("Invalid toml")
+ Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
}
-// Reads significant comments of the form: // rustfmt-key: value
-// into a hash map.
+// Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
let file =
- fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
+ fs::File::open(file_name).expect(&format!("couldn't read file {}", file_name.display()));
let reader = BufReader::new(file);
let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
- let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
+ let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
// Matches lines containing significant comments or whitespace.
let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
- .expect("Failed creating pattern 2");
+ .expect("failed creating pattern 2");
reader
.lines()
- .map(|line| line.expect("Failed getting line"))
+ .map(|line| line.expect("failed getting line"))
.take_while(|line| line_regex.is_match(line))
.filter_map(|line| {
regex.captures_iter(&line).next().map(|capture| {
(
capture
.get(1)
- .expect("Couldn't unwrap capture")
+ .expect("couldn't unwrap capture")
.as_str()
.to_owned(),
capture
.get(2)
- .expect("Couldn't unwrap capture")
+ .expect("couldn't unwrap capture")
.as_str()
.to_owned(),
)
.collect()
}
-// Compare output to input.
+// Compares output to input.
// TODO: needs a better name, more explanation.
fn handle_result(
result: HashMap<PathBuf, String>,
for (file_name, fmt_text) in result {
// If file is in tests/source, compare to file with same name in tests/target.
let target = get_target(&file_name, target);
- let open_error = format!("Couldn't open target {:?}", &target);
+ let open_error = format!("couldn't open target {:?}", &target);
let mut f = fs::File::open(&target).expect(&open_error);
let mut text = String::new();
- let read_error = format!("Failed reading target {:?}", &target);
+ let read_error = format!("failed reading target {:?}", &target);
f.read_to_string(&mut text).expect(&read_error);
// Ignore LF and CRLF difference for Windows.
}
}
-// Map source file paths to their target paths.
+// Maps source file paths to their target paths.
fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
if let Some(n) = file_name
.components()
target_file_name
}
} else {
- // This is either and idempotence check or a self check
+ // This is either and idempotence check or a self check.
file_name.to_owned()
}
}
) -> Option<ConfigurationSection> {
lazy_static! {
static ref CONFIG_NAME_REGEX: regex::Regex =
- regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
- static ref CONFIG_VALUE_REGEX: regex::Regex = regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
- .expect("Failed creating configuration value pattern");
+ regex::Regex::new(r"^## `([^`]+)`").expect("failed creating configuration pattern");
+ static ref CONFIG_VALUE_REGEX: regex::Regex =
+ regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
+ .expect("failed creating configuration value pattern");
}
loop {
Some((i, line)) => {
if line.starts_with("```rust") {
// Get the lines of the code block.
- let lines: Vec<String> = file.map(|(_i, l)| l)
+ let lines: Vec<String> = file
+ .map(|(_i, l)| l)
.take_while(|l| !l.starts_with("```"))
.collect();
let block = format!("{}\n", lines.join("\n"));
// We never expect to not have a code block.
assert!(self.code_block.is_some() && self.code_block_start.is_some());
- // See if code block begins with #![rustfmt_skip].
- let fmt_skip = self.code_block
+ // See if code block begins with #![rustfmt::skip].
+ let fmt_skip = self
+ .code_block
.as_ref()
.unwrap()
- .split('\n')
+ .lines()
.nth(0)
- .unwrap_or("") == "#![rustfmt_skip]";
+ .unwrap_or("")
+ == "#![rustfmt::skip]";
if self.config_name.is_none() && !fmt_skip {
write_message(&format!(
true
}
- fn has_parsing_errors(&self, error_summary: Summary) -> bool {
- if error_summary.has_parsing_errors() {
+ fn has_parsing_errors<T: Write>(&self, session: &Session<'_, T>) -> bool {
+ if session.has_parsing_errors() {
write_message(&format!(
"\u{261d}\u{1f3fd} Cannot format {}:{}",
CONFIGURATIONS_FILE_NAME,
});
}
- fn formatted_has_diff(&self, file_map: &FileMap) -> bool {
- let &(ref _file_name, ref text) = file_map.first().unwrap();
+ fn formatted_has_diff(&self, text: &str) -> bool {
let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
if !compare.is_empty() {
self.print_diff(compare);
}
let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
- let config = self.get_block_config();
+ let mut config = self.get_block_config();
+ config.set().emit_mode(EmitMode::Stdout);
+ let mut buf: Vec<u8> = vec![];
- let (error_summary, file_map, _report) =
- format_input::<io::Stdout>(input, &config, None).unwrap();
+ {
+ let mut session = Session::new(config, Some(&mut buf));
+ session.format(input).unwrap();
+ if self.has_parsing_errors(&session) {
+ return false;
+ }
+ }
- !self.has_parsing_errors(error_summary) && !self.formatted_has_diff(&file_map)
+ !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
}
// Extract a code block from the iterator. Behavior:
// - Rust code blocks are identifed by lines beginning with "```rust".
// - One explicit configuration setting is supported per code block.
// - Rust code blocks with no configuration setting are illegal and cause an
- // assertion failure, unless the snippet begins with #![rustfmt_skip].
+ // assertion failure, unless the snippet begins with #![rustfmt::skip].
// - Configuration names in Configurations.md must be in the form of
// "## `NAME`".
// - Configuration values in Configurations.md must be in the form of
fn get_code_blocks() -> Vec<ConfigCodeBlock> {
let mut file_iter = BufReader::new(
fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
- .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
- ).lines()
- .map(|l| l.unwrap())
- .enumerate();
+ .expect(&format!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
+ )
+ .lines()
+ .map(|l| l.unwrap())
+ .enumerate();
let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
let mut hash_set = Config::hash_set();
use std::env::var;
use std::fs::File;
- let target_dir = var("CARGO_TARGET_DIR").unwrap_or_else(|_| ".".to_owned());
+ // Used in the Rust build system.
+ let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
let path = Path::new(&target_dir).join(file_name);
- let mut file = File::create(&path).expect("Couldn't create temp file");
+ let mut file = File::create(&path).expect("couldn't create temp file");
let content = "fn main() {}\n";
file.write_all(content.as_bytes())
- .expect("Couldn't write temp file");
+ .expect("couldn't write temp file");
TempFile { path }
}
impl Drop for TempFile {
fn drop(&mut self) {
use std::fs::remove_file;
- remove_file(&self.path).expect("Couldn't delete temp file");
+ remove_file(&self.path).expect("couldn't delete temp file");
}
}
+fn rustfmt() -> PathBuf {
+ let mut me = env::current_exe().expect("failed to get current executable");
+ // Chop of the test name.
+ me.pop();
+ // Chop off `deps`.
+ me.pop();
+
+ // If we run `cargo test --release`, we might only have a release build.
+ if cfg!(release) {
+ // `../release/`
+ me.pop();
+ me.push("release");
+ }
+ me.push("rustfmt");
+ assert!(
+ me.is_file() || me.with_extension("exe").is_file(),
+ if cfg!(release) {
+ "no rustfmt bin, try running `cargo build --release` before testing"
+ } else {
+ "no rustfmt bin, try running `cargo build` before testing"
+ }
+ );
+ me
+}
+
#[test]
fn verify_check_works() {
let temp_file = make_temp_file("temp_check.rs");
- assert_cli::Assert::command(&[
- "cargo",
- "run",
- "--bin=rustfmt",
- "--",
- "--write-mode=check",
- temp_file.path.to_str().unwrap(),
- ]).succeeds()
- .unwrap();
-}
-#[test]
-fn verify_diff_works() {
- let temp_file = make_temp_file("temp_diff.rs");
- assert_cli::Assert::command(&[
- "cargo",
- "run",
- "--bin=rustfmt",
- "--",
- "--write-mode=diff",
- temp_file.path.to_str().unwrap(),
- ]).succeeds()
- .unwrap();
+ Command::new(rustfmt().to_str().unwrap())
+ .arg("--check")
+ .arg(temp_file.path.to_str().unwrap())
+ .status()
+ .expect("run with check option failed");
}