use std::ffi::OsString;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use compmd_host::{FORMAT, MANIFEST, Manifest, ManifestError};
use crate::build_error::BuildError;
use crate::origin::is_scheme;
const EMBEDDED: &str = "compmd_bundle.rs";
const SERVED: [&str; 2] = ["frames", "packs"];
pub fn bundle(folder: impl AsRef<Path>) {
bundle_with(folder.as_ref(), |name| std::env::var_os(name));
}
fn bundle_with(folder: &Path, var: impl Fn(&str) -> Option<OsString>) {
let (Some(app), Some(out)) = (var("CARGO_MANIFEST_DIR"), var("OUT_DIR")) else {
panic!(
"tauri-plugin-compmd: build::bundle runs in the app's build script, where Cargo sets CARGO_MANIFEST_DIR and OUT_DIR"
);
};
for line in embed(&Path::new(&app).join(folder), Path::new(&out)) {
println!("{line}");
}
}
fn embed(folder: &Path, out: &Path) -> Vec<String> {
let mut said = vec![format!("cargo:rerun-if-changed={}", folder.display())];
let code = match embedding(folder) {
Ok(code) => code,
Err(error @ BuildError::NoBundle(_)) => {
said.push(format!(
"cargo:warning=tauri-plugin-compmd: {error}; the app serves none"
));
NONE.to_owned()
}
Err(error) => panic!("tauri-plugin-compmd: {error}"),
};
if let Err(error) = fs::write(out.join(EMBEDDED), code) {
panic!("tauri-plugin-compmd: the bundle can't be written into OUT_DIR: {error}");
}
said
}
const NONE: &str = "::core::option::Option::None\n";
pub(crate) fn embedding(folder: &Path) -> Result<String, BuildError> {
let manifest = folder.join(MANIFEST);
let Ok(text) = fs::read_to_string(&manifest) else {
return Err(BuildError::NoBundle(folder.to_path_buf()));
};
let parsed = Manifest::parse(&text).map_err(|error| match error {
ManifestError::UnknownFormat { found, .. } => BuildError::Format {
found,
known: FORMAT,
},
other => BuildError::Manifest(other),
})?;
match parsed.scheme() {
None => return Err(BuildError::NoScheme),
Some(scheme) if !is_scheme(scheme) => return Err(BuildError::Scheme(scheme.to_owned())),
Some(_) => {}
}
let mut files = vec![(MANIFEST.to_owned(), manifest)];
for served in SERVED {
collect(&folder.join(served), served, &mut files)?;
}
files.sort();
let mut code = String::from("::core::option::Option::Some(&[\n");
for (path, file) in files {
let _ = writeln!(
code,
" ({path:?}, include_bytes!({:?})),",
file.display().to_string()
);
}
code.push_str("])\n");
Ok(code)
}
fn collect(dir: &Path, at: &str, files: &mut Vec<(String, PathBuf)>) -> Result<(), BuildError> {
if !dir.exists() {
return Ok(());
}
let unreadable = |error: std::io::Error| BuildError::Unreadable {
folder: dir.to_path_buf(),
why: error.to_string(),
};
for entry in fs::read_dir(dir).map_err(unreadable)? {
let entry = entry.map_err(unreadable)?;
let (path, name) = (
entry.path(),
format!("{at}/{}", entry.file_name().to_string_lossy()),
);
if path.is_dir() {
collect(&path, &name, files)?;
} else {
files.push((name, path));
}
}
Ok(())
}
#[cfg(test)]
mod tests;