Ajout : module variables

This commit is contained in:
Ahurac 2024-04-17 15:04:28 +02:00
parent eaa9622446
commit fa9033beea
2 changed files with 51 additions and 0 deletions

View file

@ -4,6 +4,7 @@ mod error;
mod exit_code;
mod interface;
mod parser;
mod variables;
fn main() {
control::run();

50
src/variables.rs Normal file
View file

@ -0,0 +1,50 @@
use std::collections::HashMap;
use std::env;
struct Variables {
variables: HashMap<String, String>,
}
impl Variables {
fn get(&self, key: &str) -> String {
let var_from_map = self.variables.get(key);
let value: String;
if var_from_map.is_none() {
let var_in_env = env::var(key);
value = match var_in_env {
Ok(value) => value,
Err(_e) => String::new(),
}
} else {
value = var_from_map.unwrap().clone();
}
value
}
fn unset(&mut self, key: &str) {
let old_value = self.variables.remove(key);
if old_value.is_none() {
env::remove_var(key);
}
}
fn set(&mut self, key: &str, value: &str) {
self.variables
.insert(String::from(key), String::from(value));
}
fn export(&mut self, key: &str) {
let var_to_export = self.variables.get(key);
if var_to_export.is_some() {
env::set_var(key, var_to_export.unwrap());
self.variables.remove(key);
} else {
env::set_var(key, "");
}
}
}