From cb65dcd72ac844e989107873421163bd261c7ccf Mon Sep 17 00:00:00 2001 From: Hamcha Date: Tue, 21 Jan 2020 17:42:51 +0100 Subject: [PATCH] little refactor+cleanup --- src/main.rs | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8357e96..b304934 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,10 @@ extern crate clap; -use clap::{App, Arg}; +use clap::{App, Arg, ArgMatches}; use isatty::stdout_isatty; use std::env; use std::fs::File; use std::io::{prelude::*, BufReader}; -use std::path::Path; +use std::path::{Path, PathBuf}; fn current_args() -> String { let mut out = String::from("osenv"); @@ -14,6 +14,22 @@ fn current_args() -> String { out } +fn get_file(cmd: &ArgMatches) -> Option { + let dir = cmd.value_of("directory")?; + let file = cmd.value_of("file")?; + let env = cmd.value_of("environment"); + + // If -env was specified, add it as a suffix + let filename = if env.is_some() { + format!("{}.{}", file, env.unwrap()) + } else { + String::from(file) + }; + + // Join directory and file + Some(Path::new(dir).join(filename)) +} + fn main() -> std::io::Result<()> { #[cfg(target_os = "macos")] static OS_DEFAULT_SHELL: &str = "sh"; @@ -63,21 +79,9 @@ fn main() -> std::io::Result<()> { ) .get_matches(); - let dir = cmd.value_of("directory").unwrap(); - let file = cmd.value_of("file").unwrap(); - let env = cmd.value_of("environment"); + let path = get_file(&cmd).unwrap(); let shell = cmd.value_of("shell").unwrap(); - // If -env was specified, add it as a suffix - let filename = if env.is_some() { - format!("{}.{}", file, env.unwrap()) - } else { - String::from(file) - }; - - // Join directory and file - let path = Path::new(dir).join(filename); - if !path.exists() { println!("{}: file not found", path.display()); std::process::exit(1); @@ -88,9 +92,16 @@ fn main() -> std::io::Result<()> { // Print help messages if printing to terminal if stdout_isatty() { + println!("# It looks like you are not running osenv properly"); match shell { - "ps1" => println!("#\n# It looks like you are not running osenv properly\n# The proper command on Powershell is:\n# {} | iex\n# Hope this helps!\n#", current_args()), - "sh" => println!("#\n# It looks like you are not running osenv properly\n# The proper command on unix shells is:\n# eval $({})\n# Hope this helps!\n#", current_args()), + "ps1" => println!( + "# The proper command on Powershell is:\n# {} | iex", + current_args() + ), + "sh" => println!( + "# The proper command on unix shells is:\n# eval $({})", + current_args() + ), _ => (), } }