1
0
Fork 0
mirror of https://github.com/lise-henry/crowbook synced 2024-06-13 05:06:22 +02:00

Apply more clippy lints

This commit is contained in:
Elisabeth Henry 2017-01-09 17:45:59 +01:00
parent 6752f1566a
commit a30addf218
15 changed files with 97 additions and 103 deletions

View File

@ -13,13 +13,11 @@ pub fn get_lang() -> Option<String> {
for arg in env::args() {
if found {
return Some(arg.clone());
} else {
if arg == "--lang" || arg == "-L" {
found = true;
}
} else if arg == "--lang" || arg == "-L" {
found = true;
}
}
return None;
None
}
/// Prints an error on stderr and exit the program
@ -89,7 +87,7 @@ pub fn create_book(matches: &ArgMatches) -> ! {
if matches.is_present("set") {
let mut book = Book::new();
let s = set_book_options(&mut book, matches);
f.write_all(&s.as_bytes()).unwrap();
f.write_all(s.as_bytes()).unwrap();
} else {
f.write_all(lformat!("author: Your name
title: Your title
@ -106,7 +104,7 @@ lang: en
}
f.write_all(lformat!("\n# List of chapters\n").as_bytes()).unwrap();
for file in values {
f.write_all(&format!("+ {}\n", file).as_bytes()).unwrap();
f.write_all(format!("+ {}\n", file).as_bytes()).unwrap();
}
if let Some(s) = matches.value_of("BOOK") {
println!("{}",

View File

@ -46,13 +46,12 @@ fn render_format(book: &mut Book, matches: &ArgMatches, format: &str) -> ! {
let res = book.options.get_path(&key);
let result = match(file, res, stdout) {
(Some(file), _, _) => book.render_format_to_file(format, file),
(Some(file), _, _) |
(None, Ok(file), false) => book.render_format_to_file(format, file),
(None, Err(_), _) |
(None, _, true)
=> book.render_format_to(format, &mut io::stdout()),
(None, Ok(file), false) => book.render_format_to_file(format, file)
};
match result {
@ -151,12 +150,10 @@ pub fn try_main() -> Result<()> {
} else {
book.read_markdown_config(io::stdin())?;
}
} else if s != "-" {
book.load_file(s)?;
} else {
if s != "-" {
book.load_file(s)?;
} else {
book.read_config(io::stdin())?;
}
book.read_config(io::stdin())?;
}
set_book_options(&mut book, &matches);
@ -170,8 +167,7 @@ pub fn try_main() -> Result<()> {
}
pub fn real_main() {
match try_main() {
Err(err) => print_error(&format!("{}", err)),
Ok(_) => (),
if let Err(err) = try_main() {
print_error(&format!("{}", err));
}
}

View File

@ -359,7 +359,7 @@ impl Book {
/// Sets options from a YAML block
fn set_options_from_yaml(&mut self, yaml: &str) -> Result<&mut Book> {
self.options.source = self.source.clone();
match YamlLoader::load_from_str(&yaml) {
match YamlLoader::load_from_str(yaml) {
Err(err) => {
return Err(Error::config_parser(&self.source,
lformat!("YAML block was not valid YAML: {error}",
@ -368,7 +368,7 @@ impl Book {
Ok(mut docs) => {
if docs.len() == 1 && docs[0].as_hash().is_some() {
if let Yaml::Hash(hash) = docs.pop().unwrap() {
for (key, value) in hash.into_iter() {
for (key, value) in hash {
self.options.set_yaml(key, value)?;
}
} else {
@ -471,7 +471,7 @@ impl Book {
is_next_line_ok = false;
} else {
let doc = doc.unwrap();
if doc.len() > 0 && doc[0].as_hash().is_some() {
if !doc.is_empty() && doc[0].as_hash().is_some() {
is_next_line_ok = true;
} else {
is_next_line_ok = false;
@ -619,7 +619,7 @@ impl Book {
}
}
if self.options.get_bool("proofread.repetitions").unwrap() {
self.detector = Some(RepetitionDetector::new(&self));
self.detector = Some(RepetitionDetector::new(self));
}
}
}
@ -728,7 +728,7 @@ impl Book {
format = format));
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => {
renderer.render(&self, f)?;
renderer.render(self, f)?;
self.logger.info(lformat!("Succesfully generated {format}",
format = description));
Ok(())
@ -756,7 +756,7 @@ impl Book {
format = format));
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => {
renderer.render_to_file(&self, path.as_ref())?;
renderer.render_to_file(self, path.as_ref())?;
self.logger.info(lformat!("Succesfully generated {format}: {path}",
format = description,
path = misc::normalize(path)));
@ -990,7 +990,7 @@ impl Book {
if !title.is_empty() {
data = data.insert_bool("has_chapter_title", true);
}
let number = if self.options.get_bool("rendering.chapter.roman_numerals").unwrap() == true {
let number = if self.options.get_bool("rendering.chapter.roman_numerals").unwrap() {
if n <= 0 {
return Err(Error::render(Source::empty(),
lformat!("can not use roman numerals with zero or negative chapter numbers ({n})",
@ -1085,6 +1085,7 @@ impl Book {
let key = key.replace(".", "_");
// Only render some metadata as markdown
// (actually, currently treat them all as markdown)
let content = match key.as_ref() {
"author" | "title" | "lang" => f(s),
_ => f(s),
@ -1107,7 +1108,7 @@ impl Book {
// Add localization strings
let hash = lang::get_hash(self.options.get_str("lang").unwrap());
for (key, value) in hash.into_iter() {
for (key, value) in hash {
let key = format!("loc_{}", key.as_str().unwrap());
let value = value.as_str().unwrap();
mapbuilder = mapbuilder.insert_str(&key, value);

View File

@ -444,10 +444,10 @@ impl BookOptions {
.join(&value);
let file = tmp
.to_str()
.ok_or(Error::book_option(&self.source,
lformat!("'{value}''s path contains invalid \
UTF-8 code",
value = &value)))?;
.ok_or_else(|| Error::book_option(&self.source,
lformat!("'{value}''s path contains invalid \
UTF-8 code",
value = &value)))?;
let mut book = Book::new();
book.load_file(file)?;
self.merge(book.options)?;
@ -524,7 +524,7 @@ impl BookOptions {
&value)))
}
} else if self.deprecated.contains_key(&key) {
let opt = self.deprecated.get(&key).unwrap().clone();
let opt = self.deprecated[&key].clone();
if let Some(new_key) = opt {
Logger::display_warning(lformat!("'{old_key}' has been deprecated, you should \
now use '{new_key}'",
@ -769,7 +769,7 @@ impl BookOptions {
// Check if option was already set, and if it was to default or to something else
if self.defaults.contains_key(key) {
let previous_opt = self.options.get(key);
let default = self.defaults.get(key).unwrap();
let default = &self.defaults[key];
// If new value is equal to default, don't insert it
if value == default {
continue;
@ -786,7 +786,7 @@ impl BookOptions {
// Sets key with an absolute path so it
// won't be messed up if resources.base_path is
// redefined later on
let path = other.get_path(&key).unwrap();
let path = other.get_path(key).unwrap();
let new_path = ::std::env::current_dir()
.map_err(|_| {
Error::default(Source::empty(),

View File

@ -143,7 +143,7 @@ impl<'a> EpubRenderer<'a> {
maker.add_content(content)?;
}
if self.html.book.options.get_bool("rendering.inline_toc").unwrap() == true {
if self.html.book.options.get_bool("rendering.inline_toc").unwrap() {
maker.inline_toc();
}
@ -165,7 +165,7 @@ impl<'a> EpubRenderer<'a> {
}
// horrible hack
// todo: find cleaner way
for element in self.html.toc.elements.iter() {
for element in &self.html.toc.elements {
if element.url.contains(&filenamer(i)) {
content = content.title(element.title.as_ref());
content.toc.children = element.children.clone();
@ -283,7 +283,7 @@ impl<'a> EpubRenderer<'a> {
let mut content = String::new();
for token in v {
let res = self.render_token(&token)?;
let res = self.render_token(token)?;
content.push_str(&res);
self.html.render_side_notes(&mut content);
}
@ -397,9 +397,9 @@ impl<'a> EpubRenderer<'a> {
// Use initial
let mut chars = content.chars();
let initial = chars.next()
.ok_or(Error::parser(&html.book.source,
lformat!("empty str token, could not find \
initial")))?;
.ok_or_else(|| Error::parser(&html.book.source,
lformat!("empty str token, could not find \
initial")))?;
let mut new_content = if initial.is_alphanumeric() {
format!("<span class = \"initial\">{}</span>", initial)
} else {

View File

@ -156,7 +156,7 @@ impl GrammarChecker {
}
}
}
for handle in handles.into_iter() {
for handle in handles {
if let Err(err) = handle.join() {
result = Err(err);
break;

View File

@ -64,30 +64,28 @@ impl<'a> HtmlDirRenderer<'a> {
self.html.handler.add_link(chapter.filename.as_ref(), filenamer(i));
}
match fs::metadata(&dest_path) {
Ok(metadata) => {
if metadata.is_file() {
return Err(Error::render(&self.html.book.source,
lformat!("{path} already exists and is not a \
directory",
path = dest_path.display())));
} else if metadata.is_dir() {
self.html
.book
.logger
.warning(lformat!("{path} already exists, deleting it",
path = dest_path.display()));
fs::remove_dir_all(&dest_path)
.map_err(|e| {
Error::render(&self.html.book.source,
lformat!("error deleting directory {path}: {error}",
path = dest_path.display(),
error = e))
if let Ok(metadata) = fs::metadata(&dest_path) {
if metadata.is_file() {
return Err(Error::render(&self.html.book.source,
lformat!("{path} already exists and is not a \
directory",
path = dest_path.display())));
} else if metadata.is_dir() {
self.html
.book
.logger
.warning(lformat!("{path} already exists, deleting it",
path = dest_path.display()));
fs::remove_dir_all(&dest_path)
.map_err(|e| {
Error::render(&self.html.book.source,
lformat!("error deleting directory {path}: {error}",
path = dest_path.display(),
error = e))
})?;
}
}
Err(_) => (),
}
fs::DirBuilder::new()
.recursive(true)
.create(&dest_path)
@ -102,7 +100,9 @@ impl<'a> HtmlDirRenderer<'a> {
self.write_css()?;
// Write print.css
self.write_file("print.css",
&self.html.book.get_template("html.css.print").unwrap().as_bytes())?;
self.html.book.get_template("html.css.print")
.unwrap()
.as_bytes())?;
// Write index.html and chapter_xxx.html
self.write_html()?;
// Write menu.svg
@ -113,7 +113,7 @@ impl<'a> HtmlDirRenderer<'a> {
self.write_file("highlight.js",
self.html
.book
.get_template("html.highlight.js")
.get_template("html.highlight.js")
.unwrap()
.as_bytes())?;
self.write_file("highlight.css",

View File

@ -268,7 +268,7 @@ impl BookRenderer for HtmlSingle {
fn render(&self, book: &Book, to: &mut Write) -> Result<()> {
let mut html = HtmlSingleRenderer::new(book);
let result = html.render_book()?;
to.write_all(&result.as_bytes())
to.write_all(result.as_bytes())
.map_err(|e| {
Error::render(&book.source,
lformat!("problem when writing HTML: {error}", error = e))
@ -282,7 +282,7 @@ impl BookRenderer for ProofHtmlSingle {
let mut html = HtmlSingleRenderer::new(book)
.proofread();
let result = html.render_book()?;
to.write_all(&result.as_bytes())
to.write_all(result.as_bytes())
.map_err(|e| {
Error::render(&book.source,
lformat!("problem when writing HTML: {error}", error = e))

View File

@ -84,7 +84,7 @@ impl<'a> LatexRenderer<'a> {
let content = self.render_book()?;
let mut zipper = Zipper::new(&self.book.options.get_path("crowbook.temp_dir")
.unwrap())?;
zipper.write("result.tex", &content.as_bytes(), false)?;
zipper.write("result.tex", content.as_bytes(), false)?;
// write image files
for (source, dest) in self.handler.images_mapping() {
@ -102,7 +102,7 @@ impl<'a> LatexRenderer<'a> {
}
zipper.generate_pdf(&self.book.options.get_str("tex.command").unwrap(),
zipper.generate_pdf(self.book.options.get_str("tex.command").unwrap(),
"result.tex",
to)
}
@ -240,9 +240,9 @@ impl<'a> Renderer for LatexRenderer<'a> {
if self.book.options.get_bool("rendering.initials").unwrap() {
let mut chars = content.chars().peekable();
let initial = chars.next()
.ok_or(Error::parser(&self.book.source,
lformat!("empty str token, could not find \
initial")))?;
.ok_or_else(|| Error::parser(&self.book.source,
lformat!("empty str token, could not find \
initial")))?;
let mut first_word = String::new();
loop {
let c = if let Some(next_char) = chars.peek() {
@ -319,7 +319,7 @@ impl<'a> Renderer for LatexRenderer<'a> {
4 => content.push_str(r"\subsubsection"),
_ => content.push_str(r"\paragraph"),
}
if self.current_chapter.is_numbered() == false {
if !self.current_chapter.is_numbered() {
content.push_str("*");
}
content.push_str(r"{");
@ -454,13 +454,13 @@ impl<'a> Renderer for LatexRenderer<'a> {
Token::Annotation(ref annotation, ref vec) => {
let content = self.render_vec(vec)?;
if self.proofread {
match annotation {
&Data::GrammarError(ref s) => {
match *annotation {
Data::GrammarError(ref s) => {
Ok(format!("\\underline{{{}}}\\protect\\footnote{{{}}}",
content,
escape::tex(s.as_str())))
},
&Data::Repetition(ref colour) => {
Data::Repetition(ref colour) => {
if !self.escape && colour == "red" {
Ok(format!("\\underline{{{}}}",
content))
@ -490,7 +490,7 @@ impl BookRenderer for Latex {
fn render(&self, book: &Book, to: &mut Write) -> Result<()> {
let mut latex = LatexRenderer::new(book);
let result = latex.render_book()?;
to.write_all(&result.as_bytes())
to.write_all(result.as_bytes())
.map_err(|e| {
Error::render(&book.source,
lformat!("problem when writing LaTeX: {error}", error = e))
@ -503,7 +503,7 @@ impl BookRenderer for ProofLatex {
fn render(&self, book: &Book, to: &mut Write) -> Result<()> {
let mut latex = LatexRenderer::new(book).proofread();
let result = latex.render_book()?;
to.write_all(&result.as_bytes())
to.write_all(result.as_bytes())
.map_err(|e| {
Error::render(&book.source,
lformat!("problem when writing LaTeX: {error}", error = e))

View File

@ -27,7 +27,7 @@ use std::io::Result;
/// unmodified path if it fails (e.g. if the path doesn't exist (yet))
pub fn normalize<P: AsRef<Path>>(path: P) -> String {
try_normalize(path.as_ref())
.unwrap_or(format!("{}", path.as_ref().display()))
.unwrap_or_else(|_| format!("{}", path.as_ref().display()))
}
@ -57,9 +57,8 @@ fn try_normalize<P: AsRef<Path>>(path: P) -> Result<String> {
/// Insert a title (if there is none) to a vec of tokens
pub fn insert_title(tokens: &mut Vec<Token>) {
for token in tokens.iter() {
match token {
&Token::Header(1, _) => return,
_ => {}
if let &Token::Header(1, _) = token {
return;
}
}
tokens.insert(0, Token::Header(1, vec!()));

View File

@ -69,7 +69,7 @@ impl<'a> OdtRenderer<'a> {
// unzip it
zipper.unzip("template.odt")?;
// Complete it with content.xml
zipper.write("content.xml", &content.as_bytes(), false)?;
zipper.write("content.xml", content.as_bytes(), false)?;
// Zip and copy
zipper.generate_odt(self.book.options.get_str("crowbook.zip.command").unwrap(),
to)
@ -128,7 +128,7 @@ impl<'a> OdtRenderer<'a> {
let mut res = String::new();
for token in tokens {
res.push_str(&self.parse_token(&token));
res.push_str(&self.parse_token(token));
}
res
}

View File

@ -77,7 +77,7 @@ impl RepetitionDetector {
parser.detect_local(&mut ast, self.threshold);
let repetitions = parser.ast_to_repetitions(&ast);
for repetition in repetitions.iter() {
for repetition in &repetitions {
insert_annotation(v,
&Data::Repetition(repetition.colour.to_string()),
repetition.offset,

View File

@ -87,7 +87,7 @@ impl<'r> ResourceHandler<'r> {
// If this image has already been registered, returns it
if self.images.contains_key(file.as_ref()) {
return Ok(Cow::Borrowed(self.images.get(file.as_ref()).unwrap()));
return Ok(Cow::Borrowed(&self.images[file.as_ref()]));
}
// Else, create a new file name that has same extension
@ -207,7 +207,7 @@ impl<'r> ResourceHandler<'r> {
pub fn get_files(list: Vec<String>, base: &str) -> Result<Vec<String>> {
let mut out: Vec<String> = vec![];
let base = Path::new(base);
for path in list.into_iter() {
for path in list {
let abs_path = base.join(&path);
let res = fs::metadata(&abs_path);
match res {

View File

@ -47,7 +47,7 @@ impl Syntax {
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
let theme = &self.theme_set.themes["InspiredGitHub"];
let mut h = syntect::easy::HighlightLines::new(syntax, theme);
let regions = h.highlight(&code);
let regions = h.highlight(code);
format!("<pre>{}</pre>",
syntect::html::styles_to_coloured_html(&regions[..],
syntect::html::IncludeBackground::No))
@ -60,10 +60,10 @@ impl Syntax {
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
let theme = &self.theme_set.themes["InspiredGitHub"];
let mut h = syntect::easy::HighlightLines::new(syntax, theme);
let regions = h.highlight(&code);
let regions = h.highlight(code);
let mut result = String::with_capacity(code.len());
for (style, text) in regions.into_iter() {
for (style, text) in regions {
let mut content = escape::tex(text).into_owned();
content = insert_breaks(&content);
content = content.replace('\n', "\\\\\n")

View File

@ -27,20 +27,20 @@ pub fn traverse_token<F1, F2, R>(token: &Token, f: &F1, add: &F2) -> R
R: Default,
F2: Fn(R, R) -> R
{
match token {
&Token::Str(ref s) => f(s),
match *token {
Token::Str(ref s) => f(s),
&Token::Rule |
&Token::SoftBreak |
&Token::HardBreak => f("\n"),
Token::Rule |
Token::SoftBreak |
Token::HardBreak => f("\n"),
&Token::Image(..) |
&Token::StandaloneImage(..) |
&Token::Footnote(..) |
&Token::Table(..) |
&Token::TableHead(..) |
&Token::TableRow(..) |
&Token::TableCell(..) => f(""),
Token::Image(..) |
Token::StandaloneImage(..) |
Token::Footnote(..) |
Token::Table(..) |
Token::TableHead(..) |
Token::TableRow(..) |
Token::TableCell(..) => f(""),
_ => traverse_vec(token.inner().unwrap(), f, add),
}
@ -55,7 +55,7 @@ pub fn traverse_vec<F1, F2, R>(tokens: &[Token], f: &F1, add: &F2) -> R
{
tokens.iter()
.map(|t| traverse_token(t, f, add))
.fold(R::default(), |r1, r2| add(r1, r2))
.fold(R::default(), add)
}
@ -98,7 +98,7 @@ pub fn insert_annotation(tokens: &mut Vec<Token>,
break;
}
}
pos = pos - len;
pos -= len;
false
}
@ -120,7 +120,7 @@ pub fn insert_annotation(tokens: &mut Vec<Token>,
}
_ => {
if let Some(ref inner) = tokens[i].inner() {
if let Some(inner) = tokens[i].inner() {
let len = count_length(inner);
// Only recurse if the two is in this subtree
if pos < len {