1 //! Handles build script specific information
5 process::{Command, Stdio},
10 use cargo_metadata::camino::Utf8Path;
11 use cargo_metadata::{BuildScript, Message};
12 use itertools::Itertools;
13 use paths::{AbsPath, AbsPathBuf};
14 use rustc_hash::FxHashMap;
15 use serde::Deserialize;
18 use crate::{cfg_flag::CfgFlag, CargoConfig};
20 #[derive(Debug, Clone, Default, PartialEq, Eq)]
21 pub(crate) struct PackageBuildData {
22 /// List of config flags defined by this package's build script
23 pub(crate) cfgs: Vec<CfgFlag>,
24 /// List of cargo-related environment variables with their value
26 /// If the package has a build script which defines environment variables,
27 /// they can also be found here.
28 pub(crate) envs: Vec<(String, String)>,
29 /// Directory where a build script might place its output
30 pub(crate) out_dir: Option<AbsPathBuf>,
31 /// Path to the proc-macro library file if this package exposes proc-macros
32 pub(crate) proc_macro_dylib_path: Option<AbsPathBuf>,
35 #[derive(Debug, Default, PartialEq, Eq, Clone)]
36 pub(crate) struct WorkspaceBuildData {
37 per_package: FxHashMap<String, PackageBuildData>,
38 error: Option<String>,
41 #[derive(Debug, Default, PartialEq, Eq, Clone)]
42 pub struct BuildDataResult {
43 per_workspace: FxHashMap<AbsPathBuf, WorkspaceBuildData>,
46 #[derive(Clone, Debug)]
47 pub(crate) struct BuildDataConfig {
48 cargo_toml: AbsPathBuf,
49 cargo_features: CargoConfig,
50 packages: Arc<Vec<cargo_metadata::Package>>,
53 impl PartialEq for BuildDataConfig {
54 fn eq(&self, other: &Self) -> bool {
55 Arc::ptr_eq(&self.packages, &other.packages)
59 impl Eq for BuildDataConfig {}
62 pub struct BuildDataCollector {
64 configs: FxHashMap<AbsPathBuf, BuildDataConfig>,
67 impl BuildDataCollector {
68 pub fn new(wrap_rustc: bool) -> Self {
69 Self { wrap_rustc, configs: FxHashMap::default() }
72 pub(crate) fn add_config(&mut self, workspace_root: &AbsPath, config: BuildDataConfig) {
73 self.configs.insert(workspace_root.to_path_buf(), config);
76 pub fn collect(&mut self, progress: &dyn Fn(String)) -> Result<BuildDataResult> {
77 let mut res = BuildDataResult::default();
78 for (path, config) in self.configs.iter() {
79 let workspace_build_data = WorkspaceBuildData::collect(
81 &config.cargo_features,
86 res.per_workspace.insert(path.clone(), workspace_build_data);
92 impl WorkspaceBuildData {
93 pub(crate) fn get(&self, package_id: &str) -> Option<&PackageBuildData> {
94 self.per_package.get(package_id)
98 impl BuildDataResult {
99 pub(crate) fn get(&self, workspace_root: &AbsPath) -> Option<&WorkspaceBuildData> {
100 self.per_workspace.get(workspace_root)
102 pub fn error(&self) -> Option<String> {
103 let mut buf = String::new();
104 for (_workspace_root, build_data) in &self.per_workspace {
105 if let Some(err) = &build_data.error {
106 format_to!(buf, "cargo check failed:\n{}", err);
117 impl BuildDataConfig {
119 cargo_toml: AbsPathBuf,
120 cargo_features: CargoConfig,
121 packages: Arc<Vec<cargo_metadata::Package>>,
123 Self { cargo_toml, cargo_features, packages }
127 impl WorkspaceBuildData {
129 cargo_toml: &AbsPath,
130 cargo_features: &CargoConfig,
131 packages: &Vec<cargo_metadata::Package>,
133 progress: &dyn Fn(String),
134 ) -> Result<WorkspaceBuildData> {
135 let mut cmd = Command::new(toolchain::cargo());
138 // Setup RUSTC_WRAPPER to point to `rust-analyzer` binary itself. We use
139 // that to compile only proc macros and build scripts during the initial
141 let myself = std::env::current_exe()?;
142 cmd.env("RUSTC_WRAPPER", myself);
143 cmd.env("RA_RUSTC_WRAPPER", "1");
146 cmd.args(&["check", "--quiet", "--workspace", "--message-format=json", "--manifest-path"])
147 .arg(cargo_toml.as_ref());
149 // --all-targets includes tests, benches and examples in addition to the
150 // default lib and bins. This is an independent concept from the --targets
152 cmd.arg("--all-targets");
154 if let Some(target) = &cargo_features.target {
155 cmd.args(&["--target", target]);
158 if cargo_features.all_features {
159 cmd.arg("--all-features");
161 if cargo_features.no_default_features {
162 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
163 // https://github.com/oli-obk/cargo_metadata/issues/79
164 cmd.arg("--no-default-features");
166 if !cargo_features.features.is_empty() {
167 cmd.arg("--features");
168 cmd.arg(cargo_features.features.join(" "));
172 cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null());
174 let mut res = WorkspaceBuildData::default();
176 let mut callback_err = None;
177 let output = stdx::process::streaming_output(
180 if callback_err.is_some() {
184 // Copy-pasted from existing cargo_metadata. It seems like we
185 // should be using sered_stacker here?
186 let mut deserializer = serde_json::Deserializer::from_str(&line);
187 deserializer.disable_recursion_limit();
188 let message = Message::deserialize(&mut deserializer)
189 .unwrap_or(Message::TextLine(line.to_string()));
192 Message::BuildScriptExecuted(BuildScript {
200 let mut acc = Vec::new();
202 match cfg.parse::<CfgFlag>() {
203 Ok(it) => acc.push(it),
205 callback_err = Some(anyhow::format_err!(
206 "invalid cfg from cargo-metadata: {}",
215 let package_build_data =
216 res.per_package.entry(package_id.repr.clone()).or_default();
217 // cargo_metadata crate returns default (empty) path for
218 // older cargos, which is not absolute, so work around that.
219 if !out_dir.as_str().is_empty() {
221 AbsPathBuf::assert(PathBuf::from(out_dir.into_os_string()));
222 package_build_data.out_dir = Some(out_dir);
223 package_build_data.cfgs = cfgs;
226 package_build_data.envs = env;
228 Message::CompilerArtifact(message) => {
229 progress(format!("metadata {}", message.target.name));
231 if message.target.kind.contains(&"proc-macro".to_string()) {
232 let package_id = message.package_id;
234 if let Some(filename) =
235 message.filenames.iter().find(|name| is_dylib(name))
237 let filename = AbsPathBuf::assert(PathBuf::from(&filename));
238 let package_build_data =
239 res.per_package.entry(package_id.repr.clone()).or_default();
240 package_build_data.proc_macro_dylib_path = Some(filename);
244 Message::CompilerMessage(message) => {
245 progress(message.target.name.clone());
247 Message::BuildFinished(_) => {}
248 Message::TextLine(_) => {}
255 for package in packages {
256 let package_build_data = res.per_package.entry(package.id.repr.clone()).or_default();
257 inject_cargo_env(package, package_build_data);
258 if let Some(out_dir) = &package_build_data.out_dir {
259 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
260 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
261 package_build_data.envs.push(("OUT_DIR".to_string(), out_dir));
266 if !output.status.success() {
267 let mut stderr = String::from_utf8(output.stderr).unwrap_or_default();
268 if stderr.is_empty() {
269 stderr = "cargo check failed".to_string();
271 res.error = Some(stderr)
278 // FIXME: File a better way to know if it is a dylib
279 fn is_dylib(path: &Utf8Path) -> bool {
280 match path.extension().map(|e| e.to_string().to_lowercase()) {
282 Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
286 /// Recreates the compile-time environment variables that Cargo sets.
288 /// Should be synced with <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
289 fn inject_cargo_env(package: &cargo_metadata::Package, build_data: &mut PackageBuildData) {
290 let env = &mut build_data.envs;
292 // FIXME: Missing variables:
293 // CARGO_PKG_HOMEPAGE, CARGO_CRATE_NAME, CARGO_BIN_NAME, CARGO_BIN_EXE_<name>
295 let mut manifest_dir = package.manifest_path.clone();
297 env.push(("CARGO_MANIFEST_DIR".into(), manifest_dir.into_string()));
299 // Not always right, but works for common cases.
300 env.push(("CARGO".into(), "cargo".into()));
302 env.push(("CARGO_PKG_VERSION".into(), package.version.to_string()));
303 env.push(("CARGO_PKG_VERSION_MAJOR".into(), package.version.major.to_string()));
304 env.push(("CARGO_PKG_VERSION_MINOR".into(), package.version.minor.to_string()));
305 env.push(("CARGO_PKG_VERSION_PATCH".into(), package.version.patch.to_string()));
307 let pre = package.version.pre.iter().map(|id| id.to_string()).format(".");
308 env.push(("CARGO_PKG_VERSION_PRE".into(), pre.to_string()));
310 let authors = package.authors.join(";");
311 env.push(("CARGO_PKG_AUTHORS".into(), authors));
313 env.push(("CARGO_PKG_NAME".into(), package.name.clone()));
314 env.push(("CARGO_PKG_DESCRIPTION".into(), package.description.clone().unwrap_or_default()));
315 //env.push(("CARGO_PKG_HOMEPAGE".into(), package.homepage.clone().unwrap_or_default()));
316 env.push(("CARGO_PKG_REPOSITORY".into(), package.repository.clone().unwrap_or_default()));
317 env.push(("CARGO_PKG_LICENSE".into(), package.license.clone().unwrap_or_default()));
319 let license_file = package.license_file.as_ref().map(|buf| buf.to_string()).unwrap_or_default();
320 env.push(("CARGO_PKG_LICENSE_FILE".into(), license_file));