From b1e25166433ce93403324a96f129712e4fac944d Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Sun, 11 Oct 2020 18:37:39 +0300 Subject: Properly read username and hostname username is read by using libc::getuid, and checking /etc/passwd for the uid and getting the username from there hostname is read from /proc/sys/kernel/hostname --- src/prompt.rs | 49 ++++++++++++++++++++----------------------------- 1 file changed, 20 insertions(+), 29 deletions(-) (limited to 'src/prompt.rs') diff --git a/src/prompt.rs b/src/prompt.rs index e6600b7..40c96cc 100644 --- a/src/prompt.rs +++ b/src/prompt.rs @@ -1,42 +1,33 @@ use std::io::Write; +#[path = "user.rs"] +mod user; + pub struct Prompt { ps1: std::string::String, pub home: std::path::PathBuf, } impl Prompt { - pub fn new() -> Prompt { - let username = match std::process::Command::new("whoami").output() { - Ok(s) => { - let output = std::string::String::from_utf8(s.stdout).unwrap(); - output.trim().to_string() - } - Err(e) => panic!(e), - }; - let hostname = match std::process::Command::new("hostname").output() { - Ok(s) => { - let output = std::string::String::from_utf8(s.stdout).unwrap(); - output.trim().to_string() - } - Err(e) => panic!(e), - }; - let ready = if username == "root" { - "#" - } else { - "$" - }.to_owned(); - - let ps1 = String::from(" {USER}@{HOST} [{PWD}]\n\\$ ") - .replace("{USER}", &username) - .replace("{HOST}", &hostname) - .replace("\\$", &ready); - let home = match std::env::home_dir() { - Some(p) => p, - None => std::path::Path::new("/").to_path_buf(), + pub fn new() -> Result { + let username = user::username()?; + let hostname = user::hostname()?; + let ready = if username == "root" { "#" } else { "$" }.to_owned(); + + let ps1 = match std::env::var("PS1") { + Ok(val) => val, + Err(_) => String::from(" {USER}@{HOST} [{PWD}]\n{$} "), + } + .replace("{USER}", &username) + .replace("{HOST}", &hostname) + .replace("{$}", &ready); + + let home = match std::env::var("HOME") { + Ok(val) => std::path::Path::new(&val).to_path_buf(), + Err(_) => std::path::Path::new("/").to_path_buf(), }; - Prompt { ps1, home } + Ok(Prompt { ps1, home }) } pub fn print(&self, pwd: &std::path::PathBuf) { -- cgit v1.2.1