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

@ -45,7 +45,8 @@ impl Command for Collect {
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack_captures = stack.captures_to_stack(capture_block.captures.clone());
let mut stack_captures =
stack.captures_to_stack_preserve_stdio(capture_block.captures.clone());
let metadata = input.metadata();
let input: Value = input.into_value(call.head);
@ -65,8 +66,6 @@ impl Command for Collect {
&mut stack_captures,
&block,
input.into_pipeline_data(),
call.redirect_stdout,
call.redirect_stderr,
)
.map(|x| x.set_metadata(metadata));

View File

@ -5,8 +5,8 @@ use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoSpanned, ListStream, PipelineData, RawStream, ShellError, Signature,
Span, SyntaxShape, Type, Value,
Category, Example, IntoSpanned, IoStream, ListStream, PipelineData, RawStream, ShellError,
Signature, Span, SyntaxShape, Type, Value,
};
#[derive(Clone)]
@ -79,19 +79,12 @@ impl Command for Do {
let capture_errors = call.has_flag(engine_state, caller_stack, "capture-errors")?;
let has_env = call.has_flag(engine_state, caller_stack, "env")?;
let mut callee_stack = caller_stack.captures_to_stack(block.captures);
let mut callee_stack = caller_stack.captures_to_stack_preserve_stdio(block.captures);
let block = engine_state.get_block(block.block_id);
bind_args_to(&mut callee_stack, &block.signature, rest, call.head)?;
let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
let result = eval_block_with_early_return(
engine_state,
&mut callee_stack,
block,
input,
call.redirect_stdout,
call.redirect_stdout,
);
let result = eval_block_with_early_return(engine_state, &mut callee_stack, block, input);
if has_env {
// Merge the block's environment to the current stack
@ -204,7 +197,9 @@ impl Command for Do {
span,
metadata,
trim_end_newline,
}) if ignore_program_errors && !call.redirect_stdout => {
}) if ignore_program_errors
&& !matches!(caller_stack.stdout(), IoStream::Pipe | IoStream::Capture) =>
{
Ok(PipelineData::ExternalStream {
stdout,
stderr,

View File

@ -2,8 +2,8 @@ use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, ListStream, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape,
Type, Value,
};
#[derive(Clone)]
@ -38,8 +38,13 @@ little reason to use this over just writing the values as-is."#
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = call.rest(engine_state, stack, 0);
run(engine_state, args, stack, call)
let mut args = call.rest(engine_state, stack, 0)?;
let value = match args.len() {
0 => Value::string("", call.head),
1 => args.pop().expect("one element"),
_ => Value::list(args, call.head),
};
Ok(value.into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
@ -62,43 +67,6 @@ little reason to use this over just writing the values as-is."#
}
}
fn run(
engine_state: &EngineState,
args: Result<Vec<Value>, ShellError>,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let result = args.map(|to_be_echoed| {
let n = to_be_echoed.len();
match n.cmp(&1usize) {
// More than one value is converted in a stream of values
std::cmp::Ordering::Greater => PipelineData::ListStream(
ListStream::from_stream(to_be_echoed.into_iter(), engine_state.ctrlc.clone()),
None,
),
// But a single value can be forwarded as it is
std::cmp::Ordering::Equal => PipelineData::Value(to_be_echoed[0].clone(), None),
// When there are no elements, we echo the empty string
std::cmp::Ordering::Less => PipelineData::Value(Value::string("", call.head), None),
}
});
// If echo is not redirected, then print to the screen (to behave in a similar way to other shells)
if !call.redirect_stdout {
match result {
Ok(pipeline) => {
pipeline.print(engine_state, stack, false, false)?;
Ok(PipelineData::Empty)
}
Err(err) => Err(err),
}
} else {
result
}
}
#[cfg(test)]
mod test {
#[test]

View File

@ -84,8 +84,8 @@ impl Command for For {
let ctrlc = engine_state.ctrlc.clone();
let engine_state = engine_state.clone();
let block = engine_state.get_block(block.block_id).clone();
let redirect_stdout = call.redirect_stdout;
let redirect_stderr = call.redirect_stderr;
let stack = &mut stack.push_redirection(None, None);
match values {
Value::List { vals, .. } => {
@ -109,14 +109,7 @@ impl Command for For {
},
);
match eval_block(
&engine_state,
stack,
&block,
PipelineData::empty(),
redirect_stdout,
redirect_stderr,
) {
match eval_block(&engine_state, stack, &block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => {
break;
}
@ -154,14 +147,7 @@ impl Command for For {
},
);
match eval_block(
&engine_state,
stack,
&block,
PipelineData::empty(),
redirect_stdout,
redirect_stderr,
) {
match eval_block(&engine_state, stack, &block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => {
break;
}
@ -185,15 +171,7 @@ impl Command for For {
x => {
stack.add_var(var_id, x);
eval_block(
&engine_state,
stack,
&block,
PipelineData::empty(),
redirect_stdout,
redirect_stderr,
)?
.into_value(head);
eval_block(&engine_state, stack, &block, PipelineData::empty())?.into_value(head);
}
}
Ok(PipelineData::empty())

View File

@ -115,47 +115,19 @@ impl Command for If {
Value::Bool { val, .. } => {
if *val {
let block = engine_state.get_block(then_block.block_id);
eval_block(
engine_state,
stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
)
eval_block(engine_state, stack, block, input)
} else if let Some(else_case) = else_case {
if let Some(else_expr) = else_case.as_keyword() {
if let Some(block_id) = else_expr.as_block() {
let block = engine_state.get_block(block_id);
eval_block(
engine_state,
stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
)
eval_block(engine_state, stack, block, input)
} else {
eval_expression_with_input(
engine_state,
stack,
else_expr,
input,
call.redirect_stdout,
call.redirect_stderr,
)
.map(|res| res.0)
eval_expression_with_input(engine_state, stack, else_expr, input)
.map(|res| res.0)
}
} else {
eval_expression_with_input(
engine_state,
stack,
else_case,
input,
call.redirect_stdout,
call.redirect_stderr,
)
.map(|res| res.0)
eval_expression_with_input(engine_state, stack, else_case, input)
.map(|res| res.0)
}
} else {
Ok(PipelineData::empty())

View File

@ -1,6 +1,8 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack, StateWorkingSet};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
use nu_protocol::{
Category, Example, IoStream, PipelineData, ShellError, Signature, Span, Type, Value,
};
#[derive(Clone)]
pub struct Ignore;
@ -56,6 +58,10 @@ impl Command for Ignore {
result: Some(Value::nothing(Span::test_data())),
}]
}
fn stdio_redirect(&self) -> (Option<IoStream>, Option<IoStream>) {
(Some(IoStream::Null), None)
}
}
#[cfg(test)]

View File

@ -86,10 +86,12 @@ impl Command for LazyMake {
}
}
let stack = stack.clone().reset_stdio().capture();
Ok(Value::lazy_record(
Box::new(NuLazyRecord {
engine_state: engine_state.clone(),
stack: Arc::new(Mutex::new(stack.clone())),
stack: Arc::new(Mutex::new(stack)),
columns: columns.into_iter().map(|s| s.item).collect(),
get_value,
span,
@ -152,8 +154,6 @@ impl<'a> LazyRecord<'a> for NuLazyRecord {
&mut stack,
block,
PipelineData::Value(column_value, None),
false,
false,
);
pipeline_result.map(|data| match data {

View File

@ -64,7 +64,8 @@ impl Command for Let {
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let pipeline_data = eval_block(engine_state, stack, block, input, true, false)?;
let stack = &mut stack.start_capture();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let mut value = pipeline_data.into_value(call.head);
// if given variable type is Glob, and our result is string

View File

@ -36,6 +36,8 @@ impl Command for Loop {
let block: Block = call.req(engine_state, stack, 0)?;
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.push_redirection(None, None);
loop {
if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
break;
@ -43,14 +45,7 @@ impl Command for Loop {
let block = engine_state.get_block(block.block_id);
match eval_block(
engine_state,
stack,
block,
PipelineData::empty(),
call.redirect_stdout,
call.redirect_stderr,
) {
match eval_block(engine_state, stack, block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => {
break;
}

View File

@ -70,24 +70,10 @@ impl Command for Match {
if guard_matches {
return if let Some(block_id) = match_.1.as_block() {
let block = engine_state.get_block(block_id);
eval_block(
engine_state,
stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
)
eval_block(engine_state, stack, block, input)
} else {
eval_expression_with_input(
engine_state,
stack,
&match_.1,
input,
call.redirect_stdout,
call.redirect_stderr,
)
.map(|x| x.0)
eval_expression_with_input(engine_state, stack, &match_.1, input)
.map(|x| x.0)
};
}
}

View File

@ -65,15 +65,8 @@ impl Command for Mut {
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let pipeline_data = eval_block(
engine_state,
stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
)?;
let stack = &mut stack.start_capture();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let mut value = pipeline_data.into_value(call.head);
// if given variable type is Glob, and our result is string

View File

@ -124,7 +124,9 @@ impl Command for OverlayUse {
)?;
let block = engine_state.get_block(block_id);
let mut callee_stack = caller_stack.gather_captures(engine_state, &block.captures);
let mut callee_stack = caller_stack
.gather_captures(engine_state, &block.captures)
.reset_pipes();
if let Some(path) = &maybe_path {
// Set the currently evaluated directory, if the argument is a valid path
@ -142,15 +144,7 @@ impl Command for OverlayUse {
}
let eval_block = get_eval_block(engine_state);
let _ = eval_block(
engine_state,
&mut callee_stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
);
let _ = eval_block(engine_state, &mut callee_stack, block, input);
// The export-env block should see the env vars *before* activating this overlay
caller_stack.add_overlay(overlay_name);

View File

@ -50,7 +50,7 @@ impl Command for Try {
let try_block = engine_state.get_block(try_block.block_id);
let eval_block = get_eval_block(engine_state);
let result = eval_block(engine_state, stack, try_block, input, false, false);
let result = eval_block(engine_state, stack, try_block, input);
match result {
Err(error) => {
@ -117,8 +117,6 @@ fn handle_catch(
catch_block,
// Make the error accessible with $in, too
err_value.into_pipeline_data(),
false,
false,
)
} else {
Ok(PipelineData::empty())

View File

@ -105,7 +105,9 @@ This command is a parser keyword. For details, check:
.as_ref()
.and_then(|path| path.parent().map(|p| p.to_path_buf()));
let mut callee_stack = caller_stack.gather_captures(engine_state, &block.captures);
let mut callee_stack = caller_stack
.gather_captures(engine_state, &block.captures)
.reset_pipes();
// If so, set the currently evaluated directory (file-relative PWD)
if let Some(parent) = maybe_parent {
@ -121,14 +123,7 @@ This command is a parser keyword. For details, check:
let eval_block = get_eval_block(engine_state);
// Run the block (discard the result)
let _ = eval_block(
engine_state,
&mut callee_stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
)?;
let _ = eval_block(engine_state, &mut callee_stack, block, input)?;
// Merge the block's environment to the current stack
redirect_env(engine_state, caller_stack, &callee_stack);

View File

@ -48,6 +48,8 @@ impl Command for While {
let eval_expression = get_eval_expression(engine_state);
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.push_redirection(None, None);
loop {
if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
break;
@ -60,14 +62,7 @@ impl Command for While {
if *val {
let block = engine_state.get_block(block.block_id);
match eval_block(
engine_state,
stack,
block,
PipelineData::empty(),
call.redirect_stdout,
call.redirect_stderr,
) {
match eval_block(engine_state, stack, block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => {
break;
}

View File

@ -112,12 +112,11 @@ pub fn eval_block(
.merge_delta(delta)
.expect("Error merging delta");
let mut stack = Stack::new();
let mut stack = Stack::new().capture();
stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy()));
match nu_engine::eval_block::<WithoutDebug>(engine_state, &mut stack, &block, input, true, true)
{
match nu_engine::eval_block::<WithoutDebug>(engine_state, &mut stack, &block, input) {
Err(err) => panic!("test eval error in `{}`: {:?}", "TODO", err),
Ok(result) => result.into_value(Span::test_data()),
}
@ -128,7 +127,7 @@ pub fn check_example_evaluates_to_expected_output(
cwd: &std::path::Path,
engine_state: &mut Box<EngineState>,
) {
let mut stack = Stack::new();
let mut stack = Stack::new().capture();
// Set up PWD
stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy()));