nushell/src/commands/autoview.rs

233 lines
10 KiB
Rust
Raw Normal View History

2019-08-15 07:02:02 +02:00
use crate::commands::{RawCommandArgs, WholeStreamCommand};
2019-06-07 09:50:26 +02:00
use crate::prelude::*;
use futures::stream::TryStreamExt;
2019-11-30 01:21:05 +01:00
use nu_errors::ShellError;
use nu_parser::hir::{Expression, NamedArguments};
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
use std::sync::atomic::Ordering;
2019-06-07 09:50:26 +02:00
2019-08-02 21:15:07 +02:00
pub struct Autoview;
const STREAM_PAGE_SIZE: u64 = 50;
2019-08-03 04:17:28 +02:00
#[derive(Deserialize)]
pub struct AutoviewArgs {}
2019-08-15 07:02:02 +02:00
impl WholeStreamCommand for Autoview {
2019-08-02 21:15:07 +02:00
fn name(&self) -> &str {
"autoview"
}
fn signature(&self) -> Signature {
Signature::build("autoview")
}
fn usage(&self) -> &str {
"View the contents of the pipeline as a table or list."
}
2019-08-02 21:15:07 +02:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
Ok(args.process_raw(registry, autoview)?.run())
2019-08-02 21:15:07 +02:00
}
}
2019-08-03 04:17:28 +02:00
pub fn autoview(
AutoviewArgs {}: AutoviewArgs,
context: RunnableContext,
2019-08-03 04:17:28 +02:00
raw: RawCommandArgs,
) -> Result<OutputStream, ShellError> {
let binary = context.get_command("binaryview");
let text = context.get_command("textview");
let table = context.get_command("table");
2019-09-28 02:05:18 +02:00
Ok(OutputStream::new(async_stream! {
let mut output_stream: OutputStream = context.input.into();
2019-11-04 16:47:03 +01:00
let next = output_stream.try_next().await;
match next {
Ok(Some(x)) => {
match output_stream.try_next().await {
Ok(Some(y)) => {
let ctrl_c = context.ctrl_c.clone();
let stream = async_stream! {
yield Ok(x);
yield Ok(y);
loop {
match output_stream.try_next().await {
Ok(Some(z)) => {
if ctrl_c.load(Ordering::SeqCst) {
break;
}
yield Ok(z);
}
_ => break,
}
}
};
if let Some(table) = table {
let mut new_output_stream: OutputStream = stream.to_output_stream();
let mut finished = false;
let mut current_idx = 0;
loop {
let mut new_input = VecDeque::new();
for _ in 0..STREAM_PAGE_SIZE {
match new_output_stream.try_next().await {
Ok(Some(a)) => {
if let ReturnSuccess::Value(v) = a {
new_input.push_back(v);
}
}
_ => {
finished = true;
break;
}
}
}
let raw = raw.clone();
let input: Vec<Value> = new_input.into();
2019-11-04 16:47:03 +01:00
if input.len() > 0 && input.iter().all(|value| value.value.is_error()) {
2019-11-04 16:47:03 +01:00
let first = &input[0];
let mut host = context.host.clone();
let mut host = match host.lock() {
Err(err) => {
errln!("Unexpected error acquiring host lock: {:?}", err);
return;
}
Ok(val) => val
};
crate::cli::print_err(first.value.expect_error(), &*host, &context.source);
2019-11-04 16:47:03 +01:00
return;
}
let mut command_args = raw.with_input(input);
let mut named_args = NamedArguments::new();
named_args.insert_optional("start_number", Some(Expression::number(current_idx, Tag::unknown())));
command_args.call_info.args.named = Some(named_args);
let result = table.run(command_args, &context.commands);
result.collect::<Vec<_>>().await;
2019-11-04 16:47:03 +01:00
if finished {
break;
} else {
current_idx += STREAM_PAGE_SIZE;
}
Overhaul the coloring system This commit replaces the previous naive coloring system with a coloring system that is more aligned with the parser. The main benefit of this change is that it allows us to use parsing rules to decide how to color tokens. For example, consider the following syntax: ``` $ ps | where cpu > 10 ``` Ideally, we could color `cpu` like a column name and not a string, because `cpu > 10` is a shorthand block syntax that expands to `{ $it.cpu > 10 }`. The way that we know that it's a shorthand block is that the `where` command declares that its first parameter is a `SyntaxShape::Block`, which allows the shorthand block form. In order to accomplish this, we need to color the tokens in a way that corresponds to their expanded semantics, which means that high-fidelity coloring requires expansion. This commit adds a `ColorSyntax` trait that corresponds to the `ExpandExpression` trait. The semantics are fairly similar, with a few differences. First `ExpandExpression` consumes N tokens and returns a single `hir::Expression`. `ColorSyntax` consumes N tokens and writes M `FlatShape` tokens to the output. Concretely, for syntax like `[1 2 3]` - `ExpandExpression` takes a single token node and produces a single `hir::Expression` - `ColorSyntax` takes the same token node and emits 7 `FlatShape`s (open delimiter, int, whitespace, int, whitespace, int, close delimiter) Second, `ColorSyntax` is more willing to plow through failures than `ExpandExpression`. In particular, consider syntax like ``` $ ps | where cpu > ``` In this case - `ExpandExpression` will see that the `where` command is expecting a block, see that it's not a literal block and try to parse it as a shorthand block. It will successfully find a member followed by an infix operator, but not a following expression. That means that the entire pipeline part fails to parse and is a syntax error. - `ColorSyntax` will also try to parse it as a shorthand block and ultimately fail, but it will fall back to "backoff coloring mode", which parsing any unidentified tokens in an unfallible, simple way. In this case, `cpu` will color as a string and `>` will color as an operator. Finally, it's very important that coloring a pipeline infallibly colors the entire string, doesn't fail, and doesn't get stuck in an infinite loop. In order to accomplish this, this PR separates `ColorSyntax`, which is infallible from `FallibleColorSyntax`, which might fail. This allows the type system to let us know if our coloring rules bottom out at at an infallible rule. It's not perfect: it's still possible for the coloring process to get stuck or consume tokens non-atomically. I intend to reduce the opportunity for those problems in a future commit. In the meantime, the current system catches a number of mistakes (like trying to use a fallible coloring rule in a loop without thinking about the possibility that it will never terminate).
2019-10-06 22:22:50 +02:00
}
}
}
_ => {
if let ReturnSuccess::Value(x) = x {
match x {
Value {
value: UntaggedValue::Primitive(Primitive::String(ref s)),
tag: Tag { anchor, span },
} if anchor.is_some() => {
if let Some(text) = text {
let mut stream = VecDeque::new();
stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span }));
let result = text.run(raw.with_input(stream.into()), &context.commands);
result.collect::<Vec<_>>().await;
} else {
2019-11-04 16:47:03 +01:00
outln!("{}", s);
}
}
Value {
value: UntaggedValue::Primitive(Primitive::String(s)),
..
} => {
2019-11-04 16:47:03 +01:00
outln!("{}", s);
}
Value {
value: UntaggedValue::Primitive(Primitive::Line(ref s)),
tag: Tag { anchor, span },
} if anchor.is_some() => {
if let Some(text) = text {
let mut stream = VecDeque::new();
stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span }));
let result = text.run(raw.with_input(stream.into()), &context.commands);
result.collect::<Vec<_>>().await;
} else {
outln!("{}\n", s);
}
}
Value {
value: UntaggedValue::Primitive(Primitive::Line(s)),
..
} => {
outln!("{}\n", s);
}
Value {
value: UntaggedValue::Primitive(Primitive::Path(s)),
..
} => {
outln!("{}", s.display());
}
Value {
value: UntaggedValue::Primitive(Primitive::Int(n)),
..
} => {
outln!("{}", n);
}
Value {
value: UntaggedValue::Primitive(Primitive::Decimal(n)),
..
} => {
outln!("{}", n);
}
Value { value: UntaggedValue::Primitive(Primitive::Binary(ref b)), .. } => {
if let Some(binary) = binary {
let mut stream = VecDeque::new();
stream.push_back(x);
let result = binary.run(raw.with_input(stream.into()), &context.commands);
result.collect::<Vec<_>>().await;
} else {
use pretty_hex::*;
2019-11-04 16:47:03 +01:00
outln!("{:?}", b.hex_dump());
}
}
Value { value: UntaggedValue::Error(e), .. } => {
yield Err(e);
}
Value { value: ref item, .. } => {
if let Some(table) = table {
let mut stream = VecDeque::new();
stream.push_back(x);
let result = table.run(raw.with_input(stream.into()), &context.commands);
result.collect::<Vec<_>>().await;
} else {
2019-11-04 16:47:03 +01:00
outln!("{:?}", item);
}
}
}
2019-09-08 03:35:02 +02:00
}
}
}
}
_ => {
2019-11-04 16:47:03 +01:00
//outln!("<no results>");
2019-06-07 09:50:26 +02:00
}
}
2019-09-28 02:05:18 +02:00
// Needed for async_stream to type check
if false {
yield ReturnSuccess::value(UntaggedValue::nothing().into_untagged_value());
2019-09-28 02:05:18 +02:00
}
2019-08-06 18:26:33 +02:00
}))
2019-06-07 09:50:26 +02:00
}