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
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
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()),
}
}
Use
cli structs and functions publicly so we can use them likerit::parse_args
instead ofrit::cli::parse_args
// src/lib.rs
pub use cli::*;
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