Skip to main content

alux_cli/
laws.rs

1use crate::{
2    CliCommandsAlg, CliContextAlg, CliFailureAlg, CliNamedSources, CliNestAlg, CliOperationAlg, CliOutcome,
3    CliOutcomeOf, CliSources, CommandDescription, Conventions, Part,
4};
5use alux_ext::{OperationAlg, ext};
6
7/// Observes a command collection as the commands it describes, in order.
8pub trait CliCommandsObserved {
9    /// The collection observed.
10    type Commands;
11
12    /// Returns every command the collection describes, in order.
13    fn commands_observed(&self, commands: &Self::Commands) -> Vec<CommandDescription>;
14}
15
16/// Reports a broken CLI law by the obligation it breaks.
17pub type CliLawResult = Result<(), &'static str>;
18
19fn require(condition: bool, message: &'static str) -> CliLawResult {
20    if condition { Ok(()) } else { Err(message) }
21}
22
23/// States that command collections form an ordered monoid under merge.
24#[ext(name = CliCompositionLawsExt)]
25pub impl<This, Commands> This
26where
27    This: CliCommandsAlg<Commands = Commands> + CliCommandsObserved<Commands = Commands>,
28    Commands: Clone,
29{
30    /// Checks that the empty collection describes nothing and is an identity of merge.
31    fn law_cli_identity(&self, commands: &Commands) -> CliLawResult {
32        let observed = self.commands_observed(commands);
33        require(self.commands_observed(&self.cli_empty()).is_empty(), "empty CLI was not empty")?;
34        require(
35            self.commands_observed(&self.cli_merge(self.cli_empty(), commands.clone())) == observed,
36            "left CLI identity failed",
37        )?;
38        require(
39            self.commands_observed(&self.cli_merge(commands.clone(), self.cli_empty())) == observed,
40            "right CLI identity failed",
41        )
42    }
43
44    /// Checks that merge describes `left` then `right`, losing and reordering nothing.
45    fn law_cli_merge_conservation(&self, left: &Commands, right: &Commands) -> CliLawResult {
46        let mut expected = self.commands_observed(left);
47        expected.extend(self.commands_observed(right));
48        require(
49            self.commands_observed(&self.cli_merge(left.clone(), right.clone())) == expected,
50            "CLI merge lost order or declarations",
51        )
52    }
53
54    /// Checks that merge is associative.
55    fn law_cli_associativity(&self, a: &Commands, b: &Commands, c: &Commands) -> CliLawResult {
56        let left = self.cli_merge(self.cli_merge(a.clone(), b.clone()), c.clone());
57        let right = self.cli_merge(a.clone(), self.cli_merge(b.clone(), c.clone()));
58        require(self.commands_observed(&left) == self.commands_observed(&right), "CLI merge was not associative")
59    }
60}
61
62/// States that declaring a command preserves its operation and gives every argument one source.
63#[ext(name = CliDeclarationLawsExt)]
64pub impl<This> This {
65    /// Checks that `operation` declared under `name` with `sources` describes exactly that, with
66    /// one argument per operation argument, in order, and distinct spellings and positions.
67    fn law_cli_declaration<Operation, Sources, Mode, Commands>(
68        &self,
69        name: &'static str,
70        operation: Operation,
71        sources: Sources,
72        mode: Mode,
73        conventions: Conventions,
74    ) -> CliLawResult
75    where
76        This: CliOperationAlg<Operation, Sources, Mode, Commands = Commands> + CliCommandsObserved<Commands = Commands>,
77        Operation: OperationAlg,
78        Sources: CliSources<Operation::Args>,
79    {
80        let mut expected = CommandDescription::of::<Operation, Sources>(name, &sources);
81        expected.conventions = conventions;
82        // A compound argument describes one part each; read back, its parts are one argument.
83        let mut names = expected
84            .arguments
85            .iter()
86            .map(|argument| match argument.part_of {
87                Some(Part::Product(name) | Part::Sum(name)) => name,
88                None => argument.name,
89            })
90            .collect::<Vec<_>>();
91        names.dedup();
92        require(names == Operation::ARG_NAMES, "CLI arguments are not the operation's arguments in order")?;
93        let sources_described = expected.arguments.iter().map(|argument| &argument.source).collect::<Vec<_>>();
94        require(
95            sources_described.iter().enumerate().all(|(index, source)| !sources_described[..index].contains(source)),
96            "two CLI arguments share a source",
97        )?;
98        let declared = self.cli_operation(name, operation, sources, mode, conventions);
99        require(
100            self.commands_observed(&declared) == vec![expected],
101            "CLI declaration changed its operation or arguments",
102        )
103    }
104}
105
106/// States that nesting prefixes every path and changes nothing else.
107#[ext(name = CliNestLawsExt)]
108pub impl<This, Commands> This
109where
110    This: CliNestAlg<Commands = Commands> + CliCommandsObserved<Commands = Commands>,
111    Commands: Clone,
112{
113    /// Checks that `commands` nested under `name` describe the same commands beneath `name`.
114    fn law_cli_nest(&self, name: &'static str, commands: &Commands) -> CliLawResult {
115        let mut expected = self.commands_observed(commands);
116        for description in &mut expected {
117            description.path.insert(0, name);
118        }
119        require(
120            self.commands_observed(&self.cli_nest(name, commands.clone())) == expected,
121            "subcommand nesting changed a declaration",
122        )
123    }
124}
125
126/// States that a command's outcome and its exit status agree.
127#[ext(name = CliOutcomeLawsExt)]
128pub impl<This> This {
129    /// Checks that `output` read under this mode exits with zero exactly when it succeeds.
130    fn law_cli_outcome<Output>(&self, output: Output) -> CliLawResult
131    where
132        This: CliOutcomeOf<Output>,
133        This::Error: CliFailureAlg,
134    {
135        let outcome = self.cli_outcome(output);
136        let succeeded = matches!(outcome, CliOutcome::Success(_));
137        require((outcome.cli_status() == 0) == succeeded, "a command's exit status disagreed with its outcome")
138    }
139}
140
141/// States that a context adds its global arguments to every command beneath it and changes nothing
142/// else.
143#[ext(name = CliContextLawsExt)]
144pub impl<This, Commands> This
145where
146    This: CliCommandsObserved<Commands = Commands>,
147    Commands: Clone,
148{
149    /// Checks that `commands` applied within `operation` describe the same commands, each taking the
150    /// operation's arguments, read from `sources`, ahead of any context it already had.
151    fn law_cli_within<Operation, Sources, Mode>(
152        &self,
153        operation: Operation,
154        sources: Sources,
155        mode: Mode,
156        commands: &Commands,
157    ) -> CliLawResult
158    where
159        This: CliContextAlg<Operation, Sources, Mode, InnerCommands = Commands, Commands = Commands>,
160        Operation: OperationAlg,
161        Sources: CliSources<Operation::Args> + CliNamedSources,
162    {
163        let global = sources.cli_arguments(Operation::ARG_NAMES);
164        let mut expected = self.commands_observed(commands);
165        for description in &mut expected {
166            description.context.splice(0..0, global.iter().cloned());
167        }
168        let within = self.cli_within(operation, sources, mode, commands.clone());
169        require(self.commands_observed(&within) == expected, "a context changed the commands beneath it")
170    }
171}