1use std::ffi::OsString;
19use std::path::PathBuf;
20
21pub const USAGE: &str = "serve --contract FILE | extract --library ROOT --out CONTRACT [--depfile FILE] | export --library ROOT --out DIR | new DIR";
23
24#[derive(Clone, PartialEq, Eq, Debug)]
26#[expect(
27 clippy::exhaustive_enums,
28 reason = "the grammar is closed, and each reader handles every command"
29)]
30pub enum Command {
31 Serve {
35 contract: PathBuf,
37 },
38 Extract {
43 library: PathBuf,
45 out: PathBuf,
47 depfile: Option<PathBuf>,
49 },
50 Export {
53 library: PathBuf,
55 out: PathBuf,
57 },
58 New {
60 directory: PathBuf,
62 },
63}
64
65#[derive(Clone, Copy, PartialEq, Eq, Debug)]
68#[expect(
69 clippy::exhaustive_enums,
70 reason = "the grammar is closed, and each reader handles every argument"
71)]
72pub enum Argument {
73 Contract,
75 Library,
77 Out,
79 Depfile,
81 Directory,
83}
84
85impl Argument {
86 #[must_use]
88 pub const fn word(self) -> &'static str {
89 match self {
90 Argument::Contract => "--contract",
91 Argument::Library => "--library",
92 Argument::Out => "--out",
93 Argument::Depfile => "--depfile",
94 Argument::Directory => "DIR",
95 }
96 }
97}
98
99impl std::fmt::Display for Argument {
100 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 formatter.write_str(self.word())
102 }
103}
104
105#[derive(Clone, PartialEq, Eq, Debug)]
107#[expect(
108 clippy::exhaustive_enums,
109 reason = "the grammar is closed, and a reader handles each refusal"
110)]
111pub enum UsageError {
112 Empty,
114 Unknown(OsString),
116 Unexpected(OsString),
118 NoValue(Argument),
120 Twice(Argument),
122 Missing(Argument),
124 NotUtf8 {
126 argument: Argument,
128 value: OsString,
130 },
131 NotLauncher(Command),
134}
135
136impl std::fmt::Display for UsageError {
137 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 match self {
139 UsageError::Empty => formatter.write_str("no command")?,
140 UsageError::Unknown(word) => {
141 write!(formatter, "{} is no command", word.to_string_lossy())?;
142 }
143 UsageError::Unexpected(word) => {
144 write!(
145 formatter,
146 "the command does not take {}",
147 word.to_string_lossy()
148 )?;
149 }
150 UsageError::NoValue(argument) => write!(formatter, "{argument} needs a path")?,
151 UsageError::Twice(argument) => write!(formatter, "{argument} is given twice")?,
152 UsageError::Missing(argument) => write!(formatter, "the command needs {argument}")?,
153 UsageError::NotUtf8 { argument, value } => write!(
154 formatter,
155 "{argument} {}: the path is not UTF-8",
156 value.to_string_lossy()
157 )?,
158 UsageError::NotLauncher(command) => {
159 return write!(
160 formatter,
161 "a library's launcher runs serve and extract; {} is flow-toolkit-rust's",
162 command.name()
163 );
164 }
165 }
166 write!(formatter, "; usage: {USAGE}")
167 }
168}
169
170impl std::error::Error for UsageError {}
171
172impl Command {
173 #[must_use]
175 pub const fn name(&self) -> &'static str {
176 match self {
177 Command::Serve { .. } => "serve",
178 Command::Extract { .. } => "extract",
179 Command::Export { .. } => "export",
180 Command::New { .. } => "new",
181 }
182 }
183
184 pub fn parse(arguments: &[OsString]) -> Result<Self, UsageError> {
191 type Build = fn(&mut Given) -> Result<Command, UsageError>;
192 let (name, rest) = arguments.split_first().ok_or(UsageError::Empty)?;
193 let (takes, build): (&[Argument], Build) = match name.to_str() {
194 Some("serve") => (&[Argument::Contract], |given| {
195 Ok(Command::Serve {
196 contract: given.need(Argument::Contract)?,
197 })
198 }),
199 Some("extract") => (
200 &[Argument::Library, Argument::Out, Argument::Depfile],
201 |given| {
202 Ok(Command::Extract {
203 library: given.need(Argument::Library)?,
204 out: given.need(Argument::Out)?,
205 depfile: given.take(Argument::Depfile),
206 })
207 },
208 ),
209 Some("export") => (&[Argument::Library, Argument::Out], |given| {
210 Ok(Command::Export {
211 library: given.need(Argument::Library)?,
212 out: given.need(Argument::Out)?,
213 })
214 }),
215 Some("new") => {
216 return match rest {
217 [] => Err(UsageError::Missing(Argument::Directory)),
218 [directory] => Ok(Command::New {
219 directory: path(Argument::Directory, directory)?,
220 }),
221 [_, extra, ..] => Err(UsageError::Unexpected(extra.clone())),
222 };
223 }
224 _ => return Err(UsageError::Unknown(name.clone())),
225 };
226 let mut given = Given(Vec::new());
227 let mut words = rest.iter();
228 while let Some(word) = words.next() {
229 let argument = takes
230 .iter()
231 .copied()
232 .find(|argument| word.to_str() == Some(argument.word()))
233 .ok_or_else(|| UsageError::Unexpected(word.clone()))?;
234 let value = words.next().ok_or(UsageError::NoValue(argument))?;
235 if given.0.iter().any(|(seen, _)| *seen == argument) {
236 return Err(UsageError::Twice(argument));
237 }
238 given.0.push((argument, path(argument, value)?));
239 }
240 build(&mut given)
241 }
242}
243
244struct Given(Vec<(Argument, PathBuf)>);
246
247impl Given {
248 fn take(&mut self, argument: Argument) -> Option<PathBuf> {
250 let index = self.0.iter().position(|(seen, _)| *seen == argument)?;
251 Some(self.0.swap_remove(index).1)
252 }
253
254 fn need(&mut self, argument: Argument) -> Result<PathBuf, UsageError> {
256 self.take(argument).ok_or(UsageError::Missing(argument))
257 }
258}
259
260fn path(argument: Argument, value: &OsString) -> Result<PathBuf, UsageError> {
262 value
263 .to_str()
264 .map(PathBuf::from)
265 .ok_or_else(|| UsageError::NotUtf8 {
266 argument,
267 value: value.clone(),
268 })
269}
270
271#[cfg(test)]
272#[cfg_attr(coverage, coverage(off))]
273mod tests {
274 use super::*;
275
276 fn parse(words: &[&str]) -> Result<Command, UsageError> {
277 Command::parse(&words.iter().map(OsString::from).collect::<Vec<_>>())
278 }
279
280 #[test]
281 fn each_command_reads_its_own_arguments_in_any_order() {
282 assert_eq!(
283 parse(&["serve", "--contract", "c"]),
284 Ok(Command::Serve {
285 contract: "c".into()
286 })
287 );
288 assert_eq!(
289 parse(&["extract", "--out", "o", "--library", "l"]),
290 Ok(Command::Extract {
291 library: "l".into(),
292 out: "o".into(),
293 depfile: None
294 })
295 );
296 assert_eq!(
297 parse(&["extract", "--depfile", "d", "--library", "l", "--out", "o"]),
298 Ok(Command::Extract {
299 library: "l".into(),
300 out: "o".into(),
301 depfile: Some("d".into())
302 })
303 );
304 assert_eq!(
305 parse(&["export", "--library", "l", "--out", "o"]),
306 Ok(Command::Export {
307 library: "l".into(),
308 out: "o".into()
309 })
310 );
311 assert_eq!(
312 parse(&["new", "ledger"]),
313 Ok(Command::New {
314 directory: "ledger".into()
315 })
316 );
317 }
318
319 #[test]
320 fn a_command_line_that_spells_no_command_is_refused_with_why() {
321 for (words, refused) in [
322 (&[][..], UsageError::Empty),
323 (
324 &["--contract", "c"],
325 UsageError::Unknown("--contract".into()),
326 ),
327 (
328 &["Serve", "--contract", "c"],
329 UsageError::Unknown("Serve".into()),
330 ),
331 (&["serve"], UsageError::Missing(Argument::Contract)),
332 (&["serve", "c"], UsageError::Unexpected("c".into())),
333 (
334 &["serve", "--contract"],
335 UsageError::NoValue(Argument::Contract),
336 ),
337 (
338 &["serve", "--contract", "c", "--contract", "d"],
339 UsageError::Twice(Argument::Contract),
340 ),
341 (
342 &["serve", "--contract", "c", "--out", "o"],
343 UsageError::Unexpected("--out".into()),
344 ),
345 (
346 &["extract", "--library", "l"],
347 UsageError::Missing(Argument::Out),
348 ),
349 (
350 &["extract", "/lib", "/out"],
351 UsageError::Unexpected("/lib".into()),
352 ),
353 (
354 &["export", "--library", "l", "--out", "o", "--depfile", "d"],
355 UsageError::Unexpected("--depfile".into()),
356 ),
357 (&["new"], UsageError::Missing(Argument::Directory)),
358 (&["new", "a", "b"], UsageError::Unexpected("b".into())),
359 ] {
360 assert_eq!(parse(words), Err(refused), "{words:?}");
361 }
362 }
363
364 #[cfg(unix)]
365 #[test]
366 fn a_path_that_is_not_utf8_is_refused_naming_its_argument() {
367 use std::os::unix::ffi::OsStrExt as _;
368 let not_utf8 = std::ffi::OsStr::from_bytes(b"caf\xe9").to_owned();
369 for (words, argument) in [
370 (
371 vec!["serve".into(), "--contract".into(), not_utf8.clone()],
372 Argument::Contract,
373 ),
374 (vec!["new".into(), not_utf8.clone()], Argument::Directory),
375 ] {
376 let refused = Command::parse(&words).unwrap_err();
377 assert_eq!(
378 refused,
379 UsageError::NotUtf8 {
380 argument,
381 value: not_utf8.clone()
382 }
383 );
384 assert!(refused.to_string().contains("not UTF-8"), "{refused}");
385 }
386 }
387
388 #[test]
389 fn a_refusal_says_why_and_the_usage() {
390 let refused = parse(&["serve"]).unwrap_err().to_string();
391 assert_eq!(
392 refused,
393 format!("the command needs --contract; usage: {USAGE}")
394 );
395 let refused = UsageError::NotLauncher(Command::New {
396 directory: "x".into(),
397 })
398 .to_string();
399 assert!(refused.contains("new is flow-toolkit-rust's"), "{refused}");
400 }
401}