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!(""), }; } }