]> 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 8e66f240909291dbe994761526ea37f8c86417db..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};
@@ -57,6 +56,20 @@ pub enum RustcSource {
     Discover,
 }
 
+/// Crates to disable `#[cfg(test)]` on.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum UnsetTestCrates {
+    None,
+    Only(Vec<String>),
+    All,
+}
+
+impl Default for UnsetTestCrates {
+    fn default() -> Self {
+        Self::None
+    }
+}
+
 #[derive(Default, Clone, Debug, PartialEq, Eq)]
 pub struct CargoConfig {
     /// Do not activate the `default` feature.
@@ -80,20 +93,29 @@ pub struct CargoConfig {
     pub rustc_source: Option<RustcSource>,
 
     /// crates to disable `#[cfg(test)]` on
-    pub unset_test_crates: Vec<String>,
+    pub unset_test_crates: UnsetTestCrates,
 
     pub wrap_rustc_in_build_scripts: bool,
 }
 
 impl CargoConfig {
     pub fn cfg_overrides(&self) -> CfgOverrides {
-        self.unset_test_crates
-            .iter()
-            .cloned()
-            .zip(iter::repeat_with(|| {
-                cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
-            }))
-            .collect()
+        match &self.unset_test_crates {
+            UnsetTestCrates::None => CfgOverrides::Selective(iter::empty().collect()),
+            UnsetTestCrates::Only(unset_test_crates) => CfgOverrides::Selective(
+                unset_test_crates
+                    .iter()
+                    .cloned()
+                    .zip(iter::repeat_with(|| {
+                        cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())])
+                            .unwrap()
+                    }))
+                    .collect(),
+            ),
+            UnsetTestCrates::All => CfgOverrides::Wildcard(
+                cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap(),
+            ),
+        }
     }
 }
 
@@ -108,11 +130,15 @@ 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>,
-    /// Is this package a member of the current workspace
+    /// 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>,
@@ -122,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,
 }
 
@@ -184,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)]
@@ -226,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> {
@@ -250,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]);
@@ -261,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)
     }
@@ -278,14 +306,24 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
         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 is_member = ws_members.contains(id);
             let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
-                log::error!("Failed to parse edition {}", err);
+                tracing::error!("Failed to parse edition {}", err);
                 Edition::CURRENT
             });
+            // 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(),
@@ -293,8 +331,10 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
                 version: version.clone(),
                 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(),
@@ -310,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);
             }
@@ -322,7 +363,7 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
                 // https://github.com/rust-lang/cargo/issues/7841
                 // is fixed and hits stable (around 1.43-is probably?).
                 None => {
-                    log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
+                    tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
                     continue;
                 }
             };
@@ -335,7 +376,7 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
                     Some(&pkg) => pkg,
                     None => {
-                        log::error!(
+                        tracing::error!(
                             "Dep node id do not match in cargo metadata, ignoring {}",
                             dep_node.pkg
                         );
@@ -354,23 +395,14 @@ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
         CargoWorkspace { packages, targets, workspace_root }
     }
 
-    pub fn from_cargo_metadata3(
-        cargo_toml: &ManifestPath,
-        config: &CargoConfig,
-        progress: &dyn Fn(String),
-    ) -> Result<CargoWorkspace> {
-        let meta = CargoWorkspace::fetch_metadata(cargo_toml, config, progress)?;
-        Ok(CargoWorkspace::new(meta))
-    }
-
     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
         self.packages.iter().map(|(id, _pkg)| id)
     }
 
     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()
     }
 
@@ -386,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
     }
@@ -394,7 +459,7 @@ fn is_unique(&self, name: &str) -> bool {
 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
     let mut rustc = Command::new(toolchain::rustc());
     rustc.current_dir(cargo_toml.parent()).arg("-vV");
-    log::debug!("Discovering host platform by {:?}", rustc);
+    tracing::debug!("Discovering host platform by {:?}", rustc);
     match utf8_stdout(rustc) {
         Ok(stdout) => {
             let field = "host: ";
@@ -403,12 +468,12 @@ fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
                 Some(target.to_string())
             } else {
                 // If we fail to resolve the host platform, it's not the end of the world.
-                log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
+                tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
                 None
             }
         }
         Err(e) => {
-            log::warn!("Failed to discover host platform: {}", e);
+            tracing::warn!("Failed to discover host platform: {}", e);
             None
         }
     }
@@ -421,7 +486,7 @@ fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
         .env("RUSTC_BOOTSTRAP", "1");
     // if successful we receive `build.target = "target-triple"`
-    log::debug!("Discovering cargo config target by {:?}", cargo_config);
+    tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
     match utf8_stdout(cargo_config) {
         Ok(stdout) => stdout
             .strip_prefix("build.target = \"")