use super::*;
#[derive(serde::Serialize)]
pub(super) struct BuildReport {
pub(super) output: String,
#[serde(flatten)]
pub(super) sizes: BuildSizes,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) max_size: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) inline: Option<InlineReport>,
}
#[derive(serde::Serialize)]
pub(super) struct InlineReport {
pub(super) format: &'static str,
pub(super) text: String,
}
pub(crate) fn build(src: &str, path: &str, o: &Opts) -> Result<ExitCode, String> {
let out = o.out.as_deref().unwrap_or_default();
let (song, diags) = compile(src, o);
print_diagnostics(src, path, &diags);
let Some(song) = song else {
return Ok(ExitCode::from(1));
};
let (bytes, stats) = pikopiko::export::binary::encode_with_stats(&song)
.map_err(|e| ta("cli-err-encode", &[("error", err_text(&e).into())]))?;
std::fs::write(out, &bytes).map_err(|e| write_error(out, e))?;
let report = BuildReport {
output: out.to_string(),
sizes: BuildSizes::new(&song, &stats),
max_size: o.max_size,
inline: o.inline.map(|i| InlineReport {
format: i.name(),
text: i.render(&bytes),
}),
};
let over = o.max_size.filter(|&m| report.sizes.total > m);
if o.json {
println!(
"{}",
serde_json::to_string_pretty(&report).map_err(json_error)?
);
} else {
let parts: Vec<String> = report
.sizes
.tracks
.iter()
.map(|(n, b)| format!("{n} {b}"))
.collect();
let env = if report.sizes.envelopes > 0 {
ta(
"cli-build-envelopes",
&[("bytes", report.sizes.envelopes.to_string().into())],
)
} else {
String::new()
};
eprintln!(
"{}",
ta(
"cli-build-done",
&[
("path", out.into()),
("total", report.sizes.total.to_string().into()),
("header", report.sizes.header.to_string().into()),
("envelopes", env.into()),
("tracks", parts.join(" / ").into()),
("uncompressed", report.sizes.uncompressed.to_string().into()),
]
)
);
}
if let (Some(i), false) = (&report.inline, o.json) {
print!("{}", i.text);
if !i.text.ends_with('\n') {
println!();
}
}
if let Some(max) = over {
eprintln!(
"pikopiko: {}",
ta(
"cli-build-over",
&[
("total", report.sizes.total.to_string().into()),
("max", max.to_string().into()),
("over", (report.sizes.total - max).to_string().into()),
]
)
);
return Ok(ExitCode::from(1));
}
Ok(ExitCode::SUCCESS)
}