mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 05:14:44 +02:00
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:
@ -70,6 +70,7 @@ impl CallExt for Call {
|
||||
if flag_name == name.0.item {
|
||||
return if let Some(expr) = &name.2 {
|
||||
// Check --flag=false
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?;
|
||||
match result {
|
||||
Value::Bool { val, .. } => Ok(val),
|
||||
@ -96,6 +97,7 @@ impl CallExt for Call {
|
||||
name: &str,
|
||||
) -> Result<Option<T>, ShellError> {
|
||||
if let Some(expr) = self.get_flag_expr(name) {
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?;
|
||||
FromValue::from_value(result).map(Some)
|
||||
} else {
|
||||
@ -109,6 +111,7 @@ impl CallExt for Call {
|
||||
stack: &mut Stack,
|
||||
starting_pos: usize,
|
||||
) -> Result<Vec<T>, ShellError> {
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let mut output = vec![];
|
||||
|
||||
for result in self.rest_iter_flattened(starting_pos, |expr| {
|
||||
@ -127,6 +130,7 @@ impl CallExt for Call {
|
||||
pos: usize,
|
||||
) -> Result<Option<T>, ShellError> {
|
||||
if let Some(expr) = self.positional_nth(pos) {
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?;
|
||||
FromValue::from_value(result).map(Some)
|
||||
} else {
|
||||
@ -154,6 +158,7 @@ impl CallExt for Call {
|
||||
pos: usize,
|
||||
) -> Result<T, ShellError> {
|
||||
if let Some(expr) = self.positional_nth(pos) {
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?;
|
||||
FromValue::from_value(result)
|
||||
} else if self.positional_len() == 0 {
|
||||
@ -173,6 +178,7 @@ impl CallExt for Call {
|
||||
name: &str,
|
||||
) -> Result<T, ShellError> {
|
||||
if let Some(expr) = self.get_parser_info(name) {
|
||||
let stack = &mut stack.use_call_arg_stdio();
|
||||
let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?;
|
||||
FromValue::from_value(result)
|
||||
} else if self.parser_info.is_empty() {
|
||||
|
@ -23,6 +23,9 @@ pub fn get_full_help(
|
||||
no_color: !config.use_ansi_coloring,
|
||||
brief: false,
|
||||
};
|
||||
|
||||
let stack = &mut stack.start_capture();
|
||||
|
||||
get_documentation(
|
||||
sig,
|
||||
examples,
|
||||
@ -235,16 +238,14 @@ fn get_documentation(
|
||||
));
|
||||
}
|
||||
|
||||
let mut caller_stack = Stack::new();
|
||||
let caller_stack = &mut Stack::new().capture();
|
||||
if let Ok(result) = eval_call::<WithoutDebug>(
|
||||
engine_state,
|
||||
&mut caller_stack,
|
||||
caller_stack,
|
||||
&Call {
|
||||
decl_id,
|
||||
head: span,
|
||||
arguments: vec![],
|
||||
redirect_stdout: true,
|
||||
redirect_stderr: true,
|
||||
parser_info: HashMap::new(),
|
||||
},
|
||||
PipelineData::Value(Value::list(vals, span), None),
|
||||
@ -340,7 +341,7 @@ fn get_ansi_color_for_component_or_default(
|
||||
default: &str,
|
||||
) -> String {
|
||||
if let Some(color) = &engine_state.get_config().color_config.get(theme_component) {
|
||||
let mut caller_stack = Stack::new();
|
||||
let caller_stack = &mut Stack::new().capture();
|
||||
let span = Span::unknown();
|
||||
|
||||
let argument_opt = get_argument_for_color_value(engine_state, color, span);
|
||||
@ -350,13 +351,11 @@ fn get_ansi_color_for_component_or_default(
|
||||
if let Some(decl_id) = engine_state.find_decl(b"ansi", &[]) {
|
||||
if let Ok(result) = eval_call::<WithoutDebug>(
|
||||
engine_state,
|
||||
&mut caller_stack,
|
||||
caller_stack,
|
||||
&Call {
|
||||
decl_id,
|
||||
head: span,
|
||||
arguments: vec![argument],
|
||||
redirect_stdout: true,
|
||||
redirect_stderr: true,
|
||||
parser_info: HashMap::new(),
|
||||
},
|
||||
PipelineData::Empty,
|
||||
|
@ -379,7 +379,7 @@ fn get_converted_value(
|
||||
let block = engine_state.get_block(val.block_id);
|
||||
|
||||
if let Some(var) = block.signature.get_positional(0) {
|
||||
let mut stack = stack.gather_captures(engine_state, &block.captures);
|
||||
let mut stack = stack.captures_to_stack(val.captures.clone());
|
||||
if let Some(var_id) = &var.var_id {
|
||||
stack.add_var(*var_id, orig_val.clone());
|
||||
}
|
||||
@ -391,8 +391,6 @@ fn get_converted_value(
|
||||
&mut stack,
|
||||
block,
|
||||
PipelineData::new_with_metadata(None, val_span),
|
||||
true,
|
||||
true,
|
||||
);
|
||||
|
||||
match result {
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -8,24 +8,12 @@ use nu_protocol::engine::{EngineState, Stack};
|
||||
use nu_protocol::{PipelineData, ShellError, Value};
|
||||
|
||||
/// Type of eval_block() function
|
||||
pub type EvalBlockFn = fn(
|
||||
&EngineState,
|
||||
&mut Stack,
|
||||
&Block,
|
||||
PipelineData,
|
||||
bool,
|
||||
bool,
|
||||
) -> Result<PipelineData, ShellError>;
|
||||
pub type EvalBlockFn =
|
||||
fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineData, ShellError>;
|
||||
|
||||
/// Type of eval_block_with_early_return() function
|
||||
pub type EvalBlockWithEarlyReturnFn = fn(
|
||||
&EngineState,
|
||||
&mut Stack,
|
||||
&Block,
|
||||
PipelineData,
|
||||
bool,
|
||||
bool,
|
||||
) -> Result<PipelineData, ShellError>;
|
||||
pub type EvalBlockWithEarlyReturnFn =
|
||||
fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineData, ShellError>;
|
||||
|
||||
/// Type of eval_expression() function
|
||||
pub type EvalExpressionFn = fn(&EngineState, &mut Stack, &Expression) -> Result<Value, ShellError>;
|
||||
@ -36,8 +24,6 @@ pub type EvalExpressionWithInputFn = fn(
|
||||
&mut Stack,
|
||||
&Expression,
|
||||
PipelineData,
|
||||
bool,
|
||||
bool,
|
||||
) -> Result<(PipelineData, bool), ShellError>;
|
||||
|
||||
/// Type of eval_subexpression() function
|
||||
|
Reference in New Issue
Block a user