From a5cd09a36aadb0c9f9f0e8c118121ad62c88705d Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Fri, 1 Jan 2021 18:41:59 -0800 Subject: factor out the path finding into a function find_executable_path() --- src/main.rs | 64 +++++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 21 deletions(-) (limited to 'src') 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 { 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 = 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> { Ok(result) } + +fn find_executable_path(command_name: &str) + -> Result> +{ + let file_name: path::FileName = command_name.parse()?; + let search_paths = get_search_paths()?; + + let mut executable_path: Option = 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) +} + -- cgit 1.4.1