pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! `library`:音色集(`#include "@va/bass"`)を見る。
//!
//! 音色集は音源の組み込みの音色の定義を種類ごとのファイルにまとめたもの。曲では `#include` で読み、
//! トラックで `$名前` と呼ぶ。`library` は、どのファイルにどの音色があるかを、読み込みの行と
//! 一緒に出す(人が選んで曲に書けるように)。音色 1 つを試聴フレーズで鳴らして測るのは `tone`。`--json` の形は MCP の `list_synths` の `library` と同じ。

use super::*;

/// `@名前/種類` の絞り込みの `種類` の部分(なければ `None`)。
fn file_want(want: Option<&str>) -> Option<&str> {
    want.and_then(|w| w.split_once('/')).map(|(_, f)| f)
}

/// 絞り込みの種類があり、`file`(`@名前/種類`)がそれと違うなら真(除外する)。
fn self_file(want: Option<&str>, file: &str) -> bool {
    want.is_some_and(|f| !file.ends_with(&format!("/{f}")))
}

/// 音色集の音色を一覧にする。`library` は `@va`・`va`(音源)か `@va/bass`(ファイル)で絞る。
pub(crate) fn library(
    library: Option<&str>,
    json: bool,
    user: &[pikopiko::synth::tones::user::UserLibrary],
) -> Result<(), String> {
    let tr = i18n();
    let list = synth_catalog_with(pikopiko::synth::all(), tr.lang(), &mut |k| {
        tr.override_text(k)
    });
    let want = library.map(|l| l.strip_prefix('@').unwrap_or(l));
    let (synth, file) = match want {
        Some(w) => match w.split_once('/') {
            Some((s, f)) => (Some(s), Some(f)),
            None => (Some(w), None),
        },
        None => (None, None),
    };
    let mut found = Vec::new();
    for c in list.iter().filter(|c| !c.library.is_empty()) {
        if synth.is_some_and(|s| s != c.name && !c.aliases.contains(&s)) {
            continue;
        }
        for t in &c.library {
            if file.is_some_and(|f| t.file != format!("@{}/{f}", c.name)) {
                continue;
            }
            found.push(t);
        }
    }
    // 利用者の音色集(`--tones`)。説明は種類の説明(表示の言語、なければ英語)。形は組み込みと同じ
    let lang = tr.lang();
    let mut mine: Vec<(String, String, String, String)> = Vec::new();
    for lib in user {
        if synth.is_some_and(|s| s != lib.name) {
            continue;
        }
        for k in &lib.kinds {
            let file = format!("@{}/{}", lib.name, k.name);
            if self_file(file_want(want), &file) {
                continue;
            }
            let desc = pikopiko::synth::tones::user::pick_description(&k.description, lang);
            for t in k.tones() {
                mine.push((file.clone(), t.kind, t.name, desc.to_string()));
            }
        }
    }
    if found.is_empty() && mine.is_empty() {
        if let Some(l) = library {
            let names: Vec<String> = list
                .iter()
                .flat_map(|c| c.library.iter().map(|t| t.file.clone()))
                .chain(user.iter().flat_map(|u| {
                    u.kinds
                        .iter()
                        .map(|k| format!("@{}/{}", u.name, k.name))
                        .collect::<Vec<_>>()
                }))
                .fold(Vec::new(), |mut v, f| {
                    if !v.contains(&f) {
                        v.push(f);
                    }
                    v
                });
            return Err(ta(
                "cli-err-unknown-library",
                &[("name", l.into()), ("names", names.join(", ").into())],
            ));
        }
    }
    if json {
        let mut all: Vec<serde_json::Value> = found
            .iter()
            .filter_map(|t| serde_json::to_value(t).ok())
            .collect();
        all.extend(mine.iter().map(|(file, kind, name, description)| {
            serde_json::json!({
                "name": name,
                "kind": kind,
                "file": file,
                "description": description,
                "source": "user",
            })
        }));
        println!("{}", serde_json::to_string_pretty(&all).unwrap_or_default());
        return Ok(());
    }
    let mut last = String::new();
    for t in &found {
        if t.file != last {
            if !last.is_empty() {
                println!();
            }
            println!("#include \"{}\"", t.file);
            last = t.file.clone();
        }
        println!("  [{}] ${}: {}", t.kind, t.name, t.description);
    }
    if !mine.is_empty() {
        if !found.is_empty() {
            println!();
        }
        println!("; {}", t("cli-library-user-header"));
        let mut last = String::new();
        for (file, kind, name, desc) in &mine {
            if *file != last {
                println!("#include \"{file}\"");
                last = file.clone();
            }
            println!("  [{kind}] ${name}: {desc}");
        }
    }
    Ok(())
}