little refactor+cleanup

This commit is contained in:
Hamcha 2020-01-21 17:42:51 +01:00
parent ae933735b4
commit cb65dcd72a
Signed by: hamcha
GPG key ID: 44AD3571EB09A39E

View file

@ -1,10 +1,10 @@
extern crate clap; extern crate clap;
use clap::{App, Arg}; use clap::{App, Arg, ArgMatches};
use isatty::stdout_isatty; use isatty::stdout_isatty;
use std::env; use std::env;
use std::fs::File; use std::fs::File;
use std::io::{prelude::*, BufReader}; use std::io::{prelude::*, BufReader};
use std::path::Path; use std::path::{Path, PathBuf};
fn current_args() -> String { fn current_args() -> String {
let mut out = String::from("osenv"); let mut out = String::from("osenv");
@ -14,6 +14,22 @@ fn current_args() -> String {
out out
} }
fn get_file(cmd: &ArgMatches) -> Option<PathBuf> {
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<()> { fn main() -> std::io::Result<()> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
static OS_DEFAULT_SHELL: &str = "sh"; static OS_DEFAULT_SHELL: &str = "sh";
@ -63,21 +79,9 @@ fn main() -> std::io::Result<()> {
) )
.get_matches(); .get_matches();
let dir = cmd.value_of("directory").unwrap(); let path = get_file(&cmd).unwrap();
let file = cmd.value_of("file").unwrap();
let env = cmd.value_of("environment");
let shell = cmd.value_of("shell").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() { if !path.exists() {
println!("{}: file not found", path.display()); println!("{}: file not found", path.display());
std::process::exit(1); std::process::exit(1);
@ -88,9 +92,16 @@ fn main() -> std::io::Result<()> {
// Print help messages if printing to terminal // Print help messages if printing to terminal
if stdout_isatty() { if stdout_isatty() {
println!("# It looks like you are not running osenv properly");
match shell { 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()), "ps1" => println!(
"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()), "# The proper command on Powershell is:\n# {} | iex",
current_args()
),
"sh" => println!(
"# The proper command on unix shells is:\n# eval $({})",
current_args()
),
_ => (), _ => (),
} }
} }