Allow mv multiple files at once (#6103)

* Allow mv multiple files at once

* Expand dots in mv src + dst
This commit is contained in:
Matthew Ma 2022-07-23 05:51:41 -07:00 committed by GitHub
parent 8a0bd20e84
commit 7d46177cf3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 159 additions and 103 deletions

View File

@ -1,8 +1,11 @@
use std::path::{Path, PathBuf};
use super::util::try_interaction;
use itertools::Itertools;
use nu_engine::env::current_dir;
use nu_engine::CallExt;
use nu_glob::GlobResult;
use nu_path::dots::expand_ndots;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
@ -36,11 +39,16 @@ impl Command for Mv {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("mv")
.required(
"source",
SyntaxShape::GlobPattern,
"the location to move files/directories from",
.rest(
"source(s)",
SyntaxShape::String,
"the location(s) to move files/directories from",
)
// .required(
// "source",
// SyntaxShape::GlobPattern,
// "the location to move files/directories from",
// )
.required(
"destination",
SyntaxShape::Filepath,
@ -64,29 +72,42 @@ impl Command for Mv {
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
// TODO: handle invalid directory or insufficient permissions when moving
let spanned_source: Spanned<String> = call.req(engine_state, stack, 0)?;
let spanned_destination: Spanned<String> = call.req(engine_state, stack, 1)?;
let mut spanned_sources: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
// read destination as final argument
let spanned_destination: Spanned<String> =
call.req(engine_state, stack, spanned_sources.len() - 1)?;
// don't read destination argument
spanned_sources.pop();
let verbose = call.has_flag("verbose");
let interactive = call.has_flag("interactive");
// let force = call.has_flag("force");
let ctrlc = engine_state.ctrlc.clone();
let path = current_dir(engine_state, stack)?;
let source = path.join(spanned_source.item.as_str());
let destination = path.join(spanned_destination.item.as_str());
let path = current_dir(engine_state, stack).expect("Failed current_dir");
let mut sources = nu_glob::glob_with(&source.to_string_lossy(), GLOB_PARAMS)
let span = call.head;
Ok(spanned_sources
.into_iter()
.flat_map(move |spanned_source| {
let path = path.clone();
let source = path.join(spanned_source.item.as_str());
let destination = expand_ndots(path.join(spanned_destination.item.as_str()));
let mut sources: Vec<GlobResult> =
nu_glob::glob_with(&source.to_string_lossy(), GLOB_PARAMS)
.map_or_else(|_| Vec::new(), Iterator::collect);
if sources.is_empty() {
return Err(ShellError::GenericError(
let err = ShellError::GenericError(
"Invalid file or pattern".into(),
"invalid file or pattern".into(),
Some(spanned_source.span),
None,
Vec::new(),
));
);
return Vec::from([Value::Error { error: err }]).into_iter();
}
// We have two possibilities.
@ -102,13 +123,14 @@ impl Command for Mv {
if (destination.exists() && !destination.is_dir() && sources.len() > 1)
|| (!destination.exists() && sources.len() > 1)
{
return Err(ShellError::GenericError(
let err = ShellError::GenericError(
"Can only move multiple sources if destination is a directory".into(),
"destination must be a directory when multiple sources".into(),
Some(spanned_destination.span),
None,
Vec::new(),
));
);
return Vec::from([Value::Error { error: err }]).into_iter();
}
let some_if_source_is_destination = sources
@ -116,7 +138,7 @@ impl Command for Mv {
.find(|f| matches!(f, Ok(f) if destination.starts_with(f)));
if destination.exists() && destination.is_dir() && sources.len() == 1 {
if let Some(Ok(filename)) = some_if_source_is_destination {
return Err(ShellError::GenericError(
let err = ShellError::GenericError(
format!(
"Not possible to move {:?} to itself",
filename.file_name().expect("Invalid file name")
@ -125,7 +147,8 @@ impl Command for Mv {
Some(spanned_destination.span),
None,
Vec::new(),
));
);
return Vec::from([Value::Error { error: err }]).into_iter();
}
}
@ -136,11 +159,11 @@ impl Command for Mv {
.collect();
}
let span = call.head;
Ok(sources
sources
.into_iter()
.flatten()
.filter_map(move |entry| {
let entry = expand_ndots(entry);
let result = move_file(
Spanned {
item: entry.clone(),
@ -173,6 +196,9 @@ impl Command for Mv {
None
}
})
.collect_vec()
.into_iter()
})
.into_pipeline_data(ctrlc))
}

View File

@ -22,6 +22,36 @@ fn moves_a_file() {
})
}
#[test]
fn moves_multiple_files() {
Playground::setup("mv_test_1_1", |dirs, sandbox| {
sandbox
.mkdir("expected")
.with_files(vec![EmptyFile("andres.txt"), EmptyFile("yehuda.txt")])
.within("foo")
.with_files(vec![EmptyFile("bar.txt")]);
let original_1 = dirs.test().join("andres.txt");
let original_2 = dirs.test().join("yehuda.txt");
let original_3 = dirs.test().join("foo/bar.txt");
let expected_1 = dirs.test().join("expected/andres.txt");
let expected_2 = dirs.test().join("expected/yehuda.txt");
let expected_3 = dirs.test().join("expected/bar.txt");
nu!(
cwd: dirs.test(),
"mv andres.txt yehuda.txt foo/bar.txt expected"
);
assert!(!original_1.exists());
assert!(!original_2.exists());
assert!(!original_3.exists());
assert!(expected_1.exists());
assert!(expected_2.exists());
assert!(expected_3.exists());
})
}
#[test]
fn overwrites_if_moving_to_existing_file() {
Playground::setup("mv_test_2", |dirs, sandbox| {

View File

@ -1,4 +1,4 @@
mod dots;
pub mod dots;
mod expansions;
mod helpers;
mod tilde;