pay-respects/src/files.rs

61 lines
1.5 KiB
Rust
Raw Normal View History

2023-08-07 17:12:38 +02:00
use crate::suggestions::find_similar;
2023-08-03 21:26:41 +02:00
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
}
2023-08-07 17:12:38 +02:00
pub fn get_best_match_file(input: &str) -> Option<String> {
2023-08-03 21:26:41 +02:00
let mut input = input.trim_matches(|c| c == '\'' || c == '"').to_owned();
2023-08-07 17:12:38 +02:00
let mut exit_dirs = Vec::new();
let mut files = loop {
2023-08-03 21:26:41 +02:00
match std::fs::read_dir(&input) {
Ok(files) => break files,
Err(_) => {
2023-08-07 17:12:38 +02:00
if let Some((dirs, exit_dir)) = input.rsplit_once('/') {
exit_dirs.push(exit_dir.to_owned());
2023-08-03 21:26:41 +02:00
input = dirs.to_owned();
} else {
2023-08-07 17:12:38 +02:00
exit_dirs.push(input.to_owned());
input = ".".to_owned();
2023-08-03 21:26:41 +02:00
break std::fs::read_dir("./").unwrap();
}
}
}
};
2023-08-07 17:12:38 +02:00
while let Some(exit_dir) = exit_dirs.pop() {
2023-08-07 20:21:02 +02:00
let dir_files = files
.map(|file| {
let file = file.unwrap();
file.file_name().into_string().unwrap().replace(' ', "\\ ")
2023-08-07 20:21:02 +02:00
})
.collect::<Vec<String>>();
2023-08-07 17:12:38 +02:00
2023-08-11 00:41:16 +02:00
let best_match = find_similar(&exit_dir, &dir_files);
2023-08-07 20:21:02 +02:00
best_match.as_ref()?;
2023-08-07 17:12:38 +02:00
input = format!("{}/{}", input, best_match.unwrap());
files = match std::fs::read_dir(&input) {
Ok(files) => files,
Err(_) => return Some(input),
};
2023-08-03 21:26:41 +02:00
}
2023-08-07 17:12:38 +02:00
Some(input)
2023-08-03 21:26:41 +02:00
}