aboutsummaryrefslogtreecommitdiff
path: root/src/prompt.rs
blob: 12df7e0924a958b20439aa6ea499b7709ccfb00d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
mod user;

pub struct Prompt {
    pub ps1: std::string::String,
    pub home: std::path::PathBuf,
}

impl Prompt {
    pub fn new() -> Result<Prompt, std::io::Error> {
        let username = user::username()?;
        let hostname = user::hostname()?;
        let ready = if username == "root" { "#" } else { "$" }.to_owned();

        let ps1 = match std::env::var("PROMPT") {
            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(),
        };

        Ok(Prompt { ps1, home })
    }

    pub fn print(&self) -> std::string::String {
        let pwd = std::env::current_dir().unwrap();
        let path = if pwd.starts_with(&self.home) {
            "~".to_owned() + &pwd.strip_prefix(&self.home).unwrap().display().to_string()
        } else {
            pwd.display().to_string()
        };

        self.ps1.replace("{PWD}", &path)
    }
}