1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! Lifecycle hooks for arbitrarily deep trees of clap commands.
//!
//! This module provides a way for clap commands to recursively descend into
//! children while executing lifecycle hooks at each level. This is useful for
//! building complex CLI tools where you don't want to define the entire
//! structure statically at the root level. Definitions are instead delegated to
//! the commands themselves at each level.
//!
//! # Examples
//!
//! See [examples/basic] for a more detailed example.
//!
//! ```should_panic
//! use cata::{Command, Container};
//! use clap::{Parser, Subcommand};
//!
//! #[derive(Parser, Container)]
//! pub struct Root {
//! #[command(subcommand)]
//! pub cmd: RootCmd,
//! }
//!
//! #[derive(Subcommand, Container)]
//! pub enum RootCmd {
//! Child(Child)
//! }
//! impl Command for Root {}
//!
//! #[derive(Parser, Container)]
//! pub struct Child {}
//!
//! impl Command for Child {}
//!
//! #[tokio::main]
//! async fn main() -> eyre::Result<()> {
//! cata::execute(&Root::parse()).await
//! }
//! ```
//!
//! [examples/basic]: https://github.com/grampelberg/cata/blob/main/examples/basic/src/main.rs
use Result;
/// The base structure for commands.
///
/// A command is a single unit of work, the trait exposes hooks that allow for
/// multiple commands to cooperate in a single lifecycle. There should be an
/// implementation of this for every instance of a [`Parser`] in clap.
///
/// The default implementations are no-ops and allow for commands to implement
/// only what they need. This primarily results in parent commands implementing
/// pre/post run and child commands implementing run.
///
/// Commands are called recursively, starting at the root command and traversing
/// through all the subcommands that were successfully parsed. The `pre-run` and
/// `run` hooks are called first on the parent before recursing into the child.
/// Subsequently, `post-run` is called first on the child as it recurses up to
/// the parent.
///
/// [`Parser`]: clap::Parser
/// Allows commands to optionally contain subcommands.
///
/// `cata::execute` expects commands to have implemented this trait to discover
/// if it needs to recurse into a subcommand. While it is possible to implement
/// this yourself, it is recommended that `#[derive(Command)]` is used to
/// automatically generate the code required to switch between subcommand enums.