feat: all parse in compilation

This commit is contained in:
iff 2023-08-03 21:26:41 +02:00
parent 511b309d99
commit 53c7e1fd7b
8 changed files with 410 additions and 321 deletions

41
src/files.rs Normal file
View file

@ -0,0 +1,41 @@
pub fn get_path_files() -> Vec<String> {
let path = std::env::var("PATH").unwrap();
let path = path.split(':').collect::<Vec<&str>>();
let mut all_executable = vec![];
for p in path {
let files = match std::fs::read_dir(p) {
Ok(files) => files,
Err(_) => continue,
};
for file in files {
let file = file.unwrap();
let file_name = file.file_name().into_string().unwrap();
all_executable.push(file_name);
}
}
all_executable
}
pub fn get_directory_files(input: &str) -> Vec<String> {
let mut input = input.trim_matches(|c| c == '\'' || c == '"').to_owned();
let files = loop {
match std::fs::read_dir(&input) {
Ok(files) => break files,
Err(_) => {
if let Some((dirs, _)) = input.rsplit_once('/') {
input = dirs.to_owned();
} else {
break std::fs::read_dir("./").unwrap();
}
}
}
};
let mut all_files = vec![];
for file in files {
let file = file.unwrap();
let file_name = file.path().to_str().unwrap().to_owned();
all_files.push(file_name);
}
all_files
}

View file

@ -1,6 +1,7 @@
use colored::Colorize;
mod args;
mod files;
mod shell;
mod style;
mod suggestions;

View file

@ -1,5 +1,5 @@
use std::process::exit;
use std::io::prelude::*;
use std::process::exit;
pub const PRIVILEGE_LIST: [&str; 2] = ["sudo", "doas"];
@ -95,71 +95,71 @@ pub fn last_command_expanded_alias(shell: &str) -> String {
}
pub fn print_command_with_env(shell: &str, binary_path: &str) {
let last_command;
let alias;
let last_command;
let alias;
match shell {
"bash" => {
last_command = "$(history 2)";
alias = "$(alias)"
}
"zsh" => {
last_command = "$(fc -ln -1)";
alias = "$(alias)"
}
"fish" => {
last_command = "$(history | head -n 1)";
alias = "$(alias)";
}
"nu" | "nush" | "nushell" => {
last_command = "(history | last).command";
alias = "\"\"";
let command = format!(
"with-env {{ _PR_LAST_COMMAND : {},\
match shell {
"bash" => {
last_command = "$(history 2)";
alias = "$(alias)"
}
"zsh" => {
last_command = "$(fc -ln -1)";
alias = "$(alias)"
}
"fish" => {
last_command = "$(history | head -n 1)";
alias = "$(alias)";
}
"nu" | "nush" | "nushell" => {
last_command = "(history | last).command";
alias = "\"\"";
let command = format!(
"with-env {{ _PR_LAST_COMMAND : {},\
_PR_ALIAS : {},\
_PR_SHELL : nu }} \
{{ {} }}",
last_command, alias, binary_path
);
println!("{}\n", command);
println!("Add following to your config file? (Y/n)");
let alias = format!("alias f = {}", command);
println!("{}", alias);
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
match input.trim() {
"Y" | "y" | "" => {
let output = std::process::Command::new("nu")
.arg("-c")
.arg("echo $nu.config-path")
.output()
.expect("Failed to execute process");
let config_path = String::from_utf8_lossy(&output.stdout);
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true)
.open(config_path.trim())
.expect("Failed to open config file");
last_command, alias, binary_path
);
println!("{}\n", command);
println!("Add following to your config file? (Y/n)");
let alias = format!("alias f = {}", command);
println!("{}", alias);
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
match input.trim() {
"Y" | "y" | "" => {
let output = std::process::Command::new("nu")
.arg("-c")
.arg("echo $nu.config-path")
.output()
.expect("Failed to execute process");
let config_path = String::from_utf8_lossy(&output.stdout);
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true)
.open(config_path.trim())
.expect("Failed to open config file");
writeln!(file, "{}", alias).expect("Failed to write to config file");
}
_ => std::process::exit(0),
};
std::process::exit(0);
}
_ => {
println!("Unknown shell: {}", shell);
std::process::exit(1);
}
writeln!(file, "{}", alias).expect("Failed to write to config file");
}
_ => std::process::exit(0),
};
std::process::exit(0);
}
_ => {
println!("Unknown shell: {}", shell);
std::process::exit(1);
}
}
println!(
"\
println!(
"\
_PR_LAST_COMMAND=\"{}\" \
_PR_ALIAS=\"{}\" \
_PR_SHELL=\"{}\" \
\"{}\"",
last_command, alias, shell, binary_path
);
std::process::exit(0);
last_command, alias, shell, binary_path
);
std::process::exit(0);
}

View file

@ -1,6 +1,8 @@
use crate::suggestions::split_command;
use colored::*;
// to_string() is necessary here, otherwise there won't be color in the output
#[warn(clippy::unnecessary_to_owned)]
pub fn highlight_difference(suggested_command: &str, last_command: &str) -> String {
let split_suggested_command = split_command(suggested_command);
let split_last_command = split_command(last_command);

View file

@ -1,8 +1,8 @@
use regex_lite::Regex;
use std::collections::HashMap;
use rule_parser::parse_rules;
use crate::files::{get_directory_files, get_path_files};
use crate::shell::{command_output, PRIVILEGE_LIST};
use crate::style::highlight_difference;
@ -17,14 +17,12 @@ pub fn suggest_command(shell: &str, last_command: &str) -> Option<String> {
if !PRIVILEGE_LIST.contains(&executable) {
let suggest = match_pattern("privilege", last_command, &err);
if let Some(suggest) = suggest {
let suggest = eval_suggest(&suggest, last_command);
return Some(suggest);
if suggest.is_some() {
return suggest;
}
}
let suggest = match_pattern(executable, last_command, &err);
if let Some(suggest) = suggest {
let suggest = eval_suggest(&suggest, last_command);
if PRIVILEGE_LIST.contains(&executable) {
return Some(format!("{} {}", split_command[0], suggest));
}
@ -33,201 +31,25 @@ pub fn suggest_command(shell: &str, last_command: &str) -> Option<String> {
let suggest = match_pattern("general", last_command, &err);
if let Some(suggest) = suggest {
let suggest = eval_suggest(&suggest, last_command);
return Some(suggest);
}
None
}
fn match_pattern(executable: &str, command: &str, error_msg: &str) -> Option<String> {
let rules = parse_rules!("rules");
if rules.contains_key(executable) {
let suggest = rules.get(executable).unwrap();
for (pattern, suggest) in suggest {
for pattern in pattern {
if error_msg.contains(pattern) {
for suggest in suggest {
if let Some(suggest) = check_condition(suggest, command, error_msg) {
return Some(suggest);
}
}
}
}
}
None
} else {
None
}
fn match_pattern(executable: &str, last_command: &str, error_msg: &str) -> Option<String> {
parse_rules!("rules");
}
fn check_condition(suggest: &str, command: &str, error_msg: &str) -> Option<String> {
if !suggest.starts_with('#') {
return Some(suggest.to_owned());
fn opt_regex(regex: &str, command: &mut String) -> String {
let regex = Regex::new(regex).unwrap();
let opts = regex
.find_iter(command)
.map(|cap| cap.as_str().to_owned())
.collect::<Vec<String>>();
for opt in opts.clone() {
*command = command.replace(&opt, "");
}
let mut lines = suggest.lines().collect::<Vec<&str>>();
let mut conditions = String::new();
for (i, line) in lines[0..].iter().enumerate() {
conditions.push_str(line);
if line.ends_with(']') {
lines = lines[i..].to_vec();
break;
}
}
let conditions = conditions
.trim_start_matches(['#', '['])
.trim_end_matches(']')
.split(',')
.collect::<Vec<&str>>();
for condition in conditions {
let (mut condition, arg) = condition.split_once('(').unwrap();
condition = condition.trim();
let arg = arg.trim_start_matches('(').trim_end_matches(')');
let reverse = match condition.starts_with('!') {
true => {
condition = condition.trim_start_matches('!');
true
}
false => false,
};
if eval_condition(condition, arg, command, error_msg) == reverse {
return None;
}
}
Some(lines[1..].join("\n"))
}
fn eval_condition(condition: &str, arg: &str, command: &str, error_msg: &str) -> bool {
match condition {
"executable" => {
let output = std::process::Command::new("which")
.arg(arg)
.output()
.expect("failed to execute process");
output.status.success()
}
"err_contains" => error_msg.contains(arg),
"cmd_contains" => command.contains(arg),
_ => unreachable!("Unknown condition when evaluation condition: {}", condition),
}
}
fn eval_suggest(suggest: &str, last_command: &str) -> String {
let mut suggest = suggest.to_owned();
let mut last_command = last_command.to_owned();
if suggest.contains("{{command}}") {
suggest = suggest.replace("{{command}}", &last_command);
}
while suggest.contains("{{opt::") {
let placeholder_start = "{{opt::";
let placeholder_end = "}}";
let start_index = suggest.find(placeholder_start).unwrap();
let end_index = suggest[start_index..].find(placeholder_end).unwrap()
+ start_index
+ placeholder_end.len();
let placeholder = start_index..end_index;
let args = start_index + placeholder_start.len()..end_index - placeholder_end.len();
let opt = &suggest[args.to_owned()];
let regex = opt.trim();
let regex = Regex::new(regex).unwrap();
let opts = regex
.find_iter(&last_command)
.map(|cap| cap.as_str().to_owned())
.collect::<Vec<String>>();
suggest.replace_range(placeholder, &opts.join(" "));
for opt in opts {
last_command = last_command.replace(&opt, "");
}
}
let split_command = split_command(&last_command);
while suggest.contains("{{command") {
let placeholder_start = "{{command";
let placeholder_end = "}}";
let start_index = suggest.find(placeholder_start).unwrap();
let end_index = suggest[start_index..].find(placeholder_end).unwrap()
+ start_index
+ placeholder_end.len();
let placeholder = start_index..end_index;
let args = start_index + placeholder_start.len()..end_index - placeholder_end.len();
let range = suggest[args.to_owned()].trim_matches(|c| c == '[' || c == ']');
if let Some((start, end)) = range.split_once(':') {
let start = {
let mut start = start.parse::<i32>().unwrap_or(0);
if start < 0 {
start += split_command.len() as i32;
}
start as usize
};
let end = {
let mut end = end.parse::<i32>().unwrap_or(split_command.len() as i32 - 1) + 1;
if end < 0 {
end += split_command.len() as i32;
}
end as usize
};
let command = split_command[start..end].join(" ");
suggest.replace_range(placeholder, &command);
} else {
let range = range.parse::<usize>().unwrap_or(0);
let command = split_command[range].to_owned();
suggest.replace_range(placeholder, &command);
}
}
while suggest.contains("{{typo") {
let placeholder_start = "{{typo";
let placeholder_end = "}}";
let start_index = suggest.find(placeholder_start).unwrap();
let end_index = suggest[start_index..].find(placeholder_end).unwrap()
+ start_index
+ placeholder_end.len();
let placeholder = start_index..end_index;
let args = start_index + placeholder_start.len()..end_index - placeholder_end.len();
let mut command_index;
let mut match_list = vec![];
if suggest.contains('[') {
let split = suggest[args.to_owned()]
.split(&['[', ']'])
.collect::<Vec<&str>>();
command_index = split[1].parse::<i32>().unwrap();
if command_index < 0 {
command_index += split_command.len() as i32;
}
} else {
unreachable!("Typo suggestion must have a command index");
}
if suggest.contains('(') {
let split = suggest[args.to_owned()]
.split(&['(', ')'])
.collect::<Vec<&str>>();
match_list = split[1].split(',').collect::<Vec<&str>>();
}
let match_list = match_list
.iter()
.map(|s| s.trim().to_string())
.collect::<Vec<String>>();
let command_index = command_index as usize;
let suggestion = suggest_typo(&split_command[command_index], match_list.clone());
suggest.replace_range(placeholder, &suggestion);
}
suggest
opts.join(" ")
}
pub fn split_command(command: &str) -> Vec<String> {
@ -247,68 +69,26 @@ fn suggest_typo(typo: &str, candidates: Vec<String>) -> String {
match candidates[0].as_str() {
"path" => {
let path_files = get_path_files();
if let Some(suggest) = find_fimilar(typo, path_files) {
if let Some(suggest) = find_similar(typo, path_files) {
suggestion = suggest;
}
}
"file" => {
let files = get_directory_files(typo);
if let Some(suggest) = find_fimilar(typo, files) {
if let Some(suggest) = find_similar(typo, files) {
suggestion = suggest;
}
}
_ => {}
}
} else if let Some(suggest) = find_fimilar(typo, candidates) {
} else if let Some(suggest) = find_similar(typo, candidates) {
suggestion = suggest;
}
suggestion
}
fn get_path_files() -> Vec<String> {
let path = std::env::var("PATH").unwrap();
let path = path.split(':').collect::<Vec<&str>>();
let mut all_executable = vec![];
for p in path {
let files = match std::fs::read_dir(p) {
Ok(files) => files,
Err(_) => continue,
};
for file in files {
let file = file.unwrap();
let file_name = file.file_name().into_string().unwrap();
all_executable.push(file_name);
}
}
all_executable
}
fn get_directory_files(input: &str) -> Vec<String> {
let mut input = input.trim_matches(|c| c == '\'' || c == '"').to_owned();
let files = loop {
match std::fs::read_dir(&input) {
Ok(files) => break files,
Err(_) => {
if let Some((dirs, _)) = input.rsplit_once('/') {
input = dirs.to_owned();
} else {
break std::fs::read_dir("./").unwrap();
}
}
}
};
let mut all_files = vec![];
for file in files {
let file = file.unwrap();
let file_name = file.path().to_str().unwrap().to_owned();
all_files.push(file_name);
}
all_files
}
fn find_fimilar(typo: &str, candidates: Vec<String>) -> Option<String> {
fn find_similar(typo: &str, candidates: Vec<String>) -> Option<String> {
let mut min_distance = 10;
let mut min_distance_index = None;
for (i, candidate) in candidates.iter().enumerate() {