Skip to content

Add support for findmnt #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ feat_common_core = [
"renice",
"rev",
"setsid",
"findmnt",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be in alphabetical order :)

]

[workspace.dependencies]
Expand Down Expand Up @@ -94,6 +95,7 @@ mountpoint = { optional = true, version = "0.0.1", package = "uu_mountpoint", pa
renice = { optional = true, version = "0.0.1", package = "uu_renice", path = "src/uu/renice" }
rev = { optional = true, version = "0.0.1", package = "uu_rev", path = "src/uu/rev" }
setsid = { optional = true, version = "0.0.1", package = "uu_setsid", path ="src/uu/setsid" }
findmnt = { optional = true, version = "0.0.1", package = "uu_findmnt", path = "src/uu/findmnt" }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also should be alphabetical


[dev-dependencies]
# dmesg test require fixed-boot-time feature turned on.
Expand Down
16 changes: 16 additions & 0 deletions src/uu/findmnt/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "uu_findmnt"
version = "0.0.1"
edition = "2021"

[lib]
path = "src/findmnt.rs"

[[bin]]
name = "findmnt"
path = "src/main.rs"

[dependencies]
tabled = { workspace = true }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We recently removed tabled and so this will no longer work. And as the output currently looks quite different from the output of the original findmnt, I think it is probably easier to do the output manually than trying to figure out how to do it with tabled.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Harshit933 I had started working on a findmnt implementation as well before realizing you had this PR open, feel free to take the output code from here, that version doesn't use tabled.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the pointer, I'll take a look.

uucore = { workspace = true }
clap = { workspace = true }
7 changes: 7 additions & 0 deletions src/uu/findmnt/findmnt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# findmnt

```
findmnt [options]
```

findmnt will list all mounted filesytems or search for a filesystem. The findmnt command is able to search in /etc/fstab, /etc/fstab.d, /etc/mtab or /proc/self/mountinfo. If device or mountpoint is not given, all filesystems are shown.
189 changes: 189 additions & 0 deletions src/uu/findmnt/src/findmnt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
use core::fmt;
use std::fs;

use clap::{crate_version, Command};
use tabled::{settings::Style, Table, Tabled};
use uucore::{error::UResult, help_about};

#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let _matches: clap::ArgMatches = uu_app().try_get_matches_from(args)?;

// By default findmnt reads /proc/self/mountinfo
let mut res = Findmnt::new(MOUNTINFO_DIR);
res.form_nodes();
res.print_table();
Ok(())
}

pub static MOUNTINFO_DIR: &str = "/proc/self/mountinfo";
pub static ABOUT: &str = help_about!("findmnt.md");

pub fn uu_app() -> Command {
Command::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
}

#[derive(Debug, Clone)]
pub struct Findmnt<'a> {
pub nodes_vec: Vec<Node>,
file_name: &'a str,
}

impl Findmnt<'_> {
pub fn new(file_name: &str) -> Findmnt {
Findmnt {
file_name,
nodes_vec: Vec::<Node>::new(),
}
}

pub fn form_nodes(&mut self) {
let res = fs::read_to_string(self.file_name).unwrap();
Comment on lines +42 to +43
Copy link
Preview

Copilot AI Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using unwrap() here can lead to a panic if the mountinfo file cannot be read; consider handling the error gracefully with proper error messaging.

Suggested change
pub fn form_nodes(&mut self) {
let res = fs::read_to_string(self.file_name).unwrap();
pub fn form_nodes(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let res = fs::read_to_string(self.file_name)?;

Copilot uses AI. Check for mistakes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In some niche cases, /proc might not be mounted - I agree with Copilot here - but use UError instead.

let lines = res.lines();
let mut unsorted_vec = Vec::<Node>::new();

for line in lines {
let res = Node::parse(line);
unsorted_vec.push(res);
}

self.nodes_vec = unsorted_vec;
// /, /proc, /sys, /dev, /run, /tmp, /boot
// Sort the vec according to this
self.sort_nodes();
}

pub fn print_table(&self) {
let mut table = Table::new(self.nodes_vec.clone());
table.with(Style::empty());
print!("{}", table)
}

fn sort_nodes(&mut self) {
let unsorted_vec = self.nodes_vec.clone();
let mut sorted_vec = Vec::new();

// "/"
// This should always give one element
let res = unsorted_vec
.iter()
.find(|node| node.target == Types::ROOT.to_string());
sorted_vec.push(res.unwrap().clone());

// "proc"
sorted_vec.extend(self.filter(Types::PROC));

// "/sys"
sorted_vec.extend(self.filter(Types::SYS));

// "/dev"
sorted_vec.extend(self.filter(Types::DEV));

// "/run"
sorted_vec.extend(self.filter(Types::RUN));

// "/tmp"
sorted_vec.extend(self.filter(Types::TMP));

// "/boot"
sorted_vec.extend(self.filter(Types::BOOT));

self.nodes_vec = sorted_vec;
}

fn filter(&self, pattern: Types) -> Vec<Node> {
let mut temp_vec = Vec::<Node>::new();
self.filter_with_pattern(pattern).iter().for_each(|node| {
temp_vec.push(node.clone());
});
temp_vec
}

fn filter_with_pattern(&self, pattern: Types) -> Vec<Node> {
self.nodes_vec
.iter()
.filter(|node| node.target.starts_with(&pattern.to_string()))
.cloned()
.collect()
}
}

// Different types for a particular node
#[derive(Debug, Clone)]
pub enum Types {
ROOT,
PROC,
SYS,
DEV,
RUN,
TMP,
BOOT,
}

impl fmt::Display for Types {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Types::ROOT => write!(f, "/"),
Types::PROC => write!(f, "/proc"),
Types::SYS => write!(f, "/sys"),
Types::DEV => write!(f, "/dev"),
Types::RUN => write!(f, "/run"),
Types::TMP => write!(f, "/tmp"),
Types::BOOT => write!(f, "/boot"),
}
}
}

// Represents each row for the table
#[derive(Debug, Clone, Tabled)]
pub struct Node {
target: String,
source: String,
fstype: String,
options: String,
}

impl Node {
fn new(target: String, source: String, fstype: String, options: String) -> Node {
Node {
target,
source,
fstype,
options,
}
}

pub fn filter_with_pattern(node_vec: &[Node], pattern: Types) -> Vec<Node> {
node_vec
.iter()
.filter(|node| node.target.starts_with(&pattern.to_string()))
.cloned()
.collect()
}

// This is the main function that parses the default /proc/self/mountinfo
pub fn parse(line: &str) -> Self {
let (_, rest) = line.split_once("/").unwrap();
let (target, rest) = rest.trim().split_once(" ").unwrap();
let (options, rest) = rest.trim().split_once(" ").unwrap();
let (_, rest) = rest.trim().split_once("-").unwrap();
let (fstype, rest) = rest.trim().split_once(" ").unwrap();
let (source, rest) = rest.trim().split_once(" ").unwrap();
let options_added = if rest.split_once("rw").is_some() {
Copy link
Preview

Copilot AI Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current logic splitting on "rw" may be unreliable if the options string unexpectedly contains this substring; consider a more robust parsing strategy or document the assumptions clearly.

Copilot uses AI. Check for mistakes.

Copy link
Contributor

@xbjfk xbjfk Apr 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot is correct here - I have a ro mounted partition and I'm unable to see it. This document specifies the exact format of the file.

rest.split_once("rw").unwrap().1
} else {
rest
};

let final_options = options.to_owned() + options_added;

Self::new(
target.to_string(),
source.to_string(),
fstype.to_string(),
final_options,
)
}
}
2 changes: 2 additions & 0 deletions src/uu/findmnt/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#[cfg(target_os = "linux")]
uucore::bin!(uu_findmnt);
7 changes: 7 additions & 0 deletions tests/by-util/test_findmnt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use crate::common::util::TestScenario;

#[cfg(target_os = "linux")]
#[test]
fn test_findmnt() {
new_ucmd!().succeeds().stdout_contains("/proc");
}
4 changes: 4 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ mod test_dmesg;
#[path = "by-util/test_fsfreeze.rs"]
mod test_fsfreeze;

#[cfg(feature = "findmnt")]
#[path = "by-util/test_findmnt.rs"]
mod test_findmnt;

#[cfg(feature = "mcookie")]
#[path = "by-util/test_mcookie.rs"]
mod test_mcookie;
Loading