aboutsummaryrefslogtreecommitdiff
path: root/src/prompt.rs
blob: e6600b7a5b0888c8dd97383836f09ffac1d7a90e (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::io::Write;

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

        Prompt { ps1, home }
    }

    pub fn print(&self, pwd: &std::path::PathBuf) {
        if cfg!(debug_assertions) {
            println!("pwd={}", pwd.display());
        }

        let path = if pwd.starts_with(&self.home) {
            "~".to_owned() + &pwd.strip_prefix(&self.home).unwrap().display().to_string()
        } else {
            pwd.display().to_string()
        };

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

        print!("{}", ps1);
        match std::io::stdout().flush() {
            Ok(_) => {}
            Err(_) => println!(""),
        };
    }
}