use super::*;
pub(crate) fn fmt(
src: &str,
path: &str,
o: &Opts,
width: usize,
normalize: bool,
write: bool,
check: bool,
) -> Result<ExitCode, String> {
use pikopiko::composer::edit::{format, FormatOptions};
let files = match path {
"-" => pikopiko::compiler::include::Files::new("."),
p => pikopiko::compiler::include::Files::beside(p),
};
let opts = CompileOptions {
dialect: o.dialect,
synths: pikopiko::synth::all(),
include: Some(&files),
..Default::default()
};
let out = match format(src, &FormatOptions { width, normalize }, &opts) {
Ok(t) => t,
Err(diags) => {
print_diagnostics(src, path, &diags);
return Ok(ExitCode::from(1));
}
};
let changed = out != src;
if check {
if changed {
eprintln!("{}", ta("cli-fmt-needed", &[("path", path.into())]));
return Ok(ExitCode::from(1));
}
return Ok(ExitCode::SUCCESS);
}
if write {
if changed {
std::fs::write(path, &out).map_err(|e| write_error(path, e))?;
eprintln!("{}", ta("cli-fmt-written", &[("path", path.into())]));
} else {
eprintln!("{}", ta("cli-fmt-unchanged", &[("path", path.into())]));
}
return Ok(ExitCode::SUCCESS);
}
print!("{out}");
Ok(ExitCode::SUCCESS)
}