mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 22:47:43 +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:
@ -1,9 +1,7 @@
|
||||
use crate::engine::{EngineState, Stack};
|
||||
use crate::PipelineData;
|
||||
use crate::{
|
||||
ast::{Call, Expression},
|
||||
engine::Command,
|
||||
ShellError, Signature,
|
||||
engine::{Command, EngineState, Stack},
|
||||
PipelineData, ShellError, Signature,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
|
@ -1,5 +1,5 @@
|
||||
use super::Pipeline;
|
||||
use crate::{ast::PipelineElement, Signature, Span, Type, VarId};
|
||||
use crate::{engine::EngineState, IoStream, Signature, Span, Type, VarId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@ -19,6 +19,17 @@ impl Block {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.pipelines.is_empty()
|
||||
}
|
||||
|
||||
pub fn stdio_redirect(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
) -> (Option<IoStream>, Option<IoStream>) {
|
||||
if let Some(first) = self.pipelines.first() {
|
||||
first.stdio_redirect(engine_state)
|
||||
} else {
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Block {
|
||||
@ -51,15 +62,10 @@ impl Block {
|
||||
pub fn output_type(&self) -> Type {
|
||||
if let Some(last) = self.pipelines.last() {
|
||||
if let Some(last) = last.elements.last() {
|
||||
match last {
|
||||
PipelineElement::Expression(_, expr) => expr.ty.clone(),
|
||||
PipelineElement::ErrPipedExpression(_, expr) => expr.ty.clone(),
|
||||
PipelineElement::OutErrPipedExpression(_, expr) => expr.ty.clone(),
|
||||
PipelineElement::Redirection(_, _, _, _) => Type::Any,
|
||||
PipelineElement::SeparateRedirection { .. } => Type::Any,
|
||||
PipelineElement::SameTargetRedirection { .. } => Type::Any,
|
||||
PipelineElement::And(_, expr) => expr.ty.clone(),
|
||||
PipelineElement::Or(_, expr) => expr.ty.clone(),
|
||||
if last.redirection.is_some() {
|
||||
Type::Any
|
||||
} else {
|
||||
last.expr.ty.clone()
|
||||
}
|
||||
} else {
|
||||
Type::Nothing
|
||||
|
@ -2,10 +2,9 @@ use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Expression;
|
||||
use crate::{
|
||||
engine::StateWorkingSet, eval_const::eval_constant, DeclId, FromValue, ShellError, Span,
|
||||
Spanned, Value,
|
||||
ast::Expression, engine::StateWorkingSet, eval_const::eval_constant, DeclId, FromValue,
|
||||
ShellError, Span, Spanned, Value,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@ -51,8 +50,6 @@ pub struct Call {
|
||||
pub decl_id: DeclId,
|
||||
pub head: Span,
|
||||
pub arguments: Vec<Argument>,
|
||||
pub redirect_stdout: bool,
|
||||
pub redirect_stderr: bool,
|
||||
/// this field is used by the parser to pass additional command-specific information
|
||||
pub parser_info: HashMap<String, Expression>,
|
||||
}
|
||||
@ -63,8 +60,6 @@ impl Call {
|
||||
decl_id: 0,
|
||||
head,
|
||||
arguments: vec![],
|
||||
redirect_stdout: true,
|
||||
redirect_stderr: false,
|
||||
parser_info: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,10 @@ use super::{
|
||||
Call, CellPath, Expression, ExternalArgument, FullCellPath, MatchPattern, Operator,
|
||||
RangeOperator,
|
||||
};
|
||||
use crate::{ast::ImportPattern, ast::Unit, BlockId, Signature, Span, Spanned, VarId};
|
||||
use crate::{
|
||||
ast::ImportPattern, ast::Unit, engine::EngineState, BlockId, IoStream, Signature, Span,
|
||||
Spanned, VarId,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Expr {
|
||||
@ -22,7 +25,7 @@ pub enum Expr {
|
||||
Var(VarId),
|
||||
VarDecl(VarId),
|
||||
Call(Box<Call>),
|
||||
ExternalCall(Box<Expression>, Vec<ExternalArgument>, bool), // head, args, is_subexpression
|
||||
ExternalCall(Box<Expression>, Vec<ExternalArgument>), // head, args
|
||||
Operator(Operator),
|
||||
RowCondition(BlockId),
|
||||
UnaryNot(Box<Expression>),
|
||||
@ -52,6 +55,73 @@ pub enum Expr {
|
||||
Garbage,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn stdio_redirect(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
) -> (Option<IoStream>, Option<IoStream>) {
|
||||
// Usages of `$in` will be wrapped by a `collect` call by the parser,
|
||||
// so we do not have to worry about that when considering
|
||||
// which of the expressions below may consume pipeline output.
|
||||
match self {
|
||||
Expr::Call(call) => engine_state.get_decl(call.decl_id).stdio_redirect(),
|
||||
Expr::Subexpression(block_id) | Expr::Block(block_id) => engine_state
|
||||
.get_block(*block_id)
|
||||
.stdio_redirect(engine_state),
|
||||
Expr::FullCellPath(cell_path) => cell_path.head.expr.stdio_redirect(engine_state),
|
||||
Expr::Bool(_)
|
||||
| Expr::Int(_)
|
||||
| Expr::Float(_)
|
||||
| Expr::Binary(_)
|
||||
| Expr::Range(_, _, _, _)
|
||||
| Expr::Var(_)
|
||||
| Expr::UnaryNot(_)
|
||||
| Expr::BinaryOp(_, _, _)
|
||||
| Expr::Closure(_) // piping into a closure value, not into a closure call
|
||||
| Expr::List(_)
|
||||
| Expr::Table(_, _)
|
||||
| Expr::Record(_)
|
||||
| Expr::ValueWithUnit(_, _)
|
||||
| Expr::DateTime(_)
|
||||
| Expr::String(_)
|
||||
| Expr::CellPath(_)
|
||||
| Expr::StringInterpolation(_)
|
||||
| Expr::Nothing => {
|
||||
// These expressions do not use the output of the pipeline in any meaningful way,
|
||||
// so we can discard the previous output by redirecting it to `Null`.
|
||||
(Some(IoStream::Null), None)
|
||||
}
|
||||
Expr::VarDecl(_)
|
||||
| Expr::Operator(_)
|
||||
| Expr::Filepath(_, _)
|
||||
| Expr::Directory(_, _)
|
||||
| Expr::GlobPattern(_, _)
|
||||
| Expr::ImportPattern(_)
|
||||
| Expr::Overlay(_)
|
||||
| Expr::Signature(_)
|
||||
| Expr::Spread(_)
|
||||
| Expr::Garbage => {
|
||||
// These should be impossible to pipe to,
|
||||
// but even it is, the pipeline output is not used in any way.
|
||||
(Some(IoStream::Null), None)
|
||||
}
|
||||
Expr::RowCondition(_) | Expr::MatchBlock(_) => {
|
||||
// These should be impossible to pipe to,
|
||||
// but if they are, then the pipeline output could be used.
|
||||
(None, None)
|
||||
}
|
||||
Expr::ExternalCall(_, _) => {
|
||||
// No override necessary, pipes will always be created in eval
|
||||
(None, None)
|
||||
}
|
||||
Expr::Keyword(_, _, _) => {
|
||||
// Not sure about this; let's return no redirection override for now.
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub enum RecordItem {
|
||||
/// A key: val mapping
|
||||
|
@ -184,7 +184,7 @@ impl Expression {
|
||||
}
|
||||
Expr::CellPath(_) => false,
|
||||
Expr::DateTime(_) => false,
|
||||
Expr::ExternalCall(head, args, _) => {
|
||||
Expr::ExternalCall(head, args) => {
|
||||
if head.has_in_variable(working_set) {
|
||||
return true;
|
||||
}
|
||||
@ -369,7 +369,7 @@ impl Expression {
|
||||
}
|
||||
Expr::CellPath(_) => {}
|
||||
Expr::DateTime(_) => {}
|
||||
Expr::ExternalCall(head, args, _) => {
|
||||
Expr::ExternalCall(head, args) => {
|
||||
head.replace_span(working_set, replaced, new_span);
|
||||
for ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) in args {
|
||||
expr.replace_span(working_set, replaced, new_span);
|
||||
|
@ -1,100 +1,56 @@
|
||||
use crate::{ast::Expression, engine::StateWorkingSet, Span};
|
||||
use crate::{
|
||||
ast::Expression,
|
||||
engine::{EngineState, StateWorkingSet},
|
||||
IoStream, Span,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
|
||||
pub enum Redirection {
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq)]
|
||||
pub enum RedirectionSource {
|
||||
Stdout,
|
||||
Stderr,
|
||||
StdoutAndStderr,
|
||||
}
|
||||
|
||||
// Note: Span in the below is for the span of the connector not the whole element
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum PipelineElement {
|
||||
Expression(Option<Span>, Expression),
|
||||
ErrPipedExpression(Option<Span>, Expression),
|
||||
OutErrPipedExpression(Option<Span>, Expression),
|
||||
// final field indicates if it's in append mode
|
||||
Redirection(Span, Redirection, Expression, bool),
|
||||
// final bool field indicates if it's in append mode
|
||||
SeparateRedirection {
|
||||
out: (Span, Expression, bool),
|
||||
err: (Span, Expression, bool),
|
||||
},
|
||||
// redirection's final bool field indicates if it's in append mode
|
||||
SameTargetRedirection {
|
||||
cmd: (Option<Span>, Expression),
|
||||
redirection: (Span, Expression, bool),
|
||||
},
|
||||
And(Span, Expression),
|
||||
Or(Span, Expression),
|
||||
impl Display for RedirectionSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
RedirectionSource::Stdout => "stdout",
|
||||
RedirectionSource::Stderr => "stderr",
|
||||
RedirectionSource::StdoutAndStderr => "stdout and stderr",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PipelineElement {
|
||||
pub fn expression(&self) -> &Expression {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum RedirectionTarget {
|
||||
File {
|
||||
expr: Expression,
|
||||
append: bool,
|
||||
span: Span,
|
||||
},
|
||||
Pipe {
|
||||
span: Span,
|
||||
},
|
||||
}
|
||||
|
||||
impl RedirectionTarget {
|
||||
pub fn span(&self) -> Span {
|
||||
match self {
|
||||
PipelineElement::Expression(_, expression)
|
||||
| PipelineElement::ErrPipedExpression(_, expression)
|
||||
| PipelineElement::OutErrPipedExpression(_, expression) => expression,
|
||||
PipelineElement::Redirection(_, _, expression, _) => expression,
|
||||
PipelineElement::SeparateRedirection {
|
||||
out: (_, expression, _),
|
||||
..
|
||||
} => expression,
|
||||
PipelineElement::SameTargetRedirection {
|
||||
cmd: (_, expression),
|
||||
..
|
||||
} => expression,
|
||||
PipelineElement::And(_, expression) => expression,
|
||||
PipelineElement::Or(_, expression) => expression,
|
||||
RedirectionTarget::File { span, .. } | RedirectionTarget::Pipe { span } => *span,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn span(&self) -> Span {
|
||||
pub fn expr(&self) -> Option<&Expression> {
|
||||
match self {
|
||||
PipelineElement::Expression(None, expression)
|
||||
| PipelineElement::ErrPipedExpression(None, expression)
|
||||
| PipelineElement::OutErrPipedExpression(None, expression)
|
||||
| PipelineElement::SameTargetRedirection {
|
||||
cmd: (None, expression),
|
||||
..
|
||||
} => expression.span,
|
||||
PipelineElement::Expression(Some(span), expression)
|
||||
| PipelineElement::ErrPipedExpression(Some(span), expression)
|
||||
| PipelineElement::OutErrPipedExpression(Some(span), expression)
|
||||
| PipelineElement::Redirection(span, _, expression, _)
|
||||
| PipelineElement::SeparateRedirection {
|
||||
out: (span, expression, _),
|
||||
..
|
||||
}
|
||||
| PipelineElement::And(span, expression)
|
||||
| PipelineElement::Or(span, expression)
|
||||
| PipelineElement::SameTargetRedirection {
|
||||
cmd: (Some(span), expression),
|
||||
..
|
||||
} => Span {
|
||||
start: span.start,
|
||||
end: expression.span.end,
|
||||
},
|
||||
RedirectionTarget::File { expr, .. } => Some(expr),
|
||||
RedirectionTarget::Pipe { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
|
||||
match self {
|
||||
PipelineElement::Expression(_, expression)
|
||||
| PipelineElement::ErrPipedExpression(_, expression)
|
||||
| PipelineElement::OutErrPipedExpression(_, expression)
|
||||
| PipelineElement::Redirection(_, _, expression, _)
|
||||
| PipelineElement::And(_, expression)
|
||||
| PipelineElement::Or(_, expression)
|
||||
| PipelineElement::SameTargetRedirection {
|
||||
cmd: (_, expression),
|
||||
..
|
||||
} => expression.has_in_variable(working_set),
|
||||
PipelineElement::SeparateRedirection {
|
||||
out: (_, out_expr, _),
|
||||
err: (_, err_expr, _),
|
||||
} => out_expr.has_in_variable(working_set) || err_expr.has_in_variable(working_set),
|
||||
}
|
||||
self.expr().is_some_and(|e| e.has_in_variable(working_set))
|
||||
}
|
||||
|
||||
pub fn replace_span(
|
||||
@ -104,24 +60,72 @@ impl PipelineElement {
|
||||
new_span: Span,
|
||||
) {
|
||||
match self {
|
||||
PipelineElement::Expression(_, expression)
|
||||
| PipelineElement::ErrPipedExpression(_, expression)
|
||||
| PipelineElement::OutErrPipedExpression(_, expression)
|
||||
| PipelineElement::Redirection(_, _, expression, _)
|
||||
| PipelineElement::And(_, expression)
|
||||
| PipelineElement::Or(_, expression)
|
||||
| PipelineElement::SameTargetRedirection {
|
||||
cmd: (_, expression),
|
||||
..
|
||||
RedirectionTarget::File { expr, .. } => {
|
||||
expr.replace_span(working_set, replaced, new_span)
|
||||
}
|
||||
| PipelineElement::SeparateRedirection {
|
||||
out: (_, expression, _),
|
||||
..
|
||||
} => expression.replace_span(working_set, replaced, new_span),
|
||||
RedirectionTarget::Pipe { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum PipelineRedirection {
|
||||
Single {
|
||||
source: RedirectionSource,
|
||||
target: RedirectionTarget,
|
||||
},
|
||||
Separate {
|
||||
out: RedirectionTarget,
|
||||
err: RedirectionTarget,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PipelineElement {
|
||||
pub pipe: Option<Span>,
|
||||
pub expr: Expression,
|
||||
pub redirection: Option<PipelineRedirection>,
|
||||
}
|
||||
|
||||
impl PipelineElement {
|
||||
pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
|
||||
self.expr.has_in_variable(working_set)
|
||||
|| self.redirection.as_ref().is_some_and(|r| match r {
|
||||
PipelineRedirection::Single { target, .. } => target.has_in_variable(working_set),
|
||||
PipelineRedirection::Separate { out, err } => {
|
||||
out.has_in_variable(working_set) || err.has_in_variable(working_set)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn replace_span(
|
||||
&mut self,
|
||||
working_set: &mut StateWorkingSet,
|
||||
replaced: Span,
|
||||
new_span: Span,
|
||||
) {
|
||||
self.expr.replace_span(working_set, replaced, new_span);
|
||||
if let Some(expr) = self.redirection.as_mut() {
|
||||
match expr {
|
||||
PipelineRedirection::Single { target, .. } => {
|
||||
target.replace_span(working_set, replaced, new_span)
|
||||
}
|
||||
PipelineRedirection::Separate { out, err } => {
|
||||
out.replace_span(working_set, replaced, new_span);
|
||||
err.replace_span(working_set, replaced, new_span);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stdio_redirect(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
) -> (Option<IoStream>, Option<IoStream>) {
|
||||
self.expr.expr.stdio_redirect(engine_state)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Pipeline {
|
||||
pub elements: Vec<PipelineElement>,
|
||||
@ -143,8 +147,10 @@ impl Pipeline {
|
||||
elements: expressions
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, x)| {
|
||||
PipelineElement::Expression(if idx == 0 { None } else { Some(x.span) }, x)
|
||||
.map(|(idx, expr)| PipelineElement {
|
||||
pipe: if idx == 0 { None } else { Some(expr.span) },
|
||||
expr,
|
||||
redirection: None,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
@ -157,4 +163,15 @@ impl Pipeline {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.elements.is_empty()
|
||||
}
|
||||
|
||||
pub fn stdio_redirect(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
) -> (Option<IoStream>, Option<IoStream>) {
|
||||
if let Some(first) = self.elements.first() {
|
||||
first.stdio_redirect(engine_state)
|
||||
} else {
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -142,19 +142,14 @@ impl Debugger for Profiler {
|
||||
};
|
||||
|
||||
let expr_opt = if self.collect_exprs {
|
||||
Some(match element {
|
||||
PipelineElement::Expression(_, expression) => {
|
||||
expr_to_string(engine_state, &expression.expr)
|
||||
}
|
||||
_ => "other".to_string(),
|
||||
})
|
||||
Some(expr_to_string(engine_state, &element.expr.expr))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let new_id = ElementId(self.elements.len());
|
||||
|
||||
let mut new_element = ElementInfo::new(self.depth, element.span());
|
||||
let mut new_element = ElementInfo::new(self.depth, element.expr.span);
|
||||
new_element.expr = expr_opt;
|
||||
|
||||
self.elements.push(new_element);
|
||||
@ -178,7 +173,7 @@ impl Debugger for Profiler {
|
||||
return;
|
||||
}
|
||||
|
||||
let element_span = element.span();
|
||||
let element_span = element.expr.span;
|
||||
|
||||
let out_opt = if self.collect_values {
|
||||
Some(match result {
|
||||
@ -250,7 +245,7 @@ fn expr_to_string(engine_state: &EngineState, expr: &Expr) -> String {
|
||||
Expr::Closure(_) => "closure".to_string(),
|
||||
Expr::DateTime(_) => "datetime".to_string(),
|
||||
Expr::Directory(_, _) => "directory".to_string(),
|
||||
Expr::ExternalCall(_, _, _) => "external call".to_string(),
|
||||
Expr::ExternalCall(_, _) => "external call".to_string(),
|
||||
Expr::Filepath(_, _) => "filepath".to_string(),
|
||||
Expr::Float(_) => "float".to_string(),
|
||||
Expr::FullCellPath(full_cell_path) => {
|
||||
|
@ -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 {
|
||||
|
@ -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::*;
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
288
crates/nu-protocol/src/engine/stdio.rs
Normal file
288
crates/nu-protocol/src/engine/stdio.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
@ -3,7 +3,7 @@ use std::{
|
||||
str::{from_utf8, Utf8Error},
|
||||
};
|
||||
|
||||
use crate::{did_you_mean, Span, Type};
|
||||
use crate::{ast::RedirectionSource, did_you_mean, Span, Type};
|
||||
use miette::Diagnostic;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
@ -85,6 +85,14 @@ pub enum ParseError {
|
||||
)]
|
||||
ShellOutErrRedirect(#[label("use 'out+err>' instead of '2>&1' in Nushell")] Span),
|
||||
|
||||
#[error("Multiple redirections provided for {0}.")]
|
||||
#[diagnostic(code(nu::parser::multiple_redirections))]
|
||||
MultipleRedirections(
|
||||
RedirectionSource,
|
||||
#[label = "first redirection"] Span,
|
||||
#[label = "second redirection"] Span,
|
||||
),
|
||||
|
||||
#[error("{0} is not supported on values of type {3}")]
|
||||
#[diagnostic(code(nu::parser::unsupported_operation))]
|
||||
UnsupportedOperationLHS(
|
||||
@ -449,10 +457,11 @@ pub enum ParseError {
|
||||
span: Span,
|
||||
},
|
||||
|
||||
#[error("Redirection can not be used with let/mut.")]
|
||||
#[error("Redirection can not be used with {0}.")]
|
||||
#[diagnostic()]
|
||||
RedirectionInLetMut(
|
||||
#[label("Not allowed here")] Span,
|
||||
RedirectingBuiltinCommand(
|
||||
&'static str,
|
||||
#[label("not allowed here")] Span,
|
||||
#[label("...and here")] Option<Span>,
|
||||
),
|
||||
|
||||
@ -540,10 +549,11 @@ impl ParseError {
|
||||
ParseError::ShellOrOr(s) => *s,
|
||||
ParseError::ShellErrRedirect(s) => *s,
|
||||
ParseError::ShellOutErrRedirect(s) => *s,
|
||||
ParseError::MultipleRedirections(_, _, s) => *s,
|
||||
ParseError::UnknownOperator(_, _, s) => *s,
|
||||
ParseError::InvalidLiteral(_, _, s) => *s,
|
||||
ParseError::LabeledErrorWithHelp { span: s, .. } => *s,
|
||||
ParseError::RedirectionInLetMut(s, _) => *s,
|
||||
ParseError::RedirectingBuiltinCommand(_, s, _) => *s,
|
||||
ParseError::UnexpectedSpreadArg(_, s) => *s,
|
||||
}
|
||||
}
|
||||
|
@ -145,8 +145,8 @@ pub trait Eval {
|
||||
}),
|
||||
},
|
||||
Expr::Call(call) => Self::eval_call::<D>(state, mut_state, call, expr.span),
|
||||
Expr::ExternalCall(head, args, is_subexpression) => {
|
||||
Self::eval_external_call(state, mut_state, head, args, *is_subexpression, expr.span)
|
||||
Expr::ExternalCall(head, args) => {
|
||||
Self::eval_external_call(state, mut_state, head, args, expr.span)
|
||||
}
|
||||
Expr::Subexpression(block_id) => {
|
||||
Self::eval_subexpression::<D>(state, mut_state, *block_id, expr.span)
|
||||
@ -338,7 +338,6 @@ pub trait Eval {
|
||||
mut_state: &mut Self::MutState,
|
||||
head: &Expression,
|
||||
args: &[ExternalArgument],
|
||||
is_subexpression: bool,
|
||||
span: Span,
|
||||
) -> Result<Value, ShellError>;
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
use crate::debugger::{DebugContext, WithoutDebug};
|
||||
use crate::{
|
||||
ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument, PipelineElement},
|
||||
ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument},
|
||||
engine::{EngineState, StateWorkingSet},
|
||||
eval_base::Eval,
|
||||
record, Config, HistoryFileFormat, PipelineData, Record, ShellError, Span, Value, VarId,
|
||||
@ -227,11 +227,11 @@ pub fn eval_const_subexpression(
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
for pipeline in block.pipelines.iter() {
|
||||
for element in pipeline.elements.iter() {
|
||||
let PipelineElement::Expression(_, expr) = element else {
|
||||
if element.redirection.is_some() {
|
||||
return Err(ShellError::NotAConstant { span });
|
||||
};
|
||||
}
|
||||
|
||||
input = eval_constant_with_input(working_set, expr, input)?
|
||||
input = eval_constant_with_input(working_set, &element.expr, input)?
|
||||
}
|
||||
}
|
||||
|
||||
@ -321,7 +321,6 @@ impl Eval for EvalConst {
|
||||
_: &mut (),
|
||||
_: &Expression,
|
||||
_: &[ExternalArgument],
|
||||
_: bool,
|
||||
span: Span,
|
||||
) -> Result<Value, ShellError> {
|
||||
// TODO: It may be more helpful to give not_a_const_command error
|
||||
|
53
crates/nu-protocol/src/pipeline_data/io_stream.rs
Normal file
53
crates/nu-protocol/src/pipeline_data/io_stream.rs
Normal file
@ -0,0 +1,53 @@
|
||||
use std::{fs::File, io, process::Stdio, sync::Arc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum IoStream {
|
||||
/// Redirect the `stdout` and/or `stderr` of one command as the input for the next command in the pipeline.
|
||||
///
|
||||
/// The output pipe will be available in `PipelineData::ExternalStream::stdout`.
|
||||
///
|
||||
/// If both `stdout` and `stderr` are set to `Pipe`,
|
||||
/// then they will combined into `ExternalStream::stdout`.
|
||||
Pipe,
|
||||
/// Capture output to later be collected into a [`Value`], `Vec`, or used in some other way.
|
||||
///
|
||||
/// The output stream(s) will be available in
|
||||
/// `PipelineData::ExternalStream::stdout` or `PipelineData::ExternalStream::stderr`.
|
||||
///
|
||||
/// This is similar to `Pipe` but will never combine `stdout` and `stderr`
|
||||
/// or place an external command's `stderr` into `PipelineData::ExternalStream::stdout`.
|
||||
Capture,
|
||||
/// Ignore output.
|
||||
Null,
|
||||
/// Output to nushell's `stdout` or `stderr`.
|
||||
///
|
||||
/// This causes external commands to inherit nushell's `stdout` or `stderr`.
|
||||
Inherit,
|
||||
/// Redirect output to a file.
|
||||
File(Arc<File>), // Arc<File>, since we sometimes need to clone `IoStream` into iterators, etc.
|
||||
}
|
||||
|
||||
impl From<File> for IoStream {
|
||||
fn from(file: File) -> Self {
|
||||
Arc::new(file).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Arc<File>> for IoStream {
|
||||
fn from(file: Arc<File>) -> Self {
|
||||
Self::File(file)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&IoStream> for Stdio {
|
||||
type Error = io::Error;
|
||||
|
||||
fn try_from(stream: &IoStream) -> Result<Self, Self::Error> {
|
||||
match stream {
|
||||
IoStream::Pipe | IoStream::Capture => Ok(Self::piped()),
|
||||
IoStream::Null => Ok(Self::null()),
|
||||
IoStream::Inherit => Ok(Self::inherit()),
|
||||
IoStream::File(file) => Ok(file.try_clone()?.into()),
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
mod io_stream;
|
||||
mod metadata;
|
||||
mod stream;
|
||||
|
||||
pub use io_stream::*;
|
||||
pub use metadata::*;
|
||||
pub use stream::*;
|
||||
|
||||
@ -10,7 +12,7 @@ use crate::{
|
||||
format_error, Config, ShellError, Span, Value,
|
||||
};
|
||||
use nu_utils::{stderr_write_all_and_flush, stdout_write_all_and_flush};
|
||||
use std::io::Write;
|
||||
use std::io::{self, Cursor, Read, Write};
|
||||
use std::sync::{atomic::AtomicBool, Arc};
|
||||
use std::thread;
|
||||
|
||||
@ -204,6 +206,144 @@ impl PipelineData {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes all values or redirects all output to the current stdio streams in `stack`.
|
||||
///
|
||||
/// For [`IoStream::Pipe`] and [`IoStream::Capture`], this will return the `PipelineData` as is
|
||||
/// without consuming input and without writing anything.
|
||||
///
|
||||
/// For the other [`IoStream`]s, the given `PipelineData` will be completely consumed
|
||||
/// and `PipelineData::Empty` will be returned.
|
||||
pub fn write_to_io_streams(
|
||||
self,
|
||||
engine_state: &EngineState,
|
||||
stack: &mut Stack,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
match (self, stack.stdout()) {
|
||||
(
|
||||
PipelineData::ExternalStream {
|
||||
stdout,
|
||||
stderr,
|
||||
exit_code,
|
||||
span,
|
||||
metadata,
|
||||
trim_end_newline,
|
||||
},
|
||||
_,
|
||||
) => {
|
||||
fn needs_redirect(
|
||||
stream: Option<RawStream>,
|
||||
io_stream: &IoStream,
|
||||
) -> Result<RawStream, Option<RawStream>> {
|
||||
match (stream, io_stream) {
|
||||
(Some(stream), IoStream::Pipe | IoStream::Capture) => Err(Some(stream)),
|
||||
(Some(stream), _) => Ok(stream),
|
||||
(None, _) => Err(None),
|
||||
}
|
||||
}
|
||||
|
||||
let (stdout, stderr) = match (
|
||||
needs_redirect(stdout, stack.stdout()),
|
||||
needs_redirect(stderr, stack.stderr()),
|
||||
) {
|
||||
(Ok(stdout), Ok(stderr)) => {
|
||||
// We need to redirect both stdout and stderr
|
||||
|
||||
// To avoid deadlocks, we must spawn a separate thread to wait on stderr.
|
||||
let err_thread = {
|
||||
let err = stack.stderr().clone();
|
||||
std::thread::Builder::new()
|
||||
.spawn(move || consume_child_output(stderr, &err))
|
||||
};
|
||||
|
||||
consume_child_output(stdout, stack.stdout())?;
|
||||
|
||||
match err_thread?.join() {
|
||||
Ok(result) => result?,
|
||||
Err(err) => {
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Error consuming external command stderr".into(),
|
||||
msg: format! {"{err:?}"},
|
||||
span: Some(span),
|
||||
help: None,
|
||||
inner: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
(None, None)
|
||||
}
|
||||
(Ok(stdout), Err(stderr)) => {
|
||||
// single output stream, we can consume directly
|
||||
consume_child_output(stdout, stack.stdout())?;
|
||||
(None, stderr)
|
||||
}
|
||||
(Err(stdout), Ok(stderr)) => {
|
||||
// single output stream, we can consume directly
|
||||
consume_child_output(stderr, stack.stderr())?;
|
||||
(stdout, None)
|
||||
}
|
||||
(Err(stdout), Err(stderr)) => (stdout, stderr),
|
||||
};
|
||||
|
||||
Ok(PipelineData::ExternalStream {
|
||||
stdout,
|
||||
stderr,
|
||||
exit_code,
|
||||
span,
|
||||
metadata,
|
||||
trim_end_newline,
|
||||
})
|
||||
}
|
||||
(data, IoStream::Pipe | IoStream::Capture) => Ok(data),
|
||||
(PipelineData::Empty, _) => Ok(PipelineData::Empty),
|
||||
(PipelineData::Value(_, _), IoStream::Null) => Ok(PipelineData::Empty),
|
||||
(PipelineData::ListStream(stream, _), IoStream::Null) => {
|
||||
// we need to drain the stream in case there are external commands in the pipeline
|
||||
stream.drain()?;
|
||||
Ok(PipelineData::Empty)
|
||||
}
|
||||
(PipelineData::Value(value, _), IoStream::File(file)) => {
|
||||
let bytes = value_to_bytes(value)?;
|
||||
let mut file = file.try_clone()?;
|
||||
file.write_all(&bytes)?;
|
||||
file.flush()?;
|
||||
Ok(PipelineData::Empty)
|
||||
}
|
||||
(PipelineData::ListStream(stream, _), IoStream::File(file)) => {
|
||||
let mut file = file.try_clone()?;
|
||||
// use BufWriter here?
|
||||
for value in stream {
|
||||
let bytes = value_to_bytes(value)?;
|
||||
file.write_all(&bytes)?;
|
||||
file.write_all(b"\n")?;
|
||||
}
|
||||
file.flush()?;
|
||||
Ok(PipelineData::Empty)
|
||||
}
|
||||
(
|
||||
data @ (PipelineData::Value(_, _) | PipelineData::ListStream(_, _)),
|
||||
IoStream::Inherit,
|
||||
) => {
|
||||
let config = engine_state.get_config();
|
||||
|
||||
if let Some(decl_id) = engine_state.table_decl_id {
|
||||
let command = engine_state.get_decl(decl_id);
|
||||
if command.get_block_id().is_some() {
|
||||
data.write_all_and_flush(engine_state, config, false, false)?;
|
||||
} else {
|
||||
let call = Call::new(Span::unknown());
|
||||
let stack = &mut stack.start_capture();
|
||||
let table = command.run(engine_state, stack, &call, data)?;
|
||||
table.write_all_and_flush(engine_state, config, false, false)?;
|
||||
}
|
||||
} else {
|
||||
data.write_all_and_flush(engine_state, config, false, false)?;
|
||||
};
|
||||
Ok(PipelineData::Empty)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drain(self) -> Result<(), ShellError> {
|
||||
match self {
|
||||
PipelineData::Value(Value::Error { error, .. }, _) => Err(*error),
|
||||
@ -724,10 +864,8 @@ impl PipelineData {
|
||||
return self.write_all_and_flush(engine_state, config, no_newline, to_stderr);
|
||||
}
|
||||
|
||||
let mut call = Call::new(Span::new(0, 0));
|
||||
call.redirect_stdout = false;
|
||||
let call = Call::new(Span::new(0, 0));
|
||||
let table = command.run(engine_state, stack, &call, self)?;
|
||||
|
||||
table.write_all_and_flush(engine_state, config, no_newline, to_stderr)?;
|
||||
} else {
|
||||
self.write_all_and_flush(engine_state, config, no_newline, to_stderr)?;
|
||||
@ -841,7 +979,6 @@ pub fn print_if_stream(
|
||||
exit_code: Option<ListStream>,
|
||||
) -> Result<i64, ShellError> {
|
||||
if let Some(stderr_stream) = stderr_stream {
|
||||
// Write stderr to our stderr, if it's present
|
||||
thread::Builder::new()
|
||||
.name("stderr consumer".to_string())
|
||||
.spawn(move || {
|
||||
@ -896,6 +1033,32 @@ fn drain_exit_code(exit_code: ListStream) -> Result<i64, ShellError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only call this if `output_stream` is not `IoStream::Pipe` or `IoStream::Capture`.
|
||||
fn consume_child_output(child_output: RawStream, output_stream: &IoStream) -> io::Result<()> {
|
||||
let mut output = ReadRawStream::new(child_output);
|
||||
match output_stream {
|
||||
IoStream::Pipe | IoStream::Capture => {
|
||||
// The point of `consume_child_output` is to redirect output *right now*,
|
||||
// but IoStream::Pipe means to redirect output
|
||||
// into an OS pipe for *future use* (as input for another command).
|
||||
// So, this branch makes no sense, and will simply drop `output` instead of draining it.
|
||||
// This could trigger a `SIGPIPE` for the external command,
|
||||
// since there will be no reader for its pipe.
|
||||
debug_assert!(false)
|
||||
}
|
||||
IoStream::Null => {
|
||||
io::copy(&mut output, &mut io::sink())?;
|
||||
}
|
||||
IoStream::Inherit => {
|
||||
io::copy(&mut output, &mut io::stdout())?;
|
||||
}
|
||||
IoStream::File(file) => {
|
||||
io::copy(&mut output, &mut file.try_clone()?)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Iterator for PipelineIterator {
|
||||
type Item = Value;
|
||||
|
||||
@ -978,3 +1141,61 @@ where
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn value_to_bytes(value: Value) -> Result<Vec<u8>, ShellError> {
|
||||
let bytes = match value {
|
||||
Value::String { val, .. } => val.into_bytes(),
|
||||
Value::Binary { val, .. } => val,
|
||||
Value::List { vals, .. } => {
|
||||
let val = vals
|
||||
.into_iter()
|
||||
.map(Value::coerce_into_string)
|
||||
.collect::<Result<Vec<String>, ShellError>>()?
|
||||
.join("\n")
|
||||
+ "\n";
|
||||
|
||||
val.into_bytes()
|
||||
}
|
||||
// Propagate errors by explicitly matching them before the final case.
|
||||
Value::Error { error, .. } => return Err(*error),
|
||||
value => value.coerce_into_string()?.into_bytes(),
|
||||
};
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
struct ReadRawStream {
|
||||
iter: Box<dyn Iterator<Item = Result<Vec<u8>, ShellError>>>,
|
||||
cursor: Option<Cursor<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl ReadRawStream {
|
||||
fn new(stream: RawStream) -> Self {
|
||||
debug_assert!(stream.leftover.is_empty());
|
||||
Self {
|
||||
iter: stream.stream,
|
||||
cursor: Some(Cursor::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for ReadRawStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
while let Some(cursor) = self.cursor.as_mut() {
|
||||
let read = cursor.read(buf)?;
|
||||
if read > 0 {
|
||||
return Ok(read);
|
||||
} else {
|
||||
match self.iter.next().transpose() {
|
||||
Ok(next) => {
|
||||
self.cursor = next.map(Cursor::new);
|
||||
}
|
||||
Err(err) => {
|
||||
// temporary hack
|
||||
return Err(io::Error::new(io::ErrorKind::Other, err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user