From 42cca401d21085709da7333069dbfcca99177d8d Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Mon, 21 Sep 2020 17:40:05 +0300 Subject: Initial commit --- src/prompt.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/prompt.rs (limited to 'src/prompt.rs') diff --git a/src/prompt.rs b/src/prompt.rs new file mode 100644 index 0000000..fd9c872 --- /dev/null +++ b/src/prompt.rs @@ -0,0 +1,57 @@ +use std::io::Write; + +pub struct Prompt { + home: std::path::PathBuf, + pub pwd: std::path::PathBuf, + username: std::string::String, + hostname: std::string::String, +} + +impl Prompt { + pub fn new() -> Prompt { + let home = match std::env::home_dir() { + Some(p) => p, + None => std::path::Path::new("/").to_path_buf(), + }; + let pwd = match std::env::current_dir() { + Ok(p) => p, + Err(e) => panic!(e), + }; + 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), + }; + Prompt { + home, + pwd, + username, + hostname, + } + } + + pub fn print(&self) { + let path = if self.pwd == self.home { + self.pwd.display() + } else if self.pwd.starts_with(&self.home) { + self.pwd.strip_prefix(&self.home).unwrap().display() + } else { + self.pwd.display() + }; + + print!(" {USER}@{HOST} [{PWD}]\n$ ", USER=self.username, HOST=self.hostname, PWD=path); + match std::io::stdout().flush() { + Ok(_) => {} + Err(_) => println!(""), + }; + } +} -- cgit v1.2.1