diff options
author | Irene Knapp <ireneista@gmail.com> | 2021-01-01 18:41:59 -0800 |
---|---|---|
committer | Irene Knapp <ireneista@gmail.com> | 2021-01-01 18:41:59 -0800 |
commit | a5cd09a36aadb0c9f9f0e8c118121ad62c88705d (patch) | |
tree | 93b42c3e25edd24d77d64128e7707587296b375c /src | |
parent | 3378c0c3704e1b85f23459fc1273186ec9ecbd8a (diff) |
factor out the path finding into a function find_executable_path()
Diffstat (limited to 'src')
-rw-r--r-- | src/main.rs | 64 |
1 files changed, 43 insertions, 21 deletions
diff --git a/src/main.rs b/src/main.rs index a8d8f50..ff6d90e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,7 +4,6 @@ use std::collections::HashSet; use std::io; use std::io::prelude::*; use std::os::unix::fs::PermissionsExt; -use std::str::FromStr; #[macro_use] extern crate lalrpop_util; @@ -72,33 +71,30 @@ fn read() -> Result<Input> { fn execute(input: &str) -> Result<()> { let invocation = commandline::InvocationParser::new().parse(input)?; - println!("{}", input); - match invocation.as_slice() { ["environment", ..] => { let environment = read_environment()?; println!("{:?}", environment); } ["which", command_name, ..] => { - let file_name: path::FileName = command_name.parse()?; - let search_paths = get_search_paths()?; - let mut executable_path: Option<path::AbsoluteFilePath> = None; - for search_path in &search_paths { - let candidate_path = search_path.concat_file_name(&file_name); - match candidate_path.to_sys_path().metadata() { - Ok(metadata) => { - if metadata.is_file() - && metadata.permissions().mode() & 0o111 != 0 - { - println!("{} {:?}", candidate_path, metadata); - executable_path = Some(candidate_path); - break; - } - }, - Err(_) => { }, + match find_executable_path(command_name)? { + Some(executable_path) => { + println!("{}", executable_path); } - - } + None => { + println!("Command not found: {}", command_name); + } + }; + }, + [command_name, ..] => { + match find_executable_path(command_name)? { + Some(executable_path) => { + println!("{}", executable_path); + } + None => { + println!("Command not found: {}", command_name); + } + }; }, _ => { println!("invocation '{:?}'", invocation); @@ -139,3 +135,29 @@ fn get_search_paths() -> Result<Vec<path::AbsoluteDirectoryPath>> { Ok(result) } + +fn find_executable_path(command_name: &str) + -> Result<Option<path::AbsoluteFilePath>> +{ + let file_name: path::FileName = command_name.parse()?; + let search_paths = get_search_paths()?; + + let mut executable_path: Option<path::AbsoluteFilePath> = None; + for search_path in &search_paths { + let candidate_path = search_path.concat_file_name(&file_name); + match candidate_path.to_sys_path().metadata() { + Ok(metadata) => { + if metadata.is_file() + && metadata.permissions().mode() & 0o111 != 0 + { + executable_path = Some(candidate_path); + break; + } + }, + Err(_) => { }, + } + } + + Ok(executable_path) +} + |