mod error;
#[macro_use]
extern crate uucore;
use clap::{crate_version, App, Arg, ArgMatches};
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, stdin};
#[cfg(unix)]
use std::os::unix;
#[cfg(windows)]
use std::os::windows;
use std::path::{Path, PathBuf};
use uucore::backup_control::{self, BackupMode};
use uucore::display::Quotable;
use uucore::error::{FromIo, UError, UResult, USimpleError, UUsageError};
use fs_extra::dir::{move_dir, CopyOptions as DirCopyOptions};
use crate::error::MvError;
pub struct Behavior {
overwrite: OverwriteMode,
backup: BackupMode,
suffix: String,
update: bool,
target_dir: Option<OsString>,
no_target_dir: bool,
verbose: bool,
strip_slashes: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum OverwriteMode {
NoClobber,
Interactive,
Force,
}
static ABOUT: &str = "Move SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.";
static LONG_HELP: &str = "";
static OPT_FORCE: &str = "force";
static OPT_INTERACTIVE: &str = "interactive";
static OPT_NO_CLOBBER: &str = "no-clobber";
static OPT_STRIP_TRAILING_SLASHES: &str = "strip-trailing-slashes";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_UPDATE: &str = "update";
static OPT_VERBOSE: &str = "verbose";
static ARG_FILES: &str = "files";
fn usage() -> String {
format!(
"{0} [OPTION]... [-T] SOURCE DEST
{0} [OPTION]... SOURCE... DIRECTORY
{0} [OPTION]... -t DIRECTORY SOURCE...",
uucore::execution_phrase()
)
}
#[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let usage = usage();
let matches = uu_app()
.after_help(&*format!(
"{}\n{}",
LONG_HELP,
backup_control::BACKUP_CONTROL_LONG_HELP
))
.usage(&usage[..])
.get_matches_from(args);
let files: Vec<OsString> = matches
.values_of_os(ARG_FILES)
.unwrap_or_default()
.map(|v| v.to_os_string())
.collect();
let overwrite_mode = determine_overwrite_mode(&matches);
let backup_mode = backup_control::determine_backup_mode(&matches)?;
if overwrite_mode == OverwriteMode::NoClobber && backup_mode != BackupMode::NoBackup {
return Err(UUsageError::new(
1,
"options --backup and --no-clobber are mutually exclusive",
));
}
let backup_suffix = backup_control::determine_backup_suffix(&matches);
let behavior = Behavior {
overwrite: overwrite_mode,
backup: backup_mode,
suffix: backup_suffix,
update: matches.is_present(OPT_UPDATE),
target_dir: matches
.value_of_os(OPT_TARGET_DIRECTORY)
.map(OsString::from),
no_target_dir: matches.is_present(OPT_NO_TARGET_DIRECTORY),
verbose: matches.is_present(OPT_VERBOSE),
strip_slashes: matches.is_present(OPT_STRIP_TRAILING_SLASHES),
};
exec(&files[..], behavior)
}
pub fn uu_app() -> App<'static, 'static> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.arg(
backup_control::arguments::backup()
)
.arg(
backup_control::arguments::backup_no_args()
)
.arg(
Arg::with_name(OPT_FORCE)
.short("f")
.long(OPT_FORCE)
.help("do not prompt before overwriting")
)
.arg(
Arg::with_name(OPT_INTERACTIVE)
.short("i")
.long(OPT_INTERACTIVE)
.help("prompt before override")
)
.arg(
Arg::with_name(OPT_NO_CLOBBER).short("n")
.long(OPT_NO_CLOBBER)
.help("do not overwrite an existing file")
)
.arg(
Arg::with_name(OPT_STRIP_TRAILING_SLASHES)
.long(OPT_STRIP_TRAILING_SLASHES)
.help("remove any trailing slashes from each SOURCE argument")
)
.arg(
backup_control::arguments::suffix()
)
.arg(
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("move all SOURCE arguments into DIRECTORY")
.takes_value(true)
.value_name("DIRECTORY")
.conflicts_with(OPT_NO_TARGET_DIRECTORY)
)
.arg(
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY).
help("treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_UPDATE)
.short("u")
.long(OPT_UPDATE)
.help("move only when the SOURCE file is newer than the destination file or when the destination file is missing")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE).help("explain what is being done")
)
.arg(
Arg::with_name(ARG_FILES)
.multiple(true)
.takes_value(true)
.min_values(2)
.required(true)
)
}
fn determine_overwrite_mode(matches: &ArgMatches) -> OverwriteMode {
if matches.is_present(OPT_NO_CLOBBER) {
OverwriteMode::NoClobber
} else if matches.is_present(OPT_INTERACTIVE) {
OverwriteMode::Interactive
} else {
OverwriteMode::Force
}
}
fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
let paths: Vec<PathBuf> = {
let paths = files.iter().map(Path::new);
if b.strip_slashes {
paths
.map(|p| p.components().as_path().to_owned())
.collect::<Vec<PathBuf>>()
} else {
paths.map(|p| p.to_owned()).collect::<Vec<PathBuf>>()
}
};
if let Some(ref name) = b.target_dir {
return move_files_into_dir(&paths, &PathBuf::from(name), &b);
}
match paths.len() {
2 => {
let source = &paths[0];
let target = &paths[1];
if source.symlink_metadata().is_err() {
return Err(MvError::NoSuchFile(source.quote().to_string()).into());
}
if source.eq(target) {
if source.eq(Path::new(".")) || source.ends_with("/.") || source.is_file() {
return Err(MvError::SameFile(
source.quote().to_string(),
target.quote().to_string(),
)
.into());
} else {
return Err(MvError::SelfSubdirectory(source.display().to_string()).into());
}
}
if target.is_dir() {
if b.no_target_dir {
if !source.is_dir() {
Err(MvError::DirectoryToNonDirectory(target.quote().to_string()).into())
} else {
rename(source, target, &b).map_err_context(|| {
format!("cannot move {} to {}", source.quote(), target.quote())
})
}
} else {
move_files_into_dir(&[source.clone()], target, &b)
}
} else if target.exists() && source.is_dir() {
Err(MvError::NonDirectoryToDirectory(
source.quote().to_string(),
target.quote().to_string(),
)
.into())
} else {
rename(source, target, &b).map_err(|e| USimpleError::new(1, format!("{}", e)))
}
}
_ => {
if b.no_target_dir {
return Err(UUsageError::new(
1,
format!("mv: extra operand {}", files[2].quote()),
));
}
let target_dir = paths.last().unwrap();
move_files_into_dir(&paths[..paths.len() - 1], target_dir, &b)
}
}
}
fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UResult<()> {
if !target_dir.is_dir() {
return Err(MvError::NotADirectory(target_dir.quote().to_string()).into());
}
for sourcepath in files.iter() {
let targetpath = match sourcepath.file_name() {
Some(name) => target_dir.join(name),
None => {
show!(MvError::NoSuchFile(sourcepath.quote().to_string()));
continue;
}
};
show_if_err!(
rename(sourcepath, &targetpath, b).map_err_context(|| format!(
"cannot move {} to {}",
sourcepath.quote(),
targetpath.quote()
))
)
}
Ok(())
}
fn rename(from: &Path, to: &Path, b: &Behavior) -> io::Result<()> {
let mut backup_path = None;
if to.exists() {
match b.overwrite {
OverwriteMode::NoClobber => return Ok(()),
OverwriteMode::Interactive => {
println!("{}: overwrite {}? ", uucore::util_name(), to.quote());
if !read_yes() {
return Ok(());
}
}
OverwriteMode::Force => {}
};
backup_path = backup_control::get_backup_path(b.backup, to, &b.suffix);
if let Some(ref backup_path) = backup_path {
rename_with_fallback(to, backup_path)?;
}
if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? {
return Ok(());
}
}
if to.exists() && to.is_dir() {
if from.is_dir() {
if is_empty_dir(to) {
fs::remove_dir(to)?
} else {
return Err(io::Error::new(io::ErrorKind::Other, "Directory not empty"));
}
}
}
rename_with_fallback(from, to)?;
if b.verbose {
print!("{} -> {}", from.quote(), to.quote());
match backup_path {
Some(path) => println!(" (backup: {})", path.quote()),
None => println!(),
}
}
Ok(())
}
fn rename_with_fallback(from: &Path, to: &Path) -> io::Result<()> {
if fs::rename(from, to).is_err() {
let metadata = from.symlink_metadata()?;
let file_type = metadata.file_type();
if file_type.is_symlink() {
rename_symlink_fallback(from, to)?;
} else if file_type.is_dir() {
if to.exists() {
fs::remove_dir_all(to)?;
}
let options = DirCopyOptions {
copy_inside: true,
..DirCopyOptions::new()
};
if let Err(err) = move_dir(from, to, &options) {
return match err.kind {
fs_extra::error::ErrorKind::PermissionDenied => Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Permission denied",
)),
_ => Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", err))),
};
}
} else {
fs::copy(from, to).and_then(|_| fs::remove_file(from))?;
}
}
Ok(())
}
#[inline]
fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> {
let path_symlink_points_to = fs::read_link(from)?;
#[cfg(unix)]
{
unix::fs::symlink(&path_symlink_points_to, &to).and_then(|_| fs::remove_file(&from))?;
}
#[cfg(windows)]
{
if path_symlink_points_to.exists() {
if path_symlink_points_to.is_dir() {
windows::fs::symlink_dir(&path_symlink_points_to, &to)?;
} else {
windows::fs::symlink_file(&path_symlink_points_to, &to)?;
}
fs::remove_file(&from)?;
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"can't determine symlink type, since it is dangling",
));
}
}
#[cfg(not(any(windows, unix)))]
{
return Err(io::Error::new(
io::ErrorKind::Other,
"your operating system does not support symlinks",
));
}
Ok(())
}
fn read_yes() -> bool {
let mut s = String::new();
match stdin().read_line(&mut s) {
Ok(_) => match s.chars().next() {
Some(x) => x == 'y' || x == 'Y',
_ => false,
},
_ => false,
}
}
fn is_empty_dir(path: &Path) -> bool {
match fs::read_dir(path) {
Ok(contents) => contents.peekable().peek().is_none(),
Err(_e) => false,
}
}