use clap::{Parser, Subcommand};
use std::io;
#[derive(Debug, Parser)]
#[command(name = "wr", version, disable_help_subcommand = true)]
pub(super) struct Args {
#[cfg(feature = "fm1")]
#[arg(long, global = true)]
pub fm1: bool,
#[cfg(feature = "fm1")]
#[arg(long, global = true)]
pub port: Option<String>,
#[cfg(unix)]
#[arg(long, global = true)]
pub socket: Option<std::path::PathBuf>,
#[arg(long, short, global = true, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=16))]
pub channel: u8,
#[arg(long, global = true, default_value_t = 2, value_parser = clap::value_parser!(u64).range(1..=60))]
pub timeout: u64,
#[command(subcommand)]
pub command: Option<Command>,
}
#[cfg(feature = "fm1")]
impl Args {
pub(super) fn validate_transport(&self) -> Result<(), clap::Error> {
use clap::{CommandFactory as _, error::ErrorKind};
if self.port.is_some() && !self.fm1 {
return Err(
Self::command().error(ErrorKind::MissingRequiredArgument, "--port requires --fm1")
);
}
#[cfg(unix)]
if self.fm1 && self.socket.is_some() {
return Err(
Self::command().error(ErrorKind::ArgumentConflict, "--fm1 conflicts with --socket")
);
}
Ok(())
}
}
#[derive(Debug, Parser)]
#[command(name = "wr", no_binary_name = true, disable_help_subcommand = true)]
struct Line {
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
pub(super) enum Command {
Repl,
Graph,
#[command(alias = "instruments")]
Nodes,
Inspect {
alias: String,
},
Select {
target: String,
},
Channel {
#[arg(value_parser = clap::value_parser!(u8).range(1..=16))]
number: Option<u8>,
},
Play,
Stop,
Note {
#[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
number: u8,
#[arg(default_value_t = 100, value_parser = clap::value_parser!(u8).range(1..=127))]
velocity: u8,
#[arg(default_value_t = 250, value_parser = clap::value_parser!(u64).range(1..=60_000))]
duration_ms: u64,
},
On {
#[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
number: u8,
#[arg(default_value_t = 100, value_parser = clap::value_parser!(u8).range(1..=127))]
velocity: u8,
},
Off {
#[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
number: u8,
},
Cc {
#[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
controller: u8,
#[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
value: u8,
},
Panic,
Help,
#[command(alias = "exit")]
Quit,
}
pub(super) fn parse_line(line: &str) -> io::Result<Option<Result<Command, clap::Error>>> {
let words = words(line)?;
if words.is_empty() {
Ok(None)
} else {
Ok(Some(Line::try_parse_from(words).map(|line| line.command)))
}
}
fn words(line: &str) -> io::Result<Vec<String>> {
let mut result = Vec::new();
let mut word = String::new();
let mut quote = None;
let mut escaped = false;
let mut started = false;
for ch in line.chars() {
if escaped {
word.push(ch);
escaped = false;
continue;
}
match (quote, ch) {
(Some('\''), '\'') | (Some('"'), '"') => quote = None,
(Some('\''), _) => word.push(ch),
(_, '\\') => {
escaped = true;
started = true;
}
(Some(_), _) => word.push(ch),
(None, '\'' | '"') => {
quote = Some(ch);
started = true;
}
(None, '#') if !started => break,
(None, ch) if ch.is_whitespace() => {
if started {
result.push(core::mem::take(&mut word));
started = false;
}
}
(None, _) => {
word.push(ch);
started = true;
}
}
}
if quote.is_some() || escaped {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"unfinished quote or escape",
));
}
if started {
result.push(word);
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "fm1")]
#[test]
fn fm1_is_explicit_even_when_compiled_in() -> Result<(), clap::Error> {
assert!(!Args::try_parse_from(["wr", "graph"])?.fm1);
let args = Args::try_parse_from(["wr", "graph", "--port", "FM-1"])?;
assert!(args.validate_transport().is_err());
let args = Args::try_parse_from(["wr", "--fm1", "graph", "--port", "FM-1"])?;
args.validate_transport()?;
assert!(args.fm1);
assert_eq!(args.port.as_deref(), Some("FM-1"));
#[cfg(unix)]
{
let args = Args::try_parse_from(["wr", "--socket", "host.sock", "graph", "--fm1"])?;
assert!(args.validate_transport().is_err());
}
Ok(())
}
#[cfg(not(feature = "fm1"))]
#[test]
fn fm1_options_are_absent_from_local_builds() {
for option in ["--fm1", "--port"] {
let error = Args::try_parse_from(["wr", option]).expect_err("unknown FM-1 option");
assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
}
}
#[test]
fn rejects_out_of_range_midi_before_connecting() {
for args in [
vec!["wr", "--channel", "0", "on", "60"],
vec!["wr", "--channel", "17", "on", "60"],
vec!["wr", "on", "128"],
vec!["wr", "on", "60", "0"],
vec!["wr", "off", "128"],
vec!["wr", "cc", "128", "0"],
vec!["wr", "cc", "74", "128"],
] {
assert!(Args::try_parse_from(args).is_err());
}
assert!(Args::try_parse_from(["wr", "--channel", "16", "cc", "127", "127"]).is_ok());
}
#[test]
fn defaults_to_a_repl_and_bounded_audition() -> io::Result<()> {
let args = Args::try_parse_from(["wr"]).map_err(io::Error::other)?;
assert!(args.command.is_none());
assert_eq!(args.channel, 1);
assert!(matches!(
parse_line("note 60")?,
Some(Ok(Command::Note {
number: 60,
velocity: 100,
duration_ms: 250,
}))
));
Ok(())
}
#[test]
fn repl_handles_aliases_comments_and_parse_errors() -> io::Result<()> {
assert_eq!(
words("select 'bass voice' # comment")?,
["select", "bass voice"]
);
assert_eq!(words("select bass\\ voice")?, ["select", "bass voice"]);
assert!(parse_line(" # comment")?.is_none());
assert!(matches!(parse_line("cc 74 128")?, Some(Err(_))));
assert!(matches!(parse_line("on 60 100 extra")?, Some(Err(_))));
assert!(words("select 'unfinished").is_err());
assert!(words("select trailing\\").is_err());
Ok(())
}
}