Skip to main content

btrfs_cli/subvolume/
set_default.rs

1use crate::{RunContext, Runnable};
2use anyhow::{Context, Result, anyhow};
3use btrfs_uapi::subvolume::{
4    FS_TREE_OBJECTID, subvolume_default_set, subvolume_info,
5};
6use clap::Parser;
7use std::{fs::File, os::unix::io::AsFd, path::PathBuf};
8
9/// Set the default subvolume of a filesystem.
10///
11/// Accepts either a subvolume path (btrfs subvolume set-default /mnt/fs/subvol)
12/// or a numeric ID with a filesystem path (btrfs subvolume set-default 256 /mnt/fs).
13#[derive(Parser, Debug)]
14pub struct SubvolumeSetDefaultCommand {
15    /// Subvolume path OR numeric subvolume ID
16    #[clap(required = true)]
17    subvol_or_id: String,
18
19    /// Filesystem mount point (required when first arg is a numeric ID)
20    path: Option<PathBuf>,
21}
22
23impl Runnable for SubvolumeSetDefaultCommand {
24    fn run(&self, _ctx: &RunContext) -> Result<()> {
25        if let Ok(id) = self.subvol_or_id.parse::<u64>() {
26            let mount = self.path.as_ref().ok_or_else(|| {
27                anyhow!("a filesystem path is required when specifying a subvolume ID")
28            })?;
29
30            let file = File::open(mount).with_context(|| {
31                format!("failed to open '{}'", mount.display())
32            })?;
33
34            let id_to_use = if id == 0 { FS_TREE_OBJECTID } else { id };
35
36            subvolume_default_set(file.as_fd(), id_to_use).with_context(
37                || {
38                    format!(
39                        "failed to set default subvolume to ID {} on '{}'",
40                        id_to_use,
41                        mount.display()
42                    )
43                },
44            )?;
45
46            println!("Set default subvolume to ID {id_to_use}");
47        } else {
48            let subvol_path = PathBuf::from(&self.subvol_or_id);
49
50            let file = File::open(&subvol_path).with_context(|| {
51                format!("failed to open '{}'", subvol_path.display())
52            })?;
53
54            let info = subvolume_info(file.as_fd()).with_context(|| {
55                format!(
56                    "failed to get subvolume info for '{}'",
57                    subvol_path.display()
58                )
59            })?;
60
61            subvolume_default_set(file.as_fd(), info.id).with_context(
62                || {
63                    format!(
64                        "failed to set default subvolume to '{}' (ID {})",
65                        subvol_path.display(),
66                        info.id
67                    )
68                },
69            )?;
70
71            println!(
72                "Set default subvolume to '{}' (ID {})",
73                subvol_path.display(),
74                info.id
75            );
76        }
77
78        Ok(())
79    }
80}