Sunday, July 9, 2023

Rust Cargo Workspaces

 



In this post we will review the steps to create a multi workspaces rust project.


For this example we will create a flags parsing library that gets settings from the arguments and from the environment variables, while using defaults if the setting is not configured.


Creating the workspace and crates


First we create a new folder for the workspace, and add the binary create to the project:

mkdir flagger
cd flagger/


Create a Cargo.toml file with the following content:

[workspace]

members = [
"flags_printer",


And then run:

cargo new flags_printer

 

Next we add a library to parse the flags.
We update the root Cargo.toml file:

[workspace]

members = [
"flags_printer",
"flags_parser",
]


and create the library crate:

cargo new flags_parser --lib

lastly we add dependency in flags_printer to the flags_parser in flags_printer/Cargo.toml

[dependencies]
flags_parser = { path = "../flags_parser" }


Creating the parser code

The main.rs:


use flags_parser::FlagsParser;

fn main() {
let mut parser = FlagsParser::new();
parser.configure_flag("runs","1");
parser.parse_flags();
}


The lib.rs:


use std::collections::HashMap;
use std::env;

pub struct FlagsParser {
values: HashMap<&'static str, &'static str>,
}

impl FlagsParser {
pub fn new() -> Self {
return FlagsParser {
values: Default::default(),
};
}
pub fn configure_flag(
&mut self,
name: &'static str,
default_value: &'static str,
) {
self.values.insert(name, default_value);
}

pub fn parse_flags(
&mut self,
) {
let mut last_key = "";
for argument in env::args() {
if last_key != "" {
let value:&str = Box::leak(argument.into_boxed_str());
self.values.insert(last_key, value);
last_key = ""
} else {
for (key, _) in &self.values {
if argument == "--".to_owned() + key {
last_key = key;
}
}
}
}

println!("{:?}",&self.values)
}
}




No comments:

Post a Comment