Remove required positional arguments from run-external and exec (#14765)

# Description
This PR removes the required positional argument from `run-external` and
`exec` in favor of the rest arguments, meaning lists of external
commands can be spread directly into `run-external` and `exec`. This
does have the drawback of making calling `run-external` and `exec` with
no arguments a run-time error rather than a parse error, but I don't
imagine that is an issue.

Before (for both `run-external` and `exec`):
```nushell
run-external
# => Error: nu::parser::missing_positional
# => 
# =>   × Missing required positional argument.
# =>    ╭─[entry #9:1:13]
# =>  1 │ run-external
# =>    ╰────
# =>   help: Usage: run-external <command> ...(args) . Use `--help` for more
# =>         information.

let command = ["cat" "hello.txt"]
run-external ...$command
# => Error: nu::parser::missing_positional
# => 
# =>   × Missing required positional argument.
# =>    ╭─[entry #11:1:14]
# =>  1 │ run-external ...$command
# =>    ·              ▲
# =>    ·              ╰── missing command
# =>    ╰────
# =>   help: Usage: run-external <command> ...(args) . Use `--help` for more
# =>         information.
run-external ($command | first) ...($command | skip 1)
# => hello world!
```

After (for both `run-external` and `exec`):
```nushell
run-external
# => Error: nu:🐚:missing_parameter
# => 
# =>   × Missing parameter: no command given.
# =>    ╭─[entry #2:1:1]
# =>  1 │ run-external
# =>    · ──────┬─────
# =>    ·       ╰── missing parameter: no command given
# =>    ╰────
# => 

let command = ["cat" "hello.txt"]
run-external ...$command
# => hello world!
```



# User-Facing Changes
Lists can now be spread directly into `run-external` and `exec`:

```nushell
let command = [cat hello.txt]
run-external ...$command
# => hello world!
``` 

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting
N/A
This commit is contained in:
132ikl
2025-01-15 17:10:28 -05:00
committed by GitHub
parent 46566296c0
commit 06938659d2
7 changed files with 246 additions and 160 deletions

View File

@ -1,3 +1,5 @@
use std::borrow::Cow;
use nu_engine::{command_prelude::*, env_to_strings};
#[derive(Clone)]
@ -11,7 +13,11 @@ impl Command for Exec {
fn signature(&self) -> Signature {
Signature::build("exec")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.required("command", SyntaxShape::String, "The command to execute.")
.rest(
"command",
SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]),
"External command to run, with arguments.",
)
.allows_unknown_args()
.category(Category::System)
}
@ -33,15 +39,29 @@ On Windows based systems, Nushell will wait for the command to finish and then e
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cwd = engine_state.cwd(Some(stack))?;
let rest = call.rest::<Value>(engine_state, stack, 0)?;
let name_args = rest.split_first();
let Some((name, call_args)) = name_args else {
return Err(ShellError::MissingParameter {
param_name: "no command given".into(),
span: call.head,
});
};
let name_str: Cow<str> = match &name {
Value::Glob { val, .. } => Cow::Borrowed(val),
Value::String { val, .. } => Cow::Borrowed(val),
_ => Cow::Owned(name.clone().coerce_into_string()?),
};
// Find the absolute path to the executable. If the command is not
// found, display a helpful error message.
let name: Spanned<String> = call.req(engine_state, stack, 0)?;
let executable = {
let paths = nu_engine::env::path_str(engine_state, stack, call.head)?;
let Some(executable) = crate::which(&name.item, &paths, cwd.as_ref()) else {
let Some(executable) = crate::which(name_str.as_ref(), &paths, cwd.as_ref()) else {
return Err(crate::command_not_found(
&name.item,
&name_str,
call.head,
engine_state,
stack,
@ -73,7 +93,7 @@ On Windows based systems, Nushell will wait for the command to finish and then e
}
// Configure args.
let args = crate::eval_arguments_from_call(engine_state, stack, call)?;
let args = crate::eval_external_arguments(engine_state, stack, call_args.to_vec())?;
command.args(args.into_iter().map(|s| s.item));
// Execute the child process, replacing/terminating the current process

View File

@ -33,7 +33,7 @@ pub use nu_check::NuCheck;
pub use ps::Ps;
#[cfg(windows)]
pub use registry_query::RegistryQuery;
pub use run_external::{command_not_found, eval_arguments_from_call, which, External};
pub use run_external::{command_not_found, eval_external_arguments, which, External};
pub use sys::*;
pub use uname::UName;
pub use which_::Which;

View File

@ -34,15 +34,10 @@ impl Command for External {
fn signature(&self) -> nu_protocol::Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Any, Type::Any)])
.required(
"command",
SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]),
"External command to run.",
)
.rest(
"args",
"command",
SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]),
"Arguments for external command.",
"External command to run, with arguments.",
)
.category(Category::System)
}
@ -55,7 +50,15 @@ impl Command for External {
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cwd = engine_state.cwd(Some(stack))?;
let name: Value = call.req(engine_state, stack, 0)?;
let rest = call.rest::<Value>(engine_state, stack, 0)?;
let name_args = rest.split_first();
let Some((name, call_args)) = name_args else {
return Err(ShellError::MissingParameter {
param_name: "no command given".into(),
span: call.head,
});
};
let name_str: Cow<str> = match &name {
Value::Glob { val, .. } => Cow::Borrowed(val),
@ -151,7 +154,7 @@ impl Command for External {
command.envs(envs);
// Configure args.
let args = eval_arguments_from_call(engine_state, stack, call)?;
let args = eval_external_arguments(engine_state, stack, call_args.to_vec())?;
#[cfg(windows)]
if is_cmd_internal_command(&name_str) || potential_nuscript_in_windows {
// The /D flag disables execution of AutoRun commands from registry.
@ -290,14 +293,13 @@ impl Command for External {
}
}
/// Evaluate all arguments from a call, performing expansions when necessary.
pub fn eval_arguments_from_call(
/// Evaluate all arguments, performing expansions when necessary.
pub fn eval_external_arguments(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
call_args: Vec<Value>,
) -> Result<Vec<Spanned<OsString>>, ShellError> {
let cwd = engine_state.cwd(Some(stack))?;
let call_args = call.rest::<Value>(engine_state, stack, 1)?;
let mut args: Vec<Spanned<OsString>> = Vec::with_capacity(call_args.len());
for arg in call_args {