btrfs-cli 0.13.0

User-space command-line tool for inspecting and managing Btrfs filesystems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use anyhow::{Context, Result, bail};
use chrono::{DateTime, Local};
use serde::Serialize;
use std::{
    fs::{self, File},
    os::unix::fs::FileTypeExt,
    path::Path,
    str::FromStr,
    time::{SystemTime, UNIX_EPOCH},
};
use uuid::Uuid;

/// Open a path and return the `File`, with a contextual error message on failure.
pub fn open_path(path: &Path) -> Result<File> {
    File::open(path)
        .with_context(|| format!("failed to open '{}'", path.display()))
}

/// Return `true` if `device` appears as a source in `/proc/mounts`.
///
/// Compares canonical paths so symlinks in `/dev/disk/by-*` are handled
/// Check whether a device path appears as a mount source in `/proc/mounts`.
///
/// Delegates to [`btrfs_uapi::filesystem::is_mounted`].
pub fn is_mounted(device: &Path) -> bool {
    btrfs_uapi::filesystem::is_mounted(device).unwrap_or(false)
}

/// Resolved size display mode.
pub enum SizeFormat {
    /// Print raw byte count with no suffix.
    Raw,
    /// Human-readable with base 1024 (KiB, MiB, GiB, …).
    HumanIec,
    /// Human-readable with base 1000 (kB, MB, GB, …).
    HumanSi,
    /// Divide by a fixed power and print the integer result.
    Fixed(u64),
}

/// Format a byte count according to the given [`SizeFormat`].
pub fn fmt_size(bytes: u64, mode: &SizeFormat) -> String {
    match mode {
        SizeFormat::Raw => bytes.to_string(),
        SizeFormat::HumanIec => human_bytes(bytes),
        SizeFormat::HumanSi => human_bytes_si(bytes),
        SizeFormat::Fixed(divisor) => format!("{}", bytes / divisor),
    }
}

/// Format a byte count as a human-readable string using binary prefixes.
#[allow(clippy::cast_precision_loss)]
pub fn human_bytes(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit + 1 < UNITS.len() {
        value /= 1024.0;
        unit += 1;
    }
    format!("{value:.2}{}", UNITS[unit])
}

/// Format a byte count as a human-readable string using SI (base-1000) prefixes.
#[allow(clippy::cast_precision_loss)]
pub fn human_bytes_si(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "kB", "MB", "GB", "TB", "PB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1000.0 && unit + 1 < UNITS.len() {
        value /= 1000.0;
        unit += 1;
    }
    format!("{value:.2}{}", UNITS[unit])
}

/// Format a [`SystemTime`] as a local-time datetime string in the same style
/// as the C btrfs-progs tool: `YYYY-MM-DD HH:MM:SS ±HHMM`.
///
/// Returns `"-"` when the time is [`UNIX_EPOCH`] (i.e. not set).
pub fn format_time(t: SystemTime) -> String {
    if t == UNIX_EPOCH {
        return "-".to_string();
    }
    match DateTime::<Local>::from(t)
        .format("%Y-%m-%d %H:%M:%S %z")
        .to_string()
    {
        s if s.is_empty() => "-".to_string(),
        s => s,
    }
}

/// Format a [`SystemTime`] for replace-status output: `%e.%b %T`
/// (e.g. ` 5.Mar 14:30:00`).
pub fn format_time_short(t: &SystemTime) -> String {
    DateTime::<Local>::from(*t).format("%e.%b %T").to_string()
}

/// Format a unix timestamp (sec, nsec) as `sec.nsec (YYYY-MM-DD HH:MM:SS)`.
pub fn format_timespec(sec: u64, nsec: u32) -> String {
    #[allow(clippy::cast_possible_wrap)] // timestamps fit in i64
    let sec_i64 = sec as i64;
    match DateTime::from_timestamp(sec_i64, nsec) {
        Some(utc) => {
            let local = utc.with_timezone(&Local);
            format!("{}.{} ({})", sec, nsec, local.format("%Y-%m-%d %H:%M:%S"))
        }
        None => format!("{sec}.{nsec}"),
    }
}

/// Parse a size string with an optional binary suffix (K, M, G, T, P, E).
pub fn parse_size_with_suffix(s: &str) -> Result<u64> {
    let (num_str, suffix) = match s.find(|c: char| c.is_alphabetic()) {
        Some(i) => (&s[..i], &s[i..]),
        None => (s, ""),
    };
    let n: u64 = num_str
        .parse()
        .with_context(|| format!("invalid size number: '{num_str}'"))?;
    let multiplier: u64 = match suffix.to_uppercase().as_str() {
        "" => 1,
        "K" => 1024,
        "M" => 1024 * 1024,
        "G" => 1024 * 1024 * 1024,
        "T" => 1024u64.pow(4),
        "P" => 1024u64.pow(5),
        "E" => 1024u64.pow(6),
        _ => anyhow::bail!("unknown size suffix: '{suffix}'"),
    };
    n.checked_mul(multiplier)
        .ok_or_else(|| anyhow::anyhow!("size overflow: '{s}'"))
}

/// A UUID value parsed from a CLI argument.
///
/// Accepts `clear` (nil UUID), `random` (random v4 UUID), `time` (v7
/// time-ordered UUID), or any standard UUID string (with or without hyphens).
#[derive(Debug, Clone, Copy)]
pub struct ParsedUuid(Uuid);

impl std::ops::Deref for ParsedUuid {
    type Target = Uuid;
    fn deref(&self) -> &Uuid {
        &self.0
    }
}

/// Parse a qgroup ID string of the form `"<level>/<subvolid>"` into a packed u64.
///
/// The packed form is `(level as u64) << 48 | subvolid`.
/// Example: `"0/5"` → `5`, `"1/256"` → `0x0001_0000_0000_0100`.
pub fn parse_qgroupid(s: &str) -> anyhow::Result<u64> {
    let (level_str, id_str) = s.split_once('/').ok_or_else(|| {
        anyhow::anyhow!("invalid qgroup ID '{s}': expected <level>/<id>")
    })?;
    let level: u64 = level_str.parse().map_err(|_| {
        anyhow::anyhow!("invalid qgroup level '{level_str}' in '{s}'")
    })?;
    let subvolid: u64 = id_str.parse().map_err(|_| {
        anyhow::anyhow!("invalid qgroup subvolid '{id_str}' in '{s}'")
    })?;
    Ok((level << 48) | subvolid)
}

impl FromStr for ParsedUuid {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "clear" => Ok(Self(Uuid::nil())),
            "random" => Ok(Self(Uuid::new_v4())),
            "time" => Ok(Self(Uuid::now_v7())),
            _ => Uuid::parse_str(s)
                .map(Self)
                .map_err(|e| format!("invalid UUID: {e}")),
        }
    }
}

/// Check that a device is suitable for use as a btrfs target (add or replace).
///
/// Verifies that the path is a block device, is not currently mounted, and
/// does not already contain a btrfs filesystem (unless `force` is true).
pub fn check_device_for_overwrite(device: &Path, force: bool) -> Result<()> {
    let meta = fs::metadata(device).with_context(|| {
        format!("cannot access device '{}'", device.display())
    })?;

    if !meta.file_type().is_block_device() {
        bail!("'{}' is not a block device", device.display());
    }

    if is_device_mounted(device)? {
        bail!(
            "'{}' is mounted; refusing to use a mounted device",
            device.display()
        );
    }

    if !force && has_btrfs_superblock(device) {
        bail!(
            "'{}' already contains a btrfs filesystem; use -f to force",
            device.display()
        );
    }

    Ok(())
}

/// Check if a device path appears in /proc/mounts (with error propagation).
///
/// Delegates to [`btrfs_uapi::filesystem::is_mounted`].
pub fn is_device_mounted(device: &Path) -> Result<bool> {
    btrfs_uapi::filesystem::is_mounted(device).with_context(|| {
        format!("cannot check mount status of '{}'", device.display())
    })
}

/// Try to read a btrfs superblock from the device. Returns true if a valid
/// btrfs magic signature is found.
pub fn has_btrfs_superblock(device: &Path) -> bool {
    let Ok(mut file) = File::open(device) else {
        return false;
    };
    match btrfs_disk::superblock::read_superblock(&mut file, 0) {
        Ok(sb) => sb.magic_is_valid(),
        Err(_) => false,
    }
}

/// Write structured JSON output in the btrfs-progs format.
///
/// Wraps the data in a root object with a `__header` containing a version
/// field, and the data under the given `key`:
///
/// ```json
/// {
///   "__header": { "version": "1" },
///   "<key>": <data>
/// }
/// ```
pub fn print_json(key: &str, data: &impl Serialize) -> Result<()> {
    #[derive(Serialize)]
    struct Header {
        version: &'static str,
    }

    let mut map = serde_json::Map::new();
    map.insert(
        "__header".to_string(),
        serde_json::to_value(Header { version: "1" })?,
    );
    map.insert(key.to_string(), serde_json::to_value(data)?);

    serde_json::to_writer_pretty(std::io::stdout(), &map)?;
    println!();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- human_bytes ---

    #[test]
    fn human_bytes_zero() {
        assert_eq!(human_bytes(0), "0.00B");
    }

    #[test]
    fn human_bytes_small() {
        assert_eq!(human_bytes(1), "1.00B");
        assert_eq!(human_bytes(1023), "1023.00B");
    }

    #[test]
    fn human_bytes_exact_powers() {
        assert_eq!(human_bytes(1024), "1.00KiB");
        assert_eq!(human_bytes(1024 * 1024), "1.00MiB");
        assert_eq!(human_bytes(1024 * 1024 * 1024), "1.00GiB");
        assert_eq!(human_bytes(1024u64.pow(4)), "1.00TiB");
        assert_eq!(human_bytes(1024u64.pow(5)), "1.00PiB");
    }

    #[test]
    fn human_bytes_fractional() {
        // 1.5 GiB = 1024^3 + 512*1024^2
        assert_eq!(
            human_bytes(1024 * 1024 * 1024 + 512 * 1024 * 1024),
            "1.50GiB"
        );
    }

    #[test]
    fn human_bytes_u64_max() {
        // Should not panic; lands in PiB range
        let s = human_bytes(u64::MAX);
        assert!(s.ends_with("PiB"), "expected PiB suffix, got: {s}");
    }

    // --- parse_size_with_suffix ---

    #[test]
    fn parse_size_bare_number() {
        assert_eq!(parse_size_with_suffix("0").unwrap(), 0);
        assert_eq!(parse_size_with_suffix("42").unwrap(), 42);
    }

    #[test]
    fn parse_size_all_suffixes() {
        assert_eq!(parse_size_with_suffix("1K").unwrap(), 1024);
        assert_eq!(parse_size_with_suffix("1M").unwrap(), 1024 * 1024);
        assert_eq!(parse_size_with_suffix("1G").unwrap(), 1024 * 1024 * 1024);
        assert_eq!(parse_size_with_suffix("1T").unwrap(), 1024u64.pow(4));
        assert_eq!(parse_size_with_suffix("1P").unwrap(), 1024u64.pow(5));
        assert_eq!(parse_size_with_suffix("1E").unwrap(), 1024u64.pow(6));
    }

    #[test]
    fn parse_size_case_insensitive() {
        assert_eq!(parse_size_with_suffix("4k").unwrap(), 4 * 1024);
        assert_eq!(
            parse_size_with_suffix("2g").unwrap(),
            2 * 1024 * 1024 * 1024
        );
    }

    #[test]
    fn parse_size_overflow() {
        assert!(parse_size_with_suffix("16385P").is_err());
    }

    #[test]
    fn parse_size_bad_number() {
        assert!(parse_size_with_suffix("abcM").is_err());
        assert!(parse_size_with_suffix("").is_err());
    }

    #[test]
    fn parse_size_unknown_suffix() {
        assert!(parse_size_with_suffix("10X").is_err());
    }

    // --- parse_qgroupid ---

    #[test]
    fn parse_qgroupid_level0() {
        assert_eq!(parse_qgroupid("0/5").unwrap(), 5);
        assert_eq!(parse_qgroupid("0/256").unwrap(), 256);
    }

    #[test]
    fn parse_qgroupid_higher_level() {
        assert_eq!(parse_qgroupid("1/256").unwrap(), (1u64 << 48) | 256);
        assert_eq!(parse_qgroupid("2/0").unwrap(), 2u64 << 48);
    }

    #[test]
    fn parse_qgroupid_missing_slash() {
        assert!(parse_qgroupid("5").is_err());
    }

    #[test]
    fn parse_qgroupid_bad_level() {
        assert!(parse_qgroupid("abc/5").is_err());
    }

    #[test]
    fn parse_qgroupid_bad_subvolid() {
        assert!(parse_qgroupid("0/abc").is_err());
    }

    // --- ParsedUuid ---

    #[test]
    fn parsed_uuid_clear() {
        let u: ParsedUuid = "clear".parse().unwrap();
        assert!(u.is_nil());
    }

    #[test]
    fn parsed_uuid_random() {
        let u: ParsedUuid = "random".parse().unwrap();
        assert!(!u.is_nil());
    }

    #[test]
    fn parsed_uuid_time() {
        let u: ParsedUuid = "time".parse().unwrap();
        assert!(!u.is_nil());
    }

    #[test]
    fn parsed_uuid_explicit() {
        let u: ParsedUuid =
            "550e8400-e29b-41d4-a716-446655440000".parse().unwrap();
        assert_eq!(u.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn parsed_uuid_no_hyphens() {
        let u: ParsedUuid = "550e8400e29b41d4a716446655440000".parse().unwrap();
        assert_eq!(u.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn parsed_uuid_invalid() {
        assert!("not-a-uuid".parse::<ParsedUuid>().is_err());
        assert!("".parse::<ParsedUuid>().is_err());
    }
}