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.current_dir(cargo_toml.parent().unwrap());
147 cmd.args(&["check", "--quiet", "--workspace", "--message-format=json", "--manifest-path"])
148 .arg(cargo_toml.as_ref());
150 // --all-targets includes tests, benches and examples in addition to the
151 // default lib and bins. This is an independent concept from the --targets
153 cmd.arg("--all-targets");
155 if let Some(target) = &cargo_features.target {
156 cmd.args(&["--target", target]);
159 if cargo_features.all_features {
160 cmd.arg("--all-features");
162 if cargo_features.no_default_features {
163 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
164 // https://github.com/oli-obk/cargo_metadata/issues/79
165 cmd.arg("--no-default-features");
167 if !cargo_features.features.is_empty() {
168 cmd.arg("--features");
169 cmd.arg(cargo_features.features.join(" "));
173 cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null());
175 let mut res = WorkspaceBuildData::default();
177 let mut callback_err = None;
178 let output = stdx::process::streaming_output(
181 if callback_err.is_some() {
185 // Copy-pasted from existing cargo_metadata. It seems like we
186 // should be using sered_stacker here?
187 let mut deserializer = serde_json::Deserializer::from_str(&line);
188 deserializer.disable_recursion_limit();
189 let message = Message::deserialize(&mut deserializer)
190 .unwrap_or(Message::TextLine(line.to_string()));
193 Message::BuildScriptExecuted(BuildScript {
201 let mut acc = Vec::new();
203 match cfg.parse::<CfgFlag>() {
204 Ok(it) => acc.push(it),
206 callback_err = Some(anyhow::format_err!(
207 "invalid cfg from cargo-metadata: {}",
216 let package_build_data =
217 res.per_package.entry(package_id.repr.clone()).or_default();
218 // cargo_metadata crate returns default (empty) path for
219 // older cargos, which is not absolute, so work around that.
220 if !out_dir.as_str().is_empty() {
222 AbsPathBuf::assert(PathBuf::from(out_dir.into_os_string()));
223 package_build_data.out_dir = Some(out_dir);
224 package_build_data.cfgs = cfgs;
227 package_build_data.envs = env;
229 Message::CompilerArtifact(message) => {
230 progress(format!("metadata {}", message.target.name));
232 if message.target.kind.contains(&"proc-macro".to_string()) {
233 let package_id = message.package_id;
235 if let Some(filename) =
236 message.filenames.iter().find(|name| is_dylib(name))
238 let filename = AbsPathBuf::assert(PathBuf::from(&filename));
239 let package_build_data =
240 res.per_package.entry(package_id.repr.clone()).or_default();
241 package_build_data.proc_macro_dylib_path = Some(filename);
245 Message::CompilerMessage(message) => {
246 progress(message.target.name.clone());
248 Message::BuildFinished(_) => {}
249 Message::TextLine(_) => {}
256 for package in packages {
257 let package_build_data = res.per_package.entry(package.id.repr.clone()).or_default();
258 inject_cargo_env(package, package_build_data);
259 if let Some(out_dir) = &package_build_data.out_dir {
260 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
261 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
262 package_build_data.envs.push(("OUT_DIR".to_string(), out_dir));
267 if !output.status.success() {
268 let mut stderr = String::from_utf8(output.stderr).unwrap_or_default();
269 if stderr.is_empty() {
270 stderr = "cargo check failed".to_string();
272 res.error = Some(stderr)
279 // FIXME: File a better way to know if it is a dylib
280 fn is_dylib(path: &Utf8Path) -> bool {
281 match path.extension().map(|e| e.to_string().to_lowercase()) {
283 Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
287 /// Recreates the compile-time environment variables that Cargo sets.
289 /// Should be synced with <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
290 fn inject_cargo_env(package: &cargo_metadata::Package, build_data: &mut PackageBuildData) {
291 let env = &mut build_data.envs;
293 // FIXME: Missing variables:
294 // CARGO_PKG_HOMEPAGE, CARGO_CRATE_NAME, CARGO_BIN_NAME, CARGO_BIN_EXE_<name>
296 let mut manifest_dir = package.manifest_path.clone();
298 env.push(("CARGO_MANIFEST_DIR".into(), manifest_dir.into_string()));
300 // Not always right, but works for common cases.
301 env.push(("CARGO".into(), "cargo".into()));
303 env.push(("CARGO_PKG_VERSION".into(), package.version.to_string()));
304 env.push(("CARGO_PKG_VERSION_MAJOR".into(), package.version.major.to_string()));
305 env.push(("CARGO_PKG_VERSION_MINOR".into(), package.version.minor.to_string()));
306 env.push(("CARGO_PKG_VERSION_PATCH".into(), package.version.patch.to_string()));
308 let pre = package.version.pre.iter().map(|id| id.to_string()).format(".");
309 env.push(("CARGO_PKG_VERSION_PRE".into(), pre.to_string()));
311 let authors = package.authors.join(";");
312 env.push(("CARGO_PKG_AUTHORS".into(), authors));
314 env.push(("CARGO_PKG_NAME".into(), package.name.clone()));
315 env.push(("CARGO_PKG_DESCRIPTION".into(), package.description.clone().unwrap_or_default()));
316 //env.push(("CARGO_PKG_HOMEPAGE".into(), package.homepage.clone().unwrap_or_default()));
317 env.push(("CARGO_PKG_REPOSITORY".into(), package.repository.clone().unwrap_or_default()));
318 env.push(("CARGO_PKG_LICENSE".into(), package.license.clone().unwrap_or_default()));
320 let license_file = package.license_file.as_ref().map(|buf| buf.to_string()).unwrap_or_default();
321 env.push(("CARGO_PKG_LICENSE_FILE".into(), license_file));