2022-12-21 22:33:26 +00:00
|
|
|
use super::run_external::create_external_command;
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 11:33:09 +00:00
|
|
|
#[allow(deprecated)]
|
Add `command_prelude` module (#12291)
# Description
When implementing a `Command`, one must also import all the types
present in the function signatures for `Command`. This makes it so that
we often import the same set of types in each command implementation
file. E.g., something like this:
```rust
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Type, Value,
};
```
This PR adds the `nu_engine::command_prelude` module which contains the
necessary and commonly used types to implement a `Command`:
```rust
// command_prelude.rs
pub use crate::CallExt;
pub use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, IntoSpanned,
PipelineData, Record, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
```
This should reduce the boilerplate needed to implement a command and
also gives us a place to track the breadth of the `Command` API. I tried
to be conservative with what went into the prelude modules, since it
might be hard/annoying to remove items from the prelude in the future.
Let me know if something should be included or excluded.
2024-03-26 21:17:30 +00:00
|
|
|
use nu_engine::{command_prelude::*, current_dir};
|
2024-04-09 16:48:32 +00:00
|
|
|
use nu_protocol::OutDest;
|
2022-01-25 17:27:35 +00:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Exec;
|
|
|
|
|
|
|
|
impl Command for Exec {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"exec"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("exec")
|
2022-12-21 19:20:46 +00:00
|
|
|
.input_output_types(vec![(Type::Nothing, Type::Any)])
|
2023-12-15 06:32:37 +00:00
|
|
|
.required("command", SyntaxShape::String, "The command to execute.")
|
2022-12-21 22:33:26 +00:00
|
|
|
.allows_unknown_args()
|
2022-01-25 17:27:35 +00:00
|
|
|
.category(Category::System)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
2023-11-08 20:50:25 +00:00
|
|
|
"Execute a command, replacing or exiting the current process, depending on platform."
|
2022-01-25 17:27:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn extra_usage(&self) -> &str {
|
2023-11-08 20:50:25 +00:00
|
|
|
r#"On Unix-based systems, the current process is replaced with the command.
|
|
|
|
On Windows based systems, Nushell will wait for the command to finish and then exit with the command's exit code."#
|
2022-01-25 17:27:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
_input: PipelineData,
|
2023-02-05 21:17:46 +00:00
|
|
|
) -> Result<PipelineData, ShellError> {
|
2022-01-25 17:27:35 +00:00
|
|
|
exec(engine_state, stack, call)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![
|
|
|
|
Example {
|
|
|
|
description: "Execute external 'ps aux' tool",
|
|
|
|
example: "exec ps aux",
|
|
|
|
result: None,
|
|
|
|
},
|
|
|
|
Example {
|
|
|
|
description: "Execute 'nautilus'",
|
|
|
|
example: "exec nautilus",
|
|
|
|
result: None,
|
|
|
|
},
|
|
|
|
]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn exec(
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
2023-02-05 21:17:46 +00:00
|
|
|
) -> Result<PipelineData, ShellError> {
|
IO and redirection overhaul (#11934)
# Description
The PR overhauls how IO redirection is handled, allowing more explicit
and fine-grain control over `stdout` and `stderr` output as well as more
efficient IO and piping.
To summarize the changes in this PR:
- Added a new `IoStream` type to indicate the intended destination for a
pipeline element's `stdout` and `stderr`.
- The `stdout` and `stderr` `IoStream`s are stored in the `Stack` and to
avoid adding 6 additional arguments to every eval function and
`Command::run`. The `stdout` and `stderr` streams can be temporarily
overwritten through functions on `Stack` and these functions will return
a guard that restores the original `stdout` and `stderr` when dropped.
- In the AST, redirections are now directly part of a `PipelineElement`
as a `Option<Redirection>` field instead of having multiple different
`PipelineElement` enum variants for each kind of redirection. This
required changes to the parser, mainly in `lite_parser.rs`.
- `Command`s can also set a `IoStream` override/redirection which will
apply to the previous command in the pipeline. This is used, for
example, in `ignore` to allow the previous external command to have its
stdout redirected to `Stdio::null()` at spawn time. In contrast, the
current implementation has to create an os pipe and manually consume the
output on nushell's side. File and pipe redirections (`o>`, `e>`, `e>|`,
etc.) have precedence over overrides from commands.
This PR improves piping and IO speed, partially addressing #10763. Using
the `throughput` command from that issue, this PR gives the following
speedup on my setup for the commands below:
| Command | Before (MB/s) | After (MB/s) | Bash (MB/s) |
| --------------------------- | -------------:| ------------:|
-----------:|
| `throughput o> /dev/null` | 1169 | 52938 | 54305 |
| `throughput \| ignore` | 840 | 55438 | N/A |
| `throughput \| null` | Error | 53617 | N/A |
| `throughput \| rg 'x'` | 1165 | 3049 | 3736 |
| `(throughput) \| rg 'x'` | 810 | 3085 | 3815 |
(Numbers above are the median samples for throughput)
This PR also paves the way to refactor our `ExternalStream` handling in
the various commands. For example, this PR already fixes the following
code:
```nushell
^sh -c 'echo -n "hello "; sleep 0; echo "world"' | find "hello world"
```
This returns an empty list on 0.90.1 and returns a highlighted "hello
world" on this PR.
Since the `stdout` and `stderr` `IoStream`s are available to commands
when they are run, then this unlocks the potential for more convenient
behavior. E.g., the `find` command can disable its ansi highlighting if
it detects that the output `IoStream` is not the terminal. Knowing the
output streams will also allow background job output to be redirected
more easily and efficiently.
# User-Facing Changes
- External commands returned from closures will be collected (in most
cases):
```nushell
1..2 | each {|_| nu -c "print a" }
```
This gives `["a", "a"]` on this PR, whereas this used to print "a\na\n"
and then return an empty list.
```nushell
1..2 | each {|_| nu -c "print -e a" }
```
This gives `["", ""]` and prints "a\na\n" to stderr, whereas this used
to return an empty list and print "a\na\n" to stderr.
- Trailing new lines are always trimmed for external commands when
piping into internal commands or collecting it as a value. (Failure to
decode the output as utf-8 will keep the trailing newline for the last
binary value.) In the current nushell version, the following three code
snippets differ only in parenthesis placement, but they all also have
different outputs:
1. `1..2 | each { ^echo a }`
```
a
a
╭────────────╮
│ empty list │
╰────────────╯
```
2. `1..2 | each { (^echo a) }`
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
3. `1..2 | (each { ^echo a })`
```
╭───┬───╮
│ 0 │ a │
│ │ │
│ 1 │ a │
│ │ │
╰───┴───╯
```
But in this PR, the above snippets will all have the same output:
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
- All existing flags on `run-external` are now deprecated.
- File redirections now apply to all commands inside a code block:
```nushell
(nu -c "print -e a"; nu -c "print -e b") e> test.out
```
This gives "a\nb\n" in `test.out` and prints nothing. The same result
would happen when printing to stdout and using a `o>` file redirection.
- External command output will (almost) never be ignored, and ignoring
output must be explicit now:
```nushell
(^echo a; ^echo b)
```
This prints "a\nb\n", whereas this used to print only "b\n". This only
applies to external commands; values and internal commands not in return
position will not print anything (e.g., `(echo a; echo b)` still only
prints "b").
- `complete` now always captures stderr (`do` is not necessary).
# After Submitting
The language guide and other documentation will need to be updated.
2024-03-14 20:51:55 +00:00
|
|
|
let mut external_command = create_external_command(engine_state, stack, call)?;
|
2024-04-09 16:48:32 +00:00
|
|
|
external_command.out = OutDest::Inherit;
|
|
|
|
external_command.err = OutDest::Inherit;
|
2022-01-25 17:27:35 +00:00
|
|
|
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 11:33:09 +00:00
|
|
|
#[allow(deprecated)]
|
2022-12-21 22:33:26 +00:00
|
|
|
let cwd = current_dir(engine_state, stack)?;
|
2022-06-04 06:47:36 +00:00
|
|
|
let mut command = external_command.spawn_simple_command(&cwd.to_string_lossy())?;
|
2022-12-21 22:33:26 +00:00
|
|
|
command.current_dir(cwd);
|
2023-11-08 20:50:25 +00:00
|
|
|
command.envs(external_command.env_vars);
|
|
|
|
|
|
|
|
// this either replaces our process and should not return,
|
|
|
|
// or the exec fails and we get an error back
|
|
|
|
exec_impl(command, call.head)
|
|
|
|
}
|
2022-01-25 17:27:35 +00:00
|
|
|
|
2023-11-08 20:50:25 +00:00
|
|
|
#[cfg(unix)]
|
|
|
|
fn exec_impl(mut command: std::process::Command, span: Span) -> Result<PipelineData, ShellError> {
|
|
|
|
use std::os::unix::process::CommandExt;
|
|
|
|
|
|
|
|
let error = command.exec();
|
2022-01-25 17:27:35 +00:00
|
|
|
|
2023-12-06 23:40:03 +00:00
|
|
|
Err(ShellError::GenericError {
|
|
|
|
error: "Error on exec".into(),
|
|
|
|
msg: error.to_string(),
|
|
|
|
span: Some(span),
|
|
|
|
help: None,
|
|
|
|
inner: vec![],
|
|
|
|
})
|
2022-01-25 17:27:35 +00:00
|
|
|
}
|
2023-11-08 20:50:25 +00:00
|
|
|
|
|
|
|
#[cfg(windows)]
|
|
|
|
fn exec_impl(mut command: std::process::Command, span: Span) -> Result<PipelineData, ShellError> {
|
|
|
|
match command.spawn() {
|
|
|
|
Ok(mut child) => match child.wait() {
|
|
|
|
Ok(status) => std::process::exit(status.code().unwrap_or(0)),
|
|
|
|
Err(e) => Err(ShellError::ExternalCommand {
|
|
|
|
label: "Error in external command".into(),
|
|
|
|
help: e.to_string(),
|
|
|
|
span,
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
Err(e) => Err(ShellError::ExternalCommand {
|
|
|
|
label: "Error spawning external command".into(),
|
|
|
|
help: e.to_string(),
|
|
|
|
span,
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|