From ce378a68a68eb9961ab2430bb8a0f32b4e15811c Mon Sep 17 00:00:00 2001 From: David Matos Date: Mon, 11 Sep 2023 00:54:33 +0200 Subject: [PATCH] Fix variables not allowed in ucp (#10304) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Fixes #10300 , where using variables didnt work with `ucp` as it was only expecting a `Expr::FilePath`. Before: (from the issue) ``` ❯ ucp -r $var $folder Error: × Missing file operand ╭─[entry #40:1:1] 1 │ ucp -r $var $folder · ─┬─ · ╰── Missing file operand ╰──── help: Please provide source and destination paths ``` Now: ``` `ucp -r $var $folder` # success ``` Also added the test to ensure its working:) . Oh, and I tweaked again slightly the messages on two tests because now the whole `path` is printed rather than `a`. Say: ``` #before `cp a a` --> 'a' and 'a' are the same file # now `cp a a` --> /home/current/location/a and /home/current/location/a are the same file ``` # User-Facing Changes # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - [X] `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - [X] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to check that you're using the standard code style - [X] `cargo test --workspace` to check that all tests pass (on Windows make sure to [enable developer mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging)) - [X] `cargo run -- -c "use std testing; testing run-tests --path crates/nu-std"` to run the tests for the standard library # After Submitting --- crates/nu-command/src/filesystem/ucp.rs | 41 +++++++++------------- crates/nu-command/tests/commands/ucp.rs | 46 ++++++++++++++++++------- 2 files changed, 51 insertions(+), 36 deletions(-) diff --git a/crates/nu-command/src/filesystem/ucp.rs b/crates/nu-command/src/filesystem/ucp.rs index 5d564d935..a8603295e 100644 --- a/crates/nu-command/src/filesystem/ucp.rs +++ b/crates/nu-command/src/filesystem/ucp.rs @@ -1,6 +1,7 @@ +use nu_engine::CallExt; use nu_path::expand_to_real_path; use nu_protocol::{ - ast::{Argument, Call, Expr}, + ast::Call, engine::{Command, EngineState, Stack}, Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape, Type, }; @@ -16,25 +17,10 @@ const GLOB_PARAMS: nu_glob::MatchOptions = nu_glob::MatchOptions { recursive_match_hidden_dir: true, }; -pub fn collect_filepath_arguments(call: &Call) -> Vec> { - call.arguments - .iter() - .filter_map(|arg| match arg { - Argument::Positional(expression) => { - if let Expr::Filepath(p) = &expression.expr { - let pth = Spanned { - item: nu_utils::strip_ansi_string_unlikely(p.clone()), - span: expression.span, - }; - Some(pth) - } else { - None - } - } - _ => None, - }) - .collect::>>() -} +#[cfg(not(target_os = "windows"))] +const PATH_SEPARATOR: &str = "/"; +#[cfg(target_os = "windows")] +const PATH_SEPARATOR: &str = "\\"; #[derive(Clone)] pub struct UCp; @@ -100,8 +86,8 @@ impl Command for UCp { fn run( &self, - _engine_state: &EngineState, - _stack: &mut Stack, + engine_state: &EngineState, + stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result { @@ -130,7 +116,14 @@ impl Command for UCp { let reflink_mode = uu_cp::ReflinkMode::Auto; #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "macos")))] let reflink_mode = uu_cp::ReflinkMode::Never; - let mut paths = collect_filepath_arguments(call); + let paths: Vec> = call.rest(engine_state, stack, 0)?; + let mut paths: Vec> = paths + .into_iter() + .map(|p| Spanned { + item: nu_utils::strip_ansi_string_unlikely(p.item), + span: p.span, + }) + .collect(); if paths.is_empty() { return Err(ShellError::GenericError( "Missing file operand".into(), @@ -152,7 +145,7 @@ impl Command for UCp { } let target = paths.pop().expect("Should not be reached?"); let target_path = PathBuf::from(&target.item); - if target.item.ends_with('/') && !target_path.is_dir() { + if target.item.ends_with(PATH_SEPARATOR) && !target_path.is_dir() { return Err(ShellError::GenericError( "is not a directory".into(), "is not a directory".into(), diff --git a/crates/nu-command/tests/commands/ucp.rs b/crates/nu-command/tests/commands/ucp.rs index 8d748a3c4..c359f542b 100644 --- a/crates/nu-command/tests/commands/ucp.rs +++ b/crates/nu-command/tests/commands/ucp.rs @@ -8,6 +8,11 @@ use nu_test_support::playground::Playground; use std::path::Path; +#[cfg(not(target_os = "windows"))] +const PATH_SEPARATOR: &str = "/"; +#[cfg(target_os = "windows")] +const PATH_SEPARATOR: &str = "\\"; + fn get_file_hash(file: T) -> String { nu!("open -r {} | to text | hash md5", file).out } @@ -392,15 +397,14 @@ fn copy_to_non_existing_dir() { fn copy_to_non_existing_dir_impl(progress: bool) { Playground::setup("ucp_test_11", |_dirs, sandbox| { sandbox.with_files(vec![EmptyFile("empty_file")]); - let progress_flag = if progress { "-p" } else { "" }; let actual = nu!( cwd: sandbox.cwd(), - "ucp {} empty_file ~/not_a_dir/", - progress_flag + "ucp {} empty_file ~/not_a_dir{}", + progress_flag, + PATH_SEPARATOR, ); - // assert!(actual.err.contains("failed to access")); assert!(actual.err.contains("is not a directory")); }); } @@ -508,20 +512,26 @@ fn copy_identical_file() { } fn copy_identical_file_impl(progress: bool) { - Playground::setup("ucp_test_15", |_dirs, sandbox| { + Playground::setup("ucp_test_15", |dirs, sandbox| { sandbox.with_files(vec![EmptyFile("same.txt")]); let progress_flag = if progress { "-p" } else { "" }; let actual = nu!( - cwd: sandbox.cwd(), + cwd: dirs.test(), "ucp {} same.txt same.txt", progress_flag, ); // assert!(actual.err.contains("Copy aborted")); - assert!(actual - .err - .contains("'same.txt' and 'same.txt' are the same file")); + let msg = format!( + "'{}' and '{}' are the same file", + dirs.test().join("same.txt").display(), + dirs.test().join("same.txt").display(), + ); + // debug messages in CI + if !actual.err.contains(&msg) { + panic!("stderr was: {}", actual.err); + } }); } @@ -923,15 +933,15 @@ fn test_cp_verbose_default() { let actual = nu!( cwd: dirs.root(), - "ucp --verbose {} ucp_test_31/{}", + "ucp --verbose {} {}", src.display(), TEST_HELLO_WORLD_DEST ); assert!(actual.out.contains( format!( - "'{}' -> 'ucp_test_31/{}'", + "'{}' -> '{}'", src.display(), - TEST_HELLO_WORLD_DEST + dirs.root().join(TEST_HELLO_WORLD_DEST).display() ) .as_str(), )); @@ -953,3 +963,15 @@ fn test_cp_only_source_no_dest() { assert!(actual.err.contains(TEST_HELLO_WORLD_SOURCE)); }); } + +#[test] +fn test_cp_with_vars() { + Playground::setup("ucp_test_33", |dirs, sandbox| { + sandbox.with_files(vec![EmptyFile("input")]); + nu!( + cwd: dirs.test(), + "let src = 'input'; let dst = 'target'; ucp $src $dst", + ); + assert!(dirs.test().join("target").exists()); + }); +}