pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! `library --check <フォルダー>`:利用者の音色集(`pikopiko-tones.toml` と種類ごとの `.mml`)を、
//! 組み込みの音色集と同じ見方で検査する。
//!
//! 何のためにあるか:自作の音色集を配る前に、名前の重なり・解析の誤り・説明の抜け・音量や形が種類の
//! 目安から外れていないか・既存の音色と似すぎていないかを、聴かずに確かめるため(組み込みの音色集は
//! 同じことをテストで見張っている)。誤りは終了コード 1、警告(説明・目安・似すぎ)は終了コードを変えない。
//! 測り方は `tone`・MCP の `measure_tone` と同じ(`pikopiko::report::tone`、種類が測る種類に
//! ない音色は測らず警告だけ)。`--json` は 1 件ずつ `level`・`at`・`message` を持つ配列。

use super::*;
use pikopiko::report::tone::{self, Category};
use pikopiko::synth::tones::user::{pick_description, UserLibrary, WithLibraries};

/// 試聴の音を測るサンプルレート(`tone` と同じ)。
const RATE: u32 = 44_100;
/// 音量が目安の真ん中からこれ(dB)より外れたら知らせる(組み込みの音色集の約束と同じ)。
const GAIN_TOLERANCE_DB: f32 = 0.5;

/// 検査の結果 1 件。
struct Finding {
    error: bool,
    at: String,
    message: String,
}

pub(crate) fn library_check(lib: &UserLibrary, json: bool) -> Result<ExitCode, String> {
    let lang = i18n().lang().to_string();
    let mut found: Vec<Finding> = Vec::new();
    let root = format!("@{}", lib.name);
    if lib.clashes(pikopiko::synth::all()) {
        add(&mut found, true, &root, "cli-check-clash", &[]);
    }
    if pick_description(&lib.description, &lang).is_empty() {
        add(&mut found, false, &root, "cli-check-no-description", &[]);
    }
    let spec = pikopiko::synth::find(pikopiko::synth::all(), &lib.synth);
    if spec.is_none() {
        let names: Vec<&str> = pikopiko::synth::all().iter().map(|s| s.name).collect();
        add(
            &mut found,
            true,
            &root,
            "cli-check-no-synth",
            &[
                ("synth", lib.synth.clone().into()),
                ("names", names.join(", ").into()),
            ],
        );
    }
    let loader = WithLibraries::new(None, std::slice::from_ref(lib));
    let opts = CompileOptions {
        synths: pikopiko::synth::all(),
        include: Some(&loader),
        ..Default::default()
    };
    let mut seen: Vec<String> = Vec::new();
    let mut checked = 0usize;
    for kind in &lib.kinds {
        let file = format!("@{}/{}", lib.name, kind.name);
        if pick_description(&kind.description, &lang).is_empty() {
            add(&mut found, false, &file, "cli-check-no-description", &[]);
        }
        let category = Category::from_name(&kind.name);
        if category.is_none() {
            let names: Vec<&str> = tone::ALL.iter().map(|c| c.name()).collect();
            add(
                &mut found,
                false,
                &file,
                "cli-check-unknown-kind",
                &[("names", names.join(", ").into())],
            );
        }
        for t in kind.tones() {
            let at = format!("{file} ${}", t.name);
            checked += 1;
            if seen.contains(&t.name) {
                add(&mut found, true, &at, "cli-check-dup-tone", &[]);
            } else {
                seen.push(t.name.clone());
            }
            let (Some(spec), Some(cat)) = (spec, category) else {
                // 解析の誤りだけは音源と種類がなくても確かめる
                let mml = format!("#synth {}\n#include \"{file}\"\nA ${} c", lib.synth, t.name);
                let (song, diags) = pikopiko::compile_with(&mml, &opts);
                if song.is_none() {
                    add_compile_error(&mut found, &at, &mml, &diags);
                }
                continue;
            };
            let mml =
                tone::audition_mml(cat, spec.name, &format!("#include \"{file}\"\n${}", t.name));
            let (song, diags) = pikopiko::compile_with(&mml, &opts);
            let Some(song) = song else {
                add_compile_error(&mut found, &at, &mml, &diags);
                continue;
            };
            let mut r = tone::report(cat, &song, mml, RATE);
            pikopiko::synth::tones::compare(&mut r, spec, RATE, 1);
            for d in &r.deviations {
                let range = format!(
                    "{}〜{}",
                    d.min.map_or(String::new(), |v| v.to_string()),
                    d.max.map_or(String::new(), |v| v.to_string())
                );
                found.push(Finding {
                    error: false,
                    at: at.clone(),
                    message: ta(
                        "cli-tone-out",
                        &[
                            ("metric", d.metric.name().into()),
                            ("value", d.value.to_string().into()),
                            ("range", range.into()),
                        ],
                    ),
                });
            }
            if let (Some(db), Some(gain)) = (r.gain_db, r.gain) {
                if db.abs() > GAIN_TOLERANCE_DB {
                    found.push(Finding {
                        error: false,
                        at: at.clone(),
                        message: ta(
                            "cli-check-gain",
                            &[
                                ("db", format!("{db:+.1}").into()),
                                ("gain", gain.to_string().into()),
                            ],
                        ),
                    });
                }
            }
            if let Some(s) = r.similar.first().filter(|s| s.too_close) {
                found.push(Finding {
                    error: false,
                    at: at.clone(),
                    message: ta(
                        "cli-check-too-close",
                        &[
                            ("name", s.name.clone().into()),
                            ("distance", format!("{:.3}", s.distance).into()),
                        ],
                    ),
                });
            }
        }
    }
    let errors = found.iter().filter(|f| f.error).count();
    let warnings = found.len() - errors;
    if json {
        let all: Vec<serde_json::Value> = found
            .iter()
            .map(|f| {
                serde_json::json!({
                    "level": if f.error { "error" } else { "warning" },
                    "at": f.at,
                    "message": f.message,
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&all).map_err(json_error)?
        );
    } else {
        for f in &found {
            let level = t(if f.error {
                "cli-check-level-error"
            } else {
                "cli-check-level-warning"
            });
            println!("{level}: {}: {}", f.at, f.message);
        }
        println!(
            "{}",
            ta(
                "cli-check-summary",
                &[
                    ("tones", checked.to_string().into()),
                    ("errors", errors.to_string().into()),
                    ("warnings", warnings.to_string().into()),
                ]
            )
        );
    }
    Ok(if errors > 0 {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

/// 検査の結果を 1 件足す(文は `key` と `args` から表示の言語で作る)。
fn add(found: &mut Vec<Finding>, error: bool, at: &str, key: &str, args: &[(&str, Arg)]) {
    found.push(Finding {
        error,
        at: at.to_string(),
        message: ta(key, args),
    });
}

/// 解析の誤り(診断)を、検査の結果の 1 件にする(最初の誤りの文を添える)。
fn add_compile_error(found: &mut Vec<Finding>, at: &str, mml: &str, diags: &[Diagnostic]) {
    let first = diags.iter().find(|d| d.is_error());
    let _ = mml;
    found.push(Finding {
        error: true,
        at: at.to_string(),
        message: ta(
            "cli-check-compile",
            &[(
                "error",
                first
                    .map(|d| i18n().diagnostic(d))
                    .unwrap_or_default()
                    .into(),
            )],
        ),
    });
}