nushell/crates/nu-command/src/formats/to/nuon.rs
Ian Manske 6fd854ed9f
Replace ExternalStream with new ByteStream type (#12774)
# Description
This PR introduces a `ByteStream` type which is a `Read`-able stream of
bytes. Internally, it has an enum over three different byte stream
sources:
```rust
pub enum ByteStreamSource {
    Read(Box<dyn Read + Send + 'static>),
    File(File),
    Child(ChildProcess),
}
```

This is in comparison to the current `RawStream` type, which is an
`Iterator<Item = Vec<u8>>` and has to allocate for each read chunk.

Currently, `PipelineData::ExternalStream` serves a weird dual role where
it is either external command output or a wrapper around `RawStream`.
`ByteStream` makes this distinction more clear (via `ByteStreamSource`)
and replaces `PipelineData::ExternalStream` in this PR:
```rust
pub enum PipelineData {
    Empty,
    Value(Value, Option<PipelineMetadata>),
    ListStream(ListStream, Option<PipelineMetadata>),
    ByteStream(ByteStream, Option<PipelineMetadata>),
}
```

The PR is relatively large, but a decent amount of it is just repetitive
changes.

This PR fixes #7017, fixes #10763, and fixes #12369.

This PR also improves performance when piping external commands. Nushell
should, in most cases, have competitive pipeline throughput compared to,
e.g., bash.
| Command | Before (MB/s) | After (MB/s) | Bash (MB/s) |
| -------------------------------------------------- | -------------:|
------------:| -----------:|
| `throughput \| rg 'x'` | 3059 | 3744 | 3739 |
| `throughput \| nu --testbin relay o> /dev/null` | 3508 | 8087 | 8136 |

# User-Facing Changes
- This is a breaking change for the plugin communication protocol,
because the `ExternalStreamInfo` was replaced with `ByteStreamInfo`.
Plugins now only have to deal with a single input stream, as opposed to
the previous three streams: stdout, stderr, and exit code.
- The output of `describe` has been changed for external/byte streams.
- Temporary breaking change: `bytes starts-with` no longer works with
byte streams. This is to keep the PR smaller, and `bytes ends-with`
already does not work on byte streams.
- If a process core dumped, then instead of having a `Value::Error` in
the `exit_code` column of the output returned from `complete`, it now is
a `Value::Int` with the negation of the signal number.

# After Submitting
- Update docs and book as necessary
- Release notes (e.g., plugin protocol changes)
- Adapt/convert commands to work with byte streams (high priority is
`str length`, `bytes starts-with`, and maybe `bytes ends-with`).
- Refactor the `tee` code, Devyn has already done some work on this.

---------

Co-authored-by: Devyn Cairns <devyn.cairns@gmail.com>
2024-05-16 07:11:18 -07:00

110 lines
3.4 KiB
Rust

use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct ToNuon;
impl Command for ToNuon {
fn name(&self) -> &str {
"to nuon"
}
fn signature(&self) -> Signature {
Signature::build("to nuon")
.input_output_types(vec![(Type::Any, Type::String)])
.switch(
"raw",
"remove all of the whitespace (default behaviour and overwrites -i and -t)",
Some('r'),
)
.named(
"indent",
SyntaxShape::Number,
"specify indentation width",
Some('i'),
)
.named(
"tabs",
SyntaxShape::Number,
"specify indentation tab quantity",
Some('t'),
)
.category(Category::Formats)
}
fn usage(&self) -> &str {
"Converts table data into Nuon (Nushell Object Notation) text."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let style = if call.has_flag(engine_state, stack, "raw")? {
nuon::ToStyle::Raw
} else if let Some(t) = call.get_flag(engine_state, stack, "tabs")? {
nuon::ToStyle::Tabs(t)
} else if let Some(i) = call.get_flag(engine_state, stack, "indent")? {
nuon::ToStyle::Spaces(i)
} else {
nuon::ToStyle::Raw
};
let span = call.head;
let value = input.into_value(span)?;
match nuon::to_nuon(&value, style, Some(span)) {
Ok(serde_nuon_string) => {
Ok(Value::string(serde_nuon_string, span).into_pipeline_data())
}
_ => Ok(Value::error(
ShellError::CantConvert {
to_type: "NUON".into(),
from_type: value.get_type().to_string(),
span,
help: None,
},
span,
)
.into_pipeline_data()),
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Outputs a NUON string representing the contents of this list, compact by default",
example: "[1 2 3] | to nuon",
result: Some(Value::test_string("[1, 2, 3]"))
},
Example {
description: "Outputs a NUON array of ints, with pretty indentation",
example: "[1 2 3] | to nuon --indent 2",
result: Some(Value::test_string("[\n 1,\n 2,\n 3\n]")),
},
Example {
description: "Overwrite any set option with --raw",
example: "[1 2 3] | to nuon --indent 2 --raw",
result: Some(Value::test_string("[1, 2, 3]"))
},
Example {
description: "A more complex record with multiple data types",
example: "{date: 2000-01-01, data: [1 [2 3] 4.56]} | to nuon --indent 2",
result: Some(Value::test_string("{\n date: 2000-01-01T00:00:00+00:00,\n data: [\n 1,\n [\n 2,\n 3\n ],\n 4.56\n ]\n}"))
}
]
}
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::ToNuon;
use crate::test_examples;
test_examples(ToNuon {})
}
}