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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use super::*;

/// A mount point
#[derive(Debug, Clone)]
pub struct Mount {
    pub info: MountInfo,
    pub fs_label: Option<String>,
    pub disk: Option<Disk>,
    pub stats: Result<Stats, StatsError>,
}

impl Mount {
    /// Return inodes information, when available and consistent
    pub fn inodes(&self) -> Option<&Inodes> {
        self.stats
            .as_ref()
            .ok()
            .and_then(|stats| stats.inodes.as_ref())
    }
    /// Return the stats, if they could be fetched and
    /// make sense.
    ///
    /// Most often, you don't care *why* there are no stats,
    /// because the error cases are mostly non storage volumes,
    /// so it's a best practice to no try to analyze the error
    /// but just use this option returning method.
    ///
    /// The most interesting case is when a network volume is
    /// unreachable, which you can test with is_unreachable().
    pub fn stats(&self) -> Option<&Stats> {
        self.stats.as_ref().ok()
    }
    /// Tell whether the reason we have no stats is because the
    /// filesystem is unreachable
    pub fn is_unreachable(&self) -> bool {
        matches!(self.stats, Err(StatsError::Unreachable))
    }
}

#[derive(Debug, Clone)]
pub struct ReadOptions {
    remote_stats: bool,
}
impl Default for ReadOptions {
    fn default() -> Self {
        Self {
            remote_stats: true,
        }
    }
}
impl ReadOptions {
    pub fn remote_stats(&mut self, v: bool) {
        self.remote_stats = v;
    }
}

/// Read all the mount points and load basic information on them
pub fn read_mounts(options: &ReadOptions) -> Result<Vec<Mount>, Error> {
    let labels = read_labels().ok();
    // we'll find the disk for a filesystem by taking the longest
    // disk whose name starts the one of our partition
    // hence the sorting.
    let bd_list = BlockDeviceList::read()?;
    read_mountinfo()?
        .drain(..)
        .map(|info| {
            let top_bd = bd_list.find_top(
                info.dev,
                info.dm_name(),
                info.fs_name(),
            );
            let fs_label = labels.as_ref()
                .and_then(|labels| {
                    labels
                        .iter()
                        .find(|label| label.fs_name == info.fs)
                        .map(|label| label.label.clone())
                });
            let disk = top_bd.map(|bd| Disk::new(bd.name.clone()));
            let stats = if !options.remote_stats && info.is_remote() {
                Err(StatsError::Excluded)
            } else {
                Stats::from(&info.mount_point)
            };
            Ok(Mount { info, fs_label, disk, stats })
        })
        .collect()
}