GithubHelp home page GithubHelp logo

cmd's Introduction

rusty-cmd

A crate for creating custom line-oriented command interpreters in Rust.

License: MIT Rust Documentation

I wrote this as a Rust learning project and was inspired by Python's cmd and the dev.to article: A small library for writing line oriented-command interpreters in rust.

Features

  • Create and register custom command interpreters using the CommandHandler trait, functions or closures.
  • Easily define and execute commands.
  • Implement optional command arguments.
  • Redirect output to types that implement io::Write.

Overview

rusty-cmd provides two modules:

  • cmd: Used for creating the Cmd struct that contains the CommandHandler implementations in a HashMap.
  • command_handler: Contains the CommandHandler trait.

Example

use std::io;
use std::io::Write;

use rusty_cmd::cmd::Cmd;
use rusty_cmd::command_handler::{CommandHandler, CommandResult};
use rusty_cmd::handlers::Quit;

/// CommandHandler that prints out help message
#[derive(Default)]
pub struct Help;

impl<W> CommandHandler<W> for Help
where
    W: std::io::Write,
{
    fn execute(&self, output: &mut W, _args: &[&str]) -> CommandResult {
        writeln!(output, "Help message").expect("Should be able to write to output");
        CommandResult::Continue
    }
}

/// CommandHandler that emulates the basic bash touch command to create a new file
#[derive(Default)]
pub struct Touch;

impl<W> CommandHandler<W> for Touch
where
    W: std::io::Write,
{
    fn execute(&self, output: &mut W, _args: &[&str]) -> CommandResult {
        let option_filename = _args.first();

        match option_filename {
            Some(filename) => {
                let fs_result = std::fs::File::create(filename);
                match fs_result {
                    Ok(file) => writeln!(output, "Created file: {:?}", file)
                        .expect("Should be able to write to output"),
                    Err(_) => writeln!(output, "Could not create file: {}", filename)
                        .expect("Should be able to write to output"),
                }
            }
            None => println!("Need to specify a filename"),
        }
        CommandResult::Continue
    }
}

fn main() -> Result<(), std::io::Error> {
    let mut cmd = Cmd::new(io::BufReader::new(io::stdin()), io::stdout());

    let help = Help;
    let hello = Touch;
    let quit = Quit::default();

    cmd.add_cmd(String::from("help"), help)?;
    cmd.add_cmd(String::from("touch"), hello)?;
    cmd.add_cmd_fn(String::from("greet"), |output, _args| {
        writeln!(output, "hello!").expect("Should be able to write to output");
        CommandResult::Continue
    })?;
    cmd.add_cmd(String::from("quit"), quit)?;

    cmd.run()?;

    Ok(())
}

Usage

To use rusty-cmd in your project, add the following to your Cargo.toml file:

[dependencies]
rusty-cmd = "2.0.0"

Then import the crate in your Rust code:

use rusty_cmd::command_handler::{CommandHandler, CommandResult};
use rusty_cmd::cmd::Cmd;

Contributing

We welcome contributions! See our CONTIBUTING guide

Contributors โœจ

Miguel Alizo
Miguel Alizo

๐Ÿฆ€โœ…
John Aughey
John Aughey

๐Ÿฆ€โœ…

License

This project is licensed under the MIT License - see the LICENSE file for details.

cmd's People

Contributors

aughey avatar miguelalizo avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.