added as_html switch so a selector can be passed to a selector (#2739)

This commit is contained in:
Darren Schroeder 2020-11-09 13:37:32 -06:00 committed by GitHub
parent 8df748463d
commit 3924e9d50a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 10 deletions

View File

@ -12,6 +12,7 @@ impl Plugin for Selector {
Ok(Signature::build("selector")
.desc("execute selector query on html/web")
.required("query", SyntaxShape::String, "selector query")
.switch("as_html", "return the query output as html", Some('a'))
.filter())
}
@ -27,6 +28,7 @@ impl Plugin for Selector {
self.query = query.as_string()?;
self.tag = tag;
self.as_html = call_info.args.has("as_html");
Ok(vec![])
}
@ -36,10 +38,12 @@ impl Plugin for Selector {
Value {
value: UntaggedValue::Primitive(Primitive::String(s)),
..
} => Ok(begin_selector_query(s, (*self.query).tagged(&self.tag))?
.into_iter()
.map(ReturnSuccess::value)
.collect()),
} => Ok(
begin_selector_query(s, (*self.query).tagged(&self.tag), self.as_html)?
.into_iter()
.map(ReturnSuccess::value)
.collect(),
),
Value { tag, .. } => Err(ShellError::labeled_error_with_secondary(
"Expected text from pipeline",
"requires text input",

View File

@ -6,6 +6,7 @@ use nu_source::{Tag, Tagged};
pub struct Selector {
pub query: String,
pub tag: Tag,
pub as_html: bool,
}
impl Selector {
@ -13,6 +14,7 @@ impl Selector {
Selector {
query: String::new(),
tag: Tag::unknown(),
as_html: false,
}
}
}
@ -23,14 +25,19 @@ impl Default for Selector {
}
}
pub fn begin_selector_query(raw: String, query: Tagged<&str>) -> Result<Vec<Value>, ShellError> {
execute_selector_query(raw, query.item.to_string(), query.tag())
pub fn begin_selector_query(
input: String,
query: Tagged<&str>,
as_html: bool,
) -> Result<Vec<Value>, ShellError> {
execute_selector_query(input, query.item.to_string(), query.tag(), as_html)
}
fn execute_selector_query(
input_string: String,
query_string: String,
tag: impl Into<Tag>,
as_html: bool,
) -> Result<Vec<Value>, ShellError> {
let _tag = tag.into();
let mut ret = vec![];
@ -48,10 +55,15 @@ fn execute_selector_query(
// ret.push(title_url.to_string_value_create_tag());
// });
doc.nip(&query_string).iter().for_each(|athing| {
ret.push(athing.text().to_string().to_string_value_create_tag());
});
if as_html {
doc.nip(&query_string).iter().for_each(|athing| {
ret.push(athing.html().to_string().to_string_value_create_tag());
});
} else {
doc.nip(&query_string).iter().for_each(|athing| {
ret.push(athing.text().to_string().to_string_value_create_tag());
});
}
Ok(ret)
}