| 1 | use std::fmt; |
| 2 | use std::ffi::{CStr, CString}; |
| 3 | use std::path::Path; |
| 4 | |
| 5 | use nix::mount::{MsFlags, mount}; |
| 6 | |
| 7 | use {OSError, Error}; |
| 8 | use util::{path_to_cstring, as_path}; |
| 9 | use explain::{Explainable, exists}; |
| 10 | |
| 11 | /// A move operation definition |
| 12 | /// |
| 13 | /// This is a similar to `mount --move` and allows to atomically move mount |
| 14 | /// point from one place to another |
| 15 | #[derive(Debug, Clone)] |
| 16 | pub struct Move { |
| 17 | source: CString, |
| 18 | target: CString, |
| 19 | } |
| 20 | |
| 21 | impl Move { |
| 22 | /// Create a new Move operation |
| 23 | pub fn new<A: AsRef<Path>, B: AsRef<Path>>(source: A, target: B) -> Move { |
| 24 | Move { |
| 25 | source: path_to_cstring(source.as_ref()), |
| 26 | target: path_to_cstring(target.as_ref()), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | /// Execute a move-mountpoint operation |
| 31 | pub fn bare_move_mountpoint(self) |
| 32 | -> Result<(), OSError> |
| 33 | { |
| 34 | mount(Some(&*self.source), &*self.target, None::<&CStr>, MsFlags::MS_MOVE, None::<&CStr>) |
| 35 | .map_err(|err| OSError::from_nix(err, Box::new(self))) |
| 36 | } |
| 37 | |
| 38 | /// Execute a move mountpoint operation and explain the error immediately |
| 39 | pub fn move_mountpoint(self) -> Result<(), Error> { |
| 40 | self.bare_move_mountpoint().map_err(OSError::explain) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl fmt::Display for Move { |
| 45 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 46 | write!(fmt, "move {:?} -> {:?}", |
| 47 | as_path(&self.source), as_path(&self.target)) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl Explainable for Move { |
| 52 | fn explain(&self) -> String { |
| 53 | [ |
| 54 | format!("source: {}", exists(as_path(&self.source))), |
| 55 | format!("target: {}", exists(as_path(&self.target))), |
| 56 | ].join(", ") |
| 57 | } |
| 58 | } |
| 59 |