project_model/toolchain_info/
target_tuple.rs1use std::path::Path;
3
4use anyhow::Context;
5use rustc_hash::FxHashMap;
6use toolchain::Tool;
7
8use crate::{
9 Sysroot, cargo_config_file::CargoConfigFile, toolchain_info::QueryConfig, utf8_stdout,
10};
11
12pub fn get(
15 config: QueryConfig<'_>,
16 target: Option<&str>,
17 extra_env: &FxHashMap<String, Option<String>>,
18) -> anyhow::Result<Vec<String>> {
19 let _p = tracing::info_span!("target_tuple::get").entered();
20 if let Some(target) = target {
21 return Ok(vec![target.to_owned()]);
22 }
23
24 let (sysroot, current_dir) = match config {
25 QueryConfig::Cargo(sysroot, cargo_toml, config_file) => {
26 match config_file.as_ref().and_then(cargo_config_build_target) {
27 Some(it) => return Ok(it),
28 None => (sysroot, cargo_toml.parent().as_ref()),
29 }
30 }
31 QueryConfig::Rustc(sysroot, current_dir) => (sysroot, current_dir),
32 };
33 rustc_discover_host_tuple(extra_env, sysroot, current_dir).map(|it| vec![it])
34}
35
36fn rustc_discover_host_tuple(
37 extra_env: &FxHashMap<String, Option<String>>,
38 sysroot: &Sysroot,
39 current_dir: &Path,
40) -> anyhow::Result<String> {
41 let mut cmd = sysroot.tool(Tool::Rustc, current_dir, extra_env);
42 cmd.arg("-vV");
43 let stdout = utf8_stdout(&mut cmd)
44 .with_context(|| format!("unable to discover host platform via `{cmd:?}`"))?;
45 let field = "host: ";
46 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
47 if let Some(target) = target {
48 Ok(target.to_owned())
49 } else {
50 Err(anyhow::format_err!("rustc -vV did not report host platform, got:\n{}", stdout))
52 }
53}
54
55fn cargo_config_build_target(config: &CargoConfigFile) -> Option<Vec<String>> {
56 match parse_json_cargo_config_build_target(config) {
57 Ok(v) => v,
58 Err(e) => {
59 tracing::debug!("Failed to discover cargo config build target {e:?}");
60 None
61 }
62 }
63}
64
65fn parse_json_cargo_config_build_target(
67 config: &CargoConfigFile,
68) -> anyhow::Result<Option<Vec<String>>> {
69 let target = config.get("build").and_then(|v| v.as_object()).and_then(|m| m.get("target"));
70 match target {
71 Some(serde_json::Value::String(s)) => Ok(Some(vec![s.to_owned()])),
72 Some(v) => serde_json::from_value(v.clone())
73 .map(Option::Some)
74 .context("Failed to parse `build.target` as an array of target"),
75 None => Ok(None),
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use paths::{AbsPathBuf, Utf8PathBuf};
84
85 use crate::{ManifestPath, Sysroot};
86
87 use super::*;
88
89 #[test]
90 fn cargo() {
91 let manifest_path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
92 let sysroot = Sysroot::empty();
93 let manifest_path =
94 ManifestPath::try_from(AbsPathBuf::assert(Utf8PathBuf::from(manifest_path))).unwrap();
95 let cfg = QueryConfig::Cargo(&sysroot, &manifest_path, &None);
96 assert!(get(cfg, None, &FxHashMap::default()).is_ok());
97 }
98
99 #[test]
100 fn rustc() {
101 let sysroot = Sysroot::empty();
102 let cfg = QueryConfig::Rustc(&sysroot, env!("CARGO_MANIFEST_DIR").as_ref());
103 assert!(get(cfg, None, &FxHashMap::default()).is_ok());
104 }
105}