fix: some error handlings

This commit is contained in:
iff 2023-08-07 20:21:02 +02:00
parent 1444eeab84
commit 15c1ba3370
7 changed files with 49 additions and 37 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "pay-respects" name = "pay-respects"
version = "0.4.6" version = "0.4.7"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View file

@ -93,7 +93,7 @@ fn gen_match_rules(rules: Vec<Rule>) -> TokenStream {
suggestion_tokens.push(match_tokens); suggestion_tokens.push(match_tokens);
let string_patterns = pattern.join("\", \""); let string_patterns = pattern.join("\", \"");
let string_patterns: TokenStream2 = format!("vec![\"{}\"]", string_patterns).parse().unwrap(); let string_patterns: TokenStream2 = format!("[\"{}\"]", string_patterns).parse().unwrap();
patterns_tokens.push(string_patterns); patterns_tokens.push(string_patterns);
} }

View file

@ -38,13 +38,16 @@ pub fn get_best_match_file(input: &str) -> Option<String> {
}; };
while let Some(exit_dir) = exit_dirs.pop() { while let Some(exit_dir) = exit_dirs.pop() {
let dir_files = files.filter_map(|file| { let dir_files = files
let file = file.unwrap(); .map(|file| {
let file_name = file.file_name().into_string().unwrap(); let file = file.unwrap();
Some(file_name)
}).collect::<Vec<String>>(); file.file_name().into_string().unwrap()
})
.collect::<Vec<String>>();
let best_match = find_similar(&exit_dir, dir_files); let best_match = find_similar(&exit_dir, dir_files);
best_match.as_ref()?;
input = format!("{}/{}", input, best_match.unwrap()); input = format!("{}/{}", input, best_match.unwrap());
files = match std::fs::read_dir(&input) { files = match std::fs::read_dir(&input) {

View file

@ -1,5 +1,5 @@
use colored::Colorize;
use crate::style::highlight_difference; use crate::style::highlight_difference;
use colored::Colorize;
mod args; mod args;
mod files; mod files;
@ -15,21 +15,27 @@ fn main() {
); );
let mut last_command = shell::last_command_expanded_alias(&shell); let mut last_command = shell::last_command_expanded_alias(&shell);
loop { loop {
let corrected_command = suggestions::suggest_command(&shell, &last_command); let corrected_command = suggestions::suggest_command(&shell, &last_command);
if let Some(corrected_command) = corrected_command { if let Some(corrected_command) = corrected_command {
let command_difference = highlight_difference(&shell, &corrected_command, &last_command); let command_difference =
highlight_difference(&shell, &corrected_command, &last_command);
if let Some(highlighted_command) = command_difference { if let Some(highlighted_command) = command_difference {
let execution = suggestions::confirm_suggestion(&shell, &corrected_command, &highlighted_command); let execution = suggestions::confirm_suggestion(
&shell,
&corrected_command,
&highlighted_command,
);
if execution.is_ok() { if execution.is_ok() {
return; return;
} } else {
else { let retry_message =
let retry_message = format!("{}", "Looking for new suggestion...".cyan().bold()); format!("{}", "Looking for new suggestion...".cyan().bold());
println!("\n{}\n", retry_message); println!("\n{}\n", retry_message);
last_command = corrected_command; last_command = corrected_command;
} }
} else {
break;
} }
} else { } else {
break; break;

View file

@ -1,7 +1,6 @@
use std::io::prelude::*; use std::io::prelude::*;
use std::process::exit; use std::process::exit;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -9,30 +8,30 @@ use std::time::Duration;
pub const PRIVILEGE_LIST: [&str; 2] = ["sudo", "doas"]; pub const PRIVILEGE_LIST: [&str; 2] = ["sudo", "doas"];
pub fn command_output(shell: &str, command: &str) -> String { pub fn command_output(shell: &str, command: &str) -> String {
let (sender, receiver) = channel(); let (sender, receiver) = channel();
let _shell = shell.to_owned(); let _shell = shell.to_owned();
let _command = command.to_owned(); let _command = command.to_owned();
thread::spawn(move || { thread::spawn(move || {
sender.send(std::process::Command::new(_shell) sender
.arg("-c") .send(
.arg(_command) std::process::Command::new(_shell)
.env("LC_ALL", "C") .arg("-c")
.output() .arg(_command)
.expect("failed to execute process")) .env("LC_ALL", "C")
.output()
.expect("failed to execute process"),
)
.expect("failed to send output"); .expect("failed to send output");
}); });
match receiver.recv_timeout(Duration::from_secs(3)) { match receiver.recv_timeout(Duration::from_secs(3)) {
Ok(output) => { Ok(output) => String::from_utf8_lossy(&output.stderr)
String::from_utf8_lossy(&output.stderr) .to_string()
.to_string() .split_whitespace()
.split_whitespace() .collect::<Vec<&str>>()
.collect::<Vec<&str>>() .join(" ")
.join(" ") .to_lowercase(),
.to_lowercase()
}
Err(_) => { Err(_) => {
use colored::*; use colored::*;
eprintln!("Timeout while executing command: {}", command.red()); eprintln!("Timeout while executing command: {}", command.red());
@ -46,7 +45,7 @@ fn last_command(shell: &str) -> String {
match shell { match shell {
"bash" => { "bash" => {
let first_line = last_command.lines().next().unwrap().trim(); let first_line = last_command.lines().next().unwrap().trim();
first_line.split_once(" ").unwrap().1.to_string() first_line.split_once(' ').unwrap().1.to_string()
} }
"zsh" => last_command, "zsh" => last_command,
"fish" => last_command, "fish" => last_command,

View file

@ -4,8 +4,12 @@ use colored::*;
// to_string() is necessary here, otherwise there won't be color in the output // to_string() is necessary here, otherwise there won't be color in the output
#[warn(clippy::unnecessary_to_owned)] #[warn(clippy::unnecessary_to_owned)]
pub fn highlight_difference(shell: &str, suggested_command: &str, last_command: &str) -> Option<String> { pub fn highlight_difference(
let replaced_newline = suggested_command.replace("\n", r" {{newline}}"); shell: &str,
suggested_command: &str,
last_command: &str,
) -> Option<String> {
let replaced_newline = suggested_command.replace('\n', r" {{newline}}");
let mut split_suggested_command = split_command(&replaced_newline); let mut split_suggested_command = split_command(&replaced_newline);
let split_last_command = split_command(last_command); let split_last_command = split_command(last_command);
@ -31,7 +35,7 @@ pub fn highlight_difference(shell: &str, suggested_command: &str, last_command:
// let mut highlighted = suggested_command.to_string(); // let mut highlighted = suggested_command.to_string();
'next: for entry in split_suggested_command.iter_mut() { 'next: for entry in split_suggested_command.iter_mut() {
if entry == r"{{newline}" { if entry == r"{{newline}" {
continue continue;
} }
for old in &old_entries { for old in &old_entries {
if old == entry { if old == entry {

View file

@ -167,7 +167,7 @@ fn compare_string(a: &str, b: &str) -> usize {
} }
pub fn confirm_suggestion(shell: &str, command: &str, highlighted: &str) -> Result<(), ()> { pub fn confirm_suggestion(shell: &str, command: &str, highlighted: &str) -> Result<(), ()> {
println!{"{}\n", highlighted} println! {"{}\n", highlighted}
println!("Press enter to execute the suggestion. Or press Ctrl+C to exit."); println!("Press enter to execute the suggestion. Or press Ctrl+C to exit.");
std::io::stdin().read_line(&mut String::new()).unwrap(); std::io::stdin().read_line(&mut String::new()).unwrap();
@ -201,8 +201,8 @@ pub fn confirm_suggestion(shell: &str, command: &str, highlighted: &str) -> Resu
.expect("failed to wait on process"); .expect("failed to wait on process");
if process.success() { if process.success() {
return Ok(()); Ok(())
} else { } else {
return Err(()); Err(())
} }
} }