nushell/src/commands/post.rs

434 lines
17 KiB
Rust
Raw Normal View History

2019-08-31 06:08:59 +02:00
use crate::commands::UnevaluatedCallInfo;
2019-09-29 07:18:59 +02:00
use crate::context::AnchorLocation;
use crate::data::Value;
use crate::errors::ShellError;
use crate::parser::hir::SyntaxShape;
2019-08-30 20:27:15 +02:00
use crate::parser::registry::Signature;
use crate::prelude::*;
use base64::encode;
use mime::Mime;
2019-08-31 06:08:59 +02:00
use std::path::PathBuf;
2019-08-30 20:27:15 +02:00
use std::str::FromStr;
use surf::mime;
2019-09-29 04:03:10 +02:00
pub enum HeaderKind {
ContentType(String),
ContentLength(String),
}
2019-08-30 20:27:15 +02:00
pub struct Post;
impl PerItemCommand for Post {
fn name(&self) -> &str {
"post"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.required("path", SyntaxShape::Any)
.required("body", SyntaxShape::Any)
.named("user", SyntaxShape::Any)
.named("password", SyntaxShape::Any)
2019-09-29 04:03:10 +02:00
.named("content-type", SyntaxShape::Any)
.named("content-length", SyntaxShape::Any)
2019-08-30 20:27:15 +02:00
.switch("raw")
}
fn usage(&self) -> &str {
"Post content to a url and retrieve data as a table if possible."
}
2019-08-30 20:27:15 +02:00
fn run(
&self,
call_info: &CallInfo,
2019-08-31 06:08:59 +02:00
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
2019-08-30 20:27:15 +02:00
_input: Tagged<Value>,
) -> Result<OutputStream, ShellError> {
2019-08-31 06:08:59 +02:00
run(call_info, registry, raw_args)
2019-08-30 20:27:15 +02:00
}
}
2019-08-31 06:08:59 +02:00
fn run(
call_info: &CallInfo,
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
) -> Result<OutputStream, ShellError> {
let call_info = call_info.clone();
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
let path = match call_info.args.nth(0).ok_or_else(|| {
ShellError::labeled_error("No url specified", "for command", call_info.name_tag)
})? {
2019-08-31 06:08:59 +02:00
file => file.clone(),
2019-08-30 20:27:15 +02:00
};
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
let body = match call_info.args.nth(1).ok_or_else(|| {
ShellError::labeled_error("No body specified", "for command", call_info.name_tag)
})? {
2019-08-31 06:08:59 +02:00
file => file.clone(),
2019-08-30 20:27:15 +02:00
};
let path_str = path.as_string()?;
let path_span = path.tag();
2019-08-30 20:27:15 +02:00
let has_raw = call_info.args.has("raw");
let user = call_info.args.get("user").map(|x| x.as_string().unwrap());
let password = call_info
.args
.get("password")
.map(|x| x.as_string().unwrap());
2019-08-31 06:08:59 +02:00
let registry = registry.clone();
let raw_args = raw_args.clone();
2019-08-30 20:27:15 +02:00
let headers = get_headers(&call_info)?;
2019-09-29 04:03:10 +02:00
let stream = async_stream! {
2019-09-29 07:18:59 +02:00
let (file_extension, contents, contents_tag, anchor_location) =
2019-09-29 04:03:10 +02:00
post(&path_str, &body, user, password, &headers, path_span, &registry, &raw_args).await.unwrap();
2019-08-31 06:08:59 +02:00
let file_extension = if has_raw {
None
} else {
// If the extension could not be determined via mimetype, try to use the path
// extension. Some file types do not declare their mimetypes (such as bson files).
file_extension.or(path_str.split('.').last().map(String::from))
};
2019-09-29 07:13:56 +02:00
if contents_tag.anchor != uuid::Uuid::nil() {
2019-08-31 06:08:59 +02:00
// If we have loaded something, track its source
2019-09-29 07:18:59 +02:00
yield ReturnSuccess::action(CommandAction::AddAnchorLocation(
2019-09-29 07:13:56 +02:00
contents_tag.anchor,
2019-09-29 07:18:59 +02:00
anchor_location,
2019-08-31 06:08:59 +02:00
));
}
2019-08-30 20:27:15 +02:00
2019-08-31 06:08:59 +02:00
let tagged_contents = contents.tagged(contents_tag);
2019-08-30 20:27:15 +02:00
2019-08-31 06:08:59 +02:00
if let Some(extension) = file_extension {
let command_name = format!("from-{}", extension);
if let Some(converter) = registry.get_command(&command_name) {
let new_args = RawCommandArgs {
host: raw_args.host,
shell_manager: raw_args.shell_manager,
call_info: UnevaluatedCallInfo {
args: crate::parser::hir::Call {
head: raw_args.call_info.args.head,
positional: None,
named: None
},
source: raw_args.call_info.source,
source_map: raw_args.call_info.source_map,
name_tag: raw_args.call_info.name_tag,
2019-08-31 06:08:59 +02:00
}
};
2019-09-17 04:09:15 +02:00
let mut result = converter.run(new_args.with_input(vec![tagged_contents]), &registry, false);
2019-08-31 06:08:59 +02:00
let result_vec: Vec<Result<ReturnSuccess, ShellError>> = result.drain_vec().await;
for res in result_vec {
match res {
Ok(ReturnSuccess::Value(Tagged { item: Value::Table(list), ..})) => {
2019-08-31 06:08:59 +02:00
for l in list {
yield Ok(ReturnSuccess::Value(l));
}
}
Ok(ReturnSuccess::Value(Tagged { item, .. })) => {
yield Ok(ReturnSuccess::Value(Tagged { item, tag: contents_tag }));
2019-08-31 06:08:59 +02:00
}
x => yield x,
}
}
} else {
yield ReturnSuccess::value(tagged_contents);
}
} else {
yield ReturnSuccess::value(tagged_contents);
}
2019-08-30 20:27:15 +02:00
};
Ok(stream.to_output_stream())
}
fn get_headers(call_info: &CallInfo) -> Result<Vec<HeaderKind>, ShellError> {
let mut headers = vec![];
match extract_header_value(&call_info, "content-type") {
Ok(h) => match h {
Some(ct) => headers.push(HeaderKind::ContentType(ct)),
None => {}
},
Err(e) => {
return Err(e);
}
};
match extract_header_value(&call_info, "content-length") {
Ok(h) => match h {
Some(cl) => headers.push(HeaderKind::ContentLength(cl)),
None => {}
},
Err(e) => {
return Err(e);
}
};
Ok(headers)
}
fn extract_header_value(call_info: &CallInfo, key: &str) -> Result<Option<String>, ShellError> {
if call_info.args.has(key) {
let tagged = call_info.args.get(key);
let val = match tagged {
Some(Tagged {
item: Value::Primitive(Primitive::String(s)),
..
}) => s.clone(),
Some(Tagged { tag, .. }) => {
return Err(ShellError::labeled_error(
format!("{} not in expected format. Expected string.", key),
"post error",
tag,
));
}
_ => {
return Err(ShellError::labeled_error(
format!("{} not in expected format. Expected string.", key),
"post error",
Tag::unknown(),
));
}
};
return Ok(Some(val));
}
Ok(None)
}
2019-08-30 20:27:15 +02:00
pub async fn post(
location: &str,
2019-08-31 06:08:59 +02:00
body: &Tagged<Value>,
2019-08-30 20:27:15 +02:00
user: Option<String>,
password: Option<String>,
2019-09-29 04:03:10 +02:00
headers: &Vec<HeaderKind>,
tag: Tag,
2019-08-31 06:08:59 +02:00
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
2019-09-29 07:18:59 +02:00
) -> Result<(Option<String>, Value, Tag, AnchorLocation), ShellError> {
2019-08-31 06:08:59 +02:00
let registry = registry.clone();
let raw_args = raw_args.clone();
2019-08-30 20:27:15 +02:00
if location.starts_with("http:") || location.starts_with("https:") {
2019-09-01 08:44:56 +02:00
let login = match (user, password) {
(Some(user), Some(password)) => Some(encode(&format!("{}:{}", user, password))),
(Some(user), _) => Some(encode(&format!("{}:", user))),
_ => None,
};
2019-08-31 06:08:59 +02:00
let response = match body {
Tagged {
item: Value::Primitive(Primitive::String(body_str)),
..
} => {
2019-09-01 08:44:56 +02:00
let mut s = surf::post(location).body_string(body_str.to_string());
if let Some(login) = login {
s = s.set_header("Authorization", format!("Basic {}", login));
}
2019-09-29 04:03:10 +02:00
for h in headers {
s = match h {
HeaderKind::ContentType(ct) => s.set_header("Content-Type", ct),
HeaderKind::ContentLength(cl) => s.set_header("Content-Length", cl),
};
}
2019-09-01 08:44:56 +02:00
s.await
2019-08-31 06:08:59 +02:00
}
Tagged {
item: Value::Primitive(Primitive::Binary(b)),
2019-08-31 06:08:59 +02:00
..
} => {
2019-09-01 08:44:56 +02:00
let mut s = surf::post(location).body_bytes(b);
if let Some(login) = login {
s = s.set_header("Authorization", format!("Basic {}", login));
}
s.await
2019-08-31 06:08:59 +02:00
}
Tagged { item, tag } => {
if let Some(converter) = registry.get_command("to-json") {
let new_args = RawCommandArgs {
host: raw_args.host,
shell_manager: raw_args.shell_manager,
call_info: UnevaluatedCallInfo {
args: crate::parser::hir::Call {
head: raw_args.call_info.args.head,
positional: None,
named: None,
},
source: raw_args.call_info.source,
source_map: raw_args.call_info.source_map,
name_tag: raw_args.call_info.name_tag,
2019-08-31 06:08:59 +02:00
},
};
let mut result = converter.run(
new_args.with_input(vec![item.clone().tagged(tag.clone())]),
&registry,
2019-09-17 04:09:15 +02:00
false,
2019-08-31 06:08:59 +02:00
);
let result_vec: Vec<Result<ReturnSuccess, ShellError>> =
result.drain_vec().await;
let mut result_string = String::new();
for res in result_vec {
match res {
Ok(ReturnSuccess::Value(Tagged {
item: Value::Primitive(Primitive::String(s)),
..
})) => {
result_string.push_str(&s);
}
_ => {
return Err(ShellError::labeled_error(
"Save could not successfully save",
"unexpected data during save",
*tag,
2019-08-31 06:08:59 +02:00
));
}
}
}
2019-09-01 08:44:56 +02:00
let mut s = surf::post(location).body_string(result_string);
if let Some(login) = login {
s = s.set_header("Authorization", format!("Basic {}", login));
}
s.await
2019-08-31 06:08:59 +02:00
} else {
return Err(ShellError::labeled_error(
"Could not automatically convert table",
"needs manual conversion",
*tag,
2019-08-31 06:08:59 +02:00
));
}
}
};
2019-08-30 20:27:15 +02:00
match response {
Ok(mut r) => match r.headers().get("content-type") {
Some(content_type) => {
let content_type = Mime::from_str(content_type).unwrap();
match (content_type.type_(), content_type.subtype()) {
(mime::APPLICATION, mime::XML) => Ok((
Some("xml".to_string()),
Value::string(r.body_string().await.map_err(|_| {
ShellError::labeled_error(
"Could not load text from remote url",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
)),
(mime::APPLICATION, mime::JSON) => Ok((
Some("json".to_string()),
Value::string(r.body_string().await.map_err(|_| {
ShellError::labeled_error(
"Could not load text from remote url",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
)),
(mime::APPLICATION, mime::OCTET_STREAM) => {
let buf: Vec<u8> = r.body_bytes().await.map_err(|_| {
ShellError::labeled_error(
"Could not load binary file",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?;
Ok((
None,
Value::binary(buf),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
))
}
(mime::IMAGE, image_ty) => {
let buf: Vec<u8> = r.body_bytes().await.map_err(|_| {
ShellError::labeled_error(
"Could not load image file",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?;
Ok((
Some(image_ty.to_string()),
Value::binary(buf),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
))
}
(mime::TEXT, mime::HTML) => Ok((
Some("html".to_string()),
Value::string(r.body_string().await.map_err(|_| {
ShellError::labeled_error(
"Could not load text from remote url",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
)),
(mime::TEXT, mime::PLAIN) => {
let path_extension = url::Url::parse(location)
.unwrap()
.path_segments()
.and_then(|segments| segments.last())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.and_then(|name| {
PathBuf::from(name)
.extension()
.map(|name| name.to_string_lossy().to_string())
});
Ok((
path_extension,
Value::string(r.body_string().await.map_err(|_| {
ShellError::labeled_error(
"Could not load text from remote url",
"could not load",
tag,
2019-08-30 20:27:15 +02:00
)
})?),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
))
}
(ty, sub_ty) => Ok((
None,
Value::string(format!(
"Not yet supported MIME type: {} {}",
ty, sub_ty
)),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
)),
}
}
None => Ok((
None,
Value::string(format!("No content type found")),
tag,
2019-09-29 07:18:59 +02:00
AnchorLocation::Url(location.to_string()),
2019-08-30 20:27:15 +02:00
)),
},
Err(_) => {
return Err(ShellError::labeled_error(
"URL could not be opened",
"url not found",
tag,
2019-08-30 20:27:15 +02:00
));
}
}
} else {
Err(ShellError::labeled_error(
"Expected a url",
"needs a url",
tag,
2019-08-30 20:27:15 +02:00
))
}
}