Improve help and make binary a primitive

This commit is contained in:
Jonathan Turner
2019-09-13 06:29:16 +12:00
parent 53cfa09cd2
commit 189877e4dd
17 changed files with 140 additions and 70 deletions

View File

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

View File

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

View File

@ -1,6 +1,6 @@
use crate::commands::WholeStreamCommand;
use crate::errors::ExpectedRange;
use crate::data::{Primitive, TaggedDictBuilder, Value};
use crate::errors::ExpectedRange;
use crate::prelude::*;
use bson::{decode_document, spec::BinarySubtype, Bson};
use std::str::FromStr;
@ -122,7 +122,7 @@ fn convert_bson_value_to_nu_value(
);
collected.insert_tagged(
"$binary".to_string(),
Value::Binary(bytes.to_owned()).tagged(tag),
Value::Primitive(Primitive::Binary(bytes.to_owned())).tagged(tag),
);
collected.into_tagged_value()
}
@ -207,7 +207,7 @@ fn from_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
for value in values {
let value_tag = value.tag();
match value.item {
Value::Binary(vb) =>
Value::Primitive(Primitive::Binary(vb)) =>
match from_bson_bytes_to_value(vb, span) {
Ok(x) => yield ReturnSuccess::value(x),
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.
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 {
let value_tag = value.tag();
match value.item {
Value::Binary(vb) =>
Value::Primitive(Primitive::Binary(vb)) =>
match from_sqlite_bytes_to_value(vb, span) {
Ok(x) => match x {
Tagged { item: Value::Table(list), .. } => {

View File

@ -1,8 +1,7 @@
use crate::commands::command::CommandAction;
use crate::commands::PerItemCommand;
use crate::errors::ShellError;
use crate::data::{command_dict, TaggedDictBuilder};
use crate::parser::registry;
use crate::errors::ShellError;
use crate::parser::registry::{self, NamedType, PositionalType};
use crate::prelude::*;
pub struct Help;
@ -29,44 +28,116 @@ impl PerItemCommand for Help {
) -> Result<OutputStream, ShellError> {
let span = call_info.name_span;
if call_info.args.len() == 0 {
return Ok(vec![Ok(ReturnSuccess::Action(CommandAction::EnterHelpShell(
Tagged::from_simple_spanned_item(Value::nothing(), span),
)))]
.into());
}
match call_info.args.expect_nth(0)? {
Tagged {
match call_info.args.nth(0) {
Some(Tagged {
item: Value::Primitive(Primitive::String(document)),
tag,
} => {
}) => {
let mut help = VecDeque::new();
if document == "commands" {
let mut specs = VecDeque::new();
for cmd in registry.names() {
let mut spec = TaggedDictBuilder::new(tag.clone());
let mut sorted_names = registry.names();
sorted_names.sort();
for cmd in sorted_names {
let mut short_desc = TaggedDictBuilder::new(tag.clone());
let value = command_dict(registry.get_command(&cmd).unwrap(), tag.clone());
spec.insert("name", cmd);
spec.insert(
short_desc.insert("name", cmd);
short_desc.insert(
"description",
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));
}
}
}
}
// pub struct Signature {
// pub name: String,
// #[new(default)]
// pub usage: String,
// #[new(default)]
// pub positional: Vec<PositionalType>,
// #[new(value = "None")]
// pub rest_positional: Option<SyntaxType>,
// #[new(default)]
// pub named: IndexMap<String, NamedType>,
// #[new(value = "false")]
// pub is_filter: bool,
// }
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 {
Signature::build("nth").required("amount", SyntaxType::Any)
Signature::build("nth").required("row number", SyntaxType::Any)
}
fn usage(&self) -> &str {

View File

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

View File

@ -1,7 +1,7 @@
use crate::commands::UnevaluatedCallInfo;
use crate::context::SpanSource;
use crate::errors::ShellError;
use crate::data::Value;
use crate::errors::ShellError;
use crate::parser::hir::SyntaxType;
use crate::parser::registry::Signature;
use crate::prelude::*;
@ -167,7 +167,7 @@ pub async fn post(
s.await
}
Tagged {
item: Value::Binary(b),
item: Value::Primitive(Primitive::Binary(b)),
..
} => {
let mut s = surf::post(location).body_bytes(b);
@ -277,7 +277,7 @@ pub async fn post(
})?;
Ok((
None,
Value::Binary(buf),
Value::Primitive(Primitive::Binary(buf)),
Tag {
span,
origin: Some(Uuid::new_v4()),
@ -295,7 +295,7 @@ pub async fn post(
})?;
Ok((
Some(image_ty.to_string()),
Value::Binary(buf),
Value::Primitive(Primitive::Binary(buf)),
Tag {
span,
origin: Some(Uuid::new_v4()),

View File

@ -1,6 +1,6 @@
use crate::commands::{UnevaluatedCallInfo, WholeStreamCommand};
use crate::errors::ShellError;
use crate::data::Value;
use crate::errors::ShellError;
use crate::prelude::*;
use std::path::{Path, PathBuf};
@ -60,7 +60,7 @@ macro_rules! process_binary_return_success {
for res in $result_vec {
match res {
Ok(ReturnSuccess::Value(Tagged {
item: Value::Binary(b),
item: Value::Primitive(Primitive::Binary(b)),
..
})) => {
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<_, _>>()?,
),
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)?,
})
}
@ -254,7 +254,7 @@ fn to_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream
Ok(bson_value) => {
match bson_value_to_bytes(bson_value, name_span) {
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(
"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::Block(_) => serde_json::Value::Null,
Value::Binary(b) => serde_json::Value::Array(
Value::Primitive(Primitive::Binary(b)) => serde_json::Value::Array(
b.iter()
.map(|x| {
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 {
match v {
Value::Binary(u) => format!("x'{}'", encode(u)),
Value::Primitive(p) => match p {
Primitive::Nothing => "NULL".into(),
Primitive::Int(i) => format!("{}", i),
@ -97,6 +96,7 @@ fn nu_value_to_sqlite_string(v: Value) -> String {
Primitive::Boolean(_) => "0".into(),
Primitive::Date(d) => format!("'{}'", d),
Primitive::Path(p) => format!("'{}'", p.display().to_string().replace("'", "''")),
Primitive::Binary(u) => format!("x'{}'", encode(u)),
Primitive::BeginningOfStream => "NULL".into(),
Primitive::EndOfStream => "NULL".into(),
},
@ -195,7 +195,7 @@ fn sqlite_input_stream_to_bytes(
}
let mut out = Vec::new();
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> {

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::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())
}
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)
}
Value::Block(_) => serde_yaml::Value::Null,
Value::Binary(b) => serde_yaml::Value::Sequence(
Value::Primitive(Primitive::Binary(b)) => serde_yaml::Value::Sequence(
b.iter()
.map(|x| serde_yaml::Value::Number(serde_yaml::Number::from(*x)))
.collect(),