use std::path::{Path, PathBuf};
use std::process::Command;
const SKIP_VAR: &str = "PAPERBOY_SKIP_DEP_CHECK";
struct Missing {
name: &'static str,
evidence: String,
}
fn main() {
println!("cargo::rerun-if-changed=build.rs");
for var in [
SKIP_VAR,
"LIBXML2",
"PKG_CONFIG",
"PKG_CONFIG_PATH",
"PKG_CONFIG_LIBDIR",
"PKG_CONFIG_SYSROOT_DIR",
"LIBCLANG_PATH",
"CC",
"PERL",
"OPENSSL_SRC_PERL",
"MAKE",
"VCPKG_ROOT",
"VCPKGRS_TRIPLET",
"VCPKGRS_DYNAMIC",
"VCPKGRS_DISABLE",
"VCPKGRS_NO_LIBXML2",
] {
println!("cargo::rerun-if-env-changed={var}");
}
if std::env::var_os(SKIP_VAR).is_some() {
return;
}
let certain: Vec<Missing> = [
check_libxml2(),
check_compiler(),
check_perl(),
check_make(),
]
.into_iter()
.flatten()
.collect();
let uncertain: Vec<Missing> = [check_libclang(), check_nasm()]
.into_iter()
.flatten()
.collect();
if certain.is_empty() && uncertain.is_empty() {
return;
}
let hint = install_hint();
let fatal = !certain.is_empty() && probe_is_authoritative();
report(&certain, &uncertain, &hint);
if fatal {
panic!("{}", failure_message(&certain, &uncertain, &hint));
}
if !certain.is_empty() {
warn("(Continuing anyway: this check can't be certain on this machine.)");
}
}
fn check_libxml2() -> Option<Missing> {
if std::env::var_os("LIBXML2").is_some() {
return None;
}
if is_msvc_target() {
return check_libxml2_vcpkg();
}
let pkg_config = std::env::var("PKG_CONFIG").unwrap_or_else(|_| "pkg-config".to_string());
match Command::new(&pkg_config)
.args(["--exists", "libxml-2.0"])
.output()
{
Ok(out) if out.status.success() => None,
Ok(_) => Some(Missing {
name: "libxml2",
evidence: format!("`{pkg_config} --exists libxml-2.0` says it isn't installed"),
}),
Err(_) => Some(Missing {
name: "libxml2",
evidence: format!("`{pkg_config}`, which finds it, is not on PATH"),
}),
}
}
fn check_libxml2_vcpkg() -> Option<Missing> {
if std::env::var_os("VCPKGRS_DISABLE").is_some()
|| std::env::var_os("VCPKGRS_NO_LIBXML2").is_some()
{
return None;
}
let triplet = vcpkg_triplet();
let Some(root) = vcpkg_root() else {
let evidence = match stray_vcpkg_tree() {
Some(tree) => format!(
"a vcpkg tree exists at {}, but VCPKG_ROOT is not set in this \
shell -- `setx` only affects shells opened after it ran",
tree.display()
),
None => "no vcpkg installation found: VCPKG_ROOT is unset and no \
`vcpkg integrate install` has been run"
.to_string(),
};
return Some(Missing {
name: "libxml2 (via vcpkg)",
evidence,
});
};
let lib_dir = root.join("installed").join(&triplet).join("lib");
let installed = std::fs::read_dir(&lib_dir)
.map(|entries| {
entries.flatten().any(|entry| {
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
name.starts_with("libxml2") && name.ends_with(".lib")
})
})
.unwrap_or(false);
if installed {
return None;
}
Some(Missing {
name: "libxml2 (via vcpkg)",
evidence: format!(
"the vcpkg tree at {} has no libxml2 for the `{triplet}` triplet",
root.display()
),
})
}
fn vcpkg_root() -> Option<PathBuf> {
if let Some(root) = std::env::var_os("VCPKG_ROOT") {
return Some(PathBuf::from(root));
}
let local_app_data = std::env::var_os("LOCALAPPDATA")?;
let targets = PathBuf::from(local_app_data)
.join("vcpkg")
.join("vcpkg.user.targets");
let contents = std::fs::read_to_string(targets).ok()?;
let project = contents
.lines()
.filter_map(|line| line.split("Project=\"").nth(1))
.filter_map(|rest| rest.split('"').next())
.next()?;
let mut root = PathBuf::from(project);
for _ in 0..4 {
if !root.pop() {
return None;
}
}
Some(root)
}
fn stray_vcpkg_tree() -> Option<PathBuf> {
let mut candidates = vec![PathBuf::from("C:\\vcpkg")];
if let Some(profile) = std::env::var_os("USERPROFILE") {
candidates.push(PathBuf::from(profile).join("vcpkg"));
}
candidates
.into_iter()
.find(|root| root.join("vcpkg.exe").is_file())
}
fn needs_quoting(path: &str) -> bool {
path.chars().any(|c| " \t&()^%!,;=".contains(c))
}
fn quoted(path: &str) -> String {
if needs_quoting(path) {
format!("\"{path}\"")
} else {
path.to_string()
}
}
fn vcpkg_triplet() -> String {
if let Ok(triplet) = std::env::var("VCPKGRS_TRIPLET") {
return triplet;
}
let arch = match target_cfg("CARGO_CFG_TARGET_ARCH").as_str() {
"x86_64" => "x64",
"aarch64" => "arm64",
_ => "x86",
};
if target_cfg("CARGO_CFG_TARGET_FEATURE").contains("crt-static") {
format!("{arch}-windows-static")
} else if std::env::var_os("VCPKGRS_DYNAMIC").is_some() {
format!("{arch}-windows")
} else {
format!("{arch}-windows-static-md")
}
}
fn check_compiler() -> Option<Missing> {
if std::env::var_os("CC").is_some() {
return None;
}
if is_msvc_target() {
return None;
}
if ["cc", "gcc", "clang"].iter().any(|bin| has(bin)) {
return None;
}
Some(Missing {
name: "a C compiler",
evidence: "none of `cc`, `gcc` or `clang` is on PATH, and CC is unset".to_string(),
})
}
fn check_perl() -> Option<Missing> {
if std::env::var_os("OPENSSL_SRC_PERL").is_some() || std::env::var_os("PERL").is_some() {
return None;
}
if has("perl") {
return None;
}
Some(Missing {
name: "perl",
evidence: "`perl` is not on PATH, and neither PERL nor OPENSSL_SRC_PERL is set".to_string(),
})
}
fn check_make() -> Option<Missing> {
if std::env::var_os("MAKE").is_some() {
return None;
}
if is_msvc_target() {
return None;
}
if has("make") || has("gmake") {
return None;
}
Some(Missing {
name: "make",
evidence: "neither `make` nor `gmake` is on PATH".to_string(),
})
}
fn check_nasm() -> Option<Missing> {
if !is_msvc_target() || has("nasm") {
return None;
}
Some(Missing {
name: "nasm",
evidence: "`nasm` is not on PATH".to_string(),
})
}
fn check_libclang() -> Option<Missing> {
if std::env::var_os("LIBCLANG_PATH").is_some() {
return None;
}
let mut dirs: Vec<PathBuf> = vec![
PathBuf::from("/usr/lib"),
PathBuf::from("/usr/lib64"),
PathBuf::from("/usr/local/lib"),
PathBuf::from("/usr/lib/x86_64-linux-gnu"),
PathBuf::from("/usr/lib/aarch64-linux-gnu"),
PathBuf::from("/Library/Developer/CommandLineTools/usr/lib"),
PathBuf::from(
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
),
PathBuf::from("/opt/homebrew/opt/llvm/lib"),
PathBuf::from("/usr/local/opt/llvm/lib"),
];
if let Ok(entries) = std::fs::read_dir("/usr/lib") {
for entry in entries.flatten() {
if entry.file_name().to_string_lossy().starts_with("llvm") {
dirs.push(entry.path().join("lib"));
}
}
}
if cfg!(windows) {
for var in ["ProgramFiles", "ProgramFiles(x86)"] {
if let Some(program_files) = std::env::var_os(var) {
dirs.push(PathBuf::from(program_files).join("LLVM").join("bin"));
}
}
if let Some(path) = std::env::var_os("PATH") {
dirs.extend(std::env::split_paths(&path));
}
}
if let Ok(out) = Command::new("llvm-config").arg("--libdir").output() {
if out.status.success() {
let dir = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !dir.is_empty() {
dirs.push(PathBuf::from(dir));
}
}
}
if dirs.iter().any(|dir| contains_libclang(dir)) {
return None;
}
Some(Missing {
name: "libclang",
evidence: "no libclang shared library found in the usual places".to_string(),
})
}
fn contains_libclang(dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else {
return false;
};
entries.flatten().any(|entry| {
let name = entry.file_name();
let name = name.to_string_lossy();
name.starts_with("libclang")
&& (name.contains(".so") || name.contains(".dylib") || name.contains(".dll"))
})
}
fn is_msvc_target() -> bool {
target_cfg("CARGO_CFG_TARGET_FAMILY").contains("windows")
&& target_cfg("CARGO_CFG_TARGET_ENV") == "msvc"
}
fn probe_is_authoritative() -> bool {
let host = std::env::var("HOST").unwrap_or_default();
let target = std::env::var("TARGET").unwrap_or_default();
if host.is_empty() || target.is_empty() || host != target {
return false;
}
for base in [
"PKG_CONFIG",
"PKG_CONFIG_PATH",
"PKG_CONFIG_LIBDIR",
"PKG_CONFIG_SYSROOT_DIR",
] {
let candidates = [
format!("{base}_{target}"),
format!("{base}_{}", target.replace('-', "_")),
format!("HOST_{base}"),
];
if candidates.iter().any(|var| std::env::var_os(var).is_some()) {
return false;
}
}
true
}
fn target_cfg(var: &str) -> String {
std::env::var(var).unwrap_or_default()
}
fn report(certain: &[Missing], uncertain: &[Missing], hint: &Hint) {
warn("──────────────────────────────────────────────────────────────");
warn("PaperBoy needs some build dependencies that aren't installed:");
for item in certain {
warn(&format!(" · {}", item.name));
}
for item in uncertain {
warn(&format!(" · {} (maybe)", item.name));
}
if !hint.commands.is_empty() {
warn(" Run:");
for line in &hint.commands {
warn(&format!(" {line}"));
}
}
for step in &hint.steps {
warn(&format!(" Then: {step}"));
}
warn("──────────────────────────────────────────────────────────────");
}
fn failure_message(certain: &[Missing], uncertain: &[Missing], hint: &Hint) -> String {
let subject = if certain.len() == 1 {
"a build dependency is missing"
} else {
"build dependencies are missing"
};
let mut message = format!("PaperBoy can't be built here: {subject}.\n\n");
message.push_str(" Missing:\n");
for item in certain {
message.push_str(&format!(" · {}\n", item.name));
}
for item in uncertain {
message.push_str(&format!(
" · {} (a guess — not why the build stopped)\n",
item.name
));
}
if !hint.commands.is_empty() {
message.push_str("\n Run:\n");
for line in &hint.commands {
message.push_str(&format!(" {line}\n"));
}
}
if !hint.steps.is_empty() {
message.push_str("\n Then:\n");
for step in &hint.steps {
message.push_str(&format!(" · {step}\n"));
}
}
message.push_str(&format!(
"\n Stopping now rather than failing in ten minutes inside a crate you\n \
never asked for. Details: README → \"Build prerequisites\".\n \
Wrong about your machine? {SKIP_VAR}=1 skips this check.\n"
));
message.push_str("\n How this was detected:\n");
for item in certain.iter().chain(uncertain) {
message.push_str(&wrapped(
&format!("· {}: {}.", item.name, item.evidence),
" ",
" ",
));
}
message
}
fn wrapped(text: &str, indent: &str, hang: &str) -> String {
const WIDTH: usize = 66;
let mut out = String::new();
let mut line = String::new();
let mut first = true;
let flush = |line: &mut String, first: &mut bool, out: &mut String| {
let lead = if *first { indent } else { hang };
out.push_str(&format!("{lead}{line}\n"));
line.clear();
*first = false;
};
for word in text.split_whitespace() {
if !line.is_empty() && line.chars().count() + 1 + word.chars().count() > WIDTH {
flush(&mut line, &mut first, &mut out);
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
if !line.is_empty() {
flush(&mut line, &mut first, &mut out);
}
out
}
fn warn(line: &str) {
println!("cargo::warning={line}");
}
fn install_hint() -> Hint {
if target_cfg("CARGO_CFG_TARGET_OS") == "macos" {
let mut hint = Hint::new();
hint.run("xcode-select --install");
if has("brew") {
hint.run("brew install pkg-config");
} else if has("port") {
hint.run("sudo port install pkgconfig");
} else {
hint.step("install Homebrew (https://brew.sh), then: brew install pkg-config");
}
return hint;
}
if target_cfg("CARGO_CFG_TARGET_OS") == "windows" {
let mut hint = Hint::new();
let root = match vcpkg_root().or_else(stray_vcpkg_tree) {
Some(root) => {
let root = root.display().to_string();
hint.run(&format!("setx VCPKG_ROOT {}", quoted(&root)));
root
}
None => {
hint.run("git clone https://github.com/microsoft/vcpkg C:\\vcpkg");
hint.run("C:\\vcpkg\\bootstrap-vcpkg.bat");
hint.run("setx VCPKG_ROOT C:\\vcpkg");
"C:\\vcpkg".to_string()
}
};
let exe = format!("{}\\vcpkg", root.trim_end_matches('\\'));
if needs_quoting(&exe) {
hint.run(&format!("\"{exe}\" install libxml2:{}", vcpkg_triplet()));
hint.step(&format!(
"in PowerShell, put `&` in front of that line: & \"{exe}\" install …"
));
} else {
hint.run(&format!("{exe} install libxml2:{}", vcpkg_triplet()));
}
if has("winget") {
for id in ["LLVM.LLVM", "StrawberryPerl.StrawberryPerl", "NASM.NASM"] {
hint.run(&format!(
"winget install --id {id} -e \
--accept-package-agreements --accept-source-agreements"
));
}
} else if has("choco") {
hint.run("choco install llvm strawberryperl nasm -y");
hint.step("run the `choco` line from an **Administrator** prompt");
} else {
hint.step("install LLVM, Strawberry Perl and NASM (https://nasm.us)");
}
hint.run("setx LIBCLANG_PATH \"C:\\Program Files\\LLVM\\bin\"");
hint.step("reopen your shell, so the `setx` variables are picked up");
hint.step("add NASM's install folder to PATH (its installer doesn't)");
hint.step("install \"Desktop development with C++\" from the Visual Studio Installer");
hint.step("build from an \"x64 Native Tools Command Prompt for VS\"");
return hint;
}
let candidates: &[(&str, &str)] = &[
(
"apt-get",
"sudo apt install build-essential pkg-config libxml2-dev libclang-dev perl",
),
(
"dnf",
"sudo dnf install pkgconf-pkg-config gcc make perl libxml2-devel clang-devel",
),
(
"yum",
"sudo yum install pkg-config gcc make perl libxml2-devel clang-devel",
),
(
"zypper",
"sudo zypper install pkg-config gcc make perl libxml2-devel clang-devel",
),
(
"pacman",
"sudo pacman -S pkgconf base-devel perl libxml2 clang",
),
(
"apk",
"sudo apk add build-base pkgconfig perl libxml2-dev clang-dev",
),
];
let mut hint = Hint::new();
for (bin, command) in candidates {
if has(bin) {
hint.run(command);
return hint;
}
}
hint.step(
"install your distribution's pkg-config, libxml2, clang, C compiler, perl and make packages",
);
hint
}
struct Hint {
commands: Vec<String>,
steps: Vec<String>,
}
impl Hint {
fn new() -> Self {
Hint {
commands: Vec::new(),
steps: Vec::new(),
}
}
fn run(&mut self, command: &str) {
self.commands.push(command.to_string());
}
fn step(&mut self, step: &str) {
self.steps.push(step.to_string());
}
}
fn has(bin: &str) -> bool {
let Some(path) = std::env::var_os("PATH") else {
return false;
};
let extensions: Vec<String> = if cfg!(windows) {
let pathext =
std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
std::iter::once(String::new())
.chain(pathext.split(';').map(str::to_string))
.filter(|ext| ext.is_empty() || ext.starts_with('.'))
.collect()
} else {
vec![String::new()]
};
std::env::split_paths(&path).any(|dir| {
extensions.iter().any(|ext| {
let candidate: PathBuf = dir.join(format!("{bin}{ext}"));
candidate.is_file()
})
})
}