pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! コマンドライン引数の形(clap)。`pikopiko`([`Cli`])と `pikopiko-mcp`([`McpCli`])。
//!
//! # 何のためにあるか
//!
//! 引数の解析・使い方(`--help`)・使い方の誤りの文を clap に任せ、その文を lingokit で表示の
//! 言語に訳す。ソースに書いた英語の説明(`///`)は訳のキーが無いときの予備で、画面に出る文は
//! `locales/<言語>/cli.ftl` の次のキーから作る(lingokit の約束)。
//!
//! | 対象 | キー |
//! | --- | --- |
//! | コマンドの説明 | `cli-about`・`cli-<サブコマンド>-about` |
//! | 引数の説明 | `cli-<サブコマンド>-arg-<id>`、なければ `cli-arg-<id>`(`id` はフィールド名) |
//! | clap の使い方の誤り | `cli-error-<種類>`(lingokit が英語・日本語の訳を持つ。`.ftl` で上書きできる) |
//!
//! # 守っている約束
//!
//! - 値の範囲と形(`--rate`・`--loops`・`--from`・`--max-size`・`--buffer`・`--dialect`)は、
//!   ここでは文字列のまま受け取り、使う側(`src/main.rs`)が確かめる。clap の値の検査の誤りの文は
//!   値が不正なことしか言えないので、範囲や書き方の例まで出すため(終了コードはどちらも 2)。
//! - `--lang` はどのサブコマンドの前後にも書ける(`global`)。値は [`crate::text::parse_lang`] で
//!   確かめ、対応しない言語は使い方の誤りにする。
//! - `pikopiko-mcp` の文言はキーを `mcp-` で始める約束なので、lingokit の既定のキー
//!   (`cli-about` など、`pikopiko` と同じ名前になる)は使わず、[`mcp_command`] で差し替える
//!   (`--lang`・`--help`・`--version` の説明と見出し・使い方の誤りは `pikopiko` と共有する)。

use clap::{Args, Parser, Subcommand};
use lingokit::Localizer;

/// `pikopiko` の引数。
#[derive(Debug, Parser)]
#[command(
    name = "pikopiko",
    version,
    about = "parse MML and play chiptunes",
    arg_required_else_help = true
)]
pub struct Cli {
    /// Display language (en / ja). Takes precedence over PIKOPIKO_LANG
    #[arg(long, global = true, value_name = "LANG", value_parser = crate::text::parse_lang)]
    pub lang: Option<&'static str>,
    /// Definition file of derived synths (TOML; repeatable; also PIKOPIKO_SYNTHS)
    #[arg(long, global = true, value_name = "FILE")]
    pub synth_def: Vec<String>,
    /// サブコマンド。
    #[command(subcommand)]
    pub command: Command,
}

/// `pikopiko` のサブコマンド。
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Check the grammar and print diagnostics
    Check {
        #[command(flatten)]
        input: Input,
        /// Print JSON
        #[arg(long)]
        json: bool,
    },
    /// Tidy whitespace and wrap long lines (the song's output never changes)
    Fmt {
        #[command(flatten)]
        input: Input,
        /// Overwrite the file instead of printing
        #[arg(long, conflicts_with = "check")]
        write: bool,
        /// Exit with 1 if the file needs formatting (prints nothing)
        #[arg(long)]
        check: bool,
        /// Wrap track lines longer than this many characters (0 = never; default 100)
        #[arg(long, value_name = "N")]
        width: Option<String>,
        /// Rewrite the abbreviations mp / ep / en (and mpof / epof / enof) in the @ form (@vib, @detune, @arp)
        #[arg(long)]
        normalize: bool,
    },
    /// Print the track count, duration, note range and more
    Info {
        #[command(flatten)]
        input: Input,
        /// Print JSON
        #[arg(long)]
        json: bool,
    },
    /// Write a WAV file (16-bit stereo)
    Render {
        #[command(flatten)]
        input: Input,
        /// Output file
        #[arg(short = 'o', long, value_name = "OUT.wav")]
        output: String,
        /// Sample rate (8000 to 192000, default 44100)
        #[arg(long, value_name = "HZ")]
        rate: Option<String>,
        /// Also write N passes back to the loop point (1 to 1000)
        #[arg(long, value_name = "N")]
        loops: Option<String>,
        /// Output EQ applied before writing (famicom, small-speaker, subsonic, lowcut:150, peak:2500:-4, ... joined with ,)
        #[arg(long, value_name = "EQ")]
        eq: Option<String>,
        /// Fade out the last SECS seconds with a cosine curve (0.1 to 60)
        #[arg(long, value_name = "SECS")]
        fade: Option<String>,
        /// Gain the whole render to a target integrated loudness in LUFS (-40 to -5; peaks stay under -1 dBFS)
        #[arg(long, value_name = "LUFS", allow_hyphen_values = true)]
        lufs: Option<String>,
        /// Also write one WAV per track into DIR (`<name>_<track>.wav`, through the same master processing)
        #[arg(long, value_name = "DIR")]
        stems: Option<String>,
        /// Print per-section loudness, band and width numbers of the rendered song (sections start at @mark, or every 8 bars)
        #[arg(long)]
        report: bool,
        /// With --report, print JSON
        #[arg(long)]
        json: bool,
        /// Compress a .vgm output with gzip (a .vgz name does this by itself)
        #[arg(long)]
        vgm_gzip: bool,
    },
    /// Convert to the event binary and print the size breakdown
    Build {
        #[command(flatten)]
        input: Input,
        /// Output file
        #[arg(short = 'o', long, value_name = "OUT.bin")]
        output: String,
        /// Print JSON
        #[arg(long)]
        json: bool,
        /// Size budget in bytes (16k = 16384)
        #[arg(long, value_name = "BYTES")]
        max_size: Option<String>,
        /// Also print the binary as text: hex, base64 or rust (a `pub static SONG: [u8; N]`)
        #[arg(long, value_name = "FORMAT")]
        inline: Option<String>,
    },
    /// Print the MML grammar specification (for generative AI)
    Spec,
    /// List the synths with their tones, parameters and options
    Synths {
        /// Print JSON
        #[arg(long)]
        json: bool,
    },
    /// List the tones of the built-in tone libraries (#include "@va/bass")
    Library {
        /// Only this library (@va, @va/bass)
        #[arg(value_name = "LIBRARY")]
        library: Option<String>,
        /// Print JSON
        #[arg(long)]
        json: bool,
        /// Folder of your own tone library (repeatable; also PIKOPIKO_TONES)
        #[arg(long, value_name = "DIR")]
        tones: Vec<String>,
        /// Check your own tone library folder (names, errors, descriptions, targets, closeness)
        #[arg(long, value_name = "DIR")]
        check: Option<String>,
    },
    /// Convert a Yamaha DX7 patch (SysEx) to a va @15 tone (MML macro lines)
    Dx7 {
        /// DX7 file (a 32-voice bank .syx, a single-voice dump, or a packed voice; - for standard input is not supported)
        #[arg(value_name = "FILE")]
        file: String,
        /// Only this voice (1-based; a bank has 32)
        #[arg(long, value_name = "N")]
        voice: Option<String>,
        /// Only list the voice names
        #[arg(long)]
        list: bool,
        /// Macro name for the converted voice (needs --voice, or a single-voice file)
        #[arg(long, value_name = "NAME")]
        name: Option<String>,
    },
    /// Play one timbre with the audition phrase of a category and measure it
    Tone {
        /// Category (lead, pluck, pad, chord, bell, keys, vocal, strings, guitar, bass, kick, snare, hat, crash, tom, fx)
        #[arg(value_name = "CATEGORY")]
        category: String,
        /// File with the timbre (@n %... or a macro line $name = ...; - for standard input)
        #[arg(value_name = "FILE", required_unless_present = "reference")]
        file: Option<String>,
        /// Synth to play it with (default va)
        #[arg(long, value_name = "NAME")]
        synth: Option<String>,
        /// Also write the audition as a WAV file (MP3 if the name ends in .mp3)
        #[arg(short = 'o', long, value_name = "OUT.wav|OUT.mp3")]
        output: Option<String>,
        /// Print JSON
        #[arg(long)]
        json: bool,
        /// Also measure aliasing (plays the audition again at 4 times the rate)
        #[arg(long)]
        alias: bool,
        /// Reference sound (WAV) to compare with
        #[arg(long = "ref", value_name = "REF.wav")]
        reference: Option<String>,
        /// Start of the reference to use (seconds from the head of the file)
        #[arg(long, value_name = "SECS", requires = "reference")]
        ref_from: Option<String>,
        /// End of the reference to use (seconds from the head of the file)
        #[arg(long, value_name = "SECS", requires = "reference")]
        ref_to: Option<String>,
        /// Where the note is released in the reference (seconds from the head of the file)
        #[arg(long, value_name = "SECS", requires = "reference")]
        ref_release: Option<String>,
        /// Fundamental of the reference as a note name (c5, f+4, ...)
        #[arg(long, value_name = "NOTE", requires = "reference")]
        ref_note: Option<String>,
    },
    /// Play it now
    Play {
        #[command(flatten)]
        input: Input,
        /// Play only this track
        #[arg(long, value_name = "NAME")]
        track: Option<String>,
        /// Start position (90, 1:30, 1:30.5, ...)
        #[arg(long, value_name = "TIME")]
        from: Option<String>,
        /// Loop forever (Ctrl-C to stop)
        #[arg(long = "loop", conflicts_with = "loops")]
        looping: bool,
        /// Loop N times (1 to 1000)
        #[arg(long, value_name = "N")]
        loops: Option<String>,
        /// Output buffer size in frames (16 to 16384)
        #[arg(long, value_name = "FRAMES")]
        buffer: Option<String>,
        /// Reload when the file (or an included file) changes, keeping the position (Ctrl-C to stop)
        #[arg(long)]
        watch: bool,
        /// How often to check the files with --watch, in milliseconds (50 to 5000, default 250)
        #[arg(long, value_name = "MS", requires = "watch")]
        watch_interval: Option<String>,
    },
}

/// 曲を読むサブコマンドに共通の引数。
#[derive(Debug, Args)]
pub struct Input {
    /// MML file (- for standard input)
    #[arg(value_name = "FILE")]
    pub file: String,
    /// Default dialect (pikopiko / classic / classic-reversed)
    #[arg(long, value_name = "NAME")]
    pub dialect: Option<String>,
    /// Folder of your own tone library (read as #include "@name/kind"; repeatable; also PIKOPIKO_TONES)
    #[arg(long, value_name = "DIR")]
    pub tones: Vec<String>,
}

/// `pikopiko` の使い方(表示の言語に訳したもの)。最後に、標準入力・言語の決め方・終了コードの
/// 案内(`cli-after-help`)を付ける。
pub fn command(loc: &Localizer) -> clap::Command {
    lingokit::clap::command::<Cli>(loc).after_help(loc.fmt("cli-after-help", None))
}

/// `pikopiko-mcp` の引数。
#[derive(Debug, Parser)]
#[command(name = "pikopiko-mcp", version, about = "MCP server for pikopiko")]
pub struct McpCli {
    /// Folder that render_mml writes to
    #[arg(long, value_name = "DIR")]
    pub out_dir: Option<std::path::PathBuf>,
    /// Maximum length that render_mml writes (seconds, default 120)
    #[arg(long, value_name = "SEC")]
    pub max_seconds: Option<String>,
    /// Largest binary that build_mml returns as text (bytes, 32k = 32768)
    #[arg(long, value_name = "BYTES")]
    pub max_inline: Option<String>,
    /// Display language (en / ja). Takes precedence over PIKOPIKO_LANG
    #[arg(long, value_name = "LANG", value_parser = crate::text::parse_lang)]
    pub lang: Option<&'static str>,
    /// Folder of your own tone library (repeatable; also PIKOPIKO_TONES)
    #[arg(long, value_name = "DIR")]
    pub tones: Vec<String>,
    /// Folder of reference sounds (WAV) that measure_tone can compare with (also PIKOPIKO_MCP_REF_DIR)
    #[arg(long, value_name = "DIR")]
    pub ref_dir: Option<std::path::PathBuf>,
    /// Definition file of derived synths (TOML; repeatable; also PIKOPIKO_SYNTHS)
    #[arg(long, value_name = "FILE")]
    pub synth_def: Vec<String>,
    /// Serve over Streamable HTTP at this address instead of standard input/output (needs the mcp-http feature)
    #[arg(long, value_name = "ADDR:PORT")]
    pub http: Option<String>,
    /// Bearer token that HTTP clients must send (also PIKOPIKO_MCP_TOKEN). Required unless the address is loopback
    #[arg(long, value_name = "TOKEN")]
    pub token: Option<String>,
    /// Host name the HTTP server accepts in the Host header (repeatable; for serving beyond localhost)
    #[arg(long, value_name = "HOST")]
    pub allow_host: Vec<String>,
    /// How many requests the HTTP server handles at once (default 4)
    #[arg(long, value_name = "N")]
    pub max_concurrency: Option<String>,
}

/// `pikopiko-mcp` の使い方(表示の言語に訳したもの)。説明は `mcp-…` のキー(`locales/<言語>/mcp.ftl`)。
///
/// 引数の説明は lingokit で訳す前に入れる(clap は組み立てた後の `mut_arg` を受け付けないため)。
/// `--lang` の説明は `pikopiko` と同じ `cli-arg-lang`。コマンドの説明と最後の案内は、lingokit が
/// `cli-about`(`pikopiko` の説明)を入れた後で差し替える。
pub fn mcp_command(loc: &Localizer) -> clap::Command {
    let cmd = <McpCli as clap::CommandFactory>::command()
        .mut_arg("out_dir", |a| a.help(loc.fmt("mcp-arg-out-dir", None)))
        .mut_arg("max_seconds", |a| {
            a.help(loc.fmt("mcp-arg-max-seconds", None))
        })
        .mut_arg("max_inline", |a| {
            a.help(loc.fmt("mcp-arg-max-inline", None))
        })
        .mut_arg("tones", |a| a.help(loc.fmt("mcp-arg-tones", None)))
        .mut_arg("ref_dir", |a| a.help(loc.fmt("mcp-arg-ref_dir", None)))
        .mut_arg("synth_def", |a| a.help(loc.fmt("mcp-arg-synth_def", None)))
        .mut_arg("http", |a| a.help(loc.fmt("mcp-arg-http", None)))
        .mut_arg("token", |a| a.help(loc.fmt("mcp-arg-token", None)))
        .mut_arg("allow_host", |a| {
            a.help(loc.fmt("mcp-arg-allow_host", None))
        })
        .mut_arg("max_concurrency", |a| {
            a.help(loc.fmt("mcp-arg-max_concurrency", None))
        });
    lingokit::clap::localize_command(cmd, loc)
        .about(loc.fmt("mcp-about", None))
        .after_help(format!(
            "{}\n\n{}\n  {{ \"mcpServers\": {{ \"pikopiko\": {{ \"command\": \"pikopiko-mcp\", \"args\": [\"--out-dir\", \"/path/to/out\"] }} }} }}",
            loc.fmt("mcp-after-help", None),
            loc.fmt("mcp-config-example", None)
        ))
}

/// 引数を読み、表示の言語の文言の口と一緒に返す。使い方の表示(`--help`・`--version`)と使い方の
/// 誤りは、ここで表示して終わる(誤りは終了コード 2)。
///
/// 言語は、clap で読む前に `--lang` を探して決める(使い方の誤りの文も選んだ言語にするため)。
/// 決め方は [`crate::text::requested`]。
pub fn parse<C: clap::FromArgMatches>(
    build: fn(&Localizer) -> clap::Command,
) -> (C, crate::text::Texts) {
    let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
    let cli_lang = lingokit::locale::pre_scan_lang(args.clone());
    let loc = Localizer::new(
        &crate::LOCALES,
        &crate::text::requested(cli_lang.as_deref()),
    );
    let m = build(&loc)
        .try_get_matches_from(args)
        .unwrap_or_else(|e| lingokit::clap::exit_with_clap_error(e, &loc));
    let c =
        C::from_arg_matches(&m).unwrap_or_else(|e| lingokit::clap::exit_with_clap_error(e, &loc));
    (c, crate::text::Texts::new(loc))
}