pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! `fmt`:MML の整形(空白と折り返しだけ。曲の中身は変えない)。
//!
//! 整形そのものは `pikopiko::composer::edit::format`(展開後の曲が前後で同じになることを確かめる)。
//! ここはファイルの読み書きと終了コードを受け持つ:既定は標準出力に整形後を出す、`--write` は
//! 変わるときだけ上書き、`--check` は整形が要るなら終了コード 1(何も書かない)。
//! 誤りのある曲は整形せず、診断を出して終了コード 1。

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)
}