hm-util 0.0.5

Shared OS and filesystem utilities for Harmont crates.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Platform-native copy-on-write directory cloning.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

use anyhow::{Context, Result, bail};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CowStrategy {
    ApfsClone,
    Reflink,
    FuseOverlay,
    FullCopy,
}

/// Detect the best available COW strategy for the current platform.
/// Result is cached after the first call.
#[must_use]
pub fn detect_strategy() -> CowStrategy {
    static STRATEGY: OnceLock<CowStrategy> = OnceLock::new();
    *STRATEGY.get_or_init(detect_strategy_inner)
}

/// Probe result for a single strategy.
#[derive(Debug, Clone)]
pub struct StrategyProbe {
    pub strategy: CowStrategy,
    pub available: bool,
    pub reason: &'static str,
}

/// Test all strategies and report which are available.
/// Used for diagnostics / user-facing warnings.
#[must_use]
#[allow(clippy::vec_init_then_push)]
pub fn diagnose_strategies() -> Vec<StrategyProbe> {
    let mut probes = Vec::new();

    #[cfg(target_os = "macos")]
    probes.push(StrategyProbe {
        strategy: CowStrategy::ApfsClone,
        available: true,
        reason: "macOS APFS detected",
    });

    #[cfg(target_os = "linux")]
    {
        probes.push(StrategyProbe {
            strategy: CowStrategy::Reflink,
            available: probe_reflink(),
            reason: if probe_reflink() {
                "filesystem supports reflinks"
            } else {
                "filesystem does not support reflinks (btrfs/XFS required)"
            },
        });
        let fuse_ok = probe_fuse_overlayfs();
        probes.push(StrategyProbe {
            strategy: CowStrategy::FuseOverlay,
            available: fuse_ok,
            reason: if fuse_ok {
                "fuse-overlayfs mount succeeded"
            } else if which::which("fuse-overlayfs").is_err() {
                "fuse-overlayfs not installed"
            } else {
                "fuse-overlayfs mount failed (missing /dev/fuse or user_allow_other?)"
            },
        });
    }

    probes.push(StrategyProbe {
        strategy: CowStrategy::FullCopy,
        available: true,
        reason: "always available (slow)",
    });

    probes
}

#[allow(clippy::missing_const_for_fn)]
fn detect_strategy_inner() -> CowStrategy {
    #[cfg(target_os = "macos")]
    {
        return CowStrategy::ApfsClone;
    }

    #[cfg(target_os = "linux")]
    {
        if probe_reflink() {
            return CowStrategy::Reflink;
        }
        if probe_fuse_overlayfs() {
            return CowStrategy::FuseOverlay;
        }
        return CowStrategy::FullCopy;
    }

    #[allow(unreachable_code)]
    CowStrategy::FullCopy
}

#[cfg(target_os = "linux")]
fn probe_reflink() -> bool {
    let Ok(tmp) = tempfile::tempdir() else {
        return false;
    };
    let src = tmp.path().join("src");
    let dst = tmp.path().join("dst");
    if std::fs::write(&src, b"x").is_err() {
        return false;
    }
    Command::new("cp")
        .args(["--reflink=always"])
        .arg(&src)
        .arg(&dst)
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

#[cfg(target_os = "linux")]
fn probe_fuse_overlayfs() -> bool {
    if which::which("fuse-overlayfs").is_err() {
        return false;
    }
    let Ok(tmp) = tempfile::tempdir() else {
        return false;
    };
    let lower = tmp.path().join("lower");
    let upper = tmp.path().join("upper");
    let work = tmp.path().join("work");
    let merged = tmp.path().join("merged");
    for d in [&lower, &upper, &work, &merged] {
        if std::fs::create_dir(d).is_err() {
            return false;
        }
    }
    let opts = format!(
        "lowerdir={},upperdir={},workdir={},allow_other,squash_to_uid=0,squash_to_gid=0",
        lower.display(),
        upper.display(),
        work.display(),
    );
    let ok = Command::new("fuse-overlayfs")
        .args(["-o", &opts])
        .arg(&merged)
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success());
    if ok {
        let bin = if which::which("fusermount3").is_ok() {
            "fusermount3"
        } else {
            "fusermount"
        };
        let _ = Command::new(bin)
            .args(["-u"])
            .arg(&merged)
            .stderr(std::process::Stdio::null())
            .status();
    }
    ok
}

/// Clone `src` to `dst` using the best available COW mechanism.
///
/// # Errors
///
/// Returns an error if `dst` already exists, if parent directories cannot
/// be created, or if the underlying copy operation fails.
pub fn cow_clone_dir(src: &Path, dst: &Path) -> Result<()> {
    if dst.exists() {
        bail!("destination already exists: {}", dst.display());
    }
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("create parent dirs for {}", dst.display()))?;
    }

    if try_platform_cow(src, dst)? {
        return Ok(());
    }

    copy_dir_recursive(src, dst)
}

fn try_platform_cow(src: &Path, dst: &Path) -> Result<bool> {
    #[cfg(target_os = "macos")]
    {
        let status = Command::new("cp")
            .args(["-c", "-R", "-p"])
            .arg(src)
            .arg(dst)
            .stderr(std::process::Stdio::null())
            .status()
            .context("spawn cp -c")?;
        if status.success() {
            return Ok(true);
        }
        let _ = std::fs::remove_dir_all(dst);
    }

    #[cfg(target_os = "linux")]
    {
        let status = Command::new("cp")
            .args(["--reflink=always", "-a"])
            .arg(src)
            .arg(dst)
            .stderr(std::process::Stdio::null())
            .status()
            .context("spawn cp --reflink")?;
        if status.success() {
            return Ok(true);
        }
        let _ = std::fs::remove_dir_all(dst);

        let status = Command::new("cp")
            .args(["-a"])
            .arg(src)
            .arg(dst)
            .stderr(std::process::Stdio::null())
            .status()
            .context("spawn cp -a")?;
        if status.success() {
            return Ok(true);
        }
        let _ = std::fs::remove_dir_all(dst);
    }

    Ok(false)
}

fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst).with_context(|| format!("create {}", dst.display()))?;
    for entry in std::fs::read_dir(src).with_context(|| format!("read dir {}", src.display()))? {
        let entry = entry?;
        let ty = entry.file_type()?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if ty.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else if ty.is_symlink() {
            let target = std::fs::read_link(&src_path)?;
            #[cfg(unix)]
            std::os::unix::fs::symlink(&target, &dst_path)?;
            #[cfg(windows)]
            std::os::windows::fs::symlink_file(&target, &dst_path)?;
        } else {
            std::fs::copy(&src_path, &dst_path)
                .with_context(|| format!("copy {}", src_path.display()))?;
        }
    }
    Ok(())
}

pub struct OverlayMount {
    merged: PathBuf,
    upper: PathBuf,
    mounted: std::sync::atomic::AtomicBool,
}

impl OverlayMount {
    /// Mount a fuse-overlayfs filesystem merging the given layers.
    ///
    /// # Errors
    ///
    /// Returns an error if directory creation fails or `fuse-overlayfs`
    /// exits with a non-zero status.
    pub fn mount(
        lower_dirs: &[&Path],
        upper_dir: &Path,
        work_dir: &Path,
        merged_path: &Path,
    ) -> Result<Self> {
        std::fs::create_dir_all(upper_dir)?;
        std::fs::create_dir_all(work_dir)?;
        std::fs::create_dir_all(merged_path)?;

        let lowerdir: String = lower_dirs
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join(":");

        let opts = format!(
            "lowerdir={lowerdir},upperdir={},workdir={},allow_other,squash_to_uid=0,squash_to_gid=0",
            upper_dir.display(),
            work_dir.display(),
        );

        let output = Command::new("fuse-overlayfs")
            .args(["-o", &opts])
            .arg(merged_path)
            .output()
            .context("spawn fuse-overlayfs")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!(
                "fuse-overlayfs mount failed (exit {}): {stderr}\nlowerdir={}, upper={}, merged={}",
                output.status.code().unwrap_or(-1),
                lowerdir,
                upper_dir.display(),
                merged_path.display(),
            );
        }

        Ok(Self {
            merged: merged_path.to_path_buf(),
            upper: upper_dir.to_path_buf(),
            mounted: std::sync::atomic::AtomicBool::new(true),
        })
    }

    #[must_use]
    pub fn merged_path(&self) -> &Path {
        &self.merged
    }

    #[must_use]
    pub fn upper_dir(&self) -> &Path {
        &self.upper
    }

    /// Unmount the fuse-overlayfs filesystem. Safe to call multiple times.
    ///
    /// # Errors
    ///
    /// Returns an error if `fusermount` cannot be spawned or exits
    /// with a non-zero status.
    pub fn unmount(&self) -> Result<()> {
        if !self
            .mounted
            .swap(false, std::sync::atomic::Ordering::AcqRel)
        {
            return Ok(());
        }
        let bin = if which::which("fusermount3").is_ok() {
            "fusermount3"
        } else {
            "fusermount"
        };
        let status = Command::new(bin)
            .args(["-u"])
            .arg(&self.merged)
            .stderr(std::process::Stdio::null())
            .status()
            .with_context(|| format!("spawn {bin} -u"))?;
        if !status.success() {
            bail!("{bin} -u {} failed", self.merged.display());
        }
        Ok(())
    }
}

impl std::fmt::Debug for OverlayMount {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OverlayMount")
            .field("merged", &self.merged)
            .field("upper", &self.upper)
            .finish_non_exhaustive()
    }
}

impl Drop for OverlayMount {
    fn drop(&mut self) {
        if let Err(e) = self.unmount() {
            tracing::warn!(%e, path = %self.merged.display(), "fuse-overlayfs unmount failed");
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn cow_clone_creates_identical_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        fs::create_dir_all(src.join("sub")).unwrap();
        fs::write(src.join("a.txt"), b"hello").unwrap();
        fs::write(src.join("sub/b.txt"), b"world").unwrap();

        let dst = tmp.path().join("dst");
        cow_clone_dir(&src, &dst).unwrap();

        assert_eq!(fs::read_to_string(dst.join("a.txt")).unwrap(), "hello");
        assert_eq!(fs::read_to_string(dst.join("sub/b.txt")).unwrap(), "world");
    }

    #[test]
    fn cow_clone_is_isolated() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        fs::create_dir(&src).unwrap();
        fs::write(src.join("f.txt"), b"original").unwrap();

        let dst = tmp.path().join("dst");
        cow_clone_dir(&src, &dst).unwrap();

        // Mutate dst; src must be unchanged.
        fs::write(dst.join("f.txt"), b"modified").unwrap();
        assert_eq!(fs::read_to_string(src.join("f.txt")).unwrap(), "original");
        assert_eq!(fs::read_to_string(dst.join("f.txt")).unwrap(), "modified");
    }

    #[test]
    fn cow_clone_fails_if_dst_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        fs::create_dir(&src).unwrap();
        let dst = tmp.path().join("dst");
        fs::create_dir(&dst).unwrap();

        assert!(cow_clone_dir(&src, &dst).is_err());
    }

    #[test]
    fn detect_strategy_returns_something() {
        // Should always detect at least FullCopy.
        let s = detect_strategy();
        assert!(!matches!(s, CowStrategy::FuseOverlay));
        // Can't assert specific strategy (platform-dependent) but it must not panic.
    }
}