#![feature(range_contains)]
extern crate reqwest;
use std::{
collections::HashMap, fs::File, io, process::{Command, Output, Stdio},
};
pub fn command(shell: &str, command: &str, name: &str) -> Output {
Command::new(shell)
.arg("-c")
.arg(&format!("{}", command))
.stdout(Stdio::piped())
.spawn()
.expect(&format!("Failed to execute {}", name))
.wait_with_output()
.expect(&format!("Failed to wait on {}", name))
}
pub fn dialog(question: &str, mut options: Vec<(String, fn())>) {
for i in 0..options.len() {
options[i].0.insert_str(0, "[ ] ");
}
loop {
print!("{}[2J", 27 as char);
println!("{}\n", question);
for (i, (option, _)) in options.iter().enumerate() {
println!("{}: {}", i + 1, option);
}
println!("\n0: Exit\n");
let mut choice = String::new();
io::stdin()
.read_line(&mut choice)
.expect("Failed to read line");
let choice = choice.trim().parse::<usize>().unwrap_or(100);
if choice == 0 {
return;
}
if (1..options.len() + 1).contains(&choice) {
options[choice - 1].1();
options[choice - 1].0 = options[choice - 1].0.replace("[ ]", "[X]");
}
}
}
pub fn download(url: &str, name: &str) {
if let Ok(mut f) = File::create(format!("{}", name)) {
match reqwest::get(url).unwrap().copy_to(&mut f) {
Ok(_) => (),
Err(err) => eprintln!("Couldn't download {}: {}", name, err),
}
} else {
eprintln!("File exists");
}
}
pub fn install(repo: &str, package: &str, args: &str) -> Output {
let package_managers: HashMap<&str, &str> = [("aur", "yay -S --noconfirm --needed"),
("arch", "sudo pacman -S --noconfirm --needed"),]
.iter()
.cloned()
.collect();
let mut package_manager = "sudo dnf install";
let repos = ["arch", "aur", "fedora"];
if repos.contains(&repo.to_lowercase().as_str()) {
package_manager = package_managers[&repo];
}
command(
"sh",
&format!("{} {} {}", package_manager, package, args),
&format!("install {}", package),
)
}
#[cfg(test)]
mod tests {
use {command, download};
fn test() {
}
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
fn command_with_output_works() {
if cfg!(target_os = "windows") {
return;
}
assert_eq!(
command("sh", "echo hello", "echo")
.stdout
.into_iter()
.map(|u| u as char)
.collect::<String>(),
"hello\n"
);
}
#[test]
fn dialog_format_works() {
let mut options: Vec<(String, fn())> = vec![
("Update System".to_string(), test),
("Remove Packages".to_string(), test),
("Create Folders".to_string(), test),
("Install Software".to_string(), test),
("Setup".to_string(), test),
];
for i in 0..options.len() {
options[i].0.insert_str(0, "[ ] ");
}
assert_eq!(options[0].0, "[ ] Update System");
}
#[test]
fn download_does_something() {
download("https://download.mozilla.org/?product=firefox-nightly-stub&os=win&lang=en-US", "ff.exe");
}
}