]> git.lizzy.rs Git - rust.git/blobdiff - crates/project_model/src/cargo_workspace.rs
Pass required features to cargo when using run action
[rust.git] / crates / project_model / src / cargo_workspace.rs
index 1417ac2fa1d1b0f357768b8175d1a7ead90f8730..48051e4b5e8fbc4c39bb6750a247ffbbb3c1d951 100644 (file)
@@ -1,6 +1,5 @@
 //! See [`CargoWorkspace`].
 
-use std::convert::TryInto;
 use std::iter;
 use std::path::PathBuf;
 use std::{ops, process::Command};
@@ -131,12 +130,16 @@ pub struct PackageData {
     pub version: semver::Version,
     /// Name as given in the `Cargo.toml`
     pub name: String,
+    /// Repository as given in the `Cargo.toml`
+    pub repository: Option<String>,
     /// Path containing the `Cargo.toml`
     pub manifest: ManifestPath,
     /// Targets provided by the crate (lib, bin, example, test, ...)
     pub targets: Vec<Target>,
     /// Does this package come from the local filesystem (and is editable)?
     pub is_local: bool,
+    // Whether this package is a member of the workspace
+    pub is_member: bool,
     /// List of packages this package depends on
     pub dependencies: Vec<PackageDependency>,
     /// Rust edition for this package
@@ -145,9 +148,9 @@ pub struct PackageData {
     pub features: FxHashMap<String, Vec<String>>,
     /// List of features enabled on this package
     pub active_features: Vec<String>,
-    // String representation of package id
+    /// String representation of package id
     pub id: String,
-    // The contents of [package.metadata.rust-analyzer]
+    /// The contents of [package.metadata.rust-analyzer]
     pub metadata: RustAnalyzerPackageMetaData,
 }
 
@@ -207,6 +210,8 @@ pub struct TargetData {
     pub kind: TargetKind,
     /// Is this target a proc-macro
     pub is_proc_macro: bool,
+    /// Required features of the target without which it won't build
+    pub required_features: Vec<String>,
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -249,6 +254,7 @@ struct PackageMetadata {
 impl CargoWorkspace {
     pub fn fetch_metadata(
         cargo_toml: &ManifestPath,
+        current_dir: &AbsPath,
         config: &CargoConfig,
         progress: &dyn Fn(String),
     ) -> Result<cargo_metadata::Metadata> {
@@ -273,7 +279,7 @@ pub fn fetch_metadata(
                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
             }
         }
-        meta.current_dir(cargo_toml.parent().as_os_str());
+        meta.current_dir(current_dir.as_os_str());
 
         if let Some(target) = target {
             meta.other_options(vec![String::from("--filter-platform"), target]);
@@ -284,9 +290,8 @@ pub fn fetch_metadata(
         // unclear whether cargo itself supports it.
         progress("metadata".to_string());
 
-        let meta = meta.exec().with_context(|| {
-            format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display(),)
-        })?;
+        let meta =
+            meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
 
         Ok(meta)
     }
@@ -296,10 +301,19 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
         let mut packages = Arena::default();
         let mut targets = Arena::default();
 
+        let ws_members = &meta.workspace_members;
+
         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
         for meta_pkg in &meta.packages {
             let cargo_metadata::Package {
-                id, edition, name, manifest_path, version, metadata, ..
+                id,
+                edition,
+                name,
+                manifest_path,
+                version,
+                metadata,
+                repository,
+                ..
             } = meta_pkg;
             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
             let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
@@ -309,6 +323,7 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
             // We treat packages without source as "local" packages. That includes all members of
             // the current workspace, as well as any path dependency outside the workspace.
             let is_local = meta_pkg.source.is_none();
+            let is_member = ws_members.contains(id);
 
             let pkg = packages.alloc(PackageData {
                 id: id.repr.clone(),
@@ -317,7 +332,9 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
                 targets: Vec::new(),
                 is_local,
+                is_member,
                 edition,
+                repository: repository.clone(),
                 dependencies: Vec::new(),
                 features: meta_pkg.features.clone().into_iter().collect(),
                 active_features: Vec::new(),
@@ -333,6 +350,7 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
                     is_proc_macro,
+                    required_features: meta_tgt.required_features.clone(),
                 });
                 pkg_data.targets.push(tgt);
             }
@@ -383,8 +401,8 @@ pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterat
 
     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
         self.packages()
-            .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
-            .next()
+            .filter(|&pkg| self[pkg].is_member)
+            .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
             .copied()
     }
 
@@ -400,6 +418,39 @@ pub fn package_flag(&self, package: &PackageData) -> String {
         }
     }
 
+    pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
+        let mut found = false;
+        let parent_manifests = self
+            .packages()
+            .filter_map(|pkg| {
+                if !found && &self[pkg].manifest == manifest_path {
+                    found = true
+                }
+                self[pkg].dependencies.iter().find_map(|dep| {
+                    if &self[dep.pkg].manifest == manifest_path {
+                        return Some(self[pkg].manifest.clone());
+                    }
+                    None
+                })
+            })
+            .collect::<Vec<ManifestPath>>();
+
+        // some packages has this pkg as dep. return their manifests
+        if parent_manifests.len() > 0 {
+            return Some(parent_manifests);
+        }
+
+        // this pkg is inside this cargo workspace, fallback to workspace root
+        if found {
+            return Some(vec![
+                ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
+            ]);
+        }
+
+        // not in this workspace
+        None
+    }
+
     fn is_unique(&self, name: &str) -> bool {
         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
     }