aboutsummaryrefslogtreecommitdiff
path: root/src/user.rs
blob: 9744928eb49d6715f9a3c2811af9fda032b563e5 (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
use std::io::BufRead;

pub fn hostname() -> std::result::Result<std::string::String, std::io::Error> {
    let h = std::fs::read_to_string("/proc/sys/kernel/hostname")?;
    Ok(h.trim().to_string())
}

#[test]
fn test_hostname() {
    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),
    };

    assert_eq!(hostname__, hostname().unwrap());
}

pub fn username() -> std::result::Result<std::string::String, std::io::Error> {
    let uid = unsafe { libc::getuid().to_string() };

    let file = std::fs::File::open("/etc/passwd")?;
    let reader = std::io::BufReader::new(file);

    for line in reader.lines() {
        let l = line?;
        let parts: Vec<&str> = l.split(':').collect();
        if uid == parts[2] {
            return Ok(parts[0].to_string());
        }
    }

    Ok(uid)
}

#[test]
fn test_username() {
    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),
    };
    assert_eq!(username__, username().unwrap());
}