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.
This commit is contained in:
Ian Manske
2024-03-14 20:51:55 +00:00
committed by GitHub
parent e2907e7e3a
commit b6c7656194
113 changed files with 3272 additions and 4022 deletions

View File

@ -1,4 +1,4 @@
use crate::{ast::Call, Alias, BlockId, Example, PipelineData, ShellError, Signature};
use crate::{ast::Call, Alias, BlockId, Example, IoStream, PipelineData, ShellError, Signature};
use super::{EngineState, Stack, StateWorkingSet};
@ -133,6 +133,10 @@ pub trait Command: Send + Sync + CommandClone {
_ => CommandType::Other,
}
}
fn stdio_redirect(&self) -> (Option<IoStream>, Option<IoStream>) {
(None, None)
}
}
pub trait CommandClone {

View File

@ -7,6 +7,7 @@ mod pattern_match;
mod stack;
mod state_delta;
mod state_working_set;
mod stdio;
mod usage;
mod variable;
@ -19,4 +20,5 @@ pub use pattern_match::*;
pub use stack::*;
pub use state_delta::*;
pub use state_working_set::*;
pub use stdio::*;
pub use variable::*;

View File

@ -1,10 +1,12 @@
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::engine::EngineState;
use crate::engine::DEFAULT_OVERLAY_NAME;
use crate::{ShellError, Span, Value, VarId};
use crate::{ENV_VARIABLE_ID, NU_VARIABLE_ID};
use crate::{
engine::{EngineState, DEFAULT_OVERLAY_NAME},
IoStream, ShellError, Span, Value, VarId, ENV_VARIABLE_ID, NU_VARIABLE_ID,
};
use super::{Redirection, StackCallArgGuard, StackCaptureGuard, StackIoGuard, StackStdio};
/// Environment variables per overlay
pub type EnvVars = HashMap<String, HashMap<String, Value>>;
@ -37,22 +39,36 @@ pub struct Stack {
/// List of active overlays
pub active_overlays: Vec<String>,
pub recursion_count: u64,
pub parent_stack: Option<Arc<Stack>>,
/// Variables that have been deleted (this is used to hide values from parent stack lookups)
pub parent_deletions: Vec<VarId>,
pub(crate) stdio: StackStdio,
}
impl Default for Stack {
fn default() -> Self {
Self::new()
}
}
impl Stack {
pub fn new() -> Stack {
Stack {
vars: vec![],
env_vars: vec![],
/// Create a new stack.
///
/// Stdio will be set to [`IoStream::Inherit`]. So, if the last command is an external command,
/// then its output will be forwarded to the terminal/stdio streams.
///
/// Use [`Stack::capture`] afterwards if you need to evaluate an expression to a [`Value`](crate::Value)
/// (as opposed to a [`PipelineData`](crate::PipelineData)).
pub fn new() -> Self {
Self {
vars: Vec::new(),
env_vars: Vec::new(),
env_hidden: HashMap::new(),
active_overlays: vec![DEFAULT_OVERLAY_NAME.to_string()],
recursion_count: 0,
parent_stack: None,
parent_deletions: vec![],
stdio: StackStdio::new(),
}
}
@ -82,9 +98,10 @@ impl Stack {
env_hidden: parent.env_hidden.clone(),
active_overlays: parent.active_overlays.clone(),
recursion_count: parent.recursion_count,
parent_stack: Some(parent),
vars: vec![],
parent_deletions: vec![],
stdio: parent.stdio.clone(),
parent_stack: Some(parent),
}
}
@ -235,6 +252,10 @@ impl Stack {
}
pub fn captures_to_stack(&self, captures: Vec<(VarId, Value)>) -> Stack {
self.captures_to_stack_preserve_stdio(captures).capture()
}
pub fn captures_to_stack_preserve_stdio(&self, captures: Vec<(VarId, Value)>) -> Stack {
// FIXME: this is probably slow
let mut env_vars = self.env_vars.clone();
env_vars.push(HashMap::new());
@ -247,6 +268,7 @@ impl Stack {
recursion_count: self.recursion_count,
parent_stack: None,
parent_deletions: vec![],
stdio: self.stdio.clone(),
}
}
@ -276,6 +298,7 @@ impl Stack {
recursion_count: self.recursion_count,
parent_stack: None,
parent_deletions: vec![],
stdio: self.stdio.clone(),
}
}
@ -481,11 +504,87 @@ impl Stack {
pub fn remove_overlay(&mut self, name: &str) {
self.active_overlays.retain(|o| o != name);
}
}
impl Default for Stack {
fn default() -> Self {
Self::new()
/// Returns the [`IoStream`] to use for the current command's stdout.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stdout indicated by [`IoStream::Inherit`].
pub fn stdout(&self) -> &IoStream {
self.stdio.stdout()
}
/// Returns the [`IoStream`] to use for the current command's stderr.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stderr indicated by [`IoStream::Inherit`].
pub fn stderr(&self) -> &IoStream {
self.stdio.stderr()
}
/// Returns the [`IoStream`] to use for the last command's stdout.
pub fn pipe_stdout(&self) -> Option<&IoStream> {
self.stdio.pipe_stdout.as_ref()
}
/// Returns the [`IoStream`] to use for the last command's stderr.
pub fn pipe_stderr(&self) -> Option<&IoStream> {
self.stdio.pipe_stderr.as_ref()
}
/// Temporarily set the pipe stdout redirection to [`IoStream::Capture`].
///
/// This is used before evaluating an expression into a `Value`.
pub fn start_capture(&mut self) -> StackCaptureGuard {
StackCaptureGuard::new(self)
}
/// Temporarily use the stdio redirections in the parent scope.
///
/// This is used before evaluating an argument to a call.
pub fn use_call_arg_stdio(&mut self) -> StackCallArgGuard {
StackCallArgGuard::new(self)
}
/// Temporarily apply redirections to stdout and/or stderr.
pub fn push_redirection(
&mut self,
stdout: Option<Redirection>,
stderr: Option<Redirection>,
) -> StackIoGuard {
StackIoGuard::new(self, stdout, stderr)
}
/// Mark stdout for the last command as [`IoStream::Capture`].
///
/// This will irreversibly alter the stdio redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
///
/// See [`Stack::start_capture`] which can temporarily set stdout as [`IoStream::Capture`] for a mutable `Stack` reference.
pub fn capture(mut self) -> Self {
self.stdio.pipe_stdout = Some(IoStream::Capture);
self.stdio.pipe_stderr = None;
self
}
/// Clears any pipe and file redirections and resets stdout and stderr to [`IoStream::Inherit`].
///
/// This will irreversibly reset the stdio redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
pub fn reset_stdio(mut self) -> Self {
self.stdio = StackStdio::new();
self
}
/// Clears any pipe redirections, keeping the current stdout and stderr.
///
/// This will irreversibly reset some of the stdio redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
pub fn reset_pipes(mut self) -> Self {
self.stdio.pipe_stdout = None;
self.stdio.pipe_stderr = None;
self
}
}

View File

@ -0,0 +1,288 @@
use std::{
fs::File,
mem,
ops::{Deref, DerefMut},
sync::Arc,
};
use crate::IoStream;
use super::Stack;
#[derive(Debug, Clone)]
pub enum Redirection {
/// A pipe redirection.
///
/// This will only affect the last command of a block.
/// This is created by pipes and pipe redirections (`|`, `e>|`, `o+e>|`, etc.),
/// or set by the next command in the pipeline (e.g., `ignore` sets stdout to [`IoStream::Null`]).
Pipe(IoStream),
/// A file redirection.
///
/// This will affect all commands in the block.
/// This is only created by file redirections (`o>`, `e>`, `o+e>`, etc.).
File(Arc<File>),
}
impl Redirection {
pub fn file(file: File) -> Self {
Self::File(Arc::new(file))
}
}
#[derive(Debug, Clone)]
pub(crate) struct StackStdio {
/// The stream to use for the next command's stdout.
pub pipe_stdout: Option<IoStream>,
/// The stream to use for the next command's stderr.
pub pipe_stderr: Option<IoStream>,
/// The stream used for the command stdout if `pipe_stdout` is `None`.
///
/// This should only ever be `File` or `Inherit`.
pub stdout: IoStream,
/// The stream used for the command stderr if `pipe_stderr` is `None`.
///
/// This should only ever be `File` or `Inherit`.
pub stderr: IoStream,
/// The previous stdout used before the current `stdout` was set.
///
/// This is used only when evaluating arguments to commands,
/// since the arguments are lazily evaluated inside each command
/// after redirections have already been applied to the command/stack.
///
/// This should only ever be `File` or `Inherit`.
pub parent_stdout: Option<IoStream>,
/// The previous stderr used before the current `stderr` was set.
///
/// This is used only when evaluating arguments to commands,
/// since the arguments are lazily evaluated inside each command
/// after redirections have already been applied to the command/stack.
///
/// This should only ever be `File` or `Inherit`.
pub parent_stderr: Option<IoStream>,
}
impl StackStdio {
pub(crate) fn new() -> Self {
Self {
pipe_stdout: None,
pipe_stderr: None,
stdout: IoStream::Inherit,
stderr: IoStream::Inherit,
parent_stdout: None,
parent_stderr: None,
}
}
/// Returns the [`IoStream`] to use for current command's stdout.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stdout indicated by [`IoStream::Inherit`].
pub(crate) fn stdout(&self) -> &IoStream {
self.pipe_stdout.as_ref().unwrap_or(&self.stdout)
}
/// Returns the [`IoStream`] to use for current command's stderr.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stderr indicated by [`IoStream::Inherit`].
pub(crate) fn stderr(&self) -> &IoStream {
self.pipe_stderr.as_ref().unwrap_or(&self.stderr)
}
fn push_stdout(&mut self, stdout: IoStream) -> Option<IoStream> {
let stdout = mem::replace(&mut self.stdout, stdout);
mem::replace(&mut self.parent_stdout, Some(stdout))
}
fn push_stderr(&mut self, stderr: IoStream) -> Option<IoStream> {
let stderr = mem::replace(&mut self.stderr, stderr);
mem::replace(&mut self.parent_stderr, Some(stderr))
}
}
pub struct StackIoGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<IoStream>,
old_pipe_stderr: Option<IoStream>,
old_parent_stdout: Option<IoStream>,
old_parent_stderr: Option<IoStream>,
}
impl<'a> StackIoGuard<'a> {
pub(crate) fn new(
stack: &'a mut Stack,
stdout: Option<Redirection>,
stderr: Option<Redirection>,
) -> Self {
let stdio = &mut stack.stdio;
let (old_pipe_stdout, old_parent_stdout) = match stdout {
Some(Redirection::Pipe(stdout)) => {
let old = mem::replace(&mut stdio.pipe_stdout, Some(stdout));
(old, stdio.parent_stdout.take())
}
Some(Redirection::File(file)) => {
let file = IoStream::from(file);
(
mem::replace(&mut stdio.pipe_stdout, Some(file.clone())),
stdio.push_stdout(file),
)
}
None => (stdio.pipe_stdout.take(), stdio.parent_stdout.take()),
};
let (old_pipe_stderr, old_parent_stderr) = match stderr {
Some(Redirection::Pipe(stderr)) => {
let old = mem::replace(&mut stdio.pipe_stderr, Some(stderr));
(old, stdio.parent_stderr.take())
}
Some(Redirection::File(file)) => {
(stdio.pipe_stderr.take(), stdio.push_stderr(file.into()))
}
None => (stdio.pipe_stderr.take(), stdio.parent_stderr.take()),
};
StackIoGuard {
stack,
old_pipe_stdout,
old_parent_stdout,
old_pipe_stderr,
old_parent_stderr,
}
}
}
impl<'a> Deref for StackIoGuard<'a> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
self.stack
}
}
impl<'a> DerefMut for StackIoGuard<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackIoGuard<'_> {
fn drop(&mut self) {
self.stdio.pipe_stdout = self.old_pipe_stdout.take();
self.stdio.pipe_stderr = self.old_pipe_stderr.take();
let old_stdout = self.old_parent_stdout.take();
if let Some(stdout) = mem::replace(&mut self.stdio.parent_stdout, old_stdout) {
self.stdio.stdout = stdout;
}
let old_stderr = self.old_parent_stderr.take();
if let Some(stderr) = mem::replace(&mut self.stdio.parent_stderr, old_stderr) {
self.stdio.stderr = stderr;
}
}
}
pub struct StackCaptureGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<IoStream>,
old_pipe_stderr: Option<IoStream>,
}
impl<'a> StackCaptureGuard<'a> {
pub(crate) fn new(stack: &'a mut Stack) -> Self {
let old_pipe_stdout = mem::replace(&mut stack.stdio.pipe_stdout, Some(IoStream::Capture));
let old_pipe_stderr = stack.stdio.pipe_stderr.take();
Self {
stack,
old_pipe_stdout,
old_pipe_stderr,
}
}
}
impl<'a> Deref for StackCaptureGuard<'a> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
&*self.stack
}
}
impl<'a> DerefMut for StackCaptureGuard<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackCaptureGuard<'_> {
fn drop(&mut self) {
self.stdio.pipe_stdout = self.old_pipe_stdout.take();
self.stdio.pipe_stderr = self.old_pipe_stderr.take();
}
}
pub struct StackCallArgGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<IoStream>,
old_pipe_stderr: Option<IoStream>,
old_stdout: Option<IoStream>,
old_stderr: Option<IoStream>,
}
impl<'a> StackCallArgGuard<'a> {
pub(crate) fn new(stack: &'a mut Stack) -> Self {
let old_pipe_stdout = mem::replace(&mut stack.stdio.pipe_stdout, Some(IoStream::Capture));
let old_pipe_stderr = stack.stdio.pipe_stderr.take();
let old_stdout = stack
.stdio
.parent_stdout
.take()
.map(|stdout| mem::replace(&mut stack.stdio.stdout, stdout));
let old_stderr = stack
.stdio
.parent_stderr
.take()
.map(|stderr| mem::replace(&mut stack.stdio.stderr, stderr));
Self {
stack,
old_pipe_stdout,
old_pipe_stderr,
old_stdout,
old_stderr,
}
}
}
impl<'a> Deref for StackCallArgGuard<'a> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
&*self.stack
}
}
impl<'a> DerefMut for StackCallArgGuard<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackCallArgGuard<'_> {
fn drop(&mut self) {
self.stdio.pipe_stdout = self.old_pipe_stdout.take();
self.stdio.pipe_stderr = self.old_pipe_stderr.take();
if let Some(stdout) = self.old_stdout.take() {
self.stdio.push_stdout(stdout);
}
if let Some(stderr) = self.old_stderr.take() {
self.stdio.push_stderr(stderr);
}
}
}