use std::ffi::OsString;
use std::path::PathBuf;
pub const USAGE: &str = "serve --contract FILE | extract --library ROOT --out CONTRACT [--depfile FILE] | export --library ROOT --out DIR | new DIR";
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "the grammar is closed, and each reader handles every command"
)]
pub enum Command {
Serve {
contract: PathBuf,
},
Extract {
library: PathBuf,
out: PathBuf,
depfile: Option<PathBuf>,
},
Export {
library: PathBuf,
out: PathBuf,
},
New {
directory: PathBuf,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "the grammar is closed, and each reader handles every argument"
)]
pub enum Argument {
Contract,
Library,
Out,
Depfile,
Directory,
}
impl Argument {
#[must_use]
pub const fn word(self) -> &'static str {
match self {
Argument::Contract => "--contract",
Argument::Library => "--library",
Argument::Out => "--out",
Argument::Depfile => "--depfile",
Argument::Directory => "DIR",
}
}
}
impl std::fmt::Display for Argument {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.word())
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "the grammar is closed, and a reader handles each refusal"
)]
pub enum UsageError {
Empty,
Unknown(OsString),
Unexpected(OsString),
NoValue(Argument),
Twice(Argument),
Missing(Argument),
NotUtf8 {
argument: Argument,
value: OsString,
},
NotLauncher(Command),
}
impl std::fmt::Display for UsageError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UsageError::Empty => formatter.write_str("no command")?,
UsageError::Unknown(word) => {
write!(formatter, "{} is no command", word.to_string_lossy())?;
}
UsageError::Unexpected(word) => {
write!(
formatter,
"the command does not take {}",
word.to_string_lossy()
)?;
}
UsageError::NoValue(argument) => write!(formatter, "{argument} needs a path")?,
UsageError::Twice(argument) => write!(formatter, "{argument} is given twice")?,
UsageError::Missing(argument) => write!(formatter, "the command needs {argument}")?,
UsageError::NotUtf8 { argument, value } => write!(
formatter,
"{argument} {}: the path is not UTF-8",
value.to_string_lossy()
)?,
UsageError::NotLauncher(command) => {
return write!(
formatter,
"a library's launcher runs serve and extract; {} is flow-toolkit-rust's",
command.name()
);
}
}
write!(formatter, "; usage: {USAGE}")
}
}
impl std::error::Error for UsageError {}
impl Command {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Command::Serve { .. } => "serve",
Command::Extract { .. } => "extract",
Command::Export { .. } => "export",
Command::New { .. } => "new",
}
}
pub fn parse(arguments: &[OsString]) -> Result<Self, UsageError> {
type Build = fn(&mut Given) -> Result<Command, UsageError>;
let (name, rest) = arguments.split_first().ok_or(UsageError::Empty)?;
let (takes, build): (&[Argument], Build) = match name.to_str() {
Some("serve") => (&[Argument::Contract], |given| {
Ok(Command::Serve {
contract: given.need(Argument::Contract)?,
})
}),
Some("extract") => (
&[Argument::Library, Argument::Out, Argument::Depfile],
|given| {
Ok(Command::Extract {
library: given.need(Argument::Library)?,
out: given.need(Argument::Out)?,
depfile: given.take(Argument::Depfile),
})
},
),
Some("export") => (&[Argument::Library, Argument::Out], |given| {
Ok(Command::Export {
library: given.need(Argument::Library)?,
out: given.need(Argument::Out)?,
})
}),
Some("new") => {
return match rest {
[] => Err(UsageError::Missing(Argument::Directory)),
[directory] => Ok(Command::New {
directory: path(Argument::Directory, directory)?,
}),
[_, extra, ..] => Err(UsageError::Unexpected(extra.clone())),
};
}
_ => return Err(UsageError::Unknown(name.clone())),
};
let mut given = Given(Vec::new());
let mut words = rest.iter();
while let Some(word) = words.next() {
let argument = takes
.iter()
.copied()
.find(|argument| word.to_str() == Some(argument.word()))
.ok_or_else(|| UsageError::Unexpected(word.clone()))?;
let value = words.next().ok_or(UsageError::NoValue(argument))?;
if given.0.iter().any(|(seen, _)| *seen == argument) {
return Err(UsageError::Twice(argument));
}
given.0.push((argument, path(argument, value)?));
}
build(&mut given)
}
}
struct Given(Vec<(Argument, PathBuf)>);
impl Given {
fn take(&mut self, argument: Argument) -> Option<PathBuf> {
let index = self.0.iter().position(|(seen, _)| *seen == argument)?;
Some(self.0.swap_remove(index).1)
}
fn need(&mut self, argument: Argument) -> Result<PathBuf, UsageError> {
self.take(argument).ok_or(UsageError::Missing(argument))
}
}
fn path(argument: Argument, value: &OsString) -> Result<PathBuf, UsageError> {
value
.to_str()
.map(PathBuf::from)
.ok_or_else(|| UsageError::NotUtf8 {
argument,
value: value.clone(),
})
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
fn parse(words: &[&str]) -> Result<Command, UsageError> {
Command::parse(&words.iter().map(OsString::from).collect::<Vec<_>>())
}
#[test]
fn each_command_reads_its_own_arguments_in_any_order() {
assert_eq!(
parse(&["serve", "--contract", "c"]),
Ok(Command::Serve {
contract: "c".into()
})
);
assert_eq!(
parse(&["extract", "--out", "o", "--library", "l"]),
Ok(Command::Extract {
library: "l".into(),
out: "o".into(),
depfile: None
})
);
assert_eq!(
parse(&["extract", "--depfile", "d", "--library", "l", "--out", "o"]),
Ok(Command::Extract {
library: "l".into(),
out: "o".into(),
depfile: Some("d".into())
})
);
assert_eq!(
parse(&["export", "--library", "l", "--out", "o"]),
Ok(Command::Export {
library: "l".into(),
out: "o".into()
})
);
assert_eq!(
parse(&["new", "ledger"]),
Ok(Command::New {
directory: "ledger".into()
})
);
}
#[test]
fn a_command_line_that_spells_no_command_is_refused_with_why() {
for (words, refused) in [
(&[][..], UsageError::Empty),
(
&["--contract", "c"],
UsageError::Unknown("--contract".into()),
),
(
&["Serve", "--contract", "c"],
UsageError::Unknown("Serve".into()),
),
(&["serve"], UsageError::Missing(Argument::Contract)),
(&["serve", "c"], UsageError::Unexpected("c".into())),
(
&["serve", "--contract"],
UsageError::NoValue(Argument::Contract),
),
(
&["serve", "--contract", "c", "--contract", "d"],
UsageError::Twice(Argument::Contract),
),
(
&["serve", "--contract", "c", "--out", "o"],
UsageError::Unexpected("--out".into()),
),
(
&["extract", "--library", "l"],
UsageError::Missing(Argument::Out),
),
(
&["extract", "/lib", "/out"],
UsageError::Unexpected("/lib".into()),
),
(
&["export", "--library", "l", "--out", "o", "--depfile", "d"],
UsageError::Unexpected("--depfile".into()),
),
(&["new"], UsageError::Missing(Argument::Directory)),
(&["new", "a", "b"], UsageError::Unexpected("b".into())),
] {
assert_eq!(parse(words), Err(refused), "{words:?}");
}
}
#[cfg(unix)]
#[test]
fn a_path_that_is_not_utf8_is_refused_naming_its_argument() {
use std::os::unix::ffi::OsStrExt as _;
let not_utf8 = std::ffi::OsStr::from_bytes(b"caf\xe9").to_owned();
for (words, argument) in [
(
vec!["serve".into(), "--contract".into(), not_utf8.clone()],
Argument::Contract,
),
(vec!["new".into(), not_utf8.clone()], Argument::Directory),
] {
let refused = Command::parse(&words).unwrap_err();
assert_eq!(
refused,
UsageError::NotUtf8 {
argument,
value: not_utf8.clone()
}
);
assert!(refused.to_string().contains("not UTF-8"), "{refused}");
}
}
#[test]
fn a_refusal_says_why_and_the_usage() {
let refused = parse(&["serve"]).unwrap_err().to_string();
assert_eq!(
refused,
format!("the command needs --contract; usage: {USAGE}")
);
let refused = UsageError::NotLauncher(Command::New {
directory: "x".into(),
})
.to_string();
assert!(refused.contains("new is flow-toolkit-rust's"), "{refused}");
}
}