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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! [![Build Status](https://travis-ci.com/kurtlawrence/cmdtree.svg?branch=master)](https://travis-ci.com/kurtlawrence/cmdtree)
//! [![Latest Version](https://img.shields.io/crates/v/cmdtree.svg)](https://crates.io/crates/cmdtree) 
//! [![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/cmdtree) 
//! [![codecov](https://codecov.io/gh/kurtlawrence/cmdtree/branch/master/graph/badge.svg)](https://codecov.io/gh/kurtlawrence/cmdtree)
//! 
//! (Rust) commands tree.
//! 
//! See the [rs docs](https://docs.rs/cmdtree/).
//! Look at progress and contribute on [github.](https://github.com/kurtlawrence/cmdtree)
//! 
//! # cmdtree
//! 
//! Create a tree-like data structure of commands and actions to add an intuitive and interactive experience to an application.
//! cmdtree uses a builder pattern to make constructing the tree ergonomic.
//! 
//! # Example
//! 
//! ```rust,no_run
//! extern crate cmdtree;
//! use cmdtree::*;
//! 
//! fn main() {
//!   let cmder = Builder::default_config("cmdtree-example")
//!     .begin_class("class1", "class1 help message") // a class
//!     .begin_class("inner-class1", "nested class!") // can nest a class
//!     .add_action("name", "print class name", |mut wtr, _args| {
//!       writeln!(wtr, "inner-class1",).unwrap()
//!     })
//!     .end_class()
//!     .end_class() // closes out the classes
//!     .begin_class("print", "pertains to printing stuff") // start another class sibling to `class1`
//!     .add_action("echo", "repeat stuff", |mut wtr, args| {
//!       writeln!(wtr, "{}", args.join(" ")).unwrap()
//!     })
//!     .add_action("countdown", "countdown from a number", |mut wtr, args| {
//!       if args.len() != 1 {
//!         println!("need one number",);
//!       } else {
//!         match str::parse::<u32>(args[0]) {
//!           Ok(n) => {
//!             for i in (0..=n).rev() {
//!               writeln!(wtr, "{}", i).unwrap();
//!             }
//!           }
//!           Err(_) => writeln!(wtr, "expecting a number!",).unwrap(),
//!         }
//!       }
//!     })
//!     .into_commander() // can short-circuit the closing out of classes
//!     .unwrap();
//! 
//!   cmder.run(); // run interactively
//! }
//! ```
//! 
//! Now run and in your shell:
//! 
//! ```sh
//! cmdtree-example=> help            <-- Will print help messages
//! help -- prints the help messages
//! cancel | c -- returns to the root class
//! exit -- sends the exit signal to end the interactive loop
//! Classes:
//!         class1 -- class1 help message
//!         print -- pertains to printing stuff
//! cmdtree-example=> print            <-- Can navigate the tree
//! cmdtree-example.print=> help
//! help -- prints the help messages
//! cancel | c -- returns to the root class
//! exit -- sends the exit signal to end the interactive loop
//! Actions:
//!         echo -- repeat stuff
//!         countdown -- countdown from a number
//! cmdtree-example.print=> echo hello, world!  <-- Call the actions
//! hello, world!
//! cmdtree-example.print=> countdown
//! need one number
//! cmdtree-example.print=> countdown 10
//! 10
//! 9
//! 8
//! 7
//! 6
//! 5
//! 4
//! 3
//! 2
//! 1
//! 0
//! cmdtree-example.print=> exit      <-- exit the loop!
//! ```

#![warn(missing_docs)]

use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::fmt;
use std::io::Write;
use std::sync::{Arc, Mutex};

pub mod builder;
pub mod completion;
mod parse;

pub use self::parse::LineResult;
pub use builder::{BuildError, Builder, BuilderChain};

/// A constructed command tree.
///
/// Most of the time a user will want to use `run()` which will handle all the parsing and navigating of the tree.
/// Alternatively, `parse_line` can be used to simulate a read input and update the command tree position.
///
/// To construct a command tree, look at the [`builder` module](./builder/index.html).
pub struct Commander<'r, R> {
    root: Arc<SubClass<'r, R>>,
    current: Arc<SubClass<'r, R>>,
    path: String,
}

impl<'r, R> Commander<'r, R> {
    /// Return the root name.
    ///
    /// # Example
    /// ```rust
    /// # use cmdtree::*;
    /// let mut cmder = Builder::default_config("base")
    ///		.begin_class("one", "")
    ///		.begin_class("two", "")
    ///		.into_commander().unwrap();
    ///
    ///	assert_eq!(cmder.root_name(), "base");
    /// ```
    pub fn root_name(&self) -> &str {
        &self.root.name
    }

    /// Return the path of the current class, separated by `.`.
    ///
    /// # Example
    /// ```rust
    /// # use cmdtree::*;
    /// let mut cmder = Builder::default_config("base")
    ///		.begin_class("one", "")
    ///		.begin_class("two", "")
    ///		.into_commander().unwrap();
    ///
    ///	assert_eq!(cmder.path(), "base");
    ///	cmder.parse_line("one two", true,  &mut std::io::sink());
    ///	assert_eq!(cmder.path(), "base.one.two");
    /// ```
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns if the commander is sitting at the root class.
    ///
    /// # Example
    /// ```rust
    /// # use cmdtree::*;
    /// let mut cmder = Builder::default_config("base")
    ///		.begin_class("one", "")
    ///		.begin_class("two", "")
    ///		.into_commander().unwrap();
    ///
    ///	assert!(cmder.at_root());
    ///	cmder.parse_line("one two", true,  &mut std::io::sink());
    ///	assert_eq!(cmder.at_root(), false);
    /// ```
    pub fn at_root(&self) -> bool {
        self.current == self.root
    }

    /// Run the `Commander` interactively.
    /// Consumes the instance, and blocks the thread until the loop is exited.
    ///
    /// This is the most simple way of using a `Commander`.
    #[cfg(feature = "runnable")]
    pub fn run(self) {
        self.run_with_completion(|_| linefeed::complete::DummyCompleter)
    }

    /// Returns the command structure as a sorted set.
    ///
    /// Can return from the the current class or the root.
    ///
    /// Each item is a dot separated path, except for actions which are separated by a double dot.
    ///
    /// # Examples
    /// ```rust
    /// # use cmdtree::*;
    /// let cmder = Builder::default_config("base")
    ///		.begin_class("one", "")
    ///		.begin_class("two", "")
    /// 	.end_class()
    /// 	.add_action("action", "", |_,_| ())
    /// 	.end_class()
    /// 	.add_action("action", "", |_,_| ())
    ///		.into_commander().unwrap();
    ///
    /// let structure = cmder.structure(true);
    ///
    /// assert_eq!(structure.iter().map(|x| x.path.as_str()).collect::<Vec<_>>(), vec![
    /// 	"..action",
    /// 	"one",
    /// 	"one..action",
    /// 	"one.two",
    /// ]);
    /// ```
    pub fn structure(&self, from_root: bool) -> BTreeSet<StructureInfo<'r>> {
        let mut set = BTreeSet::new();

        let mut stack: Vec<(String, _)> = {
            let r = if from_root { &self.root } else { &self.current };

            for action in r.actions.iter() {
                set.insert(StructureInfo {
                    path: format!("..{}", action.name),
                    itemtype: ItemType::Action,
                    help_msg: action.help,
                });
            }

            r.classes.iter().map(|x| (x.name.clone(), x)).collect()
        };

        while let Some(item) = stack.pop() {
            let (parent_path, parent) = item;

            for action in parent.actions.iter() {
                set.insert(StructureInfo {
                    path: format!("{}..{}", parent_path, action.name),
                    itemtype: ItemType::Action,
                    help_msg: action.help,
                });
            }

            for class in parent.classes.iter() {
                stack.push((format!("{}.{}", parent_path, class.name), class));
            }

            set.insert(StructureInfo {
                path: parent_path,
                itemtype: ItemType::Class,
                help_msg: parent.help,
            });
        }

        set
    }
}

#[derive(Debug, Eq)]
struct SubClass<'a, R> {
    name: String,
    help: &'a str,
    classes: Vec<Arc<SubClass<'a, R>>>,
    actions: Vec<Action<'a, R>>,
}

impl<'a, R> SubClass<'a, R> {
    fn with_name(name: &str, help_msg: &'a str) -> Self {
        SubClass {
            name: name.to_lowercase(),
            help: help_msg,
            classes: Vec::new(),
            actions: Vec::new(),
        }
    }
}

impl<'a, R> PartialEq for SubClass<'a, R> {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.help == other.help
            && self.classes == other.classes
            && self.actions == other.actions
    }
}

struct Action<'a, R> {
    name: String,
    help: &'a str,
    closure: Mutex<Box<dyn FnMut(&mut dyn Write, &[&str]) -> R + Send + 'a>>,
}

impl<'a, R> Action<'a, R> {
    fn call<W: Write>(&self, wtr: &mut W, arguments: &[&str]) -> R {
        let c = &mut *self.closure.lock().expect("locking command action failed");
        c(wtr, arguments)
    }
}

impl<'a> Action<'a, ()> {
    #[cfg(test)]
    fn blank_fn(name: &str, help_msg: &'a str) -> Self {
        Action {
            name: name.to_lowercase(),
            help: help_msg,
            closure: Mutex::new(Box::new(|_, _| ())),
        }
    }
}

impl<'a, R> PartialEq for Action<'a, R> {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.help == other.help
    }
}

impl<'a, R> Eq for Action<'a, R> {}

impl<'a, R> fmt::Debug for Action<'a, R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Action {{ name: {}, help: {} }}", self.name, self.help)
    }
}

/// An item in the command tree.
pub struct StructureInfo<'a> {
    /// Period delimited path. Actions are double delimted.
    ///
    /// Eg.
    /// - A class: `a.nested.class`
    /// - An action: `a.nested.class..action`
    pub path: String,
    /// Class or Action.
    pub itemtype: ItemType,
    /// The help message.
    pub help_msg: &'a str,
}

impl<'a> PartialEq for StructureInfo<'a> {
    fn eq(&self, other: &StructureInfo) -> bool {
        self.path == other.path
    }
}

impl<'a> Eq for StructureInfo<'a> {}

impl<'a> PartialOrd for StructureInfo<'a> {
    fn partial_cmp(&self, other: &StructureInfo) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a> Ord for StructureInfo<'a> {
    fn cmp(&self, other: &StructureInfo) -> Ordering {
        self.path.cmp(&other.path)
    }
}

/// A command type.
#[derive(Debug, PartialEq)]
pub enum ItemType {
    /// Class type.
    Class,
    /// Action type.
    Action,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn subclass_with_name_test() {
        let sc = SubClass::<()>::with_name("NAME", "Help Message");
        assert_eq!(&sc.name, "name");
        assert_eq!(sc.help, "Help Message");
    }

    #[test]
    fn action_debug_test() {
        let a = Action::blank_fn("action-name", "help me!");
        assert_eq!(
            &format!("{:?}", a),
            "Action { name: action-name, help: help me! }"
        );
    }

    #[test]
    fn current_path_test() {
        let mut cmder = Builder::default_config("base")
            .begin_class("one", "")
            .begin_class("two", "")
            .into_commander()
            .unwrap();

        let w = &mut std::io::sink();

        assert_eq!(cmder.path(), "base");

        cmder.parse_line("one two", true, w);
        assert_eq!(cmder.path(), "base.one.two");

        cmder.parse_line("c", true, w);
        assert_eq!(cmder.path(), "base");

        cmder.parse_line("one", true, w);
        assert_eq!(cmder.path(), "base.one");
    }

    #[test]
    fn root_test() {
        let mut cmder = Builder::default_config("base")
            .begin_class("one", "")
            .begin_class("two", "")
            .into_commander()
            .unwrap();

        let w = &mut std::io::sink();

        assert_eq!(cmder.at_root(), true);

        cmder.parse_line("one two", true, w);
        assert_eq!(cmder.at_root(), false);

        cmder.parse_line("c", true, w);
        assert_eq!(cmder.at_root(), true);
    }

    #[test]
    fn structure_test() {
        let mut cmder = Builder::default_config("base")
            .begin_class("one", "")
            .begin_class("two", "")
            .end_class()
            .add_action("action", "", |_, _| ())
            .end_class()
            .add_action("action", "", |_, _| ())
            .into_commander()
            .unwrap();

        cmder.parse_line("one", false, &mut std::io::sink());

        let structure = cmder.structure(true);

        assert_eq!(
            structure
                .iter()
                .map(|x| x.path.as_str())
                .collect::<Vec<_>>(),
            vec!["..action", "one", "one..action", "one.two",]
        );

        let structure = cmder.structure(false);

        assert_eq!(
            structure
                .iter()
                .map(|x| x.path.as_str())
                .collect::<Vec<_>>(),
            vec!["..action", "two",]
        );
    }
}