use yog_ids::Format;
use std::path::PathBuf;
pub fn codegen(path: &str) -> Result<Codegen, String> {
let file = PathBuf::from(path);
let args: &[&str] = match Format::of_path(&file) {
Some(Format::Ui) => &["ui", "gen"],
Some(Format::Res) => &["res", "check"],
Some(Format::Block | Format::Item) => &["content", "check"],
_ => return Err(format!("not a .yui, .yres, .yblock or .yitem file: {path}")),
};
let mut command = crate::design::this_cli();
command.args(args);
if args[0] == "ui" {
command.arg(&file);
}
let project = file
.ancestors()
.skip(1)
.find(|d| crate::design::project::path(d).is_file());
let dir = (if args[0] != "ui" { project } else { None })
.or(file.parent())
.filter(|d| d.is_dir());
if let Some(dir) = dir {
command.current_dir(dir);
}
let output = command
.output()
.map_err(|e| format!("failed to run yog: {e}"))?;
let log = String::from_utf8_lossy(&output.stderr).into_owned();
let ok = output.status.success();
Ok(Codegen {
generated: log
.lines()
.find_map(|l| l.rsplit_once(" -> ").map(|(_, out)| out.trim().to_string()))
.filter(|_| ok)
.unwrap_or_default(),
error: (!ok).then(|| {
let message = log
.lines()
.map(|l| l.trim_start_matches("yog: error: "))
.collect::<Vec<_>>()
.join("\n");
if message.trim().is_empty() {
format!("yog {} failed ({})", args.join(" "), output.status)
} else {
message.trim().to_string()
}
}),
root: dir.map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(),
log,
})
}
#[derive(serde::Serialize)]
pub struct Codegen {
pub generated: String,
pub error: Option<String>,
pub log: String,
pub root: String,
}