psutil/disk/sys/linux/
partitions.rs

1use std::path::PathBuf;
2use std::str::FromStr;
3
4use unescape::unescape;
5
6use crate::{read_file, Error, Result};
7
8use crate::disk::{FileSystem, Partition};
9
10const PROC_MOUNTS: &str = "/proc/mounts";
11
12impl FromStr for Partition {
13	type Err = Error;
14
15	fn from_str(line: &str) -> Result<Partition> {
16		// Example: `/dev/sda3 /home ext4 rw,relatime,data=ordered 0 0`
17		match line.split_whitespace().collect::<Vec<_>>() {
18			fields if fields.len() >= 4 => {
19				Ok(Partition {
20					device: String::from(fields[0]),
21					// need to unescape since some characters are escaped by default like the space character
22					// https://github.com/cjbassi/ytop/issues/29
23					mountpoint: PathBuf::from(unescape(fields[1]).unwrap()), // TODO: can this unwrap fail?
24					filesystem: FileSystem::from_str(fields[2]).unwrap(),    // infallible unwrap
25					mount_options: String::from(fields[3]),
26				})
27			}
28			_ => Err(Error::MissingData {
29				path: PROC_MOUNTS.into(),
30				contents: line.to_string(),
31			}),
32		}
33	}
34}
35
36pub fn partitions() -> Result<Vec<Partition>> {
37	read_file(PROC_MOUNTS)?
38		.lines()
39		.map(Partition::from_str)
40		.collect()
41}