Address warnings found by rust-clippy.

https://github.com/Manishearth/rust-clippy
This commit is contained in:
Corey Farwell 2017-02-15 22:01:26 -05:00
parent f3fb1f1e16
commit 95fd292b4f
9 changed files with 103 additions and 121 deletions

View File

@ -1,8 +1,6 @@
#[macro_use]
extern crate mdbook;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate open;
@ -204,9 +202,8 @@ fn watch(args: &ArgMatches) -> Result<(), Box<Error>> {
trigger_on_change(&mut book, |path, book| {
println!("File changed: {:?}\nBuilding book...\n", path);
match book.build() {
Err(e) => println!("Error while building: {:?}", e),
_ => {},
if let Err(e) = book.build() {
println!("Error while building: {:?}", e);
}
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
// 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
}
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
}

View File

@ -53,7 +53,7 @@ impl BookConfig {
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);
exit(2);
}
@ -81,9 +81,9 @@ impl BookConfig {
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() {
Some(x) => {x},
@ -99,9 +99,9 @@ impl BookConfig {
}
/// 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,
Err(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

View File

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

View File

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

View File

@ -47,12 +47,12 @@ fn parse_level(summary: &mut Vec<&str>, current_level: i32, mut section: Vec<i32
continue;
} else {
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 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 \
no chapters after suffix elements.")));
Prefix elements can only exist before any chapter and there can be \
no chapters after suffix elements."));
};
} 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
BookItem::Affix(_) | BookItem::Spacer if level > 0 => {
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 \
root level.\n
Prefix, Suffix and Spacer elements can only exist on the \
root level.\n
Prefix \
elements can only exist before any chapter and there can be \
no chapters after suffix elements.")))
elements can only exist before any chapter and there can be \
no chapters after suffix elements."))
},
// error if BookItem == Chapter and section == -1
BookItem::Chapter(_, _) if section[0] == -1 => {
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 \
root level.\n
Prefix, Suffix and Spacer elements can only exist on the \
root level.\n
Prefix \
elements can only exist before any chapter and there can be \
no chapters after suffix elements.")))
elements can only exist before any chapter and there can be \
no chapters after suffix elements."))
},
// Set section = -1 after suffix

View File

@ -15,6 +15,7 @@ use handlebars::Handlebars;
use serde_json;
#[derive(Default)]
pub struct HtmlHandlebars;
impl HtmlHandlebars {
@ -48,7 +49,7 @@ impl Renderer for HtmlHandlebars {
// Check if dest 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,
"Unexpected error when constructing destination path")));
}
@ -81,8 +82,8 @@ impl Renderer for HtmlHandlebars {
print_content.push_str(&content);
// Update the context with data for this file
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
"Could not convert path to str"))?;
let path = ch.path.to_str().ok_or_else(||
io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
data.insert("path".to_owned(), json!(path));
data.insert("content".to_owned(), json!(content));
data.insert("chapter_title".to_owned(), json!(ch.name));
@ -183,15 +184,15 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
match *item {
BookItem::Affix(ref ch) => {
chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
"Could not convert path to str"))?;
let path = ch.path.to_str().ok_or_else(||
io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
chapter.insert("path".to_owned(), json!(path));
},
BookItem::Chapter(ref s, ref ch) => {
chapter.insert("section".to_owned(), json!(s));
chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
"Could not convert path to str"))?;
let path = ch.path.to_str().ok_or_else(||
io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
chapter.insert("path".to_owned(), json!(path));
},
BookItem::Spacer => {

View File

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

View File

@ -17,7 +17,7 @@ impl HelperDef for RenderToc {
// param is the key of value you want to display
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("\"", "");
try!(rc.writer.write("<ul class=\"chapter\">".as_bytes()));
try!(rc.writer.write_all("<ul class=\"chapter\">".as_bytes()));
// Decode json format
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 {
// Spacer
if let Some(_) = item.get("spacer") {
try!(rc.writer.write("<li class=\"spacer\"></li>".as_bytes()));
if item.get("spacer").is_some() {
try!(rc.writer.write_all("<li class=\"spacer\"></li>".as_bytes()));
continue;
}
@ -40,33 +40,33 @@ impl HelperDef for RenderToc {
if level > current_level {
while level > current_level {
try!(rc.writer.write("<li>".as_bytes()));
try!(rc.writer.write("<ul class=\"section\">".as_bytes()));
try!(rc.writer.write_all("<li>".as_bytes()));
try!(rc.writer.write_all("<ul class=\"section\">".as_bytes()));
current_level += 1;
}
try!(rc.writer.write("<li>".as_bytes()));
try!(rc.writer.write_all("<li>".as_bytes()));
} else if level < current_level {
while level < current_level {
try!(rc.writer.write("</ul>".as_bytes()));
try!(rc.writer.write("</li>".as_bytes()));
try!(rc.writer.write_all("</ul>".as_bytes()));
try!(rc.writer.write_all("</li>".as_bytes()));
current_level -= 1;
}
try!(rc.writer.write("<li>".as_bytes()));
try!(rc.writer.write_all("<li>".as_bytes()));
} else {
try!(rc.writer.write("<li".as_bytes()));
if let None = item.get("section") {
try!(rc.writer.write(" class=\"affix\"".as_bytes()));
try!(rc.writer.write_all("<li".as_bytes()));
if item.get("section").is_none() {
try!(rc.writer.write_all(" class=\"affix\"".as_bytes()));
}
try!(rc.writer.write(">".as_bytes()));
try!(rc.writer.write_all(">".as_bytes()));
}
// Link
let path_exists = if let Some(path) = item.get("path") {
if !path.is_empty() {
try!(rc.writer.write("<a href=\"".as_bytes()));
try!(rc.writer.write_all("<a href=\"".as_bytes()));
// 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(_)"))
.with_extension("html")
.to_str()
@ -75,13 +75,13 @@ impl HelperDef for RenderToc {
.replace("\\", "/")
.as_bytes()));
try!(rc.writer.write("\"".as_bytes()));
try!(rc.writer.write_all("\"".as_bytes()));
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
} else {
false
@ -92,21 +92,21 @@ impl HelperDef for RenderToc {
// Section does not necessarily exist
if let Some(section) = item.get("section") {
try!(rc.writer.write("<strong>".as_bytes()));
try!(rc.writer.write(section.as_bytes()));
try!(rc.writer.write("</strong> ".as_bytes()));
try!(rc.writer.write_all("<strong>".as_bytes()));
try!(rc.writer.write_all(section.as_bytes()));
try!(rc.writer.write_all("</strong> ".as_bytes()));
}
if let Some(name) = item.get("name") {
// Render only inline code blocks
// filter all events that are not inline code blocks
let parser = Parser::new(&name).filter(|event| {
match event {
&Event::Start(Tag::Code) |
&Event::End(Tag::Code) => true,
&Event::InlineHtml(_) => true,
&Event::Text(_) => true,
let parser = Parser::new(name).filter(|event| {
match *event {
Event::Start(Tag::Code) |
Event::End(Tag::Code) |
Event::InlineHtml(_) |
Event::Text(_) => true,
_ => false,
}
});
@ -116,23 +116,23 @@ impl HelperDef for RenderToc {
html::push_html(&mut markdown_parsed_name, parser);
// 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 {
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 {
try!(rc.writer.write("</ul>".as_bytes()));
try!(rc.writer.write("</li>".as_bytes()));
try!(rc.writer.write_all("</ul>".as_bytes()));
try!(rc.writer.write_all("</li>".as_bytes()));
current_level -= 1;
}
try!(rc.writer.write("</ul>".as_bytes()));
try!(rc.writer.write_all("</ul>".as_bytes()));
Ok(())
}
}

View File

@ -14,7 +14,7 @@ pub fn render_markdown(text: &str) -> String {
opts.insert(OPTION_ENABLE_TABLES);
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);
s
}