Skip to content

fix self_tests #4033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions rustfmt-core/rustfmt-bin/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,13 @@ fn main() {
// (git not installed or if this is not a git repository) just return an empty string.
fn commit_info() -> String {
match (channel(), commit_hash(), commit_date()) {
(channel, Some(hash), Some(date)) => {
format!("{}-{} ({} {})", option_env!("CARGO_PKG_VERSION")
.unwrap_or("unknown"), channel, hash.trim_end(), date)
},
(channel, Some(hash), Some(date)) => format!(
"{}-{} ({} {})",
option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
channel,
hash.trim_end(),
date
),
_ => String::new(),
}
}
Expand Down
65 changes: 33 additions & 32 deletions rustfmt-core/rustfmt-bin/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ extern crate lazy_static;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::io::{self, stdout, Error as IoError, Read, Write, stdin};
use std::io::{self, stdin, stdout, Error as IoError, Read, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;

Expand Down Expand Up @@ -41,7 +41,7 @@ fn main() {

/// Format Rust code
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "rustfmt", version = include_str!(concat!(env!("OUT_DIR"), "/version-info.txt")))]
#[structopt(name = "rustfmt", version = include_str!(concat!(env!("OUT_DIR"),"/version-info.txt")))]
struct Opt {
/// Run in 'check' mode.
///
Expand All @@ -50,8 +50,8 @@ struct Opt {
#[structopt(short, long)]
check: bool,
/// Specify the format of rustfmt's output.
#[cfg_attr(nightly, structopt(long, name= "files|stdout|checkstyle|json"))]
#[cfg_attr(not(nightly), structopt(long, name= "files|stdout"))]
#[cfg_attr(nightly, structopt(long, name = "files|stdout|checkstyle|json"))]
#[cfg_attr(not(nightly), structopt(long, name = "files|stdout"))]
emit: Option<Emit>,
/// A path to the configuration file.
#[structopt(long = "config-path", parse(from_os_str))]
Expand Down Expand Up @@ -92,7 +92,6 @@ struct Opt {
verbose: bool,

// Nightly-only options.

Copy link
Member

@calebcartwright calebcartwright Jan 30, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be nice to keep the intent of this comment (and the Positional args on line 125/126 below) separate so they don't seem to be pinned to a specific opt?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now rustfmt removes the newline in this case.
So if I insert newline here, self_tests is failed...
I think this is the rustfmt bug.
maybe related: #4012

/// Limit formatting to specified ranges.
///
/// If you want to restrict reformatting to specific sets of lines, you can
Expand Down Expand Up @@ -124,7 +123,6 @@ struct Opt {
error_on_unformatted: bool,

// Positional arguments.

#[structopt(parse(from_os_str))]
files: Vec<PathBuf>,
}
Expand All @@ -148,22 +146,23 @@ impl FromStr for InlineConfig {

s.split(',')
.map(
|key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') {
Some((middle, _)) => {
let (key, val) = (&key_val[..middle], &key_val[middle + 1..]);
if !Config::is_valid_key_val(key, val) {
Err(format_err!("invalid key=val pair: `{}`", key_val))
} else {
Ok((key.to_string(), val.to_string()))
|key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') {
Some((middle, _)) => {
let (key, val) = (&key_val[..middle], &key_val[middle + 1..]);
if !Config::is_valid_key_val(key, val) {
Err(format_err!("invalid key=val pair: `{}`", key_val))
} else {
Ok((key.to_string(), val.to_string()))
}
}
}

None => Err(format_err!(
None => Err(format_err!(
"--config expects comma-separated list of key=val pairs, found `{}`",
key_val
)),
},
).collect::<Result<HashMap<_, _>, _>>()
},
)
.collect::<Result<HashMap<_, _>, _>>()
.map(|map| InlineConfig(map, false))
}
}
Expand All @@ -183,7 +182,10 @@ impl FromStr for PrintConfig {
"default" => Ok(PrintConfig::Default),
"minimal" => Ok(PrintConfig::Minimal),
"current" => Ok(PrintConfig::Current),
_ => Err(format!("expected one of [current,default,minimal], found `{}`", s)),
_ => Err(format!(
"expected one of [current,default,minimal], found `{}`",
s
)),
}
}
}
Expand Down Expand Up @@ -280,7 +282,6 @@ impl Opt {
}
}


/// Rustfmt operations errors.
#[derive(Error, Debug)]
pub enum OperationError {
Expand Down Expand Up @@ -347,7 +348,9 @@ impl CliOptions for Opt {
fn execute(mut opt: Opt) -> Result<i32> {
opt.verify()?;

if opt.inline_config.as_ref().map_or(false, |inline_configs| inline_configs.iter().any(InlineConfig::is_help)) {
if opt.inline_config.as_ref().map_or(false, |inline_configs| {
inline_configs.iter().any(InlineConfig::is_help)
}) {
Config::print_docs(&mut stdout(), cfg!(nightly));
return Ok(0);
}
Expand All @@ -369,10 +372,12 @@ fn print_default_config() -> Result<i32> {
}

fn print_config(opt: &Opt, print_config: PrintConfig) -> Result<i32> {
let (config, config_path) =
load_config(env::current_dir().ok().as_ref().map(PathBuf::as_path), Some(opt))?;
let actual_config = FileConfigPairIter::new(&opt, config_path.is_some())
.find_map(|pair| match pair.config {
let (config, config_path) = load_config(
env::current_dir().ok().as_ref().map(PathBuf::as_path),
Some(opt),
)?;
let actual_config =
FileConfigPairIter::new(&opt, config_path.is_some()).find_map(|pair| match pair.config {
FileConfig::Local(config, Some(_)) => Some(config),
_ => None,
});
Expand Down Expand Up @@ -436,8 +441,7 @@ struct FileConfigPairIter<'a> {
opt: &'a Opt,
}

impl<'a> FileConfigPairIter<'a>
{
impl<'a> FileConfigPairIter<'a> {
fn new(opt: &'a Opt, has_config_from_commandline: bool) -> Self {
FileConfigPairIter {
has_config_from_commandline,
Expand All @@ -447,8 +451,7 @@ impl<'a> FileConfigPairIter<'a>
}
}

impl<'a> Iterator for FileConfigPairIter<'a>
{
impl<'a> Iterator for FileConfigPairIter<'a> {
type Item = FileConfigPair<'a>;

fn next(&mut self) -> Option<Self::Item> {
Expand All @@ -461,13 +464,11 @@ impl<'a> Iterator for FileConfigPairIter<'a>
FileConfig::Local(local_config, config_path)
};

Some(FileConfigPair {file, config})
Some(FileConfigPair { file, config })
}
}

fn format(
opt: Opt,
) -> Result<i32> {
fn format(opt: Opt) -> Result<i32> {
if opt.files.is_empty() {
let mut buf = String::new();
stdin().read_to_string(&mut buf)?;
Expand Down
1 change: 0 additions & 1 deletion rustfmt-core/rustfmt-config/src/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,4 +340,3 @@ macro_rules! is_nightly_channel {
option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev")
};
}

5 changes: 4 additions & 1 deletion rustfmt-core/rustfmt-config/src/file_lines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,10 @@ impl FileLines {
Some(ref map) => map,
};

match canonicalize_path_string(file_name).ok().and_then(|file| map.get(&file)) {
match canonicalize_path_string(file_name)
.ok()
.and_then(|file| map.get(&file))
{
Some(ranges) => ranges.iter().any(f),
None => false,
}
Expand Down
5 changes: 1 addition & 4 deletions rustfmt-core/rustfmt-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,10 +428,7 @@ mod test {

let used_options = config.used_options();
let toml = used_options.to_toml().unwrap();
assert_eq!(
toml,
"merge_derives = false\n"
);
assert_eq!(toml, "merge_derives = false\n");
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion rustfmt-core/rustfmt-emitter/src/diff.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use rustfmt_configuration::Config;

use crate::rustfmt_diff::{make_diff, print_diff};
use super::*;
use crate::rustfmt_diff::{make_diff, print_diff};

pub struct DiffEmitter {
config: Config,
Expand Down
1 change: 0 additions & 1 deletion rustfmt-core/rustfmt-emitter/src/rustfmt_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,5 +424,4 @@ mod test {
let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
assert_eq!(diff, vec![]);
}

}
4 changes: 2 additions & 2 deletions rustfmt-core/rustfmt-lib/src/closures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,8 +415,8 @@ fn is_block_closure_forced(
false
} else {
if let ast::ExprKind::Match(..) = expr.kind {
let is_move_closure_without_brace =
capture == ast::CaptureBy::Value && !context.snippet(expr.span).trim().starts_with("{");
let is_move_closure_without_brace = capture == ast::CaptureBy::Value
&& !context.snippet(expr.span).trim().starts_with("{");

is_block_closure_forced_inner(expr) || is_move_closure_without_brace
} else {
Expand Down
4 changes: 1 addition & 3 deletions rustfmt-core/rustfmt-lib/src/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,5 @@ fn format_stmt(
}
ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
};
result.and_then(|res| {
recover_comment_removed(res, stmt.span(), context)
})
result.and_then(|res| recover_comment_removed(res, stmt.span(), context))
}
2 changes: 1 addition & 1 deletion rustfmt-core/rustfmt-lib/src/test/configuration_snippet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use std::path::{Path, PathBuf};

use rustfmt_emitter::rustfmt_diff::{make_diff, Mismatch};

use super::{print_mismatches, write_message, DIFF_CONTEXT_SIZE};
use crate::config::{Config, EmitMode, Verbosity};
use crate::{Input, Session};
use super::{print_mismatches, write_message, DIFF_CONTEXT_SIZE};

const CONFIGURATIONS_FILE_NAME: &str = "../../Configurations.md";

Expand Down
31 changes: 17 additions & 14 deletions rustfmt-core/rustfmt-lib/src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ use std::path::{Path, PathBuf};
use std::str::Chars;
use std::thread;

use rustfmt_emitter::rustfmt_diff::{
make_diff, print_diff, Mismatch, ModifiedChunk, OutputWriter,
};
use rustfmt_emitter::rustfmt_diff::{make_diff, print_diff, Mismatch, ModifiedChunk, OutputWriter};

use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle, ReportTactic};
use crate::formatting::{ReportedErrors, SourceFile};
Expand Down Expand Up @@ -87,16 +85,16 @@ where
.any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
}

fn is_file_skip(path: &Path) -> bool {
SKIP_FILE_WHITE_LIST
fn is_file_skip(skip_file_white_list: &[&str], path: &Path) -> bool {
skip_file_white_list
.iter()
.any(|file_path| is_subpath(path, 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> {
fn get_test_files(path: &Path, recursive: bool, skip_file_white_list: &[&str]) -> Vec<PathBuf> {
let mut files = vec![];
if path.is_dir() {
for entry in fs::read_dir(path)
Expand All @@ -105,8 +103,10 @@ fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
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") && !is_file_skip(&path) {
files.append(&mut get_test_files(&path, recursive, skip_file_white_list));
} else if path.extension().map_or(false, |f| f == "rs")
&& !is_file_skip(skip_file_white_list, &path)
{
files.push(path);
}
}
Expand Down Expand Up @@ -179,7 +179,7 @@ fn system_tests() {
init_log();
run_test_with(&TestSetting::default(), || {
// Get all files in the tests/source directory.
let files = get_test_files(Path::new("tests/source"), true);
let files = get_test_files(Path::new("tests/source"), true, SKIP_FILE_WHITE_LIST);
let (_reports, count, fails) = check_files(files, &None);

// Display results.
Expand All @@ -198,7 +198,11 @@ fn system_tests() {
#[test]
fn coverage_tests() {
init_log();
let files = get_test_files(Path::new("tests/coverage/source"), true);
let files = get_test_files(
Path::new("tests/coverage/source"),
true,
SKIP_FILE_WHITE_LIST,
);
let (_reports, count, fails) = check_files(files, &None);

println!("Ran {} tests in coverage mode.", count);
Expand Down Expand Up @@ -362,7 +366,7 @@ fn idempotence_tests() {
return;
}
// Get all files in the tests/target directory.
let files = get_test_files(Path::new("tests/target"), true);
let files = get_test_files(Path::new("tests/target"), true, SKIP_FILE_WHITE_LIST);
let (_reports, count, fails) = check_files(files, &None);

// Display results.
Expand All @@ -385,8 +389,8 @@ fn self_tests() {
if !is_nightly_channel!() {
return;
}
let mut files = get_test_files(Path::new("tests"), false);
files.push(PathBuf::from("src/lib.rs"));
let skip_file_white_list = ["target", "tests"];
let files = get_test_files(Path::new("../../rustfmt-core"), true, &skip_file_white_list);

let (reports, count, fails) = check_files(files, &Some(PathBuf::from("../../rustfmt.toml")));
let mut warnings = 0;
Expand Down Expand Up @@ -809,4 +813,3 @@ fn string_eq_ignore_newline_repr_test() {
assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
}