From 6aaed5b08f54ed95b692d40733a551d925363319 Mon Sep 17 00:00:00 2001 From: David Alber Date: Wed, 20 Dec 2017 21:48:59 -0800 Subject: [PATCH] Adding --version option to cargo-fmt --- src/bin/cargo-fmt.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/bin/cargo-fmt.rs b/src/bin/cargo-fmt.rs index 3916b52fe5f..15d0bbe950c 100644 --- a/src/bin/cargo-fmt.rs +++ b/src/bin/cargo-fmt.rs @@ -49,6 +49,7 @@ fn execute() -> i32 { "specify package to format (only usable in workspaces)", "", ); + opts.optflag("", "version", "print rustfmt version and exit"); opts.optflag("", "all", "format all packages (only usable in workspaces)"); // If there is any invalid argument passed to `cargo fmt`, return without formatting. @@ -87,6 +88,10 @@ fn execute() -> i32 { return success; } + if matches.opt_present("version") { + return handle_command_status(get_version(), &opts); + } + let strategy = CargoFmtStrategy::from_matches(&matches); match format_crate(verbosity, &strategy) { @@ -130,6 +135,40 @@ pub enum Verbosity { Quiet, } +fn handle_command_status(status: Result, opts: &getopts::Options) -> i32 { + let success = 0; + let failure = 1; + + match status { + Err(e) => { + print_usage_to_stderr(&opts, &e.to_string()); + failure + } + Ok(status) => { + if status.success() { + success + } else { + status.code().unwrap_or(failure) + } + } + } +} + +fn get_version() -> Result { + let mut command = Command::new("rustfmt") + .args(vec!["--version"]) + .spawn() + .map_err(|e| match e.kind() { + io::ErrorKind::NotFound => io::Error::new( + io::ErrorKind::Other, + "Could not run rustfmt, please make sure it is in your PATH.", + ), + _ => e, + })?; + + command.wait() +} + fn format_crate( verbosity: Verbosity, strategy: &CargoFmtStrategy,