Skip to main content

btrfs_cli/inspect/
min_dev_size.rs

1use crate::{Format, Runnable, util::human_bytes};
2use anyhow::{Context, Result};
3use clap::Parser;
4use std::{fs::File, os::unix::io::AsFd, path::PathBuf};
5
6/// Print the minimum size a device can be shrunk to.
7///
8/// Returns the minimum size in bytes that the specified device can be
9/// resized to without losing data. The device id 1 is used by default.
10/// Requires CAP_SYS_ADMIN.
11#[derive(Parser, Debug)]
12pub struct MinDevSizeCommand {
13    /// Specify the device id to query
14    #[arg(long = "id", default_value = "1")]
15    devid: u64,
16
17    /// Path to a file or directory on the btrfs filesystem
18    path: PathBuf,
19}
20
21impl Runnable for MinDevSizeCommand {
22    fn run(&self, _format: Format, _dry_run: bool) -> Result<()> {
23        let file = File::open(&self.path)
24            .with_context(|| format!("failed to open '{}'", self.path.display()))?;
25
26        let size =
27            btrfs_uapi::dev_extent::min_dev_size(file.as_fd(), self.devid).with_context(|| {
28                format!(
29                    "failed to determine min device size for devid {} on '{}'",
30                    self.devid,
31                    self.path.display()
32                )
33            })?;
34
35        println!("{} bytes ({})", size, human_bytes(size));
36        Ok(())
37    }
38}