1 // Inspired by Paul Woolcock's cargo-fmt (https://github.com/pwoolcoc/cargo-fmt/).
7 use std::cmp::Ordering;
8 use std::collections::{BTreeMap, BTreeSet};
12 use std::hash::{Hash, Hasher};
13 use std::io::{self, Write};
14 use std::iter::FromIterator;
15 use std::path::{Path, PathBuf};
16 use std::process::Command;
19 use structopt::StructOpt;
21 #[derive(StructOpt, Debug)]
23 bin_name = "cargo fmt",
24 about = "This utility formats all bin and lib files of \
25 the current crate using rustfmt."
28 /// No output printed to stdout
29 #[structopt(short = "q", long = "quiet")]
32 /// Use verbose output
33 #[structopt(short = "v", long = "verbose")]
36 /// Print rustfmt version and exit
37 #[structopt(long = "version")]
40 /// Specify package to format (only usable in workspaces)
41 #[structopt(short = "p", long = "package", value_name = "package")]
42 packages: Vec<String>,
44 /// Specify path to Cargo.toml
45 #[structopt(long = "manifest-path", value_name = "manifest-path")]
46 manifest_path: Option<String>,
48 /// Specify message-format: short|json|human
49 #[structopt(long = "message-format", value_name = "message-format")]
50 message_format: Option<String>,
52 /// Options passed to rustfmt
53 // 'raw = true' to make `--` explicit.
54 #[structopt(name = "rustfmt_options", raw(true))]
55 rustfmt_options: Vec<String>,
57 /// Format all packages (only usable in workspaces)
58 #[structopt(long = "all")]
63 let exit_status = execute();
64 std::io::stdout().flush().unwrap();
65 std::process::exit(exit_status);
68 const SUCCESS: i32 = 0;
69 const FAILURE: i32 = 1;
72 // Drop extra `fmt` argument provided by `cargo`.
73 let mut found_fmt = false;
74 let args = env::args().filter(|x| {
78 found_fmt = x == "fmt";
83 let opts = Opts::from_iter(args);
85 let verbosity = match (opts.verbose, opts.quiet) {
86 (false, false) => Verbosity::Normal,
87 (false, true) => Verbosity::Quiet,
88 (true, false) => Verbosity::Verbose,
90 print_usage_to_stderr("quiet mode and verbose mode are not compatible");
96 return handle_command_status(get_rustfmt_info(&[String::from("--version")]));
98 if opts.rustfmt_options.iter().any(|s| {
99 ["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str())
100 || s.starts_with("--help=")
101 || s.starts_with("--print-config=")
103 return handle_command_status(get_rustfmt_info(&opts.rustfmt_options));
106 let strategy = CargoFmtStrategy::from_opts(&opts);
107 let mut rustfmt_args = opts.rustfmt_options;
108 if let Some(message_format) = opts.message_format {
109 if let Err(msg) = convert_message_format_to_rustfmt_args(&message_format, &mut rustfmt_args)
111 print_usage_to_stderr(&msg);
116 if let Some(specified_manifest_path) = opts.manifest_path {
117 if !specified_manifest_path.ends_with("Cargo.toml") {
118 print_usage_to_stderr("the manifest-path must be a path to a Cargo.toml file");
121 let manifest_path = PathBuf::from(specified_manifest_path);
122 handle_command_status(format_crate(
126 Some(&manifest_path),
129 handle_command_status(format_crate(verbosity, &strategy, rustfmt_args, None))
133 fn rustfmt_command() -> Command {
134 let rustfmt_var = env::var_os("RUSTFMT");
135 let rustfmt = match &rustfmt_var {
136 Some(rustfmt) => rustfmt,
137 None => OsStr::new("rustfmt"),
139 Command::new(rustfmt)
142 fn convert_message_format_to_rustfmt_args(
143 message_format: &str,
144 rustfmt_args: &mut Vec<String>,
145 ) -> Result<(), String> {
146 let mut contains_emit_mode = false;
147 let mut contains_check = false;
148 let mut contains_list_files = false;
149 for arg in rustfmt_args.iter() {
150 if arg.starts_with("--emit") {
151 contains_emit_mode = true;
153 if arg == "--check" {
154 contains_check = true;
156 if arg == "-l" || arg == "--files-with-diff" {
157 contains_list_files = true;
160 match message_format {
162 if !contains_list_files {
163 rustfmt_args.push(String::from("-l"));
168 if contains_emit_mode {
169 return Err(String::from(
170 "cannot include --emit arg when --message-format is set to json",
174 return Err(String::from(
175 "cannot include --check arg when --message-format is set to json",
178 rustfmt_args.push(String::from("--emit"));
179 rustfmt_args.push(String::from("json"));
185 "invalid --message-format value: {}. Allowed values are: short|json|human",
192 fn print_usage_to_stderr(reason: &str) {
193 eprintln!("{}", reason);
194 let app = Opts::clap();
196 .write_help(&mut io::stderr())
197 .expect("failed to write to stderr");
200 #[derive(Debug, Clone, Copy, PartialEq)]
207 fn handle_command_status(status: Result<i32, io::Error>) -> i32 {
210 print_usage_to_stderr(&e.to_string());
213 Ok(status) => status,
217 fn get_rustfmt_info(args: &[String]) -> Result<i32, io::Error> {
218 let mut command = rustfmt_command()
219 .stdout(std::process::Stdio::inherit())
222 .map_err(|e| match e.kind() {
223 io::ErrorKind::NotFound => io::Error::new(
224 io::ErrorKind::Other,
225 "Could not run rustfmt, please make sure it is in your PATH.",
229 let result = command.wait()?;
230 if result.success() {
233 Ok(result.code().unwrap_or(SUCCESS))
238 verbosity: Verbosity,
239 strategy: &CargoFmtStrategy,
240 rustfmt_args: Vec<String>,
241 manifest_path: Option<&Path>,
242 ) -> Result<i32, io::Error> {
243 let targets = get_targets(strategy, manifest_path)?;
245 // Currently only bin and lib files get formatted.
246 run_rustfmt(&targets, &rustfmt_args, verbosity)
249 /// Target uses a `path` field for equality and hashing.
252 /// A path to the main source file of the target.
254 /// A kind of target (e.g., lib, bin, example, ...).
256 /// Rust edition for this target.
261 pub fn from_target(target: &cargo_metadata::Target) -> Self {
262 let path = PathBuf::from(&target.src_path);
263 let canonicalized = fs::canonicalize(&path).unwrap_or(path);
267 kind: target.kind[0].clone(),
268 edition: target.edition.clone(),
273 impl PartialEq for Target {
274 fn eq(&self, other: &Target) -> bool {
275 self.path == other.path
279 impl PartialOrd for Target {
280 fn partial_cmp(&self, other: &Target) -> Option<Ordering> {
281 Some(self.path.cmp(&other.path))
285 impl Ord for Target {
286 fn cmp(&self, other: &Target) -> Ordering {
287 self.path.cmp(&other.path)
291 impl Eq for Target {}
293 impl Hash for Target {
294 fn hash<H: Hasher>(&self, state: &mut H) {
295 self.path.hash(state);
299 #[derive(Debug, PartialEq, Eq)]
300 pub enum CargoFmtStrategy {
301 /// Format every packages and dependencies.
303 /// Format packages that are specified by the command line argument.
305 /// Format the root packages only.
309 impl CargoFmtStrategy {
310 pub fn from_opts(opts: &Opts) -> CargoFmtStrategy {
311 match (opts.format_all, opts.packages.is_empty()) {
312 (false, true) => CargoFmtStrategy::Root,
313 (true, _) => CargoFmtStrategy::All,
314 (false, false) => CargoFmtStrategy::Some(opts.packages.clone()),
319 /// Based on the specified `CargoFmtStrategy`, returns a set of main source files.
321 strategy: &CargoFmtStrategy,
322 manifest_path: Option<&Path>,
323 ) -> Result<BTreeSet<Target>, io::Error> {
324 let mut targets = BTreeSet::new();
327 CargoFmtStrategy::Root => get_targets_root_only(manifest_path, &mut targets)?,
328 CargoFmtStrategy::All => {
329 get_targets_recursive(manifest_path, &mut targets, &mut BTreeSet::new())?
331 CargoFmtStrategy::Some(ref hitlist) => {
332 get_targets_with_hitlist(manifest_path, hitlist, &mut targets)?
336 if targets.is_empty() {
338 io::ErrorKind::Other,
339 "Failed to find targets".to_owned(),
346 fn get_targets_root_only(
347 manifest_path: Option<&Path>,
348 targets: &mut BTreeSet<Target>,
349 ) -> Result<(), io::Error> {
350 let metadata = get_cargo_metadata(manifest_path, false)?;
351 let workspace_root_path = PathBuf::from(&metadata.workspace_root).canonicalize()?;
352 let (in_workspace_root, current_dir_manifest) = if let Some(target_manifest) = manifest_path {
354 workspace_root_path == target_manifest,
355 target_manifest.canonicalize()?,
358 let current_dir = env::current_dir()?.canonicalize()?;
360 workspace_root_path == current_dir,
361 current_dir.join("Cargo.toml"),
365 let package_targets = match metadata.packages.len() {
366 1 => metadata.packages.into_iter().next().unwrap().targets,
372 || PathBuf::from(&p.manifest_path)
375 == current_dir_manifest
382 for target in package_targets {
383 targets.insert(Target::from_target(&target));
389 fn get_targets_recursive(
390 manifest_path: Option<&Path>,
391 mut targets: &mut BTreeSet<Target>,
392 visited: &mut BTreeSet<String>,
393 ) -> Result<(), io::Error> {
394 let metadata = get_cargo_metadata(manifest_path, false)?;
395 let metadata_with_deps = get_cargo_metadata(manifest_path, true)?;
397 for package in metadata.packages {
398 add_targets(&package.targets, &mut targets);
400 // Look for local dependencies.
401 for dependency in package.dependencies {
402 if dependency.source.is_some() || visited.contains(&dependency.name) {
406 let dependency_package = metadata_with_deps
409 .find(|p| p.name == dependency.name && p.source.is_none());
410 let manifest_path = if dependency_package.is_some() {
411 PathBuf::from(&dependency_package.unwrap().manifest_path)
413 let mut package_manifest_path = PathBuf::from(&package.manifest_path);
414 package_manifest_path.pop();
415 package_manifest_path.push(&dependency.name);
416 package_manifest_path.push("Cargo.toml");
417 package_manifest_path
420 if manifest_path.exists() {
421 visited.insert(dependency.name);
422 get_targets_recursive(Some(&manifest_path), &mut targets, visited)?;
430 fn get_targets_with_hitlist(
431 manifest_path: Option<&Path>,
433 targets: &mut BTreeSet<Target>,
434 ) -> Result<(), io::Error> {
435 let metadata = get_cargo_metadata(manifest_path, false)?;
437 let mut workspace_hitlist: BTreeSet<&String> = BTreeSet::from_iter(hitlist);
439 for package in metadata.packages {
440 if workspace_hitlist.remove(&package.name) {
441 for target in package.targets {
442 targets.insert(Target::from_target(&target));
447 if workspace_hitlist.is_empty() {
450 let package = workspace_hitlist.iter().next().unwrap();
452 io::ErrorKind::InvalidInput,
453 format!("package `{}` is not a member of the workspace", package),
458 fn add_targets(target_paths: &[cargo_metadata::Target], targets: &mut BTreeSet<Target>) {
459 for target in target_paths {
460 targets.insert(Target::from_target(target));
465 targets: &BTreeSet<Target>,
467 verbosity: Verbosity,
468 ) -> Result<i32, io::Error> {
469 let by_edition = targets
472 if verbosity == Verbosity::Verbose {
473 println!("[{} ({})] {:?}", t.kind, t.edition, t.path)
476 .fold(BTreeMap::new(), |mut h, t| {
477 h.entry(&t.edition).or_insert_with(Vec::new).push(&t.path);
481 let mut status = vec![];
482 for (edition, files) in by_edition {
483 let stdout = if verbosity == Verbosity::Quiet {
484 std::process::Stdio::null()
486 std::process::Stdio::inherit()
489 if verbosity == Verbosity::Verbose {
491 print!(" --edition {}", edition);
492 fmt_args.iter().for_each(|f| print!(" {}", f));
493 files.iter().for_each(|f| print!(" {}", f.display()));
497 let mut command = rustfmt_command()
500 .args(&["--edition", edition])
503 .map_err(|e| match e.kind() {
504 io::ErrorKind::NotFound => io::Error::new(
505 io::ErrorKind::Other,
506 "Could not run rustfmt, please make sure it is in your PATH.",
511 status.push(command.wait()?);
516 .filter_map(|s| if s.success() { None } else { s.code() })
521 fn get_cargo_metadata(
522 manifest_path: Option<&Path>,
524 ) -> Result<cargo_metadata::Metadata, io::Error> {
525 let mut cmd = cargo_metadata::MetadataCommand::new();
529 if let Some(manifest_path) = manifest_path {
530 cmd.manifest_path(manifest_path);
532 cmd.other_options(&[String::from("--offline")]);
535 Ok(metadata) => Ok(metadata),
537 cmd.other_options(vec![]);
539 Ok(metadata) => Ok(metadata),
540 Err(error) => Err(io::Error::new(io::ErrorKind::Other, error.to_string())),
547 mod cargo_fmt_tests {
551 fn default_options() {
552 let empty: Vec<String> = vec![];
553 let o = Opts::from_iter(&empty);
554 assert_eq!(false, o.quiet);
555 assert_eq!(false, o.verbose);
556 assert_eq!(false, o.version);
557 assert_eq!(empty, o.packages);
558 assert_eq!(empty, o.rustfmt_options);
559 assert_eq!(false, o.format_all);
560 assert_eq!(None, o.manifest_path);
561 assert_eq!(None, o.message_format);
566 let o = Opts::from_iter(&[
579 assert_eq!(true, o.quiet);
580 assert_eq!(false, o.verbose);
581 assert_eq!(false, o.version);
582 assert_eq!(vec!["p1", "p2"], o.packages);
583 assert_eq!(vec!["--edition", "2018"], o.rustfmt_options);
584 assert_eq!(false, o.format_all);
585 assert_eq!(Some(String::from("short")), o.message_format);
589 fn unexpected_option() {
592 .get_matches_from_safe(&["test", "unexpected"])
598 fn unexpected_flag() {
601 .get_matches_from_safe(&["test", "--flag"])
607 fn mandatory_separator() {
610 .get_matches_from_safe(&["test", "--check"])
615 .get_matches_from_safe(&["test", "--", "--check"])
621 fn multiple_packages_one_by_one() {
622 let o = Opts::from_iter(&[
631 assert_eq!(3, o.packages.len());
635 fn multiple_packages_grouped() {
636 let o = Opts::from_iter(&[
645 assert_eq!(4, o.packages.len());
649 fn empty_packages_1() {
650 assert!(Opts::clap().get_matches_from_safe(&["test", "-p"]).is_err());
654 fn empty_packages_2() {
657 .get_matches_from_safe(&["test", "-p", "--", "--check"])
663 fn empty_packages_3() {
666 .get_matches_from_safe(&["test", "-p", "--verbose"])
672 fn empty_packages_4() {
675 .get_matches_from_safe(&["test", "-p", "--check"])
680 mod convert_message_format_to_rustfmt_args_tests {
684 fn invalid_message_format() {
686 convert_message_format_to_rustfmt_args("awesome", &mut vec![]),
688 "invalid --message-format value: awesome. Allowed values are: short|json|human"
694 fn json_message_format_and_check_arg() {
695 let mut args = vec![String::from("--check")];
697 convert_message_format_to_rustfmt_args("json", &mut args),
699 "cannot include --check arg when --message-format is set to json"
705 fn json_message_format_and_emit_arg() {
706 let mut args = vec![String::from("--emit"), String::from("checkstyle")];
708 convert_message_format_to_rustfmt_args("json", &mut args),
710 "cannot include --emit arg when --message-format is set to json"
716 fn json_message_format() {
717 let mut args = vec![String::from("--edition"), String::from("2018")];
718 assert!(convert_message_format_to_rustfmt_args("json", &mut args).is_ok());
722 String::from("--edition"),
723 String::from("2018"),
724 String::from("--emit"),
731 fn human_message_format() {
732 let exp_args = vec![String::from("--emit"), String::from("json")];
733 let mut act_args = exp_args.clone();
734 assert!(convert_message_format_to_rustfmt_args("human", &mut act_args).is_ok());
735 assert_eq!(act_args, exp_args);
739 fn short_message_format() {
740 let mut args = vec![String::from("--check")];
741 assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok());
742 assert_eq!(args, vec![String::from("--check"), String::from("-l")]);
746 fn short_message_format_included_short_list_files_flag() {
747 let mut args = vec![String::from("--check"), String::from("-l")];
748 assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok());
749 assert_eq!(args, vec![String::from("--check"), String::from("-l")]);
753 fn short_message_format_included_long_list_files_flag() {
754 let mut args = vec![String::from("--check"), String::from("--files-with-diff")];
755 assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok());
758 vec![String::from("--check"), String::from("--files-with-diff")]