From f08995548691153ea399e1c6d23ffd5b944876b5 Mon Sep 17 00:00:00 2001 From: Timm Behner Date: Thu, 20 Jun 2019 17:38:50 +0200 Subject: [PATCH] use failure for better error handling --- Cargo.lock | 1 + Cargo.toml | 1 + src/prompt.rs | 21 ++++++++++++--------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6e9a29f..8ef6d50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -333,6 +333,7 @@ dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dirs 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "git2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index 5dcafdf..fe5d3b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,3 +12,4 @@ git2 = "0.8" regex = "1.1.6" tico = "1.0.0" nix = "0.14" +failure = "0.1.5" diff --git a/src/prompt.rs b/src/prompt.rs index 6272369..73a8cbf 100644 --- a/src/prompt.rs +++ b/src/prompt.rs @@ -1,6 +1,7 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::env; use nix::unistd; +use failure::Error; const INSERT_SYMBOL: &str = "❯"; const COMMAND_SYMBOL: &str = "⬢"; @@ -9,17 +10,15 @@ const NO_ERROR: &str = "0"; const SSH_SESSION_ENV: &str = "SSH_TTY"; -fn get_username() -> String { - match env::var("USER") { - Ok(name) => name, - Err(_) => "".to_string(), - } +fn get_username() -> Result { + Ok(env::var("USER")?) } -fn get_hostname() -> String { +fn get_hostname() -> Result { let mut buf = [0u8; 64]; - let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname"); - hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8").to_string() + let hostname_cstr = unistd::gethostname(&mut buf)?; + let hostname = hostname_cstr.to_str()?; + Ok(hostname.to_string()) } pub fn display(sub_matches: &ArgMatches<'_>) { @@ -44,7 +43,11 @@ pub fn display(sub_matches: &ArgMatches<'_>) { }; let ssh_user_host = match env::var(SSH_SESSION_ENV) { - Ok(_) => format!("{}@{} ", get_username(), get_hostname()), + Ok(_) => { + let username = get_username().unwrap_or("".to_string()); + let hostname = get_hostname().unwrap_or("".to_string()); + format!("{}@{} ", username, hostname) + }, Err(_) => "".to_string(), };