Skip to main content

utz_build_cli/cmd/
gen_preset.rs

1//! Generates one preset asset, or every preset, from the canonical
2//! recipe table. The command drives `utz_build::Config::from()` over
3//! `utz_build::presets`, so the recipes exist in exactly one place
4//! and `scripts/gen-presets.sh` cannot drift from the table (the data
5//! crates' build.rs recipe guards verify the result).
6//!
7//! ```text
8//! utz_build_cli gen-preset [tiny|tiny-static|compact|balanced|accurate]
9//! ```
10
11use std::path::PathBuf;
12
13use utz_build::Config;
14use utz_build::presets::{self, Recipe};
15
16#[derive(clap::Args)]
17pub struct Args {
18    /// The preset name; omit it to generate every preset.
19    preset: Option<String>,
20    /// The output path (the default is `utz_data_<preset>/data/<preset>.utz`
21    /// with `-` as `_` in the crate dir, relative to the current directory).
22    #[arg(long, short, requires = "preset")]
23    out: Option<PathBuf>,
24}
25
26/// # Errors
27/// The command fails on an unknown preset name, a dataset load or encode
28/// failure, or an I/O error writing the asset and its guard file.
29pub fn run(args: Args) -> utz_build::Result<()> {
30    if let Some(name) = args.preset {
31        let recipe = presets::by_name(&name).ok_or_else(|| {
32            let known = presets::ALL.map(|recipe| recipe.name).join("|");
33            utz_build::Error::Msg(format!("unknown preset {name:?}: use {known}"))
34        })?;
35        generate(recipe, args.out)
36    } else {
37        for recipe in &presets::ALL {
38            generate(recipe, None)?;
39        }
40        Ok(())
41    }
42}
43
44/// Generates one preset asset, deriving the default output path from the
45/// recipe name when none is given.
46fn generate(recipe: &Recipe, out: Option<PathBuf>) -> utz_build::Result<()> {
47    let out = if let Some(out) = out {
48        out
49    } else {
50        let dir = PathBuf::from(format!("utz_data_{}", recipe.name.replace('-', "_")));
51        if !dir.is_dir() {
52            return Err(utz_build::Error::Msg(format!(
53                "default output {}/data/ expects the μTZ checkout root as the \
54                 current directory; pass --out",
55                dir.display()
56            )));
57        }
58        dir.join("data").join(format!("{}.utz", recipe.name))
59    };
60    let path = Config::from(recipe).out_path(out).generate()?;
61    println!("wrote {}", path.display());
62    Ok(())
63}