rux/src/config.rs
2017-11-07 21:28:57 -06:00

92 lines
3.5 KiB
Rust

use super::{std, help, PackageManager};
use management::Management;
use std::process::Command;
/// A struct to hold parsed arg data.
// TODO?: update to take mutltiple terms?
#[derive(Debug)]
pub struct Config {
pub action: Management,
pub term: Option<String>,
}
impl Config {
/// Actually runs the package manager. Checks what command was requested
/// and loads the appropriate data from the passed `PackageManager`.
/// Finally calls the program and passes the appropriate arguments
pub fn run(&self, pac: PackageManager) {
let get = match self.action {
Management::Search => pac.search,
Management::Install => pac.install,
Management::Uninstall => pac.uninstall,
Management::Remove => pac.purge,
Management::Update => pac.update,
Management::Upgrade => pac.upgrade,
Management::Full => pac.sup,
Management::Clear => pac.cache_clear,
Management::CompleteClear => pac.complete_cache_clear,
};
// takes `Option(Vec<&str>)` and returns `Vec<&str>` if `Some(_)`
// If `None`, tell user and exit.
let mut prog = get.unwrap_or_else(|| {
println!("Sorry, your package manager does not support this action");
std::process::exit(0)
});
//Pop's from the front of the `Vec<&str>`, which should always be the command name
let command = prog.remove(0);
// Tuple match, `prog.first()` returns an `Option<T>` on the first element of
// a Vec, `self.term` is also an `Option<T>` so this checks both for `Some`/`None`
// and formats the program call as needed
match (prog.first(), &self.term) {
(None, &None) => {
let mut child = Command::new(&command).spawn().expect(
"Failed to open package manager",
);
child.wait().expect("Failed to wait on package manager");
}
(None, &Some(ref term)) => {
let mut child = Command::new(&command).arg(term).spawn().expect(
"Failed to open package manager",
);
child.wait().expect("Failed to wait on package manager");
}
(Some(_), &None) => {
for arg in &prog {
let mut child = Command::new(&command).arg(arg).spawn().expect(
"Failed to open package manager",
);
child.wait().expect("Failed to wait on child");
}
}
(Some(_), &Some(ref term)) => {
for arg in &prog {
let mut child = Command::new(&command).arg(arg).arg(term).spawn().expect(
"Failed to open package manager",
);
child.wait().expect("Failed to wait on child");
}
}
}
}
/// Creates a `Config` from passed arguments, parses the `Management` enum
/// and term (if any). Requires an action, while the term can be `None`.
pub fn new() -> Config {
let action = match Management::parse(std::env::args().nth(1)) {
None => {
println!("No command actions passed");
help();
std::process::exit(0)
}
Some(command) => command,
};
let term = std::env::args().nth(2);
Config {
action: action,
term: term,
}
}
}