use indoc::{formatdoc, indoc};
use std::env::consts;
use std::ffi::OsString;
use which::which;
pub fn cross_compile_assistance(target_triple: impl AsRef<str>) -> CrossCompileAssistance {
let target_triple = target_triple.as_ref();
let (gcc_binary_name, help_text) = match (target_triple, consts::OS, consts::ARCH) {
(AARCH64_UNKNOWN_LINUX_MUSL, OS_LINUX, ARCH_X86_64) => (
"aarch64-linux-gnu-gcc",
indoc! {"
To install an aarch64 cross-compiler on Ubuntu:
sudo apt-get install g++-aarch64-linux-gnu libc6-dev-arm64-cross musl-tools
"},
),
(AARCH64_UNKNOWN_LINUX_MUSL, OS_MACOS, ARCH_X86_64 | ARCH_AARCH64) => (
"aarch64-unknown-linux-musl-gcc",
indoc! {"
To install an aarch64 cross-compiler on macOS:
brew install messense/macos-cross-toolchains/aarch64-unknown-linux-musl
"},
),
(AARCH64_UNKNOWN_LINUX_MUSL, OS_LINUX, ARCH_AARCH64)
| (X86_64_UNKNOWN_LINUX_MUSL, OS_LINUX, ARCH_X86_64) => (
"musl-gcc",
indoc! {"
To install musl-tools on Ubuntu:
sudo apt-get install musl-tools
"},
),
(X86_64_UNKNOWN_LINUX_MUSL, OS_LINUX, ARCH_AARCH64) => (
"x86_64-linux-gnu-gcc",
indoc! {"
To install an x86_64 cross-compiler on Ubuntu:
sudo apt-get install g++-x86-64-linux-gnu libc6-dev-amd64-cross musl-tools
"},
),
(X86_64_UNKNOWN_LINUX_MUSL, OS_MACOS, ARCH_X86_64 | ARCH_AARCH64) => (
"x86_64-unknown-linux-musl-gcc",
indoc! {"
To install an x86_64 cross-compiler on macOS:
brew install messense/macos-cross-toolchains/x86_64-unknown-linux-musl
"},
),
_ => return CrossCompileAssistance::NoAssistance,
};
match which(gcc_binary_name) {
Ok(_) => {
if gcc_binary_name == "musl-gcc" {
CrossCompileAssistance::Configuration {
cargo_env: Vec::new(),
}
} else {
CrossCompileAssistance::Configuration {
cargo_env: vec![
(
OsString::from(format!(
"CARGO_TARGET_{}_LINKER",
target_triple.to_uppercase().replace('-', "_")
)),
OsString::from(gcc_binary_name),
),
(
OsString::from(format!("CC_{}", target_triple.replace('-', "_"))),
OsString::from(gcc_binary_name),
),
],
}
}
}
Err(_) => CrossCompileAssistance::HelpText(formatdoc! {"
For cross-compilation from {0} {1} to {target_triple},
a C compiler and linker for the target platform must be installed:
{help_text}
You will also need to install the Rust target:
rustup target add {target_triple}
",
consts::ARCH,
consts::OS
}),
}
}
pub enum CrossCompileAssistance {
NoAssistance,
HelpText(String),
Configuration {
cargo_env: Vec<(OsString, OsString)>,
},
}
pub const AARCH64_UNKNOWN_LINUX_MUSL: &str = "aarch64-unknown-linux-musl";
pub const X86_64_UNKNOWN_LINUX_MUSL: &str = "x86_64-unknown-linux-musl";
const OS_LINUX: &str = "linux";
const OS_MACOS: &str = "macos";
const ARCH_X86_64: &str = "x86_64";
const ARCH_AARCH64: &str = "aarch64";