use anyhow::{anyhow, Result};
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use walkdir::WalkDir;
fn path_ignore(path: &Path) -> bool {
path.components().any(|component| {
match component {
Component::Prefix(_) => true,
Component::RootDir => true,
Component::CurDir => true,
Component::ParentDir => true,
Component::Normal(part) => {
if let Some(part) = part.to_str() {
part.starts_with('.')
|| part.ends_with('~')
|| part.ends_with(".bak")
|| part == "__pycache__"
} else {
true
}
}
}
})
}
fn gather_share_files() -> Result<Vec<PathBuf>> {
let base_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("share");
println!("cargo:rerun-if-changed={}", base_path.display());
let mut ret = Vec::new();
for entry in WalkDir::new(&base_path) {
let entry = entry?;
let entry_path = entry.path().strip_prefix(&base_path)?;
if entry_path.components().count() == 0 || path_ignore(entry_path) {
continue;
}
if entry.file_type().is_dir() {
println!("cargo:rerun-if-changed={}", entry.path().display());
continue;
}
if entry.file_type().is_symlink() {
let target = std::fs::read_link(entry.path())?;
println!("cargo:rerun-if-changed={}", target.display());
}
println!("cargo:rerun-if-changed={}", entry.path().display());
ret.push(entry_path.into());
}
if ret.is_empty() {
return Err(anyhow!(
"Unable to find any resources in `{}`",
base_path.display()
));
}
Ok(ret)
}
fn write_out_resource_file<'a>(paths: impl Iterator<Item = &'a Path>) -> Result<()> {
let mut out_path: PathBuf = std::env::var("OUT_DIR")?.into();
out_path.push("embedded_files.rs");
let mut fh = std::fs::File::create(out_path)?;
writeln!(fh, "&[")?;
for entry in paths {
let sharepath = Path::new("/share").join(entry);
writeln!(
fh,
r#"({:?}, include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), {:?}))),"#,
entry.display(),
sharepath.display()
)?;
}
writeln!(fh, "]")?;
fh.flush()?;
Ok(())
}
fn adopt_env_var(var: &str, def: &str) {
println!("cargo:rerun-if-env-changed=SUBPLOT_{var}");
if let Ok(value) = std::env::var(format!("SUBPLOT_{var}")) {
println!("cargo:rustc-env=BUILTIN_{var}={value}",);
} else {
println!("cargo:rustc-env=BUILTIN_{var}={def}");
}
}
fn main() {
println!("cargo:rerun-if-env-changed=DEB_BUILD_OPTIONS");
let paths = gather_share_files().expect("Unable to scan the share tree");
write_out_resource_file(paths.iter().map(PathBuf::as_path))
.expect("Unable to write the resource file out");
adopt_env_var("DOT_PATH", "dot");
adopt_env_var("PLANTUML_JAR_PATH", "/usr/share/plantuml/plantuml.jar");
adopt_env_var("JAVA_PATH", "java");
}