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
//! This module implements a default repl that fullfills the [Repl] trait
//!
//! You can implement your own [Repl] if you want.

use std::fmt::Debug;

use super::Repl;

use embed_doc_image::embed_doc_image;

/// [clap] help template with only usage and commands/options
pub const REPL_HELP_TEMPLATE: &str = r"{usage-heading} {usage}

{all-args}{tab}
";

use clap::{Parser, Subcommand};
use dialoguer::{BasicHistory, Completion};
use libpt_log::trace;

#[allow(clippy::needless_doctest_main)] // It makes the example look better
/// Default implementation for a REPL
///
/// Note that you need to define the commands by yourself with a Subcommands enum.
///
/// # Example
///
/// ```no_run
/// use libpt_cli::repl::{DefaultRepl, Repl};
/// use libpt_cli::clap::Subcommand;
/// use libpt_cli::strum::EnumIter;
///
/// #[derive(Subcommand, Debug, EnumIter, Clone)]
/// enum ReplCommand {
///     /// hello world
///     Hello,
///     /// leave the repl
///     Exit,
/// }
///
/// fn main() {
///     let mut repl = DefaultRepl::<ReplCommand>::default();
///     loop {
///         repl.step().unwrap();
///         match repl.command().to_owned().unwrap() {
///             ReplCommand::Hello => println!("Hello"),
///             ReplCommand::Exit => break,
///             _ => (),
///         }
///     }
/// }
/// ```
/// **Screenshot**
///
/// ![Screenshot of an example program with a REPL][repl_screenshot]
#[embed_doc_image("repl_screenshot", "data/media/repl.png")]
#[derive(Parser)]
#[command(multicall = true, help_template = REPL_HELP_TEMPLATE)]
#[allow(clippy::module_name_repetitions)] // we can't just name it `Default`, that's part of std
pub struct DefaultRepl<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    /// the command you want to execute, along with its arguments
    #[command(subcommand)]
    command: Option<C>,

    // the following fields are not to be parsed from a command, but used for the internal workings
    // of the repl
    #[clap(skip)]
    buf: String,
    #[clap(skip)]
    buf_preparsed: Vec<String>,
    #[clap(skip)]
    completion: DefaultReplCompletion<C>,
    #[clap(skip)]
    history: BasicHistory,
}

#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, PartialOrd, Ord)]
struct DefaultReplCompletion<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    commands: std::marker::PhantomData<C>,
}

impl<C> Repl<C> for DefaultRepl<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    fn new() -> Self {
        Self {
            command: None,
            buf_preparsed: Vec::new(),
            buf: String::new(),
            history: BasicHistory::new(),
            completion: DefaultReplCompletion::new(),
        }
    }
    fn command(&self) -> &Option<C> {
        &self.command
    }
    fn step(&mut self) -> Result<(), super::error::Error> {
        self.buf.clear();

        // NOTE: display::Input requires some kind of lifetime that would be a bother to store in
        // our struct. It's documentation also uses it in place, so it should be fine to do it like
        // this.
        //
        // NOTE: It would be nice if we could use the Validator mechanism of dialoguer, but
        // unfortunately we can only process our input after we've preparsed it and we need an
        // actual output. If we could set a status after the Input is over that would be amazing,
        // but that is currently not supported by dialoguer.
        // Therefore, every prompt will show as success regardless.
        self.buf = dialoguer::Input::with_theme(&dialoguer::theme::ColorfulTheme::default())
            .completion_with(&self.completion)
            .history_with(&mut self.history)
            .interact_text()?;

        self.buf_preparsed = Vec::new();
        self.buf_preparsed
            .extend(shlex::split(&self.buf).unwrap_or_default());

        trace!("read input: {:?}", self.buf_preparsed);
        trace!("repl after step: {:#?}", self);

        // HACK: find a way to not allocate a new struct for this
        let cmds = Self::try_parse_from(&self.buf_preparsed)?;
        self.command = cmds.command;
        Ok(())
    }
}

impl<C> Default for DefaultRepl<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<C> Debug for DefaultRepl<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DefaultRepl")
            .field("command", &self.command)
            .field("buf", &self.buf)
            .field("buf_preparsed", &self.buf_preparsed)
            .field("completion", &self.completion)
            .field("history", &"(no debug)")
            .finish()
    }
}

impl<C> DefaultReplCompletion<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    /// Make a new [`DefaultReplCompletion`] for the type `C`
    pub const fn new() -> Self {
        Self {
            commands: std::marker::PhantomData::<C>,
        }
    }
    fn commands() -> Vec<String> {
        let mut buf = Vec::new();
        // every crate has the help command, but it is not part of the enum
        buf.push("help".to_string());
        for c in C::iter() {
            // HACK: this is a horrible way to do this
            // I just need the names of the commands
            buf.push(
                format!("{c:?}")
                    .split_whitespace()
                    .map(str::to_lowercase)
                    .next()
                    .unwrap()
                    .to_string(),
            );
        }
        trace!("commands: {buf:?}");
        buf
    }
}

impl<C> Default for DefaultReplCompletion<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<C> Completion for DefaultReplCompletion<C>
where
    C: Debug + Subcommand + strum::IntoEnumIterator,
{
    /// Simple completion implementation based on substring
    fn get(&self, input: &str) -> Option<String> {
        let matches = Self::commands()
            .into_iter()
            .filter(|option| option.starts_with(input))
            .collect::<Vec<_>>();

        trace!("\nmatches: {matches:#?}");
        if matches.len() == 1 {
            Some(matches[0].to_string())
        } else {
            None
        }
    }
}