-
Notifications
You must be signed in to change notification settings - Fork 210
Switch from kuchiki to LOL_HTML #930
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
d7a702e
[WIP] Initial try at LOL HTML rewriter
jyn514 dad0b55
Fix broken `class="rustdoc"` handling
jyn514 22b8bc8
Add missing html files
jyn514 7889db9
Remove unused files
jyn514 452a088
Use valid HTML for all tests
jyn514 d9604a2
Cleanup
jyn514 adb8929
Use HtmlRewriter instead of rewrite_str
jyn514 b39d7c3
Use log instead of println in tests
jyn514 b888c84
Document `rewrite_lol`
jyn514 cbe962b
Add whitespace
jyn514 ec5ca48
Make parse memory configurable and raise HTML size limit
jyn514 f78472b
Improve comment
jyn514 2dc045d
Only allot 5 MB for LOL parser
jyn514 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,62 +1,67 @@ | ||
use crate::error::Result; | ||
use failure::err_msg; | ||
use kuchiki::traits::TendrilSink; | ||
use kuchiki::NodeRef; | ||
use crate::web::page::TemplateData; | ||
use lol_html::errors::RewritingError; | ||
use tera::Context; | ||
|
||
/// Extracts the contents of the `<head>` and `<body>` tags from an HTML document, as well as the | ||
/// classes on the `<body>` tag, if any. | ||
pub fn extract_head_and_body(html: &str) -> Result<(String, String, String)> { | ||
let dom = kuchiki::parse_html().one(html); | ||
pub(crate) fn rewrite_lol( | ||
html: &str, | ||
ctx: Context, | ||
templates: &TemplateData, | ||
) -> Result<String, RewritingError> { | ||
use lol_html::html_content::{ContentType, Element}; | ||
use lol_html::{ElementContentHandlers, RewriteStrSettings}; | ||
|
||
let head = dom | ||
.select_first("head") | ||
.map_err(|_| err_msg("couldn't find <head> tag in rustdoc output"))?; | ||
let body = dom | ||
.select_first("body") | ||
.map_err(|_| err_msg("couldn't find <body> tag in rustdoc output"))?; | ||
let templates = templates.templates.load(); | ||
let tera_head = templates.render("rustdoc/head.html", &ctx).unwrap(); | ||
let tera_body = templates.render("rustdoc/body.html", &ctx).unwrap(); | ||
|
||
let class = body | ||
.attributes | ||
.borrow() | ||
.get("class") | ||
.map(|v| v.to_owned()) | ||
.unwrap_or_default(); | ||
let head_handler = |head: &mut Element| { | ||
head.append(&tera_head, ContentType::Html); | ||
Ok(()) | ||
}; | ||
// Before: <body> ... rustdoc content ... </body> | ||
// After: | ||
// ```html | ||
// <div id="rustdoc_body_wrapper" class="{{ rustdoc_body_class }}" tabindex="-1"> | ||
// ... rustdoc content ... | ||
// </div> | ||
// ``` | ||
let body_handler = |rustdoc_body_class: &mut Element| { | ||
// Add the `rustdoc` classes to the html body | ||
let mut tmp; | ||
let klass = if let Some(classes) = rustdoc_body_class.get_attribute("class") { | ||
tmp = classes; | ||
tmp.push_str(" container-rustdoc"); | ||
&tmp | ||
} else { | ||
"container-rustdoc" | ||
}; | ||
rustdoc_body_class.set_attribute("class", klass)?; | ||
rustdoc_body_class.set_attribute("id", "rustdoc_body_wrapper")?; | ||
rustdoc_body_class.set_attribute("tabindex", "-1")?; | ||
// Change the `body` to a `div` | ||
rustdoc_body_class.set_tag_name("div")?; | ||
// Prepend the tera content | ||
rustdoc_body_class.prepend(&tera_body, ContentType::Html); | ||
// Now, make this a full <body> tag | ||
rustdoc_body_class.before("<body>", ContentType::Html); | ||
rustdoc_body_class.after("</body>", ContentType::Html); | ||
|
||
Ok((serialize(head.as_node()), serialize(body.as_node()), class)) | ||
} | ||
|
||
fn serialize(v: &NodeRef) -> String { | ||
let mut contents = Vec::new(); | ||
for child in v.children() { | ||
child | ||
.serialize(&mut contents) | ||
.expect("serialization failed"); | ||
} | ||
String::from_utf8(contents).expect("non utf-8 html") | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
#[test] | ||
fn small_html() { | ||
let (head, body, class) = super::extract_head_and_body( | ||
r#"<head><meta name="generator" content="rustdoc"></head><body class="rustdoc struct"><p>hello</p>"# | ||
).unwrap(); | ||
assert_eq!(head, r#"<meta content="rustdoc" name="generator">"#); | ||
assert_eq!(body, "<p>hello</p>"); | ||
assert_eq!(class, "rustdoc struct"); | ||
} | ||
Ok(()) | ||
}; | ||
|
||
// more of an integration test | ||
#[test] | ||
fn parse_regex_html() { | ||
let original = std::fs::read_to_string("benches/struct.CaptureMatches.html").unwrap(); | ||
let expected_head = std::fs::read_to_string("tests/regex/head.html").unwrap(); | ||
let expected_body = std::fs::read_to_string("tests/regex/body.html").unwrap(); | ||
let (head, body, class) = super::extract_head_and_body(&original).unwrap(); | ||
let (head_selector, body_selector) = ("head".parse().unwrap(), "body".parse().unwrap()); | ||
let head = ( | ||
&head_selector, | ||
ElementContentHandlers::default().element(head_handler), | ||
); | ||
let body = ( | ||
&body_selector, | ||
ElementContentHandlers::default().element(body_handler), | ||
); | ||
let settings = RewriteStrSettings { | ||
element_content_handlers: vec![head, body], | ||
..RewriteStrSettings::default() | ||
}; | ||
|
||
assert_eq!(head, expected_head.trim()); | ||
assert_eq!(&body, &expected_body.trim()); | ||
assert_eq!(class, "rustdoc struct"); | ||
} | ||
lol_html::rewrite_str(html, settings) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.