Skip to main content

alef_component_runtime/
target.rs

1//! Host target detection for native components.
2
3/// The Rust target triple of the host this crate was compiled for, when it is one a component
4/// artifact can be published for; `None` otherwise (e.g. mobile, wasm, musl or 32-bit hosts).
5///
6/// The result is the `identity.target` string used to select a lock entry, so it must agree
7/// with the triples `alef component package` records. Generated bindings use the same table.
8#[must_use]
9#[allow(unreachable_code)]
10pub fn host_target() -> Option<&'static str> {
11    #[cfg(all(target_arch = "x86_64", target_os = "linux", target_env = "gnu"))]
12    return Some("x86_64-unknown-linux-gnu");
13    #[cfg(all(target_arch = "aarch64", target_os = "linux", target_env = "gnu"))]
14    return Some("aarch64-unknown-linux-gnu");
15    #[cfg(all(target_arch = "x86_64", target_os = "macos"))]
16    return Some("x86_64-apple-darwin");
17    #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
18    return Some("aarch64-apple-darwin");
19    #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "msvc"))]
20    return Some("x86_64-pc-windows-msvc");
21    #[cfg(all(target_arch = "aarch64", target_os = "windows", target_env = "msvc"))]
22    return Some("aarch64-pc-windows-msvc");
23    None
24}
25
26#[cfg(test)]
27mod tests {
28    use super::host_target;
29
30    #[test]
31    fn host_target_matches_the_compile_time_platform() {
32        let Some(triple) = host_target() else {
33            return;
34        };
35        let arch = triple.split('-').next().unwrap();
36        assert_eq!(arch, std::env::consts::ARCH);
37        let os_marker = match std::env::consts::OS {
38            "linux" => "linux",
39            "macos" => "apple-darwin",
40            "windows" => "windows-msvc",
41            other => panic!("host_target returned {triple} on unexpected OS {other}"),
42        };
43        assert!(triple.ends_with(os_marker) || triple.contains(os_marker), "{triple}");
44    }
45
46    #[test]
47    fn host_target_is_a_well_formed_triple() {
48        if let Some(triple) = host_target() {
49            assert!(triple.split('-').count() >= 3, "{triple}");
50            assert!(!triple.contains(char::is_whitespace), "{triple}");
51        }
52    }
53
54    #[test]
55    fn supported_linux_and_macos_ci_hosts_are_detected() {
56        if cfg!(all(
57            target_os = "linux",
58            target_env = "gnu",
59            any(target_arch = "x86_64", target_arch = "aarch64")
60        )) || cfg!(all(
61            target_os = "macos",
62            any(target_arch = "x86_64", target_arch = "aarch64")
63        )) {
64            assert!(host_target().is_some());
65        }
66    }
67}