sysinfo/unix/
groups.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3#[cfg(not(any(target_os = "macos", target_os = "ios")))]
4use crate::Group;
5
6impl crate::GroupInner {
7    pub(crate) fn new(id: crate::Gid, name: String) -> Self {
8        Self { id, name }
9    }
10
11    pub(crate) fn id(&self) -> &crate::Gid {
12        &self.id
13    }
14
15    pub(crate) fn name(&self) -> &str {
16        &self.name
17    }
18}
19
20// Not used by mac.
21#[cfg(not(any(target_os = "macos", target_os = "ios")))]
22pub(crate) fn get_groups(groups: &mut Vec<Group>) {
23    use crate::common::{Gid, GroupInner};
24    use std::fs::File;
25    use std::io::Read;
26
27    #[inline]
28    fn parse_id(id: &str) -> Option<u32> {
29        id.parse::<u32>().ok()
30    }
31
32    groups.clear();
33
34    let mut s = String::new();
35
36    let _ = File::open("/etc/group").and_then(|mut f| f.read_to_string(&mut s));
37
38    for line in s.lines() {
39        let mut parts = line.split(':');
40        if let Some(name) = parts.next() {
41            let mut parts = parts.skip(1);
42            // Skip the user if the uid cannot be parsed correctly
43            if let Some(gid) = parts.next().and_then(parse_id) {
44                groups.push(Group {
45                    inner: GroupInner::new(Gid(gid), name.to_owned()),
46                });
47            }
48        }
49    }
50}
51
52#[cfg(any(target_os = "macos", target_os = "ios"))]
53pub(crate) use crate::unix::apple::groups::get_groups;