1
0
Fork 0
mirror of https://github.com/lise-henry/crowbook synced 2024-05-28 18:16:32 +02:00

Use log crate to display log messages

This commit is contained in:
Elisabeth Henry 2017-10-04 03:12:02 +02:00
parent a4e074f68b
commit 63fe7b2a6f
19 changed files with 149 additions and 148 deletions

15
Cargo.lock generated
View File

@ -1,6 +1,6 @@
[root]
name = "crowbook"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"caribon 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
"clap 2.26.2 (registry+https://github.com/rust-lang/crates.io-index)",
@ -10,12 +10,14 @@ dependencies = [
"epub-builder 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"mime_guess 1.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
"mustache 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
"numerals 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"pulldown-cmark 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rayon 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
"simplelog 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"syntect 1.7.3 (registry+https://github.com/rust-lang/crates.io-index)",
"term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"url 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
@ -700,6 +702,16 @@ dependencies = [
"serde 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "simplelog"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "siphasher"
version = "0.2.2"
@ -1032,6 +1044,7 @@ dependencies = [
"checksum serde_derive 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)" = "1afcaae083fd1c46952a315062326bc9957f182358eb7da03b57ef1c688f7aa9"
"checksum serde_derive_internals 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bd381f6d01a6616cdba8530492d453b7761b456ba974e98768a18cad2cd76f58"
"checksum serde_json 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d243424e06f9f9c39e3cd36147470fd340db785825e367625f79298a6ac6b7ac"
"checksum simplelog 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2c3a63f2b74bc3359ed6050da62e32cc0e10a162c4f62a0c1d80cd89d432234b"
"checksum siphasher 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0df90a788073e8d0235a67e50441d47db7c8ad9debd91cbf43736a2a92d36537"
"checksum stemmer 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8bc851510b472ff407137208a23f4f58e0cb41fdb5c3e38c9fd4482ea03c46f1"
"checksum strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d15c810519a91cf877e7e36e63fe068815c678181439f2f29e2562147c3694"

View File

@ -37,8 +37,9 @@ path = "src/bin/main.rs"
doc = false
[features]
default = ["clap", "proofread", "syntect"]
default = ["binary", "proofread", "syntect"]
proofread = ["caribon", "hyper", "url"]
binary = ["clap", "simplelog"]
[build-dependencies]
crowbook-intl = "0.2"
@ -58,8 +59,10 @@ term = "0.4"
crowbook-intl-runtime = "0.1"
numerals = "0.1"
epub-builder = "0.3"
log = "0.3"
caribon = { version = "0.8", optional = true }
clap = { version = "2.19", optional = true }
simplelog = { version = "0.4", optional = true }
url = { version = "1", optional = true }
syntect = { version = "1", optional = true }
@ -67,3 +70,5 @@ syntect = { version = "1", optional = true }
version = "0.10"
optional = true
default-features = false

View File

@ -30,10 +30,10 @@ build: false
# Equivalent to Travis' `script` phase
# TODO modify this phase as you see fit
test_script:
- cargo build --no-default-features --features="clap proofread" --verbose
- cargo run --no-default-features --features="clap proofread"
- cargo test --no-default-features --features="clap proofread"
- cargo build --release --no-default-features --features="clap proofread"
- cargo build --no-default-features --features="binary proofread" --verbose
- cargo run --no-default-features --features="binary proofread"
- cargo test --no-default-features --features="binary proofread"
- cargo build --release --no-default-features --features="binary proofread"
# Equivalent to `before_deploy` phase
after_test:

View File

@ -22,11 +22,7 @@ pub fn get_lang() -> Option<String> {
/// Prints an error on stderr and exit the program
pub fn print_error(s: &str) -> ! {
writeln!(&mut io::stderr(),
"{} {}",
Format::Error(lformat!("Error:")),
s)
.unwrap();
error!("{}", s);
exit(0);
}

View File

@ -1,29 +1,34 @@
extern crate crowbook;
extern crate crowbook_intl_runtime;
#[macro_use]
extern crate log;
#[cfg(feature = "clap")]
#[cfg(feature= "binary")]
extern crate simplelog;
#[cfg(feature = "binary")]
extern crate clap;
#[macro_use]
mod localize_macros;
#[cfg(feature = "clap")]
#[cfg(feature = "binary")]
mod real_main;
#[cfg(feature = "clap")]
#[cfg(feature = "binary")]
mod helpers;
#[cfg(feature = "clap")]
#[cfg(feature = "binary")]
#[cfg(feature = "clap")]
#[cfg(feature = "binary")]
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "clap")]
#[cfg(feature = "binary")]
fn main() {
real_main::real_main();
}
#[cfg(not(feature = "clap"))]
#[cfg(not(feature = "binary"))]
fn main() {
println!("Clap dependency is required to build the binary.");
println!("In order to work, the binary must be compiled with the \"binary\" feature.");
}

View File

@ -26,7 +26,7 @@ use clap::ArgMatches;
use std::process::exit;
use std::io;
use std::env;
use simplelog::{Config, TermLogger, CombinedLogger, LogLevel, LogLevelFilter, SimpleLogger, SharedLogger};
/// Render a book to specific format
fn render_format(book: &mut Book, matches: &ArgMatches, format: &str) -> ! {
@ -131,17 +131,26 @@ pub fn try_main() -> Result<()> {
// ok to unwrap since clap checks it's there
let s = matches.value_of("BOOK").unwrap();
let verbosity = if matches.is_present("verbose") {
InfoLevel::Debug
} else if matches.is_present("quiet") {
InfoLevel::Quiet
} else {
InfoLevel::Warning
};
// Initalize logger
let verbosity = if matches.is_present("verbose") {
LogLevelFilter::Debug
} else if matches.is_present("quiet") {
LogLevelFilter::Error
} else {
LogLevelFilter::Info
};
let mut log_config = Config::default();
log_config.time = Some(LogLevel::Debug);
if TermLogger::init(verbosity, log_config).is_err() {
SimpleLogger::init(verbosity, log_config).unwrap();
}
let mut book = Book::new();
book.set_verbosity(verbosity)
.set_options(&get_book_options(&matches));
book.set_options(&get_book_options(&matches));
if matches.is_present("single") {
if s != "-" {

View File

@ -259,11 +259,10 @@ impl Book {
// set options
for &(key, value) in options {
if let Err(err) = self.options.set(key, value) {
self.logger
.error(lformat!("Error initializing book: could not set {key} to {value}: {error}",
key = key,
value = value,
error = err));
error!("{}", lformat!("Error initializing book: could not set {key} to {value}: {error}",
key = key,
value = value,
error = err));
}
}
// set cleaner according to lang and autoclean settings
@ -422,7 +421,7 @@ impl Book {
if let Yaml::Hash(hash) = docs.pop().unwrap() {
for (key, value) in hash {
if let Err(err) = self.options.set_yaml(key, value) {
self.logger.error(format!("{}", err));
error!("{}", err);
};
}
} else {
@ -794,13 +793,13 @@ impl Book {
/// * `render_format`, which won't do anything if `output.{format}` isn't specified
/// in the book configuration file.
pub fn render_format_to<T: Write>(&self, format: &str, f: &mut T) -> Result<()> {
self.logger.debug(lformat!("Attempting to generate {format}...",
format = format));
debug!("{}", lformat!("Attempting to generate {format}...",
format = format));
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => {
renderer.render(self, f)?;
self.logger.info(lformat!("Succesfully generated {format}",
format = description));
info!("{}", lformat!("Succesfully generated {format}",
format = description));
Ok(())
},
None => {
@ -822,8 +821,8 @@ impl Book {
/// * `render_format`, which won't do anything if `output.{format}` isn't specified
/// in the book configuration file.
pub fn render_format_to_file<P:Into<PathBuf>>(&self, format: &str, path: P) -> Result<()> {
self.logger.debug(lformat!("Attempting to generate {format}...",
format = format));
debug!("{}", lformat!("Attempting to generate {format}...",
format = format));
let path = path.into();
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => {
@ -846,9 +845,9 @@ impl Book {
path
};
renderer.render_to_file(self, &path)?;
self.logger.info(lformat!("Succesfully generated {format}: {path}",
format = description,
path = misc::normalize(path)));
info!("{}", lformat!("Succesfully generated {format}: {path}",
format = description,
path = misc::normalize(path)));
Ok(())
},
None => {
@ -891,8 +890,7 @@ impl Book {
Path::new("")
};
if offset.starts_with("..") {
self.logger
.debug(lformat!("Warning: book contains chapter '{file}' in a directory above \
debug!("{}", lformat!("Warning: book contains chapter '{file}' in a directory above \
the book file, this might cause problems",
file = misc::normalize(file)));
}
@ -926,34 +924,31 @@ impl Book {
// If one of the renderers requires it, perform grammarcheck
if cfg!(feature = "proofread") && self.is_proofread() {
if let Some(ref checker) = self.checker {
self.logger
.info(lformat!("Trying to run languagetool on {file}, this might take a \
info!("{}", lformat!("Trying to run languagetool on {file}, this might take a \
while...",
file = misc::normalize(file)));
file = misc::normalize(file)));
if let Err(err) = checker.check_chapter(&mut tokens) {
self.logger.error(lformat!("Error running languagetool on {file}: {error}",
file = misc::normalize(file),
error = err));
error!("{}", lformat!("Error running languagetool on {file}: {error}",
file = misc::normalize(file),
error = err));
}
}
if let Some(ref checker) = self.grammalecte {
self.logger
.info(lformat!("Trying to run grammalecte on {file}, this might take a \
info!("{}", lformat!("Trying to run grammalecte on {file}, this might take a \
while...",
file = misc::normalize(file)));
if let Err(err) = checker.check_chapter(&mut tokens) {
self.logger.error(lformat!("Error running grammalecte on {file}: {error}",
error!("{}", lformat!("Error running grammalecte on {file}: {error}",
file = misc::normalize(file),
error = err));
}
}
if let Some(ref detector) = self.detector {
self.logger
.info(lformat!("Trying to run repetition detector on {file}, this might take a \
while...",
file = misc::normalize(file)));
info!("{}", lformat!("Trying to run repetition detector on {file}, this might take a \
while...",
file = misc::normalize(file)));
if let Err(err) = detector.check_chapter(&mut tokens) {
self.logger.error(lformat!("Error running repetition detector on {file}: {error}",
error!("{}", lformat!("Error running repetition detector on {file}: {error}",
file = misc::normalize(file),
error = err));
}
@ -1012,7 +1007,7 @@ impl Book {
/// **Returns** an error if `file` does not exist, could not be read, of if there was
/// some error parsing it.
pub fn add_chapter(&mut self, number: Number, file: &str) -> Result<&mut Self> {
self.logger.debug(lformat!("Parsing chapter: {file}...",
debug!("{}", lformat!("Parsing chapter: {file}...",
file = misc::normalize(file)));
// try to open file
@ -1338,7 +1333,7 @@ impl Book {
}
}
} else {
self.logger.debug(lformat!("Ignoring YAML \
debug!("{}", lformat!("Ignoring YAML \
block:\n---\n{block}---",
block = &yaml_block));
}

View File

@ -614,7 +614,7 @@ impl BookOptions {
} else if self.deprecated.contains_key(&key) {
let opt = self.deprecated[&key].clone();
if let Some(new_key) = opt {
Logger::display_warning(lformat!("'{old_key}' has been deprecated, you should \
warn!("{}", lformat!("'{old_key}' has been deprecated, you should \
now use '{new_key}'",
old_key = &key,
new_key = &new_key));

View File

@ -362,13 +362,10 @@ impl<'a> EpubRenderer<'a> {
self.chapter_title = self.html.render_vec(vec)?;
self.chapter_title_raw = view_as_text(vec);
} else {
self.html
.book
.logger
.warning(lformat!("EPUB ({source}): detected two chapter titles inside the \
same markdown file, in a file where chapter titles are \
not even rendered.",
source = self.html.source));
warn!("{}", lformat!("EPUB ({source}): detected two chapter titles inside the \
same markdown file, in a file where chapter titles are \
not even rendered.",
source = self.html.source));
}
} else {
let header;
@ -401,19 +398,13 @@ impl<'a> EpubRenderer<'a> {
})?
.text;
} else {
self.html
.book
.logger
.warning(lformat!("EPUB ({source}): detected two chapters inside the same \
markdown file.",
source = self.html.source));
self.html
.book
.logger
.warning(lformat!("EPUB ({source}): conflict between: {title1} and {title2}",
source = self.html.source,
title1 = self.chapter_title,
title2 = s));
warn!("{}", lformat!("EPUB ({source}): detected two chapters inside the same \
markdown file.",
source = self.html.source));
warn!("{}", lformat!("EPUB ({source}): conflict between: {title1} and {title2}",
source = self.html.source,
title1 = self.chapter_title,
title2 = s));
}
}
Ok(())
@ -425,12 +416,9 @@ impl<'a> EpubRenderer<'a> {
match opt {
Some(s) => s.to_string(),
None => {
self.html
.book
.logger
.error(lformat!("EPUB: could not guess the format of {file} based on \
extension. Assuming png.",
file = s));
error!("{}", lformat!("EPUB: could not guess the format of {file} based on \
extension. Assuming png.",
file = s));
String::from("png")
}
}

View File

@ -152,7 +152,7 @@ impl GrammalecteChecker {
}
}
if check.data.len() > 1 {
Logger::display_warning(lformat!("some error messages from Grammalecte were ignored because of format"));
warn!("{}", lformat!("some error messages from Grammalecte were ignored because of format"));
}
Ok(())
},

View File

@ -128,8 +128,8 @@ impl<'a> HtmlRenderer<'a> {
"none" => (Highlight::None, None),
"highlight.js" => (Highlight::Js, None),
value => {
Logger::display_error(lformat!("rendering.highlight set to '{}', not a valid value",
value));
error!("{}", lformat!("rendering.highlight set to '{}', not a valid value",
value));
(Highlight::None, None)
}
}
@ -347,8 +347,8 @@ impl<'a> HtmlRenderer<'a> {
"{:X}.",
Roman::from(self.current_chapter[i] as i16)).unwrap();
} else {
self.book.logger.error(lformat!("can not use roman numerals with zero or negative chapter numbers ({n})",
n = self.current_chapter[i]));
error!("{}", lformat!("can not use roman numerals with zero or negative chapter numbers ({n})",
n = self.current_chapter[i]));
}
}
output

View File

@ -77,10 +77,7 @@ impl<'a> HtmlDirRenderer<'a> {
directory",
path = dest_path.display())));
} else if metadata.is_dir() {
self.html
.book
.logger
.debug(lformat!("{path} already exists, deleting it",
debug!("{}", lformat!("{path} already exists, deleting it",
path = dest_path.display()));
fs::remove_dir_all(&dest_path)
.map_err(|e| {

View File

@ -200,11 +200,9 @@ impl<'a> LatexRenderer<'a> {
"uk" => "ukrainian",
"cy" => "welsh",
_ => {
self.book
.logger
.warning(lformat!("LaTeX: can't find a tex equivalent for lang '{lang}', \
fallbacking on english",
lang = self.book.options.get_str("lang").unwrap()));
warn!("{}", lformat!("LaTeX: can't find a tex equivalent for lang '{lang}', \
fallbacking on english",
lang = self.book.options.get_str("lang").unwrap()));
"english"
}
});
@ -455,12 +453,10 @@ impl<'a> Renderer for LatexRenderer<'a> {
img))
} else {
self.book
.logger
.debug(lformat!("LaTeX ({source}): image '{url}' doesn't seem to be \
local; ignoring it.",
source = self.source,
url = url));
debug!("{}", lformat!("LaTeX ({source}): image '{url}' doesn't seem to be \
local; ignoring it.",
source = self.source,
url = url));
Ok(String::new())
}
}
@ -469,12 +465,10 @@ impl<'a> Renderer for LatexRenderer<'a> {
Ok(format!("\\mdimage{{{}}}",
self.handler.map_image(&self.source, url.as_ref())?))
} else {
self.book
.logger
.debug(lformat!("LaTeX ({source}): image '{url}' doesn't seem to be \
local; ignoring it.",
source = self.source,
url = url));
debug!("{}", lformat!("LaTeX ({source}): image '{url}' doesn't seem to be \
local; ignoring it.",
source = self.source,
url = url));
Ok(String::new())
}
}

View File

@ -118,6 +118,8 @@ extern crate numerals;
extern crate epub_builder;
extern crate uuid;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "proofread")]

View File

@ -91,9 +91,9 @@ impl<'a> OdtRenderer<'a> {
if !missing.is_empty() {
let missing = missing.join(", ");
self.book.logger.warning(lformat!("ODT: The document uses the following features, that are not implemented for ODT output: {features}",
features = missing));
self.book.logger.warning(lformat!("ODT: They will be ignored in the generated document."));
warn!("{}", lformat!("ODT: The document uses the following features, that are not implemented for ODT output: {features}",
features = missing));
warn!("{}", lformat!("ODT: They will be ignored in the generated document."));
}
@ -119,7 +119,7 @@ impl<'a> OdtRenderer<'a> {
}
}
if n.is_part() {
self.book.logger.error(lformat!("Parts are not supported yet in ODT"));
error!("{}", lformat!("Parts are not supported yet in ODT"));
}
for token in v {

View File

@ -333,7 +333,7 @@ impl Parser {
if self.html_as_text {
v.push(Token::Str(text.into_owned()));
} else {
Logger::display_debug(lformat!("ignoring HTML block '{}'", text));
debug!("{}", lformat!("ignoring HTML block '{}'", text));
}
},
@ -411,11 +411,11 @@ impl Parser {
Tag::TableCell => Token::TableCell(res),
Tag::FootnoteDefinition(reference) => {
if self.footnotes.contains_key(reference.as_ref()) {
Logger::display_warning(lformat!("in {file}, found footnote definition for \
note '{reference}' but previous \
definition already exist, overriding it",
file = self.source,
reference = reference));
warn!("{}", lformat!("in {file}, found footnote definition for \
note '{reference}' but previous \
definition already exist, overriding it",
file = self.source,
reference = reference));
}
self.footnotes.insert(reference.into_owned(), res);
Token::SoftBreak

View File

@ -68,10 +68,9 @@ impl<'r> ResourceHandler<'r> {
// If image is not local, do nothing much
let file = file.into();
if !Self::is_local(file.as_ref()) {
self.logger
.warning(lformat!("Resources: book includes non-local image {file}, which might \
cause problem for proper inclusion.",
file = file));
warn!("{}", lformat!("Resources: book includes non-local image {file}, which might \
cause problem for proper inclusion.",
file = file));
return Ok(file);
}
@ -98,10 +97,9 @@ impl<'r> ResourceHandler<'r> {
self.images.len(),
extension.to_string_lossy())
} else {
self.logger
.warning(lformat!("Resources: book includes image {file} which doesn't have \
an extension",
file = file));
warn!("{}", lformat!("Resources: book includes image {file} which doesn't have \
an extension",
file = file));
format!("images/image_{}", self.images.len())
}
} else {
@ -116,15 +114,14 @@ impl<'r> ResourceHandler<'r> {
};
let mut content: Vec<u8> = vec![];
if f.read_to_end(&mut content).is_err() {
self.logger.error(lformat!("Resources: could not read file {file}", file = file));
error!("{}", lformat!("Resources: could not read file {file}", file = file));
return Ok(file);
}
let base64 = content.to_base64(base64::STANDARD);
match mime_guess::guess_mime_type_opt(file.as_ref()) {
None => {
self.logger
.error(lformat!("Resources: could not guess mime type of file {file}",
file = file));
error!("{}", lformat!("Resources: could not guess mime type of file {file}",
file = file));
return Ok(file);
}
Some(s) => format!("data:{};base64,{}", s.to_string(), base64),
@ -158,9 +155,9 @@ impl<'r> ResourceHandler<'r> {
if let Some(link) = self.links.get(&new_from) {
link
} else {
self.logger.warning(lformat!("Resources: could not find an in-book match for link \
{file}",
file = from));
warn!("{}", lformat!("Resources: could not find an in-book match for link \
{file}",
file = from));
from
}
}

View File

@ -42,9 +42,9 @@ impl Syntax {
let theme = match theme_set.themes.remove(theme_name) {
Some(theme) => theme,
None => {
book.logger.error(lformat!("could not set syntect theme to {theme}, defaulting to \"InspiredGithub\"",
error!("{}", lformat!("could not set syntect theme to {theme}, defaulting to \"InspiredGithub\"",
theme = theme_name));
book.logger.info(lformat!("valid theme names are: {themes}",
info!("{}", lformat!("valid theme names are: {themes}",
themes = theme_set.themes
.keys()
.map(|s| s.to_owned())
@ -128,7 +128,7 @@ fn strip_language(language: &str) -> &str {
#[cfg(not(feature="syntect"))]
impl Syntax {
pub fn new(book: &Book, _: &str) -> Syntax {
book.logger.error(lformat!("crowbook was compiled without syntect support, syntax highlighting will be disabled"));
error!("{}", lformat!("crowbook was compiled without syntect support, syntax highlighting will be disabled"));
Syntax {}
}

View File

@ -128,10 +128,10 @@ pub fn insert_annotation(tokens: &mut Vec<Token>,
if found_left.is_none() {
true
} else {
Logger::display_warning(lformat!("ignored annotation {:?} as it \
wasn't compatible with the \
Markdown structure",
annotation));
warn!("{}", lformat!("ignored annotation {:?} as it \
wasn't compatible with the \
Markdown structure",
annotation));
return None;
}
} else {
@ -256,7 +256,7 @@ pub fn insert_annotation(tokens: &mut Vec<Token>,
} else if found_left.is_none() && found_right.is_none() {
return Some(pos);
} else {
Logger::display_warning(lformat!("ignored annotation {:?} as it wasn't compatible \
warn!("{}", lformat!("ignored annotation {:?} as it wasn't compatible \
with the Markdown structure",
annotation));
return None;