pgs_files/
group.rs

1//! Fuctions and Structs for dealing with /etc/group
2
3use std::path::Path;
4use std::num::ParseIntError;
5use libc::gid_t;
6use entries::{Entries,Entry};
7
8
9/// An entry from /etc/group
10#[derive(Debug, PartialEq, PartialOrd)]
11pub struct GroupEntry {
12
13    /// Group Name
14    pub name: String,
15
16    /// Group Password
17    pub passwd: String,
18
19    /// Group ID
20    pub gid: gid_t,
21
22    /// Group Members
23    pub members: Vec<String>,
24
25}
26
27
28impl Entry for GroupEntry {
29    fn from_line(line: &str) -> Result<GroupEntry, ParseIntError> {
30
31        let parts: Vec<&str> = line.split(":").map(|part| part.trim()).collect();
32        let members: Vec<String> = match parts[3].len() {
33            0 => Vec::new(),
34            _ => parts[3]
35                .split(",")
36                .map(|member| member.trim())
37                .map(|member| member.to_string())
38                .collect()
39        };
40
41        Ok(GroupEntry {
42            name: parts[0].to_string(),
43            passwd: parts[1].to_string(),
44            gid: try!(parts[2].parse()),
45            members: members,
46        })
47    }
48}
49
50
51/// Return a [`GroupEntry`](struct.GroupEntry.html)
52/// for a given `uid` and `&Path`
53pub fn get_entry_by_gid_from_path(path: &Path, gid: gid_t) -> Option<GroupEntry> {
54    Entries::<GroupEntry>::new(path).find(|x| x.gid == gid)
55}
56
57
58/// Return a [`GroupEntry`](struct.GroupEntry.html)
59/// for a given `uid` from `/etc/group`
60pub fn get_entry_by_gid(gid: gid_t) -> Option<GroupEntry> {
61    get_entry_by_gid_from_path(&Path::new("/etc/group"), gid)
62}
63
64
65/// Return a [`GroupEntry`](struct.GroupEntry.html)
66/// for a given `name` and `&Path`
67pub fn get_entry_by_name_from_path(path: &Path, name: &str) -> Option<GroupEntry> {
68    Entries::<GroupEntry>::new(path).find(|x| x.name == name)
69}
70
71
72/// Return a [`GroupEntry`](struct.GroupEntry.html)
73/// for a given `name` from `/etc/group`
74pub fn get_entry_by_name(name: &str) -> Option<GroupEntry> {
75    get_entry_by_name_from_path(&Path::new("/etc/group"), name)
76}
77
78
79/// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all
80/// [`GroupEntry`](struct.GroupEntry.html)'s for a given `&Path`
81pub fn get_all_entries_from_path(path: &Path) -> Vec<GroupEntry> {
82    Entries::new(path).collect()
83}
84
85
86/// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all
87/// [`GroupEntry`](struct.GroupEntry.html)'s from `/etc/group`
88pub fn get_all_entries() -> Vec<GroupEntry> {
89    get_all_entries_from_path(&Path::new("/etc/group"))
90}