83 lines
2.9 KiB
Rust
83 lines
2.9 KiB
Rust
use std::process::{Command, Output};
|
|
use std::io::Result as IoResult;
|
|
use inquire::{Text, validator::{Validation}};
|
|
use inquire::{error::InquireError, Select};
|
|
use inquire::ui::{RenderConfig, Styled};
|
|
use regex::Regex;
|
|
|
|
fn execute_command(command: &str) -> IoResult<String> {
|
|
// Use Command to run the bash shell with the -c option to pass the command string
|
|
let output: Output = Command::new("bash")
|
|
.arg("-c")
|
|
.arg(command)
|
|
.output()?;
|
|
|
|
if output.status.success() {
|
|
// Convert the stdout of the command to a String
|
|
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
|
} else {
|
|
// Handle errors by converting stderr to a String and returning an Err variant
|
|
let error_message = String::from_utf8_lossy(&output.stderr);
|
|
Err(std::io::Error::new(
|
|
std::io::ErrorKind::Other,
|
|
format!("Command failed with error: {}", error_message),
|
|
))
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
let prompt_gen_command = "echo -n \"[${USER}@${HOSTNAME} ${PWD##*/}]$\"";
|
|
let prompt_gen = match execute_command(&prompt_gen_command) {
|
|
Ok(output) => output,
|
|
Err(_) => return
|
|
};
|
|
|
|
let mut empty_render_config: RenderConfig = RenderConfig::default();
|
|
empty_render_config = empty_render_config.with_prompt_prefix(Styled::new(""));
|
|
|
|
let re = Regex::new(r"CHG[0-9]{6}$").unwrap();
|
|
let options: Vec<&str> = vec!["File change", "Package Update", "Package Removal",
|
|
"File Removal", "Misc. Command"];
|
|
|
|
let change_validator = move |input: &str| if input.chars().count() == 0 {
|
|
Ok(Validation::Invalid("Change request cannot be empty".into()))
|
|
} else if re.is_match(input) {
|
|
Ok(Validation::Valid)
|
|
} else {
|
|
Ok(Validation::Invalid("Invalid change request (e.g: CHGXXXXXX)".into()))
|
|
};
|
|
|
|
let validator = |input: &str| if input.chars().count() > 140 {
|
|
Ok(Validation::Invalid("You're only allowed 140 characters.".into()))
|
|
} else if input.chars().count() == 0 {
|
|
Ok(Validation::Invalid("".into()))
|
|
} else {
|
|
Ok(Validation::Valid)
|
|
};
|
|
|
|
let prompt_command = match Text::new(&prompt_gen)
|
|
.with_validator(validator)
|
|
.with_render_config(empty_render_config)
|
|
.prompt() {
|
|
Ok(input) => input,
|
|
Err(_) => {
|
|
eprintln!("Failed to get system input.");
|
|
return;
|
|
}
|
|
};
|
|
|
|
let _ = Text::new("(e.g. CHGXXXXXX) Enter change request: ").with_validator(change_validator).prompt();
|
|
|
|
let ans: Result<&str, InquireError> = Select::new("Change Type?", options).prompt();
|
|
|
|
match ans {
|
|
Ok(_) => {
|
|
match execute_command(&prompt_command) {
|
|
Ok(output) => print!("{}", output),
|
|
Err(e) => eprintln!("Command failed: {}", e),
|
|
}
|
|
},
|
|
Err(_) => println!("not running command..."),
|
|
}
|
|
}
|