1 unstable release
| new 0.1.0 | Jan 16, 2026 |
|---|
#817 in Filesystem
18KB
223 lines
blkpath
Resolve the underlying block device path from a file path or file descriptor.
Overview
This crate provides a reliable way to determine which block device underlies a given file or directory. It uses a multi-step resolution strategy:
- First, it uses the
statsystem call to get the device ID (major:minor numbers) - Then, it looks up the device path via
/sys/dev/block/{major}:{minor} - If that fails, it falls back to parsing
/proc/self/mountinfo
Installation
Add blkpath to your Cargo.toml:
[dependencies]
blkpath = "0.1"
Or install the CLI tool:
cargo install blkpath
Usage
Library Usage
Use the ResolveDevice trait to resolve device paths from Path or File:
use blkpath::ResolveDevice;
use std::path::Path;
fn main() -> Result<(), blkpath::DeviceResolveError> {
let path = Path::new("/home");
let device = path.resolve_device()?;
println!("Device: {}", device.display());
Ok(())
}
You can also use it with file descriptors:
use blkpath::ResolveDevice;
use std::fs::File;
fn main() -> Result<(), blkpath::DeviceResolveError> {
let file = File::open("/home")?;
let device = file.resolve_device()?;
println!("Device: {}", device.display());
Ok(())
}
Or use the convenience functions:
use blkpath::{resolve_device, resolve_device_from_file};
use std::path::Path;
use std::fs::File;
fn main() -> Result<(), blkpath::DeviceResolveError> {
// From path
let device = resolve_device(Path::new("/home"))?;
println!("Device: {}", device.display());
// From file
let file = File::open("/home")?;
let device = resolve_device_from_file(&file)?;
println!("Device: {}", device.display());
Ok(())
}
CLI Usage
# Get the block device for a path
blkpath /home
# Output: /dev/sda1
# Get help
blkpath --help
How It Works
The resolution process works as follows:
- Stat the file/path: Get the device ID (major:minor numbers) from file metadata
- Sysfs lookup: Check
/sys/dev/block/{major}:{minor}for the device symlink - Mountinfo fallback: If sysfs fails, parse
/proc/self/mountinfoto find the mount source
This multi-step approach ensures reliability across different Linux configurations and container environments.
Requirements
- Linux operating system
- Access to
/sys/dev/block/or/proc/self/mountinfo
Dependencies
~1–1.6MB
~30K SLoC