Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Last active July 26, 2023 08:20
Show Gist options
  • Save isurfer21/267acf904a0543935fa58075f7d36d93 to your computer and use it in GitHub Desktop.
Save isurfer21/267acf904a0543935fa58075f7d36d93 to your computer and use it in GitHub Desktop.
Minimalistic embeddable CLI argument parser in rust without any dependencies.
use std::collections::HashMap;
use regex::Regex;
// Define a function that returns a tuple of a hashmap of flags and values and an array of non-flag arguments
fn parse_args() -> (HashMap<String, String>, Vec<String>) {
// Create a hashmap to store the flags and values
let mut flags = HashMap::new();
// Create an array to store the non-flag arguments
let mut args = Vec::new();
// Create regular expressions to match different kinds of flags
let flag_with_value = Regex::new(r"^[\-\-]{1,2}.+[\=\:].*$").unwrap();
let flag_without_value = Regex::new(r"^[\-\-]{1,2}.+$").unwrap();
// Iterate over the command-line arguments, skipping the first two
for arg in std::env::args() {
match arg.as_str() {
// If the argument matches a flag with a value, split it and insert it into the hashmap
s if flag_with_value.is_match(s) => {
let parts = s.splitn(2, |c| c == '=' || c == ':').collect::<Vec<&str>>();
let key = parts[0].trim_start_matches('-');
let value = parts[1];
flags.insert(key.to_string(), value.to_string());
}
// If the argument matches a flag without a value, insert it into the hashmap with a true value
s if flag_without_value.is_match(s) => {
let key = s.trim_start_matches('-');
flags.insert(key.to_string(), true.to_string());
}
// Otherwise, push the argument into the array
s => {
args.push(s.to_string());
}
}
}
// Return the tuple of hashmap and array
(flags, args)
}
// Call the function from the main function or anywhere else
fn main() {
let (flags, args) = parse_args();
// Print the hashmap and array for testing
println!("{:?}", flags);
println!("{:?}", args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment