Skip to main content

flow_toolkit/
cli.rs

1//! The Rust toolkit's one command grammar, which `flow-toolkit-rust` and
2//! every launcher it builds read alike (`abi.md`, *Toolkits*):
3//!
4//! ```text
5//! serve --contract FILE
6//! extract --library ROOT --out CONTRACT [--depfile FILE]
7//! export --library ROOT --out DIR
8//! new DIR
9//! ```
10//!
11//! `flow-toolkit-rust` runs each command. A library's launcher runs
12//! `serve` and `extract` and refuses the others with
13//! [`UsageError::NotLauncher`], so a bundle names an exported launcher as
14//! `<launcher> serve`, the way a library names `flow-toolkit-rust serve`.
15//! Every path is UTF-8, which the toolkit needs to name it in a Cargo
16//! manifest or a depfile.
17
18use std::ffi::OsString;
19use std::path::PathBuf;
20
21/// The command lines the grammar takes, after the program.
22pub const USAGE: &str = "serve --contract FILE | extract --library ROOT --out CONTRACT [--depfile FILE] | export --library ROOT --out DIR | new DIR";
23
24/// A command of the Rust toolkit.
25#[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 --contract FILE`: serve the Tools the host's `--contract`
32    /// file lists, as a `[process]` library's command is started
33    /// (`abi.md`, *Binding*).
34    Serve {
35        /// The `--contract` file.
36        contract: PathBuf,
37    },
38    /// `extract --library ROOT --out CONTRACT [--depfile FILE]`: write the
39    /// contract of the library at `library` to `out` in the value encoding,
40    /// and list in `depfile` every file read (`abi.md`, *Extracting a
41    /// contract*).
42    Extract {
43        /// The library's root.
44        library: PathBuf,
45        /// The file the contract is written to.
46        out: PathBuf,
47        /// The depfile, when one is asked for.
48        depfile: Option<PathBuf>,
49    },
50    /// `export --library ROOT --out DIR`: build the library's launcher
51    /// for a release and copy it into `out`.
52    Export {
53        /// The library's root.
54        library: PathBuf,
55        /// The directory the launcher is copied into.
56        out: PathBuf,
57    },
58    /// `new DIR`: write a library to start from at `directory`.
59    New {
60        /// Where the library is written.
61        directory: PathBuf,
62    },
63}
64
65/// A word of a command that carries a path: an option, or `new`'s
66/// directory.
67#[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 FILE`.
74    Contract,
75    /// `--library ROOT`.
76    Library,
77    /// `--out`: `extract`'s contract file, `export`'s directory.
78    Out,
79    /// `--depfile FILE`.
80    Depfile,
81    /// `new`'s `DIR`.
82    Directory,
83}
84
85impl Argument {
86    /// The word naming the argument: the option, or `DIR`.
87    #[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/// Why a command line is no command this reader runs.
106#[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    /// The command line is empty.
113    Empty,
114    /// The first word names no command.
115    Unknown(OsString),
116    /// A word the command does not take.
117    Unexpected(OsString),
118    /// The argument is given with no value after it.
119    NoValue(Argument),
120    /// The argument is given twice.
121    Twice(Argument),
122    /// The command needs the argument, and it is not given.
123    Missing(Argument),
124    /// The argument's value is not UTF-8.
125    NotUtf8 {
126        /// The argument.
127        argument: Argument,
128        /// Its value.
129        value: OsString,
130    },
131    /// A library's launcher runs `serve` and `extract` only, and this is
132    /// another command.
133    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    /// The command's name, its first word.
174    #[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    /// The command `arguments` spell, the program's own name not among
185    /// them.
186    ///
187    /// # Errors
188    ///
189    /// Why `arguments` spell no command.
190    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
244/// The options a command line gives, each once.
245struct Given(Vec<(Argument, PathBuf)>);
246
247impl Given {
248    /// The value of `argument`, if it is given.
249    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    /// The value of `argument`, which the command needs.
255    fn need(&mut self, argument: Argument) -> Result<PathBuf, UsageError> {
256        self.take(argument).ok_or(UsageError::Missing(argument))
257    }
258}
259
260/// `value`, the value of `argument`, as a path.
261fn 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}