use std::path::PathBuf;
use yog_ids::Format;
pub(crate) 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::sources::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, problems) = crate::diagnostics::collected(&mut command)
.map_err(|e| format!("failed to run yog: {e}"))?;
let failed = || {
let errors: Vec<String> = problems
.iter()
.filter(|d| d.is_error())
.map(ToString::to_string)
.collect();
if errors.is_empty() {
format!("yog {} failed ({})", args.join(" "), output.status)
} else {
errors.join("\n")
}
};
Ok(Codegen {
error: (!output.status.success()).then(failed),
root: project
.map(|d| d.to_string_lossy().into_owned())
.unwrap_or_default(),
problems,
})
}
#[derive(yog_data::Schema)]
pub(crate) struct Codegen {
pub(crate) error: Option<String>,
pub(crate) problems: Vec<yog_data::Diagnostic>,
pub(crate) root: String,
}