xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / gen.rs

1.9 KB
1// Writes $OUT_DIR/widgets.rs: the API, one module per widgets/<name>.rs, ALL and ABOUT.
2// `api` is how the API comes in: the preview compiles api.rs itself (and defines `HostState:
3// api::Host`, the state every handler gets); the app's widgets build uses the app's.
4// Shared by both build.rs files with include!, so keep it dependency free.
5fn generate_widgets(lib: &std::path::Path, api: Option<&str>) {
6    let dir = lib.join("widgets");
7    println!("cargo:rerun-if-changed={}", dir.display());
8    println!("cargo:rerun-if-changed={}", lib.join("api.rs").display());
9    let mut names: Vec<String> = std::fs::read_dir(&dir).into_iter().flatten().flatten()
10        .filter_map(|e| { let p = e.path(); (p.extension()? == "rs").then_some(p.file_stem()?.to_str()?.to_owned()) })
11        .collect();
12    names.sort();
13    let mut out = match api {
14        Some(line) => format!("{line}\n"),
15        None => format!("#[allow(dead_code)]\n#[path = {:?}] pub mod api;\n", lib.join("api.rs")),
16    };
17    for n in &names { out += &format!("#[path = {:?}] pub mod {n};\n", dir.join(format!("{n}.rs"))); }
18    // A file without `pub const WIDGET` is a helper module the widgets share, not a kind.
19    let src = |n: &str| std::fs::read_to_string(dir.join(format!("{n}.rs"))).unwrap_or_default();
20    names.retain(|n| src(n).contains("pub const WIDGET"));
21    out += "pub const ALL: &[(&str, &api::Widget)] = &[";
22    for n in &names { out += &format!("({n:?}, &{n}::WIDGET), "); }
23    out += "];\npub const ABOUT: &[(&str, &str)] = &[";
24    for n in &names {
25        // The first paragraph of the file's `//!` comment.
26        let src = src(n);
27        let about: Vec<&str> = src.lines().map_while(|l| l.strip_prefix("//!")).map(str::trim).take_while(|l| !l.is_empty()).collect();
28        out += &format!("({n:?}, {:?}), ", about.join(" "));
29    }
30    out += "];\n";
31    std::fs::write(std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("widgets.rs"), out).unwrap();
32}