🎉 ✨ add CLI args (help and version).
parent
f413c33c24
commit
1cc295a63b
|
@ -0,0 +1 @@
|
|||
/target
|
|
@ -0,0 +1,7 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "alchimake"
|
||||
version = "0.1.0"
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "alchimake"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1 @@
|
|||
pub mod parse;
|
|
@ -0,0 +1,145 @@
|
|||
pub fn getval(args: &Vec<&str>, flag: &str)
|
||||
-> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let mut val: Option<String> = None;
|
||||
let mut found = false;
|
||||
|
||||
for (i, arg) in args.iter().enumerate() {
|
||||
if flag == *arg {
|
||||
found = true;
|
||||
if let Some(next) = args.iter().nth(i + 1) {
|
||||
val = Some(next.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
Ok(val)
|
||||
} else {
|
||||
Err(format!("flag {} not found", flag).into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
pub help: String
|
||||
}
|
||||
|
||||
type Callback = Box<dyn Fn(Option<String>, Context)>;
|
||||
|
||||
pub struct Arg {
|
||||
pub flags: Vec<String>,
|
||||
pub description: Option<String>,
|
||||
pub callback: Option<Callback>
|
||||
}
|
||||
|
||||
pub struct Args {
|
||||
args: Vec<Arg>,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
args: vec![]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn help(&self) -> String {
|
||||
let mut res = String::from("Usage: alchimake [OPTION]...\n");
|
||||
res += "OPTIONS:\n";
|
||||
for arg in self.args.iter() {
|
||||
if let Some(description) = &arg.description {
|
||||
res += format!(
|
||||
"\t{}\t{}\n",
|
||||
arg.flags.join(", "),
|
||||
description
|
||||
).as_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
pub fn parse(&mut self, args: &Vec<&str>)
|
||||
-> Result<(), Box<dyn std::error::Error>> {
|
||||
let help = self.help();
|
||||
|
||||
for cli_arg in args {
|
||||
for arg in self.args.iter_mut() {
|
||||
for flag in arg.flags.iter() {
|
||||
if &flag == cli_arg {
|
||||
if let Some(ref callback) = arg.callback {
|
||||
let value = getval(&args, &flag)?;
|
||||
callback(value.clone(), Context {
|
||||
help: help.clone()
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register(&mut self, flags: &Vec<&str>) -> &mut Self {
|
||||
let arg = Arg {
|
||||
flags: flags.iter().map(|&v| v.to_owned()).collect(),
|
||||
description: None,
|
||||
callback: None
|
||||
};
|
||||
self.args.push(arg);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn description(&mut self, desc: &str) -> &mut Self {
|
||||
let idx = self.args.len() - 1;
|
||||
self.args[idx].description = Some(desc.to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn callback(&mut self,
|
||||
callback: Callback) -> &mut Self{
|
||||
let idx = self.args.len() - 1;
|
||||
self.args[idx].callback = Some(Box::new(callback));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
#[test]
|
||||
fn get_value() {
|
||||
let args: Vec<&str> = vec![
|
||||
"gcc", "-o", "output", "input"
|
||||
];
|
||||
|
||||
assert_eq!(Some(String::from("output")),
|
||||
getval(&args, "-o").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_command() -> TestResult {
|
||||
let mut args = Args::new();
|
||||
|
||||
args.register(&vec!["-o", "--output"])
|
||||
.description("set output file")
|
||||
.callback(Box::new(|value, _| {
|
||||
assert_eq!(value, Some("hello.elf".to_owned()));
|
||||
}));
|
||||
|
||||
args.register(&vec!["-c"])
|
||||
.description("make obj")
|
||||
.callback(Box::new(|_, _| {
|
||||
assert!(false);
|
||||
}));
|
||||
|
||||
args.parse(&vec!["gcc", "-o", "hello.elf", "hello.c"])?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
mod cli;
|
||||
|
||||
use crate::cli::parse;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = parse::Args::new();
|
||||
let sys_args: Vec<String> = std::env::args().collect();
|
||||
|
||||
args.register(&vec!["-h", "--help"])
|
||||
.description("show this help")
|
||||
.callback(Box::new(|_, ctx| {
|
||||
println!("{}", ctx.help);
|
||||
std::process::exit(0);
|
||||
}));
|
||||
|
||||
args.register(&vec!["-v", "--version"])
|
||||
.description("show alchimake version")
|
||||
.callback(Box::new(|_, _| {
|
||||
println!("Alchimake v0.0.0");
|
||||
println!("Copyright (C) 2024 bog");
|
||||
println!("Licensed under the GPLv3+ (see LICENSE)");
|
||||
std::process::exit(0);
|
||||
}));
|
||||
|
||||
args.parse(&sys_args.iter().map(|v| v.as_str()).collect())?;
|
||||
|
||||
Ok(())
|
||||
}
|
Loading…
Reference in New Issue