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
use std::io;
use std::fmt;
use std::ptr::null;
use std::ffi::CString;
use std::path::Path;

use libc::mount;
use nix::mount::MsFlags;

use {OSError, Error};
use util::{path_to_cstring, as_path};
use explain::{Explainable, exists};

/// A move operation definition
///
/// This is a similar to `mount --move` and allows to atomically move mount
/// point from one place to another
#[derive(Debug, Clone)]
pub struct Move {
    source: CString,
    target: CString,
}

impl Move {
    /// Create a new Move operation
    pub fn new<A: AsRef<Path>, B: AsRef<Path>>(source: A, target: B) -> Move {
        Move {
            source: path_to_cstring(source.as_ref()),
            target: path_to_cstring(target.as_ref()),
        }
    }

    /// Execute a move-mountpoint operation
    pub fn bare_move_mountpoint(self)
        -> Result<(), OSError>
    {
        let rc = unsafe { mount(
                self.source.as_ptr(),
                self.target.as_ptr(),
                null(),
                MsFlags::MS_MOVE.bits(),
                null()) };
        if rc < 0 {
            Err(OSError::from_io(io::Error::last_os_error(), Box::new(self)))
        } else {
            Ok(())
        }
    }

    /// Execute a move mountpoint operation and explain the error immediately
    pub fn move_mountpoint(self) -> Result<(), Error> {
        self.bare_move_mountpoint().map_err(OSError::explain)
    }
}

impl fmt::Display for Move {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "move {:?} -> {:?}",
            as_path(&self.source), as_path(&self.target))
    }
}

impl Explainable for Move {
    fn explain(&self) -> String {
        [
            format!("source: {}", exists(as_path(&self.source))),
            format!("target: {}", exists(as_path(&self.target))),
        ].join(", ")
    }
}