]> 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 ac079f83e6d6eed18c77ea6ef6785f19313abe72..48051e4b5e8fbc4c39bb6750a247ffbbb3c1d951 100644 (file)
@@ -1,7 +1,8 @@
 //! See [`CargoWorkspace`].
 
+use std::iter;
 use std::path::PathBuf;
-use std::{convert::TryInto, ops, process::Command, sync::Arc};
+use std::{ops, process::Command};
 
 use anyhow::{Context, Result};
 use base_db::Edition;
@@ -12,7 +13,8 @@
 use serde::Deserialize;
 use serde_json::from_value;
 
-use crate::{build_data::BuildDataConfig, utf8_stdout};
+use crate::CfgOverrides;
+use crate::{utf8_stdout, ManifestPath};
 
 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
 /// workspace. It pretty closely mirrors `cargo metadata` output.
@@ -29,7 +31,6 @@ pub struct CargoWorkspace {
     packages: Arena<PackageData>,
     targets: Arena<TargetData>,
     workspace_root: AbsPathBuf,
-    build_data_config: BuildDataConfig,
 }
 
 impl ops::Index<Package> for CargoWorkspace {
@@ -55,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.
@@ -76,6 +91,32 @@ pub struct CargoConfig {
 
     /// rustc private crate source
     pub rustc_source: Option<RustcSource>,
+
+    /// crates to disable `#[cfg(test)]` on
+    pub unset_test_crates: UnsetTestCrates,
+
+    pub wrap_rustc_in_build_scripts: bool,
+}
+
+impl CargoConfig {
+    pub fn cfg_overrides(&self) -> CfgOverrides {
+        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(),
+            ),
+        }
+    }
 }
 
 pub type Package = Idx<PackageData>;
@@ -86,14 +127,18 @@ pub struct CargoConfig {
 #[derive(Debug, Clone, Eq, PartialEq)]
 pub struct PackageData {
     /// Version given in the `Cargo.toml`
-    pub version: String,
+    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: AbsPathBuf,
+    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>,
@@ -103,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,
 }
 
@@ -165,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)]
@@ -197,12 +244,6 @@ fn new(kinds: &[String]) -> TargetKind {
     }
 }
 
-impl PackageData {
-    pub fn root(&self) -> &AbsPath {
-        self.manifest.parent().unwrap()
-    }
-}
-
 #[derive(Deserialize, Default)]
 // Deserialise helper for the cargo metadata
 struct PackageMetadata {
@@ -211,11 +252,18 @@ struct PackageMetadata {
 }
 
 impl CargoWorkspace {
-    pub fn from_cargo_metadata(
-        cargo_toml: &AbsPath,
+    pub fn fetch_metadata(
+        cargo_toml: &ManifestPath,
+        current_dir: &AbsPath,
         config: &CargoConfig,
         progress: &dyn Fn(String),
-    ) -> Result<CargoWorkspace> {
+    ) -> Result<cargo_metadata::Metadata> {
+        let target = config
+            .target
+            .clone()
+            .or_else(|| cargo_config_build_target(cargo_toml))
+            .or_else(|| rustc_discover_host_triple(cargo_toml));
+
         let mut meta = MetadataCommand::new();
         meta.cargo_path(toolchain::cargo());
         meta.manifest_path(cargo_toml.to_path_buf());
@@ -231,41 +279,24 @@ pub fn from_cargo_metadata(
                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
             }
         }
-        if let Some(parent) = cargo_toml.parent() {
-            meta.current_dir(parent.to_path_buf());
-        }
-        let target = if let Some(target) = &config.target {
-            Some(target.clone())
-        } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
-            stdout
-        } else {
-            rustc_discover_host_triple(cargo_toml)
-        };
+        meta.current_dir(current_dir.as_os_str());
+
         if let Some(target) = target {
             meta.other_options(vec![String::from("--filter-platform"), target]);
         }
 
-        // FIXME: Currently MetadataCommand is not based on parse_stream,
-        // So we just report it as a whole
+        // FIXME: Fetching metadata is a slow process, as it might require
+        // calling crates.io. We should be reporting progress here, but it's
+        // unclear whether cargo itself supports it.
         progress("metadata".to_string());
-        let mut meta = meta.exec().with_context(|| {
-            let cwd: Option<AbsPathBuf> =
-                std::env::current_dir().ok().and_then(|p| p.try_into().ok());
-
-            let workdir = cargo_toml
-                .parent()
-                .map(|p| p.to_path_buf())
-                .or(cwd)
-                .map(|dir| dir.to_string_lossy().to_string())
-                .unwrap_or_else(|| "<failed to get path>".into());
-
-            format!(
-                "Failed to run `cargo metadata --manifest-path {}` in `{}`",
-                cargo_toml.display(),
-                workdir
-            )
-        })?;
 
+        let meta =
+            meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
+
+        Ok(meta)
+    }
+
+    pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
         let mut pkg_by_id = FxHashMap::default();
         let mut packages = Arena::default();
         let mut targets = Arena::default();
@@ -275,22 +306,35 @@ pub fn from_cargo_metadata(
         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| {
+                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 edition = edition
-                .parse::<Edition>()
-                .with_context(|| format!("Failed to parse edition {}", edition))?;
 
             let pkg = packages.alloc(PackageData {
                 id: id.repr.clone(),
                 name: name.clone(),
-                version: version.to_string(),
-                manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
+                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(),
@@ -306,6 +350,7 @@ pub fn from_cargo_metadata(
                     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);
             }
@@ -318,7 +363,7 @@ pub fn from_cargo_metadata(
                 // 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;
                 }
             };
@@ -331,7 +376,7 @@ pub fn from_cargo_metadata(
                 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
                         );
@@ -346,10 +391,8 @@ pub fn from_cargo_metadata(
 
         let workspace_root =
             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
-        let build_data_config =
-            BuildDataConfig::new(cargo_toml.to_path_buf(), config.clone(), Arc::new(meta.packages));
 
-        Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
+        CargoWorkspace { packages, targets, workspace_root }
     }
 
     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
@@ -358,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()
     }
 
@@ -375,8 +418,37 @@ pub fn package_flag(&self, package: &PackageData) -> String {
         }
     }
 
-    pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
-        &self.build_data_config
+    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 {
@@ -384,10 +456,10 @@ fn is_unique(&self, name: &str) -> bool {
     }
 }
 
-fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
+fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
     let mut rustc = Command::new(toolchain::rustc());
-    rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
-    log::debug!("Discovering host platform by {:?}", rustc);
+    rustc.current_dir(cargo_toml.parent()).arg("-vV");
+    tracing::debug!("Discovering host platform by {:?}", rustc);
     match utf8_stdout(rustc) {
         Ok(stdout) => {
             let field = "host: ";
@@ -396,25 +468,25 @@ fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> 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
         }
     }
 }
 
-fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
+fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
     let mut cargo_config = Command::new(toolchain::cargo());
     cargo_config
-        .current_dir(cargo_toml.parent().unwrap())
+        .current_dir(cargo_toml.parent())
         .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 = \"")