native-theme 0.7.2

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
//! Generates the by-name SVG tables for the bundled icon sets from the
//! directory listings under `icons/`, so the tables cannot drift from the
//! files (v0.5.8 spec ยง10.5). No panics: every error is returned to Cargo.

use std::error::Error;
use std::fs;
use std::io::Write;
use std::path::Path;

fn main() -> Result<(), Box<dyn Error>> {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")?;
    let out_dir = std::env::var("OUT_DIR")?;

    for (set, dir, fn_name) in [
        ("Lucide", "lucide", "lucide_svg_by_name"),
        ("Material", "material", "material_svg_by_name"),
    ] {
        let icons_dir = Path::new(&manifest_dir).join("icons").join(dir);
        // A directory path makes Cargo re-run this script when entries are
        // added, removed or modified.
        println!("cargo:rerun-if-changed={}", icons_dir.display());

        let entries = fs::read_dir(&icons_dir)?
            .map(|entry| entry.map(|e| e.file_name().to_string_lossy().into_owned()))
            .collect::<Result<Vec<_>, _>>()?;
        let mut names: Vec<String> = entries
            .into_iter()
            .filter_map(|file| file.strip_suffix(".svg").map(str::to_owned))
            .collect();
        names.sort();

        let mut out = fs::File::create(Path::new(&out_dir).join(format!("{fn_name}.rs")))?;
        writeln!(
            out,
            "// Generated by build.rs from `icons/{dir}/*.svg` ({set}). Do not edit."
        )?;
        writeln!(out, "fn {fn_name}(name: &str) -> Option<&'static [u8]> {{")?;
        writeln!(out, "    match name {{")?;
        for name in &names {
            writeln!(
                out,
                "        {name:?} => Some(include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/icons/{dir}/\", {name:?}, \".svg\"))),"
            )?;
        }
        writeln!(out, "        _ => None,")?;
        writeln!(out, "    }}")?;
        writeln!(out, "}}")?;
    }
    Ok(())
}