Skip to content
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

Fix using --help, --verbose, etc. #3620

Merged
merged 1 commit into from
Jul 14, 2019
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
22 changes: 11 additions & 11 deletions src/cargo-fmt/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,14 @@ fn execute() -> i32 {
};

if opts.version {
return handle_command_status(get_version());
return handle_command_status(get_rustfmt_info(&[String::from("--version")]));
}
if opts.rustfmt_options.iter().any(|s| {
["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str())
|| s.starts_with("--help=")
|| s.starts_with("--print-config=")
}) {
return handle_command_status(get_rustfmt_info(&opts.rustfmt_options));
}

let strategy = CargoFmtStrategy::from_opts(&opts);
Expand Down Expand Up @@ -118,10 +125,10 @@ fn handle_command_status(status: Result<i32, io::Error>) -> i32 {
}
}

fn get_version() -> Result<i32, io::Error> {
fn get_rustfmt_info(args: &[String]) -> Result<i32, io::Error> {
let mut command = Command::new("rustfmt")
.stdout(std::process::Stdio::inherit())
.args(&[String::from("--version")])
.args(args)
.spawn()
.map_err(|e| match e.kind() {
io::ErrorKind::NotFound => io::Error::new(
Expand All @@ -143,14 +150,7 @@ fn format_crate(
strategy: &CargoFmtStrategy,
rustfmt_args: Vec<String>,
) -> Result<i32, io::Error> {
let targets = if rustfmt_args
.iter()
.any(|s| ["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str()))
{
BTreeSet::new()
} else {
get_targets(strategy)?
};
let targets = get_targets(strategy)?;

// Currently only bin and lib files get formatted.
run_rustfmt(&targets, &rustfmt_args, verbosity)
Expand Down
70 changes: 70 additions & 0 deletions tests/cargo-fmt/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Integration tests for cargo-fmt.

use std::env;
use std::process::Command;

/// Run the cargo-fmt executable and return its output.
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you add comment that the tuple corresponds to (stdout, stderr) of the execution ?

fn cargo_fmt(args: &[&str]) -> (String, String) {
let mut bin_dir = env::current_exe().unwrap();
bin_dir.pop(); // chop off test exe name
if bin_dir.ends_with("deps") {
bin_dir.pop();
}
let cmd = bin_dir.join(format!("cargo-fmt{}", env::consts::EXE_SUFFIX));

// Ensure cargo-fmt runs the rustfmt binary from the local target dir.
let path = env::var_os("PATH").unwrap_or_default();
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
paths.insert(0, bin_dir);
let new_path = env::join_paths(paths).unwrap();

match Command::new(&cmd).args(args).env("PATH", new_path).output() {
Ok(output) => (
String::from_utf8(output.stdout).expect("utf-8"),
String::from_utf8(output.stderr).expect("utf-8"),
),
Err(e) => panic!("failed to run `{:?} {:?}`: {}", cmd, args, e),
}
}

macro_rules! assert_that {
($args:expr, $check:ident $check_args:tt) => {
let (stdout, stderr) = cargo_fmt($args);
if !stdout.$check$check_args {
panic!(
"Output not expected for cargo-fmt {:?}\n\
expected: {}{}\n\
actual stdout:\n{}\n\
actual stderr:\n{}",
$args,
stringify!($check),
stringify!($check_args),
stdout,
stderr
);
}
};
}

#[test]
fn version() {
assert_that!(&["--version"], starts_with("rustfmt "));
assert_that!(&["--version"], starts_with("rustfmt "));
assert_that!(&["--", "-V"], starts_with("rustfmt "));
assert_that!(&["--", "--version"], starts_with("rustfmt "));
}

#[test]
fn print_config() {
assert_that!(
&["--", "--print-config", "current", "."],
contains("max_width = ")
);
}

#[test]
fn rustfmt_help() {
assert_that!(&["--", "--help"], contains("Format Rust code"));
assert_that!(&["--", "-h"], contains("Format Rust code"));
assert_that!(&["--", "--help=config"], contains("Configuration Options:"));
}