pikopiko_cli/args.rs
1//! コマンドライン引数の形(clap)。`pikopiko`([`Cli`])と `pikopiko-mcp`([`McpCli`])。
2//!
3//! # 何のためにあるか
4//!
5//! 引数の解析・使い方(`--help`)・使い方の誤りの文を clap に任せ、その文を lingokit で表示の
6//! 言語に訳す。ソースに書いた英語の説明(`///`)は訳のキーが無いときの予備で、画面に出る文は
7//! `locales/<言語>/cli.ftl` の次のキーから作る(lingokit の約束)。
8//!
9//! | 対象 | キー |
10//! | --- | --- |
11//! | コマンドの説明 | `cli-about`・`cli-<サブコマンド>-about` |
12//! | 引数の説明 | `cli-<サブコマンド>-arg-<id>`、なければ `cli-arg-<id>`(`id` はフィールド名) |
13//! | clap の使い方の誤り | `cli-error-<種類>`(lingokit が英語・日本語の訳を持つ。`.ftl` で上書きできる) |
14//!
15//! # 守っている約束
16//!
17//! - 値の範囲と形(`--rate`・`--loops`・`--from`・`--max-size`・`--buffer`・`--dialect`)は、
18//! ここでは文字列のまま受け取り、使う側(`src/main.rs`)が確かめる。clap の値の検査の誤りの文は
19//! 値が不正なことしか言えないので、範囲や書き方の例まで出すため(終了コードはどちらも 2)。
20//! - `--lang` はどのサブコマンドの前後にも書ける(`global`)。値は [`crate::text::parse_lang`] で
21//! 確かめ、対応しない言語は使い方の誤りにする。
22//! - `pikopiko-mcp` の文言はキーを `mcp-` で始める約束なので、lingokit の既定のキー
23//! (`cli-about` など、`pikopiko` と同じ名前になる)は使わず、[`mcp_command`] で差し替える
24//! (`--lang`・`--help`・`--version` の説明と見出し・使い方の誤りは `pikopiko` と共有する)。
25
26use clap::{Args, Parser, Subcommand};
27use lingokit::Localizer;
28
29/// `pikopiko` の引数。
30#[derive(Debug, Parser)]
31#[command(
32 name = "pikopiko",
33 version,
34 about = "parse MML and play chiptunes",
35 arg_required_else_help = true
36)]
37pub struct Cli {
38 /// Display language (en / ja). Takes precedence over PIKOPIKO_LANG
39 #[arg(long, global = true, value_name = "LANG", value_parser = crate::text::parse_lang)]
40 pub lang: Option<&'static str>,
41 /// Definition file of derived synths (TOML; repeatable; also PIKOPIKO_SYNTHS)
42 #[arg(long, global = true, value_name = "FILE")]
43 pub synth_def: Vec<String>,
44 /// サブコマンド。
45 #[command(subcommand)]
46 pub command: Command,
47}
48
49/// `pikopiko` のサブコマンド。
50#[derive(Debug, Subcommand)]
51pub enum Command {
52 /// Check the grammar and print diagnostics
53 Check {
54 #[command(flatten)]
55 input: Input,
56 /// Print JSON
57 #[arg(long)]
58 json: bool,
59 },
60 /// Tidy whitespace and wrap long lines (the song's output never changes)
61 Fmt {
62 #[command(flatten)]
63 input: Input,
64 /// Overwrite the file instead of printing
65 #[arg(long, conflicts_with = "check")]
66 write: bool,
67 /// Exit with 1 if the file needs formatting (prints nothing)
68 #[arg(long)]
69 check: bool,
70 /// Wrap track lines longer than this many characters (0 = never; default 100)
71 #[arg(long, value_name = "N")]
72 width: Option<String>,
73 /// Rewrite the abbreviations mp / ep / en (and mpof / epof / enof) in the @ form (@vib, @detune, @arp)
74 #[arg(long)]
75 normalize: bool,
76 },
77 /// Print the track count, duration, note range and more
78 Info {
79 #[command(flatten)]
80 input: Input,
81 /// Print JSON
82 #[arg(long)]
83 json: bool,
84 },
85 /// Write a WAV file (16-bit stereo)
86 Render {
87 #[command(flatten)]
88 input: Input,
89 /// Output file
90 #[arg(short = 'o', long, value_name = "OUT.wav")]
91 output: String,
92 /// Sample rate (8000 to 192000, default 44100)
93 #[arg(long, value_name = "HZ")]
94 rate: Option<String>,
95 /// Also write N passes back to the loop point (1 to 1000)
96 #[arg(long, value_name = "N")]
97 loops: Option<String>,
98 /// Output EQ applied before writing (famicom, small-speaker, subsonic, lowcut:150, peak:2500:-4, ... joined with ,)
99 #[arg(long, value_name = "EQ")]
100 eq: Option<String>,
101 /// Fade out the last SECS seconds with a cosine curve (0.1 to 60)
102 #[arg(long, value_name = "SECS")]
103 fade: Option<String>,
104 /// Gain the whole render to a target integrated loudness in LUFS (-40 to -5; peaks stay under -1 dBFS)
105 #[arg(long, value_name = "LUFS", allow_hyphen_values = true)]
106 lufs: Option<String>,
107 /// Also write one WAV per track into DIR (`<name>_<track>.wav`, through the same master processing)
108 #[arg(long, value_name = "DIR")]
109 stems: Option<String>,
110 /// Print per-section loudness, band and width numbers of the rendered song (sections start at @mark, or every 8 bars)
111 #[arg(long)]
112 report: bool,
113 /// With --report, print JSON
114 #[arg(long)]
115 json: bool,
116 /// Compress a .vgm output with gzip (a .vgz name does this by itself)
117 #[arg(long)]
118 vgm_gzip: bool,
119 },
120 /// Convert to the event binary and print the size breakdown
121 Build {
122 #[command(flatten)]
123 input: Input,
124 /// Output file
125 #[arg(short = 'o', long, value_name = "OUT.bin")]
126 output: String,
127 /// Print JSON
128 #[arg(long)]
129 json: bool,
130 /// Size budget in bytes (16k = 16384)
131 #[arg(long, value_name = "BYTES")]
132 max_size: Option<String>,
133 /// Also print the binary as text: hex, base64 or rust (a `pub static SONG: [u8; N]`)
134 #[arg(long, value_name = "FORMAT")]
135 inline: Option<String>,
136 },
137 /// Print the MML grammar specification (for generative AI)
138 Spec,
139 /// List the synths with their tones, parameters and options
140 Synths {
141 /// Print JSON
142 #[arg(long)]
143 json: bool,
144 },
145 /// List the tones of the built-in tone libraries (#include "@va/bass")
146 Library {
147 /// Only this library (@va, @va/bass)
148 #[arg(value_name = "LIBRARY")]
149 library: Option<String>,
150 /// Print JSON
151 #[arg(long)]
152 json: bool,
153 /// Folder of your own tone library (repeatable; also PIKOPIKO_TONES)
154 #[arg(long, value_name = "DIR")]
155 tones: Vec<String>,
156 /// Check your own tone library folder (names, errors, descriptions, targets, closeness)
157 #[arg(long, value_name = "DIR")]
158 check: Option<String>,
159 },
160 /// Convert a Yamaha DX7 patch (SysEx) to a va @15 tone (MML macro lines)
161 Dx7 {
162 /// DX7 file (a 32-voice bank .syx, a single-voice dump, or a packed voice; - for standard input is not supported)
163 #[arg(value_name = "FILE")]
164 file: String,
165 /// Only this voice (1-based; a bank has 32)
166 #[arg(long, value_name = "N")]
167 voice: Option<String>,
168 /// Only list the voice names
169 #[arg(long)]
170 list: bool,
171 /// Macro name for the converted voice (needs --voice, or a single-voice file)
172 #[arg(long, value_name = "NAME")]
173 name: Option<String>,
174 },
175 /// Play one timbre with the audition phrase of a category and measure it
176 Tone {
177 /// Category (lead, pluck, pad, chord, bell, keys, vocal, strings, guitar, bass, kick, snare, hat, crash, tom, fx)
178 #[arg(value_name = "CATEGORY")]
179 category: String,
180 /// File with the timbre (@n %... or a macro line $name = ...; - for standard input)
181 #[arg(value_name = "FILE", required_unless_present = "reference")]
182 file: Option<String>,
183 /// Synth to play it with (default va)
184 #[arg(long, value_name = "NAME")]
185 synth: Option<String>,
186 /// Also write the audition as a WAV file (MP3 if the name ends in .mp3)
187 #[arg(short = 'o', long, value_name = "OUT.wav|OUT.mp3")]
188 output: Option<String>,
189 /// Print JSON
190 #[arg(long)]
191 json: bool,
192 /// Also measure aliasing (plays the audition again at 4 times the rate)
193 #[arg(long)]
194 alias: bool,
195 /// Reference sound (WAV) to compare with
196 #[arg(long = "ref", value_name = "REF.wav")]
197 reference: Option<String>,
198 /// Start of the reference to use (seconds from the head of the file)
199 #[arg(long, value_name = "SECS", requires = "reference")]
200 ref_from: Option<String>,
201 /// End of the reference to use (seconds from the head of the file)
202 #[arg(long, value_name = "SECS", requires = "reference")]
203 ref_to: Option<String>,
204 /// Where the note is released in the reference (seconds from the head of the file)
205 #[arg(long, value_name = "SECS", requires = "reference")]
206 ref_release: Option<String>,
207 /// Fundamental of the reference as a note name (c5, f+4, ...)
208 #[arg(long, value_name = "NOTE", requires = "reference")]
209 ref_note: Option<String>,
210 },
211 /// Play it now
212 Play {
213 #[command(flatten)]
214 input: Input,
215 /// Play only this track
216 #[arg(long, value_name = "NAME")]
217 track: Option<String>,
218 /// Start position (90, 1:30, 1:30.5, ...)
219 #[arg(long, value_name = "TIME")]
220 from: Option<String>,
221 /// Loop forever (Ctrl-C to stop)
222 #[arg(long = "loop", conflicts_with = "loops")]
223 looping: bool,
224 /// Loop N times (1 to 1000)
225 #[arg(long, value_name = "N")]
226 loops: Option<String>,
227 /// Output buffer size in frames (16 to 16384)
228 #[arg(long, value_name = "FRAMES")]
229 buffer: Option<String>,
230 /// Reload when the file (or an included file) changes, keeping the position (Ctrl-C to stop)
231 #[arg(long)]
232 watch: bool,
233 /// How often to check the files with --watch, in milliseconds (50 to 5000, default 250)
234 #[arg(long, value_name = "MS", requires = "watch")]
235 watch_interval: Option<String>,
236 },
237}
238
239/// 曲を読むサブコマンドに共通の引数。
240#[derive(Debug, Args)]
241pub struct Input {
242 /// MML file (- for standard input)
243 #[arg(value_name = "FILE")]
244 pub file: String,
245 /// Default dialect (pikopiko / classic / classic-reversed)
246 #[arg(long, value_name = "NAME")]
247 pub dialect: Option<String>,
248 /// Folder of your own tone library (read as #include "@name/kind"; repeatable; also PIKOPIKO_TONES)
249 #[arg(long, value_name = "DIR")]
250 pub tones: Vec<String>,
251}
252
253/// `pikopiko` の使い方(表示の言語に訳したもの)。最後に、標準入力・言語の決め方・終了コードの
254/// 案内(`cli-after-help`)を付ける。
255pub fn command(loc: &Localizer) -> clap::Command {
256 lingokit::clap::command::<Cli>(loc).after_help(loc.fmt("cli-after-help", None))
257}
258
259/// `pikopiko-mcp` の引数。
260#[derive(Debug, Parser)]
261#[command(name = "pikopiko-mcp", version, about = "MCP server for pikopiko")]
262pub struct McpCli {
263 /// Folder that render_mml writes to
264 #[arg(long, value_name = "DIR")]
265 pub out_dir: Option<std::path::PathBuf>,
266 /// Maximum length that render_mml writes (seconds, default 120)
267 #[arg(long, value_name = "SEC")]
268 pub max_seconds: Option<String>,
269 /// Largest binary that build_mml returns as text (bytes, 32k = 32768)
270 #[arg(long, value_name = "BYTES")]
271 pub max_inline: Option<String>,
272 /// Display language (en / ja). Takes precedence over PIKOPIKO_LANG
273 #[arg(long, value_name = "LANG", value_parser = crate::text::parse_lang)]
274 pub lang: Option<&'static str>,
275 /// Folder of your own tone library (repeatable; also PIKOPIKO_TONES)
276 #[arg(long, value_name = "DIR")]
277 pub tones: Vec<String>,
278 /// Folder of reference sounds (WAV) that measure_tone can compare with (also PIKOPIKO_MCP_REF_DIR)
279 #[arg(long, value_name = "DIR")]
280 pub ref_dir: Option<std::path::PathBuf>,
281 /// Definition file of derived synths (TOML; repeatable; also PIKOPIKO_SYNTHS)
282 #[arg(long, value_name = "FILE")]
283 pub synth_def: Vec<String>,
284 /// Serve over Streamable HTTP at this address instead of standard input/output (needs the mcp-http feature)
285 #[arg(long, value_name = "ADDR:PORT")]
286 pub http: Option<String>,
287 /// Bearer token that HTTP clients must send (also PIKOPIKO_MCP_TOKEN). Required unless the address is loopback
288 #[arg(long, value_name = "TOKEN")]
289 pub token: Option<String>,
290 /// Host name the HTTP server accepts in the Host header (repeatable; for serving beyond localhost)
291 #[arg(long, value_name = "HOST")]
292 pub allow_host: Vec<String>,
293 /// How many requests the HTTP server handles at once (default 4)
294 #[arg(long, value_name = "N")]
295 pub max_concurrency: Option<String>,
296}
297
298/// `pikopiko-mcp` の使い方(表示の言語に訳したもの)。説明は `mcp-…` のキー(`locales/<言語>/mcp.ftl`)。
299///
300/// 引数の説明は lingokit で訳す前に入れる(clap は組み立てた後の `mut_arg` を受け付けないため)。
301/// `--lang` の説明は `pikopiko` と同じ `cli-arg-lang`。コマンドの説明と最後の案内は、lingokit が
302/// `cli-about`(`pikopiko` の説明)を入れた後で差し替える。
303pub fn mcp_command(loc: &Localizer) -> clap::Command {
304 let cmd = <McpCli as clap::CommandFactory>::command()
305 .mut_arg("out_dir", |a| a.help(loc.fmt("mcp-arg-out-dir", None)))
306 .mut_arg("max_seconds", |a| {
307 a.help(loc.fmt("mcp-arg-max-seconds", None))
308 })
309 .mut_arg("max_inline", |a| {
310 a.help(loc.fmt("mcp-arg-max-inline", None))
311 })
312 .mut_arg("tones", |a| a.help(loc.fmt("mcp-arg-tones", None)))
313 .mut_arg("ref_dir", |a| a.help(loc.fmt("mcp-arg-ref_dir", None)))
314 .mut_arg("synth_def", |a| a.help(loc.fmt("mcp-arg-synth_def", None)))
315 .mut_arg("http", |a| a.help(loc.fmt("mcp-arg-http", None)))
316 .mut_arg("token", |a| a.help(loc.fmt("mcp-arg-token", None)))
317 .mut_arg("allow_host", |a| {
318 a.help(loc.fmt("mcp-arg-allow_host", None))
319 })
320 .mut_arg("max_concurrency", |a| {
321 a.help(loc.fmt("mcp-arg-max_concurrency", None))
322 });
323 lingokit::clap::localize_command(cmd, loc)
324 .about(loc.fmt("mcp-about", None))
325 .after_help(format!(
326 "{}\n\n{}\n {{ \"mcpServers\": {{ \"pikopiko\": {{ \"command\": \"pikopiko-mcp\", \"args\": [\"--out-dir\", \"/path/to/out\"] }} }} }}",
327 loc.fmt("mcp-after-help", None),
328 loc.fmt("mcp-config-example", None)
329 ))
330}
331
332/// 引数を読み、表示の言語の文言の口と一緒に返す。使い方の表示(`--help`・`--version`)と使い方の
333/// 誤りは、ここで表示して終わる(誤りは終了コード 2)。
334///
335/// 言語は、clap で読む前に `--lang` を探して決める(使い方の誤りの文も選んだ言語にするため)。
336/// 決め方は [`crate::text::requested`]。
337pub fn parse<C: clap::FromArgMatches>(
338 build: fn(&Localizer) -> clap::Command,
339) -> (C, crate::text::Texts) {
340 let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
341 let cli_lang = lingokit::locale::pre_scan_lang(args.clone());
342 let loc = Localizer::new(
343 &crate::LOCALES,
344 &crate::text::requested(cli_lang.as_deref()),
345 );
346 let m = build(&loc)
347 .try_get_matches_from(args)
348 .unwrap_or_else(|e| lingokit::clap::exit_with_clap_error(e, &loc));
349 let c =
350 C::from_arg_matches(&m).unwrap_or_else(|e| lingokit::clap::exit_with_clap_error(e, &loc));
351 (c, crate::text::Texts::new(loc))
352}