fm/modes/fs/
users.rs

1use std::collections::HashMap;
2
3/// Holds 2 hashmaps, one for users, one for groups.
4/// it looks into `/etc/passwd` and `/etc/group` to map `uid` & `gid` to user name or group name.
5/// Holding them avoid to access the files every time.
6#[derive(Clone, Debug)]
7pub struct Users {
8    users: HashMap<u32, String>,
9    groups: HashMap<u32, String>,
10}
11
12impl Default for Users {
13    /// Creates both hashmaps of uid:user and gid:group read from `/etc/passwd` and `/etc/groups`.
14    fn default() -> Self {
15        let mut users = Self {
16            users: HashMap::new(),
17            groups: HashMap::new(),
18        };
19        users.update();
20        users
21    }
22}
23
24impl Users {
25    pub fn only_users() -> Self {
26        let mut users = Self {
27            users: HashMap::new(),
28            groups: HashMap::new(),
29        };
30        users.update_users();
31        users
32    }
33
34    /// Refresh the users from `/etc/passwd` and `/etc/groups`
35    pub fn update(&mut self) {
36        self.update_users();
37        self.update_groups();
38    }
39
40    fn update_users(&mut self) {
41        self.users = pgs_files::passwd::get_all_entries()
42            .iter()
43            .map(|entry| (entry.uid, entry.name.to_owned()))
44            .collect();
45    }
46
47    fn update_groups(&mut self) {
48        self.groups = pgs_files::group::get_all_entries()
49            .iter()
50            .map(|entry| (entry.gid, entry.name.to_owned()))
51            .collect();
52    }
53
54    /// Name of the user from its uid.
55    pub fn get_user_by_uid(&self, uid: u32) -> Option<&String> {
56        self.users.get(&uid)
57    }
58
59    /// Name of the group from its gid.
60    pub fn get_group_by_gid(&self, gid: u32) -> Option<&String> {
61        self.groups.get(&gid)
62    }
63}