Merge pull request #657 from jonathandturner/help_and_binary

Help and binary
This commit is contained in:
Jonathan Turner 2019-09-13 07:27:27 +12:00 committed by GitHub
commit ea3b3e42c4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 124 additions and 66 deletions

View file

@ -39,7 +39,7 @@ pub fn autoview(
if input.len() > 0 { if input.len() > 0 {
if let Tagged { if let Tagged {
item: Value::Binary(_), item: Value::Primitive(Primitive::Binary(_)),
.. ..
} = input[0usize] } = input[0usize]
{ {
@ -50,7 +50,7 @@ pub fn autoview(
} else { } else {
for i in input { for i in input {
match i.item { match i.item {
Value::Binary(b) => { Value::Primitive(Primitive::Binary(b)) => {
use pretty_hex::*; use pretty_hex::*;
println!("{:?}", b.hex_dump()); println!("{:?}", b.hex_dump());
} }

View file

@ -186,7 +186,7 @@ pub async fn fetch(
})?; })?;
Ok(( Ok((
None, None,
Value::Binary(buf), Value::Primitive(Primitive::Binary(buf)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -219,7 +219,7 @@ pub async fn fetch(
})?; })?;
Ok(( Ok((
Some(image_ty.to_string()), Some(image_ty.to_string()),
Value::Binary(buf), Value::Primitive(Primitive::Binary(buf)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),

View file

@ -122,7 +122,7 @@ fn convert_bson_value_to_nu_value(
); );
collected.insert_tagged( collected.insert_tagged(
"$binary".to_string(), "$binary".to_string(),
Value::Binary(bytes.to_owned()).tagged(tag), Value::Primitive(Primitive::Binary(bytes.to_owned())).tagged(tag),
); );
collected.into_tagged_value() collected.into_tagged_value()
} }
@ -207,7 +207,7 @@ fn from_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
for value in values { for value in values {
let value_tag = value.tag(); let value_tag = value.tag();
match value.item { match value.item {
Value::Binary(vb) => Value::Primitive(Primitive::Binary(vb)) =>
match from_bson_bytes_to_value(vb, span) { match from_bson_bytes_to_value(vb, span) {
Ok(x) => yield ReturnSuccess::value(x), Ok(x) => yield ReturnSuccess::value(x),
Err(_) => { Err(_) => {

View file

@ -106,7 +106,7 @@ fn convert_sqlite_value_to_nu_value(value: ValueRef, tag: impl Into<Tag> + Clone
// this unwrap is safe because we know the ValueRef is Text. // this unwrap is safe because we know the ValueRef is Text.
Value::Primitive(Primitive::String(t.as_str().unwrap().to_string())).tagged(tag) Value::Primitive(Primitive::String(t.as_str().unwrap().to_string())).tagged(tag)
} }
ValueRef::Blob(u) => Value::Binary(u.to_owned()).tagged(tag), ValueRef::Blob(u) => Value::binary(u.to_owned()).tagged(tag),
} }
} }
@ -137,7 +137,7 @@ fn from_sqlite(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputSt
for value in values { for value in values {
let value_tag = value.tag(); let value_tag = value.tag();
match value.item { match value.item {
Value::Binary(vb) => Value::Primitive(Primitive::Binary(vb)) =>
match from_sqlite_bytes_to_value(vb, span) { match from_sqlite_bytes_to_value(vb, span) {
Ok(x) => match x { Ok(x) => match x {
Tagged { item: Value::Table(list), .. } => { Tagged { item: Value::Table(list), .. } => {

View file

@ -1,8 +1,7 @@
use crate::commands::command::CommandAction;
use crate::commands::PerItemCommand; use crate::commands::PerItemCommand;
use crate::data::{command_dict, TaggedDictBuilder}; use crate::data::{command_dict, TaggedDictBuilder};
use crate::errors::ShellError; use crate::errors::ShellError;
use crate::parser::registry; use crate::parser::registry::{self, NamedType, PositionalType};
use crate::prelude::*; use crate::prelude::*;
pub struct Help; pub struct Help;
@ -29,44 +28,104 @@ impl PerItemCommand for Help {
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let span = call_info.name_span; let span = call_info.name_span;
if call_info.args.len() == 0 { match call_info.args.nth(0) {
return Ok(vec![Ok(ReturnSuccess::Action(CommandAction::EnterHelpShell( Some(Tagged {
Tagged::from_simple_spanned_item(Value::nothing(), span),
)))]
.into());
}
match call_info.args.expect_nth(0)? {
Tagged {
item: Value::Primitive(Primitive::String(document)), item: Value::Primitive(Primitive::String(document)),
tag, tag,
} => { }) => {
let mut help = VecDeque::new();
if document == "commands" { if document == "commands" {
let mut specs = VecDeque::new(); let mut sorted_names = registry.names();
sorted_names.sort();
for cmd in registry.names() { for cmd in sorted_names {
let mut spec = TaggedDictBuilder::new(tag.clone()); let mut short_desc = TaggedDictBuilder::new(tag.clone());
let value = command_dict(registry.get_command(&cmd).unwrap(), tag.clone()); let value = command_dict(registry.get_command(&cmd).unwrap(), tag.clone());
spec.insert("name", cmd); short_desc.insert("name", cmd);
spec.insert( short_desc.insert(
"description", "description",
value.get_data_by_key("usage").unwrap().as_string().unwrap(), value.get_data_by_key("usage").unwrap().as_string().unwrap(),
); );
spec.insert_tagged("details", value);
specs.push_back(ReturnSuccess::value(spec.into_tagged_value())); help.push_back(ReturnSuccess::value(short_desc.into_tagged_value()));
} }
} else {
if let Some(command) = registry.get_command(document) {
let mut long_desc = String::new();
return Ok(specs.to_output_stream()); long_desc.push_str(&command.usage());
long_desc.push_str("\n");
let signature = command.signature();
let mut one_liner = String::new();
one_liner.push_str(&signature.name);
one_liner.push_str(" ");
if signature.named.len() > 0 {
one_liner.push_str("{flags} ");
}
for positional in signature.positional {
match positional {
PositionalType::Mandatory(name, _m) => {
one_liner.push_str(&format!("<{}> ", name));
}
PositionalType::Optional(name, _o) => {
one_liner.push_str(&format!("({}) ", name));
}
}
}
if signature.rest_positional.is_some() {
one_liner.push_str(" ...args");
}
long_desc.push_str(&format!("\nUsage:\n > {}\n", one_liner));
if signature.named.len() > 0 {
long_desc.push_str("\nflags:\n");
for (flag, ty) in signature.named {
match ty {
NamedType::Switch => {
long_desc.push_str(&format!(" --{}\n", flag));
}
NamedType::Mandatory(m) => {
long_desc.push_str(&format!(
" --{} <{}> (required parameter)\n",
flag, m
));
}
NamedType::Optional(o) => {
long_desc.push_str(&format!(" --{} <{}>\n", flag, o));
}
}
}
}
help.push_back(ReturnSuccess::value(
Value::string(long_desc).tagged(tag.clone()),
));
}
} }
Ok(OutputStream::empty()) Ok(help.to_output_stream())
}
_ => {
let msg = r#"Welcome to Nushell.
Here are some tips to help you get started.
* help commands - list all available commands
* help <command name> - display help about a particular command
You can also learn more at http://book.nushell.sh"#;
let mut output_stream = VecDeque::new();
output_stream.push_back(ReturnSuccess::value(
Value::string(msg).simple_spanned(span),
));
Ok(output_stream.to_output_stream())
} }
x => Ok(vec![Ok(ReturnSuccess::Action(CommandAction::EnterHelpShell(
x.clone(),
)))]
.into()),
} }
} }
} }

View file

@ -16,7 +16,7 @@ impl WholeStreamCommand for Nth {
} }
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("nth").required("amount", SyntaxType::Any) Signature::build("nth").required("row number", SyntaxType::Any)
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {

View file

@ -171,7 +171,7 @@ pub async fn fetch(
)), )),
Err(_) => Ok(( Err(_) => Ok((
None, None,
Value::Binary(bytes), Value::Primitive(Primitive::Binary(bytes)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -182,7 +182,7 @@ pub async fn fetch(
} else { } else {
Ok(( Ok((
None, None,
Value::Binary(bytes), Value::Primitive(Primitive::Binary(bytes)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -209,7 +209,7 @@ pub async fn fetch(
)), )),
Err(_) => Ok(( Err(_) => Ok((
None, None,
Value::Binary(bytes), Value::Primitive(Primitive::Binary(bytes)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -220,7 +220,7 @@ pub async fn fetch(
} else { } else {
Ok(( Ok((
None, None,
Value::Binary(bytes), Value::Primitive(Primitive::Binary(bytes)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -231,7 +231,7 @@ pub async fn fetch(
} }
_ => Ok(( _ => Ok((
None, None,
Value::Binary(bytes), Value::Primitive(Primitive::Binary(bytes)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),

View file

@ -167,7 +167,7 @@ pub async fn post(
s.await s.await
} }
Tagged { Tagged {
item: Value::Binary(b), item: Value::Primitive(Primitive::Binary(b)),
.. ..
} => { } => {
let mut s = surf::post(location).body_bytes(b); let mut s = surf::post(location).body_bytes(b);
@ -277,7 +277,7 @@ pub async fn post(
})?; })?;
Ok(( Ok((
None, None,
Value::Binary(buf), Value::Primitive(Primitive::Binary(buf)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),
@ -295,7 +295,7 @@ pub async fn post(
})?; })?;
Ok(( Ok((
Some(image_ty.to_string()), Some(image_ty.to_string()),
Value::Binary(buf), Value::Primitive(Primitive::Binary(buf)),
Tag { Tag {
span, span,
origin: Some(Uuid::new_v4()), origin: Some(Uuid::new_v4()),

View file

@ -60,7 +60,7 @@ macro_rules! process_binary_return_success {
for res in $result_vec { for res in $result_vec {
match res { match res {
Ok(ReturnSuccess::Value(Tagged { Ok(ReturnSuccess::Value(Tagged {
item: Value::Binary(b), item: Value::Primitive(Primitive::Binary(b)),
.. ..
})) => { })) => {
for u in b.into_iter() { for u in b.into_iter() {

View file

@ -58,7 +58,7 @@ pub fn value_to_bson_value(v: &Tagged<Value>) -> Result<Bson, ShellError> {
.collect::<Result<_, _>>()?, .collect::<Result<_, _>>()?,
), ),
Value::Block(_) => Bson::Null, Value::Block(_) => Bson::Null,
Value::Binary(b) => Bson::Binary(BinarySubtype::Generic, b.clone()), Value::Primitive(Primitive::Binary(b)) => Bson::Binary(BinarySubtype::Generic, b.clone()),
Value::Row(o) => object_value_to_bson(o)?, Value::Row(o) => object_value_to_bson(o)?,
}) })
} }
@ -254,7 +254,7 @@ fn to_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream
Ok(bson_value) => { Ok(bson_value) => {
match bson_value_to_bytes(bson_value, name_span) { match bson_value_to_bytes(bson_value, name_span) {
Ok(x) => yield ReturnSuccess::value( Ok(x) => yield ReturnSuccess::value(
Value::Binary(x).simple_spanned(name_span), Value::Primitive(Primitive::Binary(x)).simple_spanned(name_span),
), ),
_ => yield Err(ShellError::labeled_error_with_secondary( _ => yield Err(ShellError::labeled_error_with_secondary(
"Expected a table with BSON-compatible structure.span() from pipeline", "Expected a table with BSON-compatible structure.span() from pipeline",

View file

@ -51,7 +51,7 @@ pub fn value_to_json_value(v: &Tagged<Value>) -> Result<serde_json::Value, Shell
Value::Table(l) => serde_json::Value::Array(json_list(l)?), Value::Table(l) => serde_json::Value::Array(json_list(l)?),
Value::Block(_) => serde_json::Value::Null, Value::Block(_) => serde_json::Value::Null,
Value::Binary(b) => serde_json::Value::Array( Value::Primitive(Primitive::Binary(b)) => serde_json::Value::Array(
b.iter() b.iter()
.map(|x| { .map(|x| {
serde_json::Value::Number(serde_json::Number::from_f64(*x as f64).unwrap()) serde_json::Value::Number(serde_json::Number::from_f64(*x as f64).unwrap())

View file

@ -85,7 +85,6 @@ fn get_columns(rows: &Vec<Tagged<Value>>) -> Result<String, std::io::Error> {
fn nu_value_to_sqlite_string(v: Value) -> String { fn nu_value_to_sqlite_string(v: Value) -> String {
match v { match v {
Value::Binary(u) => format!("x'{}'", encode(u)),
Value::Primitive(p) => match p { Value::Primitive(p) => match p {
Primitive::Nothing => "NULL".into(), Primitive::Nothing => "NULL".into(),
Primitive::Int(i) => format!("{}", i), Primitive::Int(i) => format!("{}", i),
@ -97,6 +96,7 @@ fn nu_value_to_sqlite_string(v: Value) -> String {
Primitive::Boolean(_) => "0".into(), Primitive::Boolean(_) => "0".into(),
Primitive::Date(d) => format!("'{}'", d), Primitive::Date(d) => format!("'{}'", d),
Primitive::Path(p) => format!("'{}'", p.display().to_string().replace("'", "''")), Primitive::Path(p) => format!("'{}'", p.display().to_string().replace("'", "''")),
Primitive::Binary(u) => format!("x'{}'", encode(u)),
Primitive::BeginningOfStream => "NULL".into(), Primitive::BeginningOfStream => "NULL".into(),
Primitive::EndOfStream => "NULL".into(), Primitive::EndOfStream => "NULL".into(),
}, },
@ -195,7 +195,7 @@ fn sqlite_input_stream_to_bytes(
} }
let mut out = Vec::new(); let mut out = Vec::new();
tempfile.read_to_end(&mut out)?; tempfile.read_to_end(&mut out)?;
Ok(Value::Binary(out).tagged(tag)) Ok(Value::binary(out).tagged(tag))
} }
fn to_sqlite(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> { fn to_sqlite(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {

View file

@ -50,7 +50,7 @@ pub fn value_to_toml_value(v: &Tagged<Value>) -> Result<toml::Value, ShellError>
Value::Table(l) => toml::Value::Array(collect_values(l)?), Value::Table(l) => toml::Value::Array(collect_values(l)?),
Value::Block(_) => toml::Value::String("<Block>".to_string()), Value::Block(_) => toml::Value::String("<Block>".to_string()),
Value::Binary(b) => { Value::Primitive(Primitive::Binary(b)) => {
toml::Value::Array(b.iter().map(|x| toml::Value::Integer(*x as i64)).collect()) toml::Value::Array(b.iter().map(|x| toml::Value::Integer(*x as i64)).collect())
} }
Value::Row(o) => { Value::Row(o) => {

View file

@ -56,7 +56,7 @@ pub fn value_to_yaml_value(v: &Tagged<Value>) -> Result<serde_yaml::Value, Shell
serde_yaml::Value::Sequence(out) serde_yaml::Value::Sequence(out)
} }
Value::Block(_) => serde_yaml::Value::Null, Value::Block(_) => serde_yaml::Value::Null,
Value::Binary(b) => serde_yaml::Value::Sequence( Value::Primitive(Primitive::Binary(b)) => serde_yaml::Value::Sequence(
b.iter() b.iter()
.map(|x| serde_yaml::Value::Number(serde_yaml::Number::from(*x))) .map(|x| serde_yaml::Value::Number(serde_yaml::Number::from(*x)))
.collect(), .collect(),

View file

@ -24,6 +24,8 @@ pub enum Primitive {
Boolean(bool), Boolean(bool),
Date(DateTime<Utc>), Date(DateTime<Utc>),
Path(PathBuf), Path(PathBuf),
#[serde(with = "serde_bytes")]
Binary(Vec<u8>),
// Stream markers (used as bookend markers rather than actual values) // Stream markers (used as bookend markers rather than actual values)
BeginningOfStream, BeginningOfStream,
@ -58,6 +60,7 @@ impl Primitive {
String(_) => "string", String(_) => "string",
Boolean(_) => "boolean", Boolean(_) => "boolean",
Date(_) => "date", Date(_) => "date",
Binary(_) => "binary",
} }
.to_string() .to_string()
} }
@ -77,6 +80,7 @@ impl Primitive {
String(string) => write!(f, "{:?}", string), String(string) => write!(f, "{:?}", string),
Boolean(boolean) => write!(f, "{}", boolean), Boolean(boolean) => write!(f, "{}", boolean),
Date(date) => write!(f, "{}", date), Date(date) => write!(f, "{}", date),
Binary(binary) => write!(f, "{:?}", binary),
} }
} }
@ -121,6 +125,7 @@ impl Primitive {
(true, Some(_)) => format!("Yes"), (true, Some(_)) => format!("Yes"),
(false, Some(_)) => format!("No"), (false, Some(_)) => format!("No"),
}, },
Primitive::Binary(_) => format!("<binary>"),
Primitive::Date(d) => format!("{}", d.humanize()), Primitive::Date(d) => format!("{}", d.humanize()),
} }
} }
@ -175,8 +180,6 @@ impl Block {
pub enum Value { pub enum Value {
Primitive(Primitive), Primitive(Primitive),
Row(crate::data::Dictionary), Row(crate::data::Dictionary),
#[serde(with = "serde_bytes")]
Binary(Vec<u8>),
Table(Vec<Tagged<Value>>), Table(Vec<Tagged<Value>>),
Block(Block), Block(Block),
@ -227,7 +230,6 @@ impl fmt::Debug for ValueDebug<'_> {
Value::Row(o) => o.debug(f), Value::Row(o) => o.debug(f),
Value::Table(l) => debug_list(l).fmt(f), Value::Table(l) => debug_list(l).fmt(f),
Value::Block(_) => write!(f, "[[block]]"), Value::Block(_) => write!(f, "[[block]]"),
Value::Binary(_) => write!(f, "[[binary]]"),
} }
} }
} }
@ -288,7 +290,7 @@ impl std::convert::TryFrom<&Tagged<Value>> for Vec<u8> {
fn try_from(value: &Tagged<Value>) -> Result<Vec<u8>, ShellError> { fn try_from(value: &Tagged<Value>) -> Result<Vec<u8>, ShellError> {
match value.item() { match value.item() {
Value::Binary(b) => Ok(b.clone()), Value::Primitive(Primitive::Binary(b)) => Ok(b.clone()),
v => Err(ShellError::type_error( v => Err(ShellError::type_error(
"Binary", "Binary",
value.copy_span(v.type_name()), value.copy_span(v.type_name()),
@ -347,7 +349,6 @@ impl Value {
Value::Row(_) => format!("object"), Value::Row(_) => format!("object"),
Value::Table(_) => format!("list"), Value::Table(_) => format!("list"),
Value::Block(_) => format!("block"), Value::Block(_) => format!("block"),
Value::Binary(_) => format!("binary"),
} }
} }
@ -363,7 +364,6 @@ impl Value {
.collect(), .collect(),
Value::Block(_) => vec![], Value::Block(_) => vec![],
Value::Table(_) => vec![], Value::Table(_) => vec![],
Value::Binary(_) => vec![],
} }
} }
@ -495,7 +495,6 @@ impl Value {
Value::Row(o) => o.get_data(desc), Value::Row(o) => o.get_data(desc),
Value::Block(_) => MaybeOwned::Owned(Value::nothing()), Value::Block(_) => MaybeOwned::Owned(Value::nothing()),
Value::Table(_) => MaybeOwned::Owned(Value::nothing()), Value::Table(_) => MaybeOwned::Owned(Value::nothing()),
Value::Binary(_) => MaybeOwned::Owned(Value::nothing()),
} }
} }
@ -514,7 +513,6 @@ impl Value {
l.len(), l.len(),
if l.len() == 1 { "row" } else { "rows" } if l.len() == 1 { "row" } else { "rows" }
), ),
Value::Binary(_) => format!("<binary>"),
} }
} }
@ -602,6 +600,10 @@ impl Value {
Value::Primitive(Primitive::Decimal(s.into())) Value::Primitive(Primitive::Decimal(s.into()))
} }
pub fn binary(binary: Vec<u8>) -> Value {
Value::Primitive(Primitive::Binary(binary))
}
pub fn number(s: impl Into<Number>) -> Value { pub fn number(s: impl Into<Number>) -> Value {
let num = s.into(); let num = s.into();

View file

@ -35,11 +35,6 @@ impl RenderView for GenericView<'_> {
view.render_view(host)?; view.render_view(host)?;
Ok(()) Ok(())
} }
Value::Binary(_) => {
host.stdout("<Binary>");
Ok(())
}
} }
} }
} }

View file

@ -1,5 +1,7 @@
use crossterm::{cursor, terminal, Attribute, RawScreen}; use crossterm::{cursor, terminal, Attribute, RawScreen};
use nu::{serve_plugin, CallInfo, Plugin, ShellError, Signature, SpanSource, Tagged, Value}; use nu::{
serve_plugin, CallInfo, Plugin, Primitive, ShellError, Signature, SpanSource, Tagged, Value,
};
use pretty_hex::*; use pretty_hex::*;
struct BinaryView; struct BinaryView;
@ -21,7 +23,7 @@ impl Plugin for BinaryView {
for v in input { for v in input {
let value_origin = v.origin(); let value_origin = v.origin();
match v.item { match v.item {
Value::Binary(b) => { Value::Primitive(Primitive::Binary(b)) => {
let source = value_origin.and_then(|x| call_info.source_map.get(&x)); let source = value_origin.and_then(|x| call_info.source_map.get(&x));
let _ = view_binary(&b, source, call_info.args.has("lores")); let _ = view_binary(&b, source, call_info.args.has("lores"));
} }