]> git.lizzy.rs Git - rust.git/blobdiff - src/cargo-fmt/main.rs
Use concat() instead of join("")
[rust.git] / src / cargo-fmt / main.rs
index 1acad99688a25cc8563813acd7cbc505e7fdb1eb..eee102b6bf8b8ab03e0df774000cfd24b2798065 100644 (file)
@@ -97,7 +97,7 @@ fn execute() -> i32 {
 }
 
 macro_rules! print_usage {
-    ($print: ident, $opts: ident, $reason: expr) => {{
+    ($print:ident, $opts:ident, $reason:expr) => {{
         let msg = format!("{}\nusage: cargo fmt [options]", $reason);
         $print!(
             "{}\nThis utility formats all bin and lib files of the current crate using rustfmt. \
@@ -147,7 +147,10 @@ fn format_crate(
     strategy: &CargoFmtStrategy,
 ) -> Result<ExitStatus, io::Error> {
     let rustfmt_args = get_fmt_args();
-    let targets = if rustfmt_args.iter().any(|s| s == "--dump-default-config") {
+    let targets = if rustfmt_args
+        .iter()
+        .any(|s| ["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str()))
+    {
         HashSet::new()
     } else {
         get_targets(strategy)?
@@ -211,7 +214,7 @@ fn hash<H: Hasher>(&self, state: &mut H) {
 pub enum CargoFmtStrategy {
     /// Format every packages and dependencies.
     All,
-    /// Format pacakges that are specified by the command line argument.
+    /// Format packages that are specified by the command line argument.
     Some(Vec<String>),
     /// Format the root packages only.
     Root,
@@ -249,10 +252,16 @@ fn get_targets(strategy: &CargoFmtStrategy) -> Result<HashSet<Target>, io::Error
 
 fn get_targets_root_only(targets: &mut HashSet<Target>) -> Result<(), io::Error> {
     let metadata = get_cargo_metadata(None)?;
+    let current_dir = env::current_dir()?.canonicalize()?;
+    let current_dir_manifest = current_dir.join("Cargo.toml");
+    let workspace_root_path = PathBuf::from(&metadata.workspace_root).canonicalize()?;
+    let in_workspace_root = workspace_root_path == current_dir;
 
     for package in metadata.packages {
-        for target in package.targets {
-            targets.insert(Target::from_target(&target));
+        if in_workspace_root || PathBuf::from(&package.manifest_path) == current_dir_manifest {
+            for target in package.targets {
+                targets.insert(Target::from_target(&target));
+            }
         }
     }
 
@@ -365,9 +374,6 @@ fn run_rustfmt(
 fn get_cargo_metadata(manifest_path: Option<&Path>) -> Result<cargo_metadata::Metadata, io::Error> {
     match cargo_metadata::metadata(manifest_path) {
         Ok(metadata) => Ok(metadata),
-        Err(..) => Err(io::Error::new(
-            io::ErrorKind::Other,
-            "`cargo manifest` failed.",
-        )),
+        Err(error) => Err(io::Error::new(io::ErrorKind::Other, error.to_string())),
     }
 }