Skip to main content

alux_cli_multicall/
interpreter.rs

1use alux_cli::{CliCommandsAlg, CliContextAlg, CliNestAlg, CliOperationAlg, CliProgramAlg, Conventions};
2use alux_ext::OperationAlg;
3use std::{ffi::OsString, path::Path};
4
5/// Compiles a CLI program into the paths of its commands, which is all multicall reads.
6#[derive(Clone, Copy, Debug, Default)]
7pub struct MulticallCompiler;
8
9/// The commands of one program, as their paths, read for the names the executable answers to.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Multicall {
12    paths: Vec<Vec<&'static str>>,
13}
14
15/// A command line as a multicall executable reads it: the program name its help shows, and the
16/// words to run, the first of them the program's own.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct MulticallInvocation {
19    /// The name help shows for the program: empty when the executable was invoked by a command's
20    /// name, so help shows that command beneath no program name.
21    pub name: String,
22    /// The full command line to run.
23    pub words: Vec<OsString>,
24    /// The first-layer command the words name, invoked by its name or written after the
25    /// executable's; only its commands need compiling to run them.
26    pub command: Option<&'static str>,
27}
28
29impl Multicall {
30    /// Reads the commands `program` declares.
31    pub fn new<Program>(program: Program) -> Self
32    where
33        Program: CliProgramAlg<MulticallCompiler, Commands = Vec<Vec<&'static str>>>,
34    {
35        Self { paths: program.compile_cli(&MulticallCompiler) }
36    }
37
38    /// The names the executable answers to: each first-layer command's, once, in declaration order.
39    ///
40    /// An installer links each of them to the executable.
41    pub fn names(&self) -> Vec<&'static str> {
42        let mut names = Vec::new();
43        // The program's own command has no name to be invoked by.
44        for name in self.paths.iter().filter_map(|path| path.first()).filter(|name| !name.is_empty()) {
45            if !names.contains(name) {
46                names.push(*name);
47            }
48        }
49        names
50    }
51
52    /// Reads a command line: invoked by a first-layer command's name, that name is also its first
53    /// word; invoked under any other name, the words that follow select as usual.
54    pub fn invocation<Words>(&self, words: Words) -> MulticallInvocation
55    where
56        Words: IntoIterator,
57        Words::Item: Into<OsString>,
58    {
59        let mut words = words.into_iter().map(Into::into).collect::<Vec<OsString>>();
60        let names = self.names();
61        let invoked_as = |word: Option<&OsString>| {
62            let word = word.and_then(|word| Path::new(word).file_name()).and_then(|name| name.to_str())?;
63            names.iter().copied().find(|name| *name == word)
64        };
65        if let Some(command) = invoked_as(words.first()) {
66            words.insert(1, OsString::from(command));
67            return MulticallInvocation { name: String::new(), words, command: Some(command) };
68        }
69        let invoked = words.first().and_then(|first| Path::new(first).file_name()).and_then(|name| name.to_str());
70        let name = invoked.unwrap_or_default().to_owned();
71        // Beneath the executable's own name, the next word names the command, unless it is an option.
72        let command = words
73            .get(1)
74            .filter(|word| !word.as_encoded_bytes().starts_with(b"-"))
75            .and_then(|word| names.iter().copied().find(|name| word.to_str() == Some(*name)));
76        MulticallInvocation { name, words, command }
77    }
78}
79
80impl CliCommandsAlg for MulticallCompiler {
81    type Commands = Vec<Vec<&'static str>>;
82
83    fn cli_empty(&self) -> Self::Commands {
84        Vec::new()
85    }
86
87    fn cli_merge(&self, mut left: Self::Commands, right: Self::Commands) -> Self::Commands {
88        left.extend(right);
89        left
90    }
91}
92
93impl CliNestAlg for MulticallCompiler {
94    type Commands = Vec<Vec<&'static str>>;
95
96    fn cli_nest(&self, name: &'static str, mut commands: Self::Commands) -> Self::Commands {
97        for path in &mut commands {
98            path.insert(0, name);
99        }
100        commands
101    }
102}
103
104impl<Operation, Inputs, Mode> CliOperationAlg<Operation, Inputs, Mode> for MulticallCompiler
105where
106    Operation: OperationAlg,
107{
108    type Commands = Vec<Vec<&'static str>>;
109
110    fn cli_operation(&self, name: &'static str, _: Operation, _: Inputs, _: Mode, _: Conventions) -> Self::Commands {
111        vec![if name.is_empty() { Vec::new() } else { vec![name] }]
112    }
113}
114
115/// A context adds global arguments and changes no path.
116impl<Operation, Inputs, Mode> CliContextAlg<Operation, Inputs, Mode> for MulticallCompiler {
117    type Inner = Self;
118    type InnerCommands = Vec<Vec<&'static str>>;
119    type Commands = Vec<Vec<&'static str>>;
120
121    fn cli_inner(&self) -> Self {
122        Self
123    }
124
125    fn cli_within(&self, _: Operation, _: Inputs, _: Mode, commands: Self::InnerCommands) -> Self::Commands {
126        commands
127    }
128}