Skip to main content

alux_cli/
program.rs

1use crate::{
2    CliCommandsAlg, CliContextAlg, CliNamedSources, CliNestAlg, CliOperationAlg, CliProgramAlg, CliSources,
3    Conventions, Fallible, FallibleByError, NamedSource, PositionalSource, ProductSource, SumSource, Total,
4};
5use alux_ext::OperationAlg;
6
7/// Compiles a first-order CLI program with a concrete interpreter.
8pub trait CompileCliProgram<Compiler> {
9    /// The command collection produced by `Compiler`.
10    type Commands;
11
12    /// Folds the complete first-order program through `compiler`.
13    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands;
14}
15
16/// Represents the empty CLI program.
17#[derive(Debug, Default)]
18pub struct Empty;
19
20/// Represents the composition of two CLI programs, `left` first.
21#[derive(Debug)]
22pub struct Merge<Left, Right> {
23    left: Left,
24    right: Right,
25}
26
27/// Includes a separately named CLI program.
28#[derive(Debug)]
29pub struct Named<Program>(Program);
30
31/// Places a CLI program beneath one subcommand name.
32#[derive(Debug)]
33pub struct Nest<Program> {
34    name: &'static str,
35    program: Program,
36}
37
38/// Applies every command of a program to the context an operation answers.
39///
40/// The operation's arguments are the subtree's global arguments: every command of `program` takes
41/// them besides its own.
42#[derive(Debug)]
43pub struct Within<Handler, Inputs, Mode, Program> {
44    handler: Handler,
45    inputs: Inputs,
46    mode: Mode,
47    program: Program,
48}
49
50/// Represents one named command without choosing an interpreter.
51#[derive(Debug)]
52pub struct Command<Handler, Inputs, Mode = Total> {
53    name: &'static str,
54    handler: Handler,
55    inputs: Inputs,
56    mode: Mode,
57    conventions: Conventions,
58}
59
60/// Carries a typed operation, the sources of its arguments (one per argument, in order), and how
61/// its output is read as the command's outcome.
62#[derive(Debug)]
63pub struct Operation<Handler, Inputs = (), Mode = Total> {
64    handler: Handler,
65    inputs: Inputs,
66    mode: Mode,
67    conventions: Conventions,
68}
69
70/// Carries a typed CLI program during fluent composition.
71#[derive(Debug)]
72pub struct CliProgram<Program>(Program);
73
74/// Constructs neutral CLI programs.
75#[derive(Debug, Default)]
76pub struct CliProgramBuilder;
77
78impl CliProgramBuilder {
79    /// Starts an empty, uninterpreted CLI program.
80    pub fn commands(&self) -> CliProgram<Empty> {
81        CliProgram(Empty)
82    }
83
84    /// Wraps a first-order handler operation in a neutral declaration with no arguments.
85    pub fn op<Handler>(&self, handler: Handler) -> Operation<Handler> {
86        Operation { handler, inputs: (), mode: Total, conventions: Conventions::default() }
87    }
88
89    /// Includes a named CLI program in another program.
90    pub fn program<Program>(&self, program: Program) -> CliProgram<Named<Program>> {
91        CliProgram(Named(program))
92    }
93
94    /// Declares a source taking an argument's words by position.
95    pub fn positional(&self, doc: &'static str) -> PositionalSource {
96        PositionalSource::new(doc)
97    }
98
99    /// Declares a product: an argument made of fields given together, one named source each.
100    pub fn product(&self) -> ProductSource<()> {
101        ProductSource::new()
102    }
103
104    /// Declares a sum: an argument given as exactly one of its alternatives, one named source each.
105    pub fn sum(&self) -> SumSource<()> {
106        SumSource::new()
107    }
108
109    /// Declares a source taking an argument's words after its spelling, `--argument-name`.
110    pub fn named(&self, doc: &'static str) -> NamedSource {
111        NamedSource::new(doc)
112    }
113}
114
115impl<Handler, Inputs, Mode> Operation<Handler, Inputs, Mode> {
116    /// Declares the source of the operation's next argument, the one named `name`, after those
117    /// already declared.
118    ///
119    /// `defunc(via = cli)` checks the name against the operation's own when the program compiles,
120    /// reporting a source written for another argument where it is written.
121    pub fn arg<Source>(self, name: &'static str, source: Source) -> Operation<Handler, (Inputs, Source), Mode> {
122        let _: &'static str = name;
123        Operation {
124            handler: self.handler,
125            inputs: (self.inputs, source),
126            mode: self.mode,
127            conventions: self.conventions,
128        }
129    }
130
131    /// Declares this operation under one command name, with no program around it.
132    ///
133    /// A program that states many commands composes their registrations rather than their types,
134    /// so it needs each command on its own. `CliProgram::cmd` states the same thing inside a
135    /// composition, and is what an author writes.
136    pub fn declare(self, name: &'static str) -> Command<Handler, Inputs, Mode> {
137        Command { name, handler: self.handler, inputs: self.inputs, mode: self.mode, conventions: self.conventions }
138    }
139}
140
141impl<Handler, Inputs, Mode> Operation<Handler, Inputs, Mode> {
142    /// Ends the command's options at its first operand.
143    #[must_use]
144    pub fn options_first(mut self) -> Self {
145        self.conventions.options_first = true;
146        self
147    }
148
149    /// Reads a word naming no option of the command as an operand.
150    #[must_use]
151    pub fn unknown_options_as_operands(mut self) -> Self {
152        self.conventions.unknown_options_are_operands = true;
153        self
154    }
155
156    /// Reads `--` as an operand rather than the end of the options.
157    #[must_use]
158    pub fn no_end_of_options(mut self) -> Self {
159        self.conventions.double_dash_ends_options = false;
160        self
161    }
162
163    /// Reads a word of a dash and digits as the option spelled `--long` given those digits, as
164    /// `head -5` is `head -n 5`.
165    #[must_use]
166    pub fn numeric_option(mut self, long: &'static str) -> Self {
167        self.conventions.numeric_option = Some(long);
168        self
169    }
170
171    /// Reads every word as an operand, ignores operands beyond the command's own, and answers no
172    /// help.
173    #[must_use]
174    pub fn verbatim(mut self) -> Self {
175        self.conventions.verbatim = true;
176        self
177    }
178
179    /// Applies every command of `program` to the context this operation answers, with no program
180    /// around it.
181    pub fn within<Program>(self, program: CliProgram<Program>) -> Within<Handler, Inputs, Mode, Program> {
182        Within { handler: self.handler, inputs: self.inputs, mode: self.mode, program: program.0 }
183    }
184}
185
186impl<Handler, Inputs> Operation<Handler, Inputs, Total> {
187    /// Reads the operation's `Result` output as success or a failure exiting with status `1`. The
188    /// error can be any error that displays, `anyhow::Error` among them.
189    pub fn fallible(self) -> Operation<Handler, Inputs, Fallible> {
190        self.with_mode(Fallible::default())
191    }
192
193    /// Reads the operation's `Result` output as success or a failure exiting with `status`.
194    ///
195    /// # Panics
196    ///
197    /// Panics when `status` is zero, which is success.
198    #[track_caller]
199    pub fn fallible_as(self, status: u8) -> Operation<Handler, Inputs, Fallible> {
200        self.with_mode(Fallible::new(status))
201    }
202
203    /// Reads the operation's `Result` output as success or a failure with the status its error
204    /// states through `CliFailureAlg`, which may also say it was reported as it happened.
205    pub fn fallible_by_error(self) -> Operation<Handler, Inputs, FallibleByError> {
206        self.with_mode(FallibleByError)
207    }
208
209    fn with_mode<Mode>(self, mode: Mode) -> Operation<Handler, Inputs, Mode> {
210        Operation { handler: self.handler, inputs: self.inputs, mode, conventions: self.conventions }
211    }
212}
213
214impl<Program> CliProgram<Program> {
215    /// Records the composition of two typed CLI programs.
216    pub fn merge<Other>(self, other: CliProgram<Other>) -> CliProgram<Merge<Program, Other>> {
217        CliProgram(Merge { left: self.0, right: other.0 })
218    }
219
220    /// Registers a typed operation under a command name.
221    pub fn cmd<Handler, Inputs, Mode>(
222        self,
223        name: &'static str,
224        operation: Operation<Handler, Inputs, Mode>,
225    ) -> CliProgram<Merge<Program, Command<Handler, Inputs, Mode>>> {
226        self.merge(CliProgram(operation.declare(name)))
227    }
228
229    /// Declares the program's own command: the one a command line naming no command runs.
230    ///
231    /// It sits beside named commands, which a command line naming one selects first.
232    pub fn cmd_root<Handler, Inputs, Mode>(
233        self,
234        operation: Operation<Handler, Inputs, Mode>,
235    ) -> CliProgram<Merge<Program, Command<Handler, Inputs, Mode>>> {
236        self.merge(CliProgram(operation.declare("")))
237    }
238
239    /// Places `other` beneath the subcommand `name`.
240    pub fn nest<Other>(self, name: &'static str, other: CliProgram<Other>) -> CliProgram<Merge<Program, Nest<Other>>> {
241        self.merge(CliProgram(other.under(name)))
242    }
243
244    /// Applies every command of `other` to the context `operation` answers.
245    pub fn within<Handler, Inputs, Mode, Other>(
246        self,
247        operation: Operation<Handler, Inputs, Mode>,
248        other: CliProgram<Other>,
249    ) -> CliProgram<Merge<Program, Within<Handler, Inputs, Mode, Other>>> {
250        self.merge(CliProgram(operation.within(other)))
251    }
252
253    /// Places this program beneath the subcommand `name`, with no program around it.
254    pub fn under(self, name: &'static str) -> Nest<Program> {
255        Nest { name, program: self.0 }
256    }
257
258    /// Removes the fluent wrapper and returns the first-order syntax tree.
259    pub fn into_program(self) -> Program {
260        self.0
261    }
262}
263
264impl<Compiler> CompileCliProgram<Compiler> for Empty
265where
266    Compiler: CliCommandsAlg,
267{
268    type Commands = Compiler::Commands;
269
270    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
271        compiler.cli_empty()
272    }
273}
274
275impl<Compiler, Left, Right, Commands> CompileCliProgram<Compiler> for Merge<Left, Right>
276where
277    Compiler: CliCommandsAlg<Commands = Commands>,
278    Left: CompileCliProgram<Compiler, Commands = Commands>,
279    Right: CompileCliProgram<Compiler, Commands = Commands>,
280{
281    type Commands = Commands;
282
283    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
284        compiler.cli_merge(self.left.compile_cli_program(compiler), self.right.compile_cli_program(compiler))
285    }
286}
287
288impl<Compiler, Program> CompileCliProgram<Compiler> for Named<Program>
289where
290    Program: CliProgramAlg<Compiler>,
291{
292    type Commands = Program::Commands;
293
294    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
295        self.0.compile_cli(compiler)
296    }
297}
298
299impl<Compiler, Program, Commands> CompileCliProgram<Compiler> for Nest<Program>
300where
301    Compiler: CliNestAlg<Commands = Commands>,
302    Program: CompileCliProgram<Compiler, Commands = Commands>,
303{
304    type Commands = Commands;
305
306    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
307        let program = self.program;
308        compiler.cli_nest_with(self.name, |compiler| program.compile_cli_program(compiler))
309    }
310}
311
312impl<Compiler, Handler, Inputs, Mode> CompileCliProgram<Compiler> for Command<Handler, Inputs, Mode>
313where
314    Compiler: CliOperationAlg<Handler, Inputs, Mode>,
315    Handler: OperationAlg,
316    Inputs: CliSources<Handler::Args>,
317{
318    type Commands = Compiler::Commands;
319
320    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
321        compiler.cli_operation(self.name, self.handler, self.inputs, self.mode, self.conventions)
322    }
323}
324
325impl<Compiler, Handler, Inputs, Mode, Program, Inner, InnerCommands> CompileCliProgram<Compiler>
326    for Within<Handler, Inputs, Mode, Program>
327where
328    Compiler: CliContextAlg<Handler, Inputs, Mode, Inner = Inner, InnerCommands = InnerCommands>,
329    Handler: OperationAlg,
330    Inputs: CliSources<Handler::Args> + CliNamedSources,
331    Program: CompileCliProgram<Inner, Commands = InnerCommands>,
332{
333    type Commands = Compiler::Commands;
334
335    fn compile_cli_program(self, compiler: &Compiler) -> Self::Commands {
336        let inner = self.program.compile_cli_program(&compiler.cli_inner());
337        compiler.cli_within(self.handler, self.inputs, self.mode, inner)
338    }
339}