Merge pull request #205 from frewsxcv/clippy

Address warnings found by rust-clippy.
This commit is contained in:
Mathieu David 2017-02-17 11:05:33 +01:00 committed by GitHub
commit d7f38d08fd
9 changed files with 103 additions and 121 deletions

View file

@ -1,8 +1,6 @@
#[macro_use]
extern crate mdbook; extern crate mdbook;
#[macro_use] #[macro_use]
extern crate clap; extern crate clap;
#[macro_use]
extern crate log; extern crate log;
extern crate env_logger; extern crate env_logger;
extern crate open; extern crate open;
@ -204,9 +202,8 @@ fn watch(args: &ArgMatches) -> Result<(), Box<Error>> {
trigger_on_change(&mut book, |path, book| { trigger_on_change(&mut book, |path, book| {
println!("File changed: {:?}\nBuilding book...\n", path); println!("File changed: {:?}\nBuilding book...\n", path);
match book.build() { if let Err(e) = book.build() {
Err(e) => println!("Error while building: {:?}", e), println!("Error while building: {:?}", e);
_ => {},
} }
println!(""); println!("");
}); });
@ -348,10 +345,10 @@ fn trigger_on_change<F>(book: &mut MDBook, closure: F) -> ()
// Add the book.{json,toml} file to the watcher if it exists, because it's not // Add the book.{json,toml} file to the watcher if it exists, because it's not
// located in the source directory // located in the source directory
if let Err(_) = watcher.watch(book.get_root().join("book.json"), NonRecursive) { if watcher.watch(book.get_root().join("book.json"), NonRecursive).is_err() {
// do nothing if book.json is not found // do nothing if book.json is not found
} }
if let Err(_) = watcher.watch(book.get_root().join("book.toml"), NonRecursive) { if watcher.watch(book.get_root().join("book.toml"), NonRecursive).is_err() {
// do nothing if book.toml is not found // do nothing if book.toml is not found
} }

View file

@ -53,7 +53,7 @@ impl BookConfig {
exit(2); exit(2);
} }
}; };
if let Err(_) = f.read_to_string(&mut data) { if f.read_to_string(&mut data).is_err() {
error!("[*]: Failed to read {:?}", &path); error!("[*]: Failed to read {:?}", &path);
exit(2); exit(2);
} }
@ -81,9 +81,9 @@ impl BookConfig {
self self
} }
pub fn parse_from_toml_string(&mut self, data: &String) -> &mut Self { pub fn parse_from_toml_string(&mut self, data: &str) -> &mut Self {
let mut parser = toml::Parser::new(&data); let mut parser = toml::Parser::new(data);
let config = match parser.parse() { let config = match parser.parse() {
Some(x) => {x}, Some(x) => {x},
@ -99,9 +99,9 @@ impl BookConfig {
} }
/// Parses the string to JSON and converts it to BTreeMap<String, toml::Value>. /// Parses the string to JSON and converts it to BTreeMap<String, toml::Value>.
pub fn parse_from_json_string(&mut self, data: &String) -> &mut Self { pub fn parse_from_json_string(&mut self, data: &str) -> &mut Self {
let c: serde_json::Value = match serde_json::from_str(&data) { let c: serde_json::Value = match serde_json::from_str(data) {
Ok(x) => x, Ok(x) => x,
Err(e) => { Err(e) => {
error!("[*]: JSON parse errors in book.json: {:?}", e); error!("[*]: JSON parse errors in book.json: {:?}", e);
@ -109,7 +109,7 @@ impl BookConfig {
} }
}; };
let config = json_object_to_btreemap(&c.as_object().unwrap()); let config = json_object_to_btreemap(c.as_object().unwrap());
self.parse_from_btreemap(&config); self.parse_from_btreemap(&config);
self self

View file

@ -63,7 +63,7 @@ impl<'a> Iterator for BookItems<'a> {
}, },
} }
} else { } else {
let cur = self.items.get(self.current_index).unwrap(); let cur = &self.items[self.current_index];
match *cur { match *cur {
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => { BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {

View file

@ -346,29 +346,26 @@ impl MDBook {
try!(self.parse_summary()); try!(self.parse_summary());
for item in self.iter() { for item in self.iter() {
match *item { if let BookItem::Chapter(_, ref ch) = *item {
BookItem::Chapter(_, ref ch) => { if ch.path != PathBuf::new() {
if ch.path != PathBuf::new() {
let path = self.get_src().join(&ch.path); let path = self.get_src().join(&ch.path);
println!("[*]: Testing file: {:?}", path); println!("[*]: Testing file: {:?}", path);
let output_result = Command::new("rustdoc") let output_result = Command::new("rustdoc")
.arg(&path) .arg(&path)
.arg("--test") .arg("--test")
.output(); .output();
let output = try!(output_result); let output = try!(output_result);
if !output.status.success() { if !output.status.success() {
return Err(Box::new(io::Error::new(ErrorKind::Other, format!( return Err(Box::new(io::Error::new(ErrorKind::Other, format!(
"{}\n{}", "{}\n{}",
String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)))) as Box<Error>); String::from_utf8_lossy(&output.stderr)))) as Box<Error>);
}
} }
}, }
_ => {},
} }
} }
Ok(()) Ok(())
@ -381,14 +378,11 @@ impl MDBook {
pub fn set_dest(mut self, dest: &Path) -> Self { pub fn set_dest(mut self, dest: &Path) -> Self {
// Handle absolute and relative paths // Handle absolute and relative paths
match dest.is_absolute() { if dest.is_absolute() {
true => { self.dest = dest.to_owned();
self.dest = dest.to_owned(); } else {
}, let dest = self.root.join(dest).to_owned();
false => { self.dest = dest;
let dest = self.root.join(dest).to_owned();
self.dest = dest;
},
} }
self self
@ -401,14 +395,11 @@ impl MDBook {
pub fn set_src(mut self, src: &Path) -> Self { pub fn set_src(mut self, src: &Path) -> Self {
// Handle absolute and relative paths // Handle absolute and relative paths
match src.is_absolute() { if src.is_absolute() {
true => { self.src = src.to_owned();
self.src = src.to_owned(); } else {
}, let src = self.root.join(src).to_owned();
false => { self.src = src;
let src = self.root.join(src).to_owned();
self.src = src;
},
} }
self self
@ -456,16 +447,14 @@ impl MDBook {
} }
pub fn get_livereload(&self) -> Option<&String> { pub fn get_livereload(&self) -> Option<&String> {
match self.livereload { self.livereload.as_ref()
Some(ref livereload) => Some(&livereload),
None => None,
}
} }
pub fn set_theme_path(mut self, theme_path: &Path) -> Self { pub fn set_theme_path(mut self, theme_path: &Path) -> Self {
self.theme_path = match theme_path.is_absolute() { self.theme_path = if theme_path.is_absolute() {
true => theme_path.to_owned(), theme_path.to_owned()
false => self.root.join(theme_path).to_owned(), } else {
self.root.join(theme_path).to_owned()
}; };
self self
} }

View file

@ -47,12 +47,12 @@ fn parse_level(summary: &mut Vec<&str>, current_level: i32, mut section: Vec<i32
continue; continue;
} else { } else {
return Err(Error::new(ErrorKind::Other, return Err(Error::new(ErrorKind::Other,
format!("Your summary.md is messed up\n\n "Your summary.md is messed up\n\n
Prefix, \ Prefix, \
Suffix and Spacer elements can only exist on the root level.\n Suffix and Spacer elements can only exist on the root level.\n
\ \
Prefix elements can only exist before any chapter and there can be \ Prefix elements can only exist before any chapter and there can be \
no chapters after suffix elements."))); no chapters after suffix elements."));
}; };
} else { } else {
@ -64,25 +64,25 @@ fn parse_level(summary: &mut Vec<&str>, current_level: i32, mut section: Vec<i32
// error if level != 0 and BookItem is != Chapter // error if level != 0 and BookItem is != Chapter
BookItem::Affix(_) | BookItem::Spacer if level > 0 => { BookItem::Affix(_) | BookItem::Spacer if level > 0 => {
return Err(Error::new(ErrorKind::Other, return Err(Error::new(ErrorKind::Other,
format!("Your summary.md is messed up\n\n "Your summary.md is messed up\n\n
\ \
Prefix, Suffix and Spacer elements can only exist on the \ Prefix, Suffix and Spacer elements can only exist on the \
root level.\n root level.\n
Prefix \ Prefix \
elements can only exist before any chapter and there can be \ elements can only exist before any chapter and there can be \
no chapters after suffix elements."))) no chapters after suffix elements."))
}, },
// error if BookItem == Chapter and section == -1 // error if BookItem == Chapter and section == -1
BookItem::Chapter(_, _) if section[0] == -1 => { BookItem::Chapter(_, _) if section[0] == -1 => {
return Err(Error::new(ErrorKind::Other, return Err(Error::new(ErrorKind::Other,
format!("Your summary.md is messed up\n\n "Your summary.md is messed up\n\n
\ \
Prefix, Suffix and Spacer elements can only exist on the \ Prefix, Suffix and Spacer elements can only exist on the \
root level.\n root level.\n
Prefix \ Prefix \
elements can only exist before any chapter and there can be \ elements can only exist before any chapter and there can be \
no chapters after suffix elements."))) no chapters after suffix elements."))
}, },
// Set section = -1 after suffix // Set section = -1 after suffix

View file

@ -17,6 +17,7 @@ use handlebars::Handlebars;
use serde_json; use serde_json;
#[derive(Default)]
pub struct HtmlHandlebars; pub struct HtmlHandlebars;
impl HtmlHandlebars { impl HtmlHandlebars {
@ -50,7 +51,7 @@ impl Renderer for HtmlHandlebars {
// Check if dest directory exists // Check if dest directory exists
debug!("[*]: Check if destination directory exists"); debug!("[*]: Check if destination directory exists");
if let Err(_) = fs::create_dir_all(book.get_dest()) { if fs::create_dir_all(book.get_dest()).is_err() {
return Err(Box::new(io::Error::new(io::ErrorKind::Other, return Err(Box::new(io::Error::new(io::ErrorKind::Other,
"Unexpected error when constructing destination path"))); "Unexpected error when constructing destination path")));
} }
@ -83,8 +84,8 @@ impl Renderer for HtmlHandlebars {
print_content.push_str(&content); print_content.push_str(&content);
// Update the context with data for this file // Update the context with data for this file
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other, let path = ch.path.to_str().ok_or_else(||
"Could not convert path to str"))?; io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
data.insert("path".to_owned(), json!(path)); data.insert("path".to_owned(), json!(path));
data.insert("content".to_owned(), json!(content)); data.insert("content".to_owned(), json!(content));
data.insert("chapter_title".to_owned(), json!(ch.name)); data.insert("chapter_title".to_owned(), json!(ch.name));
@ -188,15 +189,15 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
match *item { match *item {
BookItem::Affix(ref ch) => { BookItem::Affix(ref ch) => {
chapter.insert("name".to_owned(), json!(ch.name)); chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other, let path = ch.path.to_str().ok_or_else(||
"Could not convert path to str"))?; io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
chapter.insert("path".to_owned(), json!(path)); chapter.insert("path".to_owned(), json!(path));
}, },
BookItem::Chapter(ref s, ref ch) => { BookItem::Chapter(ref s, ref ch) => {
chapter.insert("section".to_owned(), json!(s)); chapter.insert("section".to_owned(), json!(s));
chapter.insert("name".to_owned(), json!(ch.name)); chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other, let path = ch.path.to_str().ok_or_else(||
"Could not convert path to str"))?; io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
chapter.insert("path".to_owned(), json!(path)); chapter.insert("path".to_owned(), json!(path));
}, },
BookItem::Spacer => { BookItem::Spacer => {

View file

@ -31,7 +31,7 @@ pub fn render_playpen(s: &str, path: &Path) -> String {
continue; continue;
}; };
let mut file_content = String::new(); let mut file_content = String::new();
if let Err(_) = file.read_to_string(&mut file_content) { if file.read_to_string(&mut file_content).is_err() {
continue; continue;
}; };
@ -86,7 +86,7 @@ fn find_playpens(s: &str, base_path: &Path) -> Vec<Playpen> {
if end_i - 2 - (i + 10) < 1 { if end_i - 2 - (i + 10) < 1 {
continue; continue;
} }
if s[i + 10..end_i - 2].trim().len() == 0 { if s[i + 10..end_i - 2].trim().is_empty() {
continue; continue;
} }
@ -94,15 +94,10 @@ fn find_playpens(s: &str, base_path: &Path) -> Vec<Playpen> {
// Split on whitespaces // Split on whitespaces
let params: Vec<&str> = s[i + 10..end_i - 2].split_whitespace().collect(); let params: Vec<&str> = s[i + 10..end_i - 2].split_whitespace().collect();
let mut editable = false; let editable = params
.get(1)
if params.len() > 1 { .map(|p| p.find("editable").is_some())
editable = if let Some(_) = params[1].find("editable") { .unwrap_or(false);
true
} else {
false
};
}
playpens.push(Playpen { playpens.push(Playpen {
start_index: i, start_index: i,

View file

@ -17,7 +17,7 @@ impl HelperDef for RenderToc {
// param is the key of value you want to display // param is the key of value you want to display
let chapters = rc.context().navigate(rc.get_path(), &VecDeque::new(), "chapters").to_owned(); let chapters = rc.context().navigate(rc.get_path(), &VecDeque::new(), "chapters").to_owned();
let current = rc.context().navigate(rc.get_path(), &VecDeque::new(), "path").to_string().replace("\"", ""); let current = rc.context().navigate(rc.get_path(), &VecDeque::new(), "path").to_string().replace("\"", "");
try!(rc.writer.write("<ul class=\"chapter\">".as_bytes())); try!(rc.writer.write_all("<ul class=\"chapter\">".as_bytes()));
// Decode json format // Decode json format
let decoded: Vec<BTreeMap<String, String>> = serde_json::from_str(&chapters.to_string()).unwrap(); let decoded: Vec<BTreeMap<String, String>> = serde_json::from_str(&chapters.to_string()).unwrap();
@ -27,8 +27,8 @@ impl HelperDef for RenderToc {
for item in decoded { for item in decoded {
// Spacer // Spacer
if let Some(_) = item.get("spacer") { if item.get("spacer").is_some() {
try!(rc.writer.write("<li class=\"spacer\"></li>".as_bytes())); try!(rc.writer.write_all("<li class=\"spacer\"></li>".as_bytes()));
continue; continue;
} }
@ -40,33 +40,33 @@ impl HelperDef for RenderToc {
if level > current_level { if level > current_level {
while level > current_level { while level > current_level {
try!(rc.writer.write("<li>".as_bytes())); try!(rc.writer.write_all("<li>".as_bytes()));
try!(rc.writer.write("<ul class=\"section\">".as_bytes())); try!(rc.writer.write_all("<ul class=\"section\">".as_bytes()));
current_level += 1; current_level += 1;
} }
try!(rc.writer.write("<li>".as_bytes())); try!(rc.writer.write_all("<li>".as_bytes()));
} else if level < current_level { } else if level < current_level {
while level < current_level { while level < current_level {
try!(rc.writer.write("</ul>".as_bytes())); try!(rc.writer.write_all("</ul>".as_bytes()));
try!(rc.writer.write("</li>".as_bytes())); try!(rc.writer.write_all("</li>".as_bytes()));
current_level -= 1; current_level -= 1;
} }
try!(rc.writer.write("<li>".as_bytes())); try!(rc.writer.write_all("<li>".as_bytes()));
} else { } else {
try!(rc.writer.write("<li".as_bytes())); try!(rc.writer.write_all("<li".as_bytes()));
if let None = item.get("section") { if item.get("section").is_none() {
try!(rc.writer.write(" class=\"affix\"".as_bytes())); try!(rc.writer.write_all(" class=\"affix\"".as_bytes()));
} }
try!(rc.writer.write(">".as_bytes())); try!(rc.writer.write_all(">".as_bytes()));
} }
// Link // Link
let path_exists = if let Some(path) = item.get("path") { let path_exists = if let Some(path) = item.get("path") {
if !path.is_empty() { if !path.is_empty() {
try!(rc.writer.write("<a href=\"".as_bytes())); try!(rc.writer.write_all("<a href=\"".as_bytes()));
// Add link // Add link
try!(rc.writer.write(Path::new(item.get("path") try!(rc.writer.write_all(Path::new(item.get("path")
.expect("Error: path should be Some(_)")) .expect("Error: path should be Some(_)"))
.with_extension("html") .with_extension("html")
.to_str() .to_str()
@ -75,13 +75,13 @@ impl HelperDef for RenderToc {
.replace("\\", "/") .replace("\\", "/")
.as_bytes())); .as_bytes()));
try!(rc.writer.write("\"".as_bytes())); try!(rc.writer.write_all("\"".as_bytes()));
if path == &current { if path == &current {
try!(rc.writer.write(" class=\"active\"".as_bytes())); try!(rc.writer.write_all(" class=\"active\"".as_bytes()));
} }
try!(rc.writer.write(">".as_bytes())); try!(rc.writer.write_all(">".as_bytes()));
true true
} else { } else {
false false
@ -92,21 +92,21 @@ impl HelperDef for RenderToc {
// Section does not necessarily exist // Section does not necessarily exist
if let Some(section) = item.get("section") { if let Some(section) = item.get("section") {
try!(rc.writer.write("<strong>".as_bytes())); try!(rc.writer.write_all("<strong>".as_bytes()));
try!(rc.writer.write(section.as_bytes())); try!(rc.writer.write_all(section.as_bytes()));
try!(rc.writer.write("</strong> ".as_bytes())); try!(rc.writer.write_all("</strong> ".as_bytes()));
} }
if let Some(name) = item.get("name") { if let Some(name) = item.get("name") {
// Render only inline code blocks // Render only inline code blocks
// filter all events that are not inline code blocks // filter all events that are not inline code blocks
let parser = Parser::new(&name).filter(|event| { let parser = Parser::new(name).filter(|event| {
match event { match *event {
&Event::Start(Tag::Code) | Event::Start(Tag::Code) |
&Event::End(Tag::Code) => true, Event::End(Tag::Code) |
&Event::InlineHtml(_) => true, Event::InlineHtml(_) |
&Event::Text(_) => true, Event::Text(_) => true,
_ => false, _ => false,
} }
}); });
@ -116,23 +116,23 @@ impl HelperDef for RenderToc {
html::push_html(&mut markdown_parsed_name, parser); html::push_html(&mut markdown_parsed_name, parser);
// write to the handlebars template // write to the handlebars template
try!(rc.writer.write(markdown_parsed_name.as_bytes())); try!(rc.writer.write_all(markdown_parsed_name.as_bytes()));
} }
if path_exists { if path_exists {
try!(rc.writer.write("</a>".as_bytes())); try!(rc.writer.write_all("</a>".as_bytes()));
} }
try!(rc.writer.write("</li>".as_bytes())); try!(rc.writer.write_all("</li>".as_bytes()));
} }
while current_level > 1 { while current_level > 1 {
try!(rc.writer.write("</ul>".as_bytes())); try!(rc.writer.write_all("</ul>".as_bytes()));
try!(rc.writer.write("</li>".as_bytes())); try!(rc.writer.write_all("</li>".as_bytes()));
current_level -= 1; current_level -= 1;
} }
try!(rc.writer.write("</ul>".as_bytes())); try!(rc.writer.write_all("</ul>".as_bytes()));
Ok(()) Ok(())
} }
} }

View file

@ -14,7 +14,7 @@ pub fn render_markdown(text: &str) -> String {
opts.insert(OPTION_ENABLE_TABLES); opts.insert(OPTION_ENABLE_TABLES);
opts.insert(OPTION_ENABLE_FOOTNOTES); opts.insert(OPTION_ENABLE_FOOTNOTES);
let p = Parser::new_ext(&text, opts); let p = Parser::new_ext(text, opts);
html::push_html(&mut s, p); html::push_html(&mut s, p);
s s
} }