Skip to main content

yog_cli/design/
yui_codegen.rs

1//! `.yui` screen files (the screen designer's format) — regenerating their
2//! code (`.yog-build/generated/**/*.g.rs`, what the code-behind pulls in
3//! with `yog_api::ui_include!`) when one is saved, through `yog ui gen` —
4//! and the same for `.yres` resource files (`resources/<Set>.g.rs`,
5//! through `yog res check`).
6
7use yog_ids::Format;
8use std::path::PathBuf;
9
10/// Runs `yog ui gen <path>` in the file's folder, so a saved screen's
11/// generated `foo.g.rs` is current without a full build (`yog` finds the
12/// project from the `yog.toml` above the file). The result carries what
13/// `yog` printed either way — its errors and warnings go to the Error List;
14/// `Err` only when `yog` couldn't run at all.
15pub fn codegen(path: &str) -> Result<Codegen, String> {
16    let file = PathBuf::from(path);
17    let args: &[&str] = match Format::of_path(&file) {
18        Some(Format::Ui) => &["ui", "gen"],
19        // Regenerates `.yog-build/generated/resources/<Set>.g.rs` (and checks the set).
20        Some(Format::Res) => &["res", "check"],
21        // Regenerates `.yog-build/generated/yog-content.g.rs` and its parts (and checks every content file).
22        Some(Format::Block | Format::Item) => &["content", "check"],
23        _ => return Err(format!("not a .yui, .yres, .yblock or .yitem file: {path}")),
24    };
25    let mut command = crate::design::this_cli();
26    command.args(args);
27    if args[0] == "ui" {
28        command.arg(&file);
29    }
30    // `yog res check` / `yog content check` work on the project in the current folder.
31    let project = file
32        .ancestors()
33        .skip(1)
34        .find(|d| crate::design::project::path(d).is_file());
35    let dir = (if args[0] != "ui" { project } else { None })
36        .or(file.parent())
37        .filter(|d| d.is_dir());
38    if let Some(dir) = dir {
39        command.current_dir(dir);
40    }
41    let output = command
42        .output()
43        .map_err(|e| format!("failed to run yog: {e}"))?;
44    let log = String::from_utf8_lossy(&output.stderr).into_owned();
45    let ok = output.status.success();
46    Ok(Codegen {
47        // "==> src/foo.yui -> /project/.yog-build/generated/foo.g.rs"
48        generated: log
49            .lines()
50            .find_map(|l| l.rsplit_once(" -> ").map(|(_, out)| out.trim().to_string()))
51            .filter(|_| ok)
52            .unwrap_or_default(),
53        error: (!ok).then(|| {
54            let message = log
55                .lines()
56                .map(|l| l.trim_start_matches("yog: error: "))
57                .collect::<Vec<_>>()
58                .join("\n");
59            if message.trim().is_empty() {
60                format!("yog {} failed ({})", args.join(" "), output.status)
61            } else {
62                message.trim().to_string()
63            }
64        }),
65        root: dir.map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(),
66        log,
67    })
68}
69
70/// One regeneration: the generated file (empty on failure), the failure's
71/// message, and `yog`'s full output with the folder it ran in — what the
72/// Error List reads the file's errors and warnings from.
73#[derive(serde::Serialize)]
74pub struct Codegen {
75    pub generated: String,
76    pub error: Option<String>,
77    pub log: String,
78    pub root: String,
79}