rusty_cmd/lib.rs
1//! A crate for creating custom line-oriented command interpreters.
2//!
3//! # A tour of cmd
4//!
5//! cmd consists of three crates:
6//! - cmd: Used for creating the cmd::Cmd struct that contains the CommandHandler implementations as in a HashMap
7//! - command_handler: Contains the CommandHandler trait
8//! - handlers: Contains ready-to-use Quit CommandHandler struct
9//!
10//! ## Example
11//! ```rust
12//! use std::io;
13//! use std::io::Write;
14//!
15//! use rusty_cmd::cmd::Cmd;
16//! use rusty_cmd::command_handler::{CommandHandler, CommandResult};
17//! use rusty_cmd::handlers::Quit;
18//!
19//! /// CommandHandler that prints out help message
20//! #[derive(Default)]
21//! pub struct Help;
22//!
23//! impl<W> CommandHandler<W> for Help
24//! where
25//! W: std::io::Write,
26//! {
27//! fn execute(&self, output: &mut W, _args: &[&str]) -> CommandResult {
28//! writeln!(output, "Help message").expect("Should be able to write to output");
29//! CommandResult::Continue
30//! }
31//! }
32//!
33//! /// CommandHandler that emulates the basic bash touch command to create a new file
34//! #[derive(Default)]
35//! pub struct Touch;
36//!
37//! impl<W> CommandHandler<W> for Touch
38//! where
39//! W: std::io::Write,
40//! {
41//! fn execute(&self, output: &mut W, _args: &[&str]) -> CommandResult {
42//! let option_filename = _args.first();
43//!
44//! match option_filename {
45//! Some(filename) => {
46//! let fs_result = std::fs::File::create(filename);
47//! match fs_result {
48//! Ok(file) => writeln!(output, "Created file: {:?}", file)
49//! .expect("Should be able to write to output"),
50//! Err(_) => writeln!(output, "Could not create file: {}", filename)
51//! .expect("Should be able to write to output"),
52//! }
53//! }
54//! None => println!("Need to specify a filename"),
55//! }
56//! CommandResult::Continue
57//! }
58//! }
59//!
60//! fn main() -> Result<(), std::io::Error> {
61//! let mut cmd = Cmd::new(io::BufReader::new(io::stdin()), io::stdout());
62//!
63//! let help = Help;
64//! let hello = Touch;
65//! let quit = Quit::default();
66//!
67//! cmd.add_cmd(String::from("help"), help)?;
68//! cmd.add_cmd(String::from("touch"), hello)?;
69//! cmd.add_cmd_fn(String::from("greet"), |output, _args| {
70//! writeln!(output, "hello!").expect("Should be able to write to output");
71//! CommandResult::Continue
72//! })?;
73//! cmd.add_cmd(String::from("quit"), quit)?;
74//!
75//! // cmd.run()?; // uncomment to run
76//!
77//! Ok(())
78//! }
79//! ```
80
81/// Used for creating the cmd::Cmd struct that contains the CommandHandler implementations as in a HashMap.
82pub mod cmd;
83
84/// Contains the CommandHandler trait.
85pub mod command_handler;
86
87/// Contains common ready-to-use handlers
88pub mod handlers;