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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use std::error::Error;

use rustyline::Editor;

use clap::Command;

use crate::async_stdout::AsyncStdout;
use crate::builder::{ClapCmdBuilder, ExitError};
use crate::group::{HandlerGroup, HandlerGroupMeta};
use crate::handler::{Callback, ClapCmdResult, Handler};
use crate::helper::ClapCmdHelper;
use crate::shell_parser::split;

///
/// An interactive CLI interface, holding state and responsible for acquiring user input and
/// assigning tasks to callback functions.
pub struct ClapCmd<State = ()>
where
    State: Clone + Default,
{
    pub(crate) editor: Editor<ClapCmdHelper<State>>,
    pub(crate) prompt: String,
    pub(crate) about: String,
}

impl<State> Default for ClapCmd<State>
where
    State: Clone + Default + Send + Sync + 'static,
{
    fn default() -> Self {
        let builder = ClapCmdBuilder::default();
        builder.build()
    }
}

impl<State> ClapCmd<State>
where
    State: Clone + Default,
{
    /// Generate a `ClapCmdBuilder` object used mainly to expose rustyline settings
    pub fn builder() -> ClapCmdBuilder {
        ClapCmdBuilder::default()
    }

    /// Set the internal state that is provided to callbacks
    pub fn set_state(&mut self, state: State) {
        self.editor
            .helper_mut()
            .expect("helper is always provided")
            .set_state(state);
    }

    /// Retrieve the current state from a callback
    pub fn get_state(&self) -> &State {
        self.editor
            .helper()
            .expect("helper is always provided")
            .get_state()
    }

    /// Retrieve a mutable reference to the current state from a callback
    pub fn get_state_mut(&mut self) -> &mut State {
        self.editor
            .helper_mut()
            .expect("helper is always provided")
            .get_state_mut()
    }

    /// Set the current prompt
    pub fn set_prompt(&mut self, prompt: &str) {
        self.prompt = prompt.to_owned();
    }

    /// Checks if a given &str is connected to a command
    pub fn has_command(&self, command: &str) -> bool {
        self.editor
            .helper()
            .expect("helper is always provided")
            .dispatcher
            .iter()
            .any(|c| c.command.get_name() == command)
    }

    /// Adds the specified command to the default group
    pub fn add_command(&mut self, callback: impl Callback<State>, command: Command) {
        self.add_command_from_handler(Handler {
            command,
            group: None,
            callback: callback.clone_box(),
        })
    }

    fn add_command_from_handler(&mut self, handler: Handler<State>) {
        if self.has_command(handler.command.get_name()) {
            return;
        }
        self.editor
            .helper_mut()
            .expect("helper is always provided")
            .dispatcher
            .push(handler);
    }

    /// Removes the command distinguished by the string `command`
    pub fn remove_command(&mut self, command: &str) {
        self.editor
            .helper_mut()
            .expect("helper is always provided")
            .dispatcher
            .retain(|c| c.command.get_name() != command);
    }

    /// Creates a new group that can be loaded an unloaded
    pub fn group(name: &str) -> HandlerGroup<State> {
        HandlerGroup {
            group: HandlerGroupMeta {
                name: name.to_owned(),
                description: "".to_owned(),
                visible: true,
            },
            ..Default::default()
        }
    }

    /// Creates a new unnamed group that can be loaded an unloaded
    pub fn unnamed_group() -> HandlerGroup<State> {
        HandlerGroup {
            group: HandlerGroupMeta {
                name: "".to_owned(),
                description: "".to_owned(),
                visible: false,
            },
            ..Default::default()
        }
    }

    /// Adds all the commands in a group
    pub fn add_group(&mut self, groups: &HandlerGroup<State>) {
        for handler in &groups.groups {
            self.add_command_from_handler(handler.clone());
        }
    }

    /// Removes all the commands in a group
    pub fn remove_group(&mut self, groups: &HandlerGroup<State>) {
        for command in &groups.groups {
            if self
                .editor
                .helper()
                .expect("helper is always provided")
                .dispatcher
                .iter()
                .any(|h| {
                    h.command.get_name() == command.command.get_name()
                        && h.group
                            .as_ref()
                            .map_or(false, |g| g.name == groups.group.name)
                })
            {
                self.remove_command(command.command.get_name());
            }
        }
    }

    /// Returns a thread-safe `Write` object that can be used to asyncronously write output to stdout
    /// without interferring with the promptline
    pub fn get_async_writer(&mut self) -> Result<impl std::io::Write, Box<dyn Error>> {
        let printer = self.editor.create_external_printer()?;
        Ok(AsyncStdout { printer })
    }

    /// Creates a prompt and reads a single line from the user
    pub fn read_line(&mut self, prompt: &str) -> Option<String> {
        self.editor.readline(prompt).ok()
    }

    /// Executes the appropriate command specified by the line read from the user
    pub fn one_cmd(&mut self, line: &str) -> ClapCmdResult {
        let words = split(line);
        let mut argv = vec![];
        for word in words {
            argv.push(&line[word.start..word.end]);
        }
        let argv: Vec<&str> = argv
            .into_iter()
            .skip_while(|word| word.is_empty())
            .collect();
        if argv.is_empty() {
            return Ok(());
        }
        let command_to_run = &argv[0].to_owned();
        let helper = self.editor.helper().expect("helper is always provided");
        let handler = helper
            .dispatcher
            .iter()
            .find(|h| h.command.get_name() == command_to_run);

        if handler.is_none() {
            println!("unknown command: '{command_to_run}'");
            return Ok(());
        }

        let handler = handler.expect("some type can always be unwrapped");
        let matches = handler.command.clone().try_get_matches_from_mut(argv);
        if matches.is_ok() {
            return handler
                .clone()
                .callback
                .call(self, matches.unwrap_or_default());
        }
        let err = matches.unwrap_err().kind();
        if err == clap::error::ErrorKind::DisplayHelp {
            handler.command.clone().print_help().unwrap_or_default();
            println!();
            return Ok(());
        }
        println!("error occured while parsing line: {:?}", err);
        Ok(())
    }

    /// Run the command loop until a callback returns `false`
    pub fn run_loop(&mut self) {
        loop {
            let prompt = self.prompt.clone();
            let prompt = prompt.as_str();
            let input = self.read_line(prompt);
            if input.is_none() {
                break;
            }
            let input = input.expect("input needs to be utf-8");
            if let Err(err) = self.one_cmd(&input) {
                if !err.is::<ExitError>() {
                    println!(
                        "received error: {}",
                        err.source().expect("error source unknown")
                    );
                    continue;
                }
                break;
            }
        }
    }
}