Fix variables not allowed in ucp (#10304)

<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# 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
```
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking 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
<!--

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
This commit is contained in:
David Matos 2023-09-11 00:54:33 +02:00 committed by GitHub
parent fa40740e77
commit ce378a68a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 36 deletions

View File

@ -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<Spanned<String>> {
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::<Vec<Spanned<String>>>()
}
#[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<PipelineData, ShellError> {
@ -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<Spanned<String>> = call.rest(engine_state, stack, 0)?;
let mut paths: Vec<Spanned<String>> = 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(),

View File

@ -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<T: std::fmt::Display>(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());
});
}