summaryrefslogtreecommitdiff
path: root/src/user_info.rs
blob: a352adbeb912127c1b60e6480d18bc4416a0bf89 (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
use nix::unistd::{getgroups, getuid, Gid, Group, User};

pub fn get_username() -> Option<String> {
    let uid = getuid();
    User::from_uid(uid).ok().flatten().map(|user| user.name)
}

pub fn get_user_groups() -> Vec<String> {
    let gids = getgroups().unwrap_or(Vec::default());
    gids.into_iter()
        .filter_map(|gid| Group::from_gid(gid).ok().flatten())
        .map(|group| group.name)
        .collect()
}

pub fn get_gid(group_name: &str) -> Option<Gid> {
    nix::unistd::Group::from_name(&group_name)
        .ok()
        .flatten()
        .map(|group| group.gid)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn it_returns_a_username() {
        // We can't get too specific here because this is your actual username,
        // but we at lease expect it to be some string, not None.
        let username = get_username();
        let username_len = username.unwrap().trim().len();
        assert!(username_len > 0);
    }

    #[test]
    fn it_returns_some_groups() {
        let groups = get_user_groups();
        assert!(groups.len() > 0);
        for group in groups {
            assert!(group.trim().len() > 0);
        }
    }
}