Skip to content
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
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions src/uu/mountpoint/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ edition = "2021"
uucore = { workspace = true }
clap = { workspace = true }

[target.'cfg(unix)'.dependencies]
libc = { workspace = true }

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

Expand Down
101 changes: 100 additions & 1 deletion src/uu/mountpoint/src/mountpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use clap::Arg;
use clap::{crate_version, Command};
use clap::{Arg, ArgAction};
use std::env;
#[cfg(not(windows))]
use std::fs;
Expand All @@ -23,6 +23,20 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let path = matches.get_one::<String>("path");

if let Some(path) = path {
if matches.get_flag("devno") {
return print_block_devno(path);
}
if matches.get_flag("fs-devno") {
match fs_devno(path) {
Ok(Some(devno)) => println!("{devno}"),
Ok(None) => {
println!("{path} is not a mountpoint");
set_exit_code(32);
}
Err(e) => return Err(USimpleError::new(1, format!("{path}: {}", strip_errno(&e)))),
}
return Ok(());
}
match is_mountpoint(path) {
Ok(true) => println!("{path} is a mountpoint"),
Ok(false) => {
Expand Down Expand Up @@ -56,6 +70,77 @@ fn is_mountpoint(path: &str) -> std::io::Result<bool> {
.any(|mount_point| unescape_mountinfo(mount_point) == target.as_os_str().as_bytes()))
}

/// The `major:minor` of the filesystem mounted on `path`, or `None` when it is
/// not a mount point. Like util-linux, this is the device number of the
/// topmost (last) mountinfo entry for the path, which can differ from the
/// path's `st_dev`, for example for a bind-mounted file.
#[cfg(target_os = "linux")]
fn fs_devno(path: &str) -> std::io::Result<Option<String>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this is almost the same code as is_mountpoint (mountinfo scan + by-device fallback)
could is_mountpoint just be fs_devno(path).map(|d| d.is_some()), no?

use std::os::unix::ffi::OsStrExt;

let target = fs::canonicalize(path)?;
let Ok(mountinfo) = fs::read("/proc/self/mountinfo") else {
return fs_devno_by_device(path);
};
// the last entry for a mount point is the topmost mount
Ok(mountinfo.rsplit(|&b| b == b'\n').find_map(|line| {
let mut fields = line.split(|&b| b == b' ');
let devno = fields.nth(2)?;
let mount_point = fields.nth(1)?;
(unescape_mountinfo(mount_point) == target.as_os_str().as_bytes())
.then(|| String::from_utf8_lossy(devno).into_owned())
}))
}

#[cfg(all(not(windows), not(target_os = "linux")))]
fn fs_devno(path: &str) -> std::io::Result<Option<String>> {
fs_devno_by_device(path)
}

#[cfg(not(windows))]
fn fs_devno_by_device(path: &str) -> std::io::Result<Option<String>> {
if !is_mountpoint_by_device(path)? {
return Ok(None);
}
Ok(Some(format_devno(fs::metadata(path)?.dev())))
}

#[cfg(windows)]
fn fs_devno(_path: &str) -> std::io::Result<Option<String>> {
Ok(None)
}

#[cfg(not(windows))]
fn format_devno(dev: u64) -> String {
// dev_t is narrower than u64 on some platforms, such as macOS
#[allow(clippy::unnecessary_cast)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could we avoid the #[allow]? e.g. libc::dev_t::try_from(dev) or take a libc::dev_t directly

let dev = dev as libc::dev_t;
format!("{}:{}", libc::major(dev), libc::minor(dev))
}

/// Prints the `major:minor` of the block device `path`.
#[cfg(not(windows))]
fn print_block_devno(path: &str) -> UResult<()> {
use std::os::unix::fs::FileTypeExt;

let metadata = fs::metadata(path)
.map_err(|e| USimpleError::new(1, format!("{path}: {}", strip_errno(&e))))?;
if metadata.file_type().is_block_device() {
println!("{}", format_devno(metadata.rdev()));
} else {
uucore::show_error!("{path}: not a block device");
set_exit_code(32);
}
Ok(())
}

#[cfg(windows)]
fn print_block_devno(path: &str) -> UResult<()> {
uucore::show_error!("{path}: not a block device");
set_exit_code(32);
Ok(())
}

/// mountinfo writes space, tab, newline and backslash as `\ooo` octal escapes.
#[cfg(target_os = "linux")]
fn unescape_mountinfo(field: &[u8]) -> Vec<u8> {
Expand Down Expand Up @@ -108,6 +193,20 @@ pub fn uu_app() -> Command {
.about(ABOUT)
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.arg(
Arg::new("fs-devno")
.short('d')
.long("fs-devno")
.action(ArgAction::SetTrue)
.help("Print the major/minor device number of the filesystem mounted on PATH"),
)
.arg(
Arg::new("devno")
.short('x')
.long("devno")
.action(ArgAction::SetTrue)
.help("Print the major/minor device number of the block device PATH"),
)
.arg(
Arg::new("path")
.value_name("PATH")
Expand Down
54 changes: 54 additions & 0 deletions tests/by-util/test_mountpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,57 @@ fn test_proc_is_a_mountpoint() {
.succeeds()
.stdout_is("/proc/ is a mountpoint\n");
}

#[test]
#[cfg(target_os = "linux")]
fn test_fs_devno_of_root() {
// the device number of the topmost mount on `/`, as in mountinfo
let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").unwrap();
let devno = mountinfo
.lines()
.rev()
.find_map(|line| {
let fields: Vec<&str> = line.split(' ').collect();
(fields[4] == "/").then(|| fields[2].to_string())
})
.unwrap();
for flag in ["-d", "--fs-devno"] {
new_ucmd!()
.args(&[flag, "/"])
.succeeds()
.stdout_is(format!("{devno}\n"));
}
}

#[test]
#[cfg(unix)]
fn test_fs_devno_not_a_mountpoint() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("dir");
ucmd.args(&["-d", &at.plus_as_string("dir")])
.current_dir("/")
.fails()
.code_is(32)
.stdout_is(format!(
"{} is not a mountpoint\n",
at.plus_as_string("dir")
));
}

#[test]
#[cfg(unix)]
fn test_devno_not_a_block_device() {
for flag in ["-x", "--devno"] {
new_ucmd!()
.args(&[flag, "/dev/null"])
.fails()
.code_is(32)
.no_stdout()
.stderr_is("mountpoint: /dev/null: not a block device\n");
}
new_ucmd!()
.args(&["-x", "does-not-exist"])
.fails()
.code_is(1)
.stderr_contains("does-not-exist: No such file or directory");
}
Loading