tokiocli 0.1.3

An Unix CLI based on Tokio
Documentation
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! A Unix [`Cli`] based on Tokio.
//!
//! This crate provide a simple library allowing to write
//! interactive Command Line Interface in an Unix spirit.
//!
//! APIs are async and thus can be easily integrated in a Tokio crate.
use eyre::Result;
use termios::*;
use tokio::io::{stdin, AsyncReadExt, BufReader, Stdin};

/** An Action performed by the user: execute a command or auto-complete the current command. */
pub enum Action {
    /** User demand to execute the following command (Command Name + Arguments). */
    Command(Vec<String>),
    /** User demand to auto-complete the following command (Command Name + Arguments). */
    AutoComplete(Vec<String>),
    /** getaction stopped without any actions to report (e.g. EOT was received, on an empty line). */
    NoAction,
}

/** Human-readable ANSI Escape Sequences */
#[allow(dead_code)]
enum EscSeq {
    Up(usize),
    Down(usize),
    Right(usize),
    Left(usize),
    HorizontalAbs(usize),
    EraseInDisplay(usize),
    EraseInLineFromCursorToEnd,
    EraseInLineFromCursorToBegining,
    EraseInLineAll,
}

impl std::fmt::Display for EscSeq {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Up(value) => write!(f, "\x1B[{}A", value),
            Self::Down(value) => write!(f, "\x1B[{}B", value),
            Self::Right(value) => write!(f, "\x1B[{}C", value),
            Self::Left(value) => write!(f, "\x1B[{}D", value),
            Self::HorizontalAbs(value) => write!(f, "\x1B[{}G", value),
            Self::EraseInDisplay(value) => write!(f, "\x1B[{}J", value),
            Self::EraseInLineFromCursorToEnd => write!(f, "\x1B[0K"),
            Self::EraseInLineFromCursorToBegining => write!(f, "\x1B[1K"),
            Self::EraseInLineAll => write!(f, "\x1B[2K"),
        }
    }
}

/** Provide APIs to interact with the Command Line Interface */
pub struct Cli {
    saved_termios: Termios,
    reader: BufReader<Stdin>,
    do_reset: bool,
    prompt: String,
    cmd: String,
    cursor: usize,
    history: Vec<String>,
    history_idx: Option<usize>,
}

impl Cli {
    /**
     * Create a new Command Line Interface.
     *
     * Note that it configures the terminal in character mode.
     */
    pub fn new() -> Result<Self> {
        let fd = 0;
        let saved = Termios::from_fd(fd)?;
        let mut termios = saved;
        termios.c_lflag &= !(ECHO | ECHONL | ICANON);
        tcsetattr(fd, TCSANOW, &termios)?;

        Ok(Self {
            saved_termios: saved,
            reader: BufReader::new(stdin()),
            do_reset: true,
            prompt: String::from("> "),
            cmd: String::new(),
            cursor: 0,
            history: Vec::<String>::new(),
            history_idx: None,
        })
    }

    fn cmd2args(&self) -> Vec<String> {
        let mut args = Vec::<String>::new();
        let mut arg = String::new();
        let mut is_string = false;
        let mut is_escaped = false;
        for c in self.cmd.chars() {
            if is_escaped {
                arg.push(c);
                is_escaped = false;
                continue;
            }
            match c {
                '\\' => {
                    is_escaped = true;
                }
                '"' => {
                    is_string = !is_string;
                }
                ' ' => {
                    match is_string {
                        true => {
                            arg.push(c);
                        }
                        false => {
                            args.push(arg.clone());
                            arg.clear();
                        }
                    };
                }
                _ => {
                    arg.push(c);
                }
            }
        }
        args.push(arg);
        args
    }

    fn clear_line(&self) -> Result<()> {
        eprint!("{}{}", EscSeq::EraseInLineAll, EscSeq::HorizontalAbs(0));
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        self.cmd.clear();
        self.cursor = 0;
        self.history_idx = None;
        eprint!("{}", self.prompt);
        Ok(())
    }

    fn history_restore(&mut self) -> Result<()> {
        let word = match self.history_idx {
            Some(idx) => &self.history[idx],
            None => {
                return Ok(());
            }
        };

        self.cmd = word.clone();
        self.cursor = match self.cmd.len() {
            0 => 0,
            len => len,
        };
        self.clear_line()?;
        eprint!("{}{}", self.prompt, self.cmd);

        Ok(())
    }

    fn history_prev(&mut self) -> Result<()> {
        self.history_idx = match self.history_idx {
            Some(idx) => match idx {
                0 => Some(idx),
                idx => Some(idx - 1),
            },
            None => match self.history.len() {
                0 => None,
                idx => Some(idx - 1),
            },
        };

        self.history_restore()
    }

    fn history_next(&mut self) -> Result<()> {
        self.history_idx = match self.history_idx {
            Some(idx) => {
                if (idx + 1) < self.history.len() {
                    Some(idx + 1)
                } else {
                    None
                }
            }
            None => None,
        };

        self.history_restore()
    }

    fn cursor_reset(&mut self) -> Result<()> {
        eprint!("{}", EscSeq::Left(self.cursor));
        self.cursor = 0;
        Ok(())
    }

    fn cursor_left(&mut self) -> Result<()> {
        if self.cursor > 0 {
            eprint!("{}", EscSeq::Left(1));
            self.cursor -= 1;
        }
        Ok(())
    }

    fn cursor_right(&mut self) -> Result<()> {
        if self.cursor < self.cmd.len() {
            eprint!("{}", EscSeq::Right(1));
            self.cursor += 1;
        }
        Ok(())
    }

    async fn escape(&mut self) -> Result<()> {
        let c = self.reader.read_u8().await?;
        if c != 0x5B {
            return Ok(());
        }
        let c = self.reader.read_u8().await?;
        match c {
            0x33 => {
                // SUPPR
                self.suppr().await?;
            }
            0x41 => {
                // UP
                self.history_prev()?;
            }
            0x42 => {
                // LOW
                self.history_next()?;
            }
            0x43 => {
                // RIGHT
                self.cursor_right()?;
            }
            0x44 => {
                // LEFT
                self.cursor_left()?;
            }
            _ => {
                eprintln!("Unhandled ANSI Escape Sequence: {}", c);
            }
        }
        Ok(())
    }

    fn addchar(&mut self, c: char) -> Result<()> {
        if self.cursor < self.cmd.len() {
            let right = &self.cmd[self.cursor..];
            eprint!("{}{}{}", c, right, EscSeq::Left(right.len()));
        } else {
            eprint!("{}", c);
        }

        self.cmd.insert(self.cursor, c);
        self.cursor += 1;
        Ok(())
    }

    fn backspace(&mut self) -> Result<()> {
        if self.cursor == 0 {
            return Ok(());
        }

        let right = &self.cmd[self.cursor..];
        self.cursor -= 1;
        eprint!("\x08{} {}", right, EscSeq::Left(right.len() + 1));
        self.cmd.remove(self.cursor);

        Ok(())
    }

    async fn suppr(&mut self) -> Result<()> {
        let c = self.reader.read_u8().await? as char;
        if c != '~' {
            eprintln!("Unexpect character {}", c);
            return Ok(());
        }
        if self.cursor + 1 < self.cmd.len() {
            let right = &self.cmd[self.cursor + 1..];
            eprint!("{} {}", right, EscSeq::Left(right.len() + 1));
            self.cmd.remove(self.cursor);
        }
        Ok(())
    }

    fn eol(&mut self) -> Result<Vec<String>> {
        eprintln!();
        let args = self.cmd2args();
        if !args[0].is_empty() {
            self.history.push(self.cmd.clone());
        }
        Ok(args)
    }

    /**
     * Return an Action demanded by the user in CLI.
     */
    pub async fn getaction(&mut self) -> Result<Action> {
        if self.do_reset {
            self.reset()?;
            self.do_reset = false;
        }
        loop {
            let c = self.reader.read_u8().await?;

            match c {
                0x01 | 0x02 => {
                    self.cursor_reset()?;
                }
                0x04 => {
                    if self.cmd.len() == 0 {
                        return Ok(Action::NoAction)
                    }
                }
                0x1B => {
                    // ESC (escap)
                    self.escape().await?;
                }
                0x7F => {
                    // DEL
                    self.backspace()?;
                }
                b'\n' => {
                    self.do_reset = true;
                    return Ok(Action::Command(self.eol()?));
                }
                b'\t' => {
                    return Ok(Action::AutoComplete(self.cmd2args()));
                }
                _ => {
                    self.addchar(c as char)?;
                }
            }
        }
    }

    /**
     * Auto-complete the current command with the provided list of possible words
     *
     * <div class="warning">The word list should only contains possible words for the current
     * input. This function does not filter out the word list, and expect all words in the list to
     * start with current input.</div>
     */
    pub fn autocomplete(&mut self, words: &Vec<String>) -> Result<()> {
        if words.is_empty() {
            // Nothing to do
            return Ok(());
        }

        // Retrieve common word
        let mut common = words[0].as_str();
        for word in words {
            common = common_chars(word, common);
        }

        // Get completion word from common word
        let args = self.cmd2args();
        let lastarg = args.last().unwrap();
        let complete = &common[lastarg.len()..];

        if words.len() == 1 {
            // Complete current line
            self.cmd += complete;
            self.cursor += complete.len();
            eprint!("{}", complete);
        } else {
            // Display all possibilites
            eprintln!();
            for word in words {
                eprint!("{} ", word);
            }
            // Write back partially completed command
            self.cmd += complete;
            self.cursor += complete.len();
            eprint!("\n{}{}", self.prompt, self.cmd);
        }

        Ok(())
    }

    /** Set the name of the prompt */
    pub fn setprompt(&mut self, prompt: &str) -> &mut Self {
        self.prompt = prompt.into();
        self
    }
}

impl Drop for Cli {
    /**
     * Release Cli ressources and configure back the terminal in its orignal state.
     */
    fn drop(&mut self) {
        let fd = 0;
        if let Err(e) = tcsetattr(fd, TCSANOW, &self.saved_termios) {
            eprintln!("Failed to restore terminal config: {:?}", e);
        }
    }
}

fn common_chars<'a>(lstr: &'a str, rstr: &'_ str) -> &'a str {
    let lindices = lstr.char_indices();
    let mut rindices = rstr.char_indices();
    let mut common = 0;

    for (_, lchar) in lindices {
        match rindices.next() {
            Some((_, rchar)) => {
                if lchar != rchar {
                    break;
                }
                common += 1;
            }
            None => {
                break;
            }
        };
    }

    &lstr[0..common]
}