Implement git init Command

Add parsing arguments basics using clap crate. Parse to have a simple CLI realizing the init command. No more than just respecting rit init

  1. Create a new module named cli

// src/lib.rs
pub mod cli;

the directory structure should be like:

src/
├── cli
│   └── mod.rs
├── lib.rs
└── main.rs
  1. Start parsing arguments in src/cli/mod.rs like:

We're not going to use any crates for errors right now, Let's just return a simple String error.

// 1. Import necessary structs.
use clap::{command, Arg, Command as ClapCommand};

// 2. Add Debug trait to be able to print it out
#[derive(Debug)]
pub enum Command {
    Init,
}

// 3. Implement initial argument parsing.
pub fn parse_args() -> Result<Command, String> {
    let matches = command!()
        .subcommand(ClapCommand::new("init").arg(Arg::new("init")))
        .get_matches();

    match matches.subcommand_matches("init") {
        Some(_subcommand) => Ok(Command::Init),
        None => Err("Failed to parse".to_string()),
    }
}
  1. Use cli structs and functions publicly so we can use them like rit::parse_args instead of rit::cli::parse_args

// src/lib.rs

pub use cli::*;
  1. Use parse_args and print the results in the main:

// src/main.rs
use rit::parse_args;

fn main() {
    let command = parse_args().unwrap();
    println!("{:?}", command);
}

Last updated