Made the logging a lot quieter by default (#569)

This commit is contained in:
Michael Bryan 2018-01-23 01:28:37 +08:00 committed by GitHub
parent 0d146ffa82
commit 5379a0bdf8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 117 additions and 126 deletions

View file

@ -46,7 +46,7 @@ fn create_missing(src_dir: &Path, summary: &Summary) -> Result<()> {
fs::create_dir_all(parent)?;
}
}
debug!("[*] Creating missing file {}", filename.display());
debug!("Creating missing file {}", filename.display());
let mut f = File::create(&filename)?;
writeln!(f, "# {}", link.name)?;
@ -159,7 +159,7 @@ impl Chapter {
/// You need to pass in the book's source directory because all the links in
/// `SUMMARY.md` give the chapter locations relative to it.
fn load_book_from_disk<P: AsRef<Path>>(summary: &Summary, src_dir: P) -> Result<Book> {
debug!("[*] Loading the book from disk");
debug!("Loading the book from disk");
let src_dir = src_dir.as_ref();
let prefix = summary.prefix_chapters.iter();
@ -186,7 +186,7 @@ fn load_summary_item<P: AsRef<Path>>(item: &SummaryItem, src_dir: P) -> Result<B
}
fn load_chapter<P: AsRef<Path>>(link: &Link, src_dir: P) -> Result<Chapter> {
debug!("[*] Loading {} ({})", link.name, link.location.display());
debug!("Loading {} ({})", link.name, link.location.display());
let src_dir = src_dir.as_ref();
let location = if link.location.is_absolute() {

View file

@ -8,7 +8,6 @@ use super::MDBook;
use theme;
use errors::*;
/// A helper for setting up a new book and its directory structure.
#[derive(Debug, Clone, PartialEq)]
pub struct BookBuilder {
@ -97,7 +96,7 @@ impl BookBuilder {
}
fn write_book_toml(&self) -> Result<()> {
debug!("[*] Writing book.toml");
debug!("Writing book.toml");
let book_toml = self.root.join("book.toml");
let cfg = toml::to_vec(&self.config).chain_err(|| "Unable to serialize the config")?;
@ -109,7 +108,7 @@ impl BookBuilder {
}
fn copy_across_theme(&self) -> Result<()> {
debug!("[*] Copying theme");
debug!("Copying theme");
let themedir = self.config
.html_config()
@ -118,7 +117,10 @@ impl BookBuilder {
let themedir = self.root.join(themedir);
if !themedir.exists() {
debug!("[*]: {:?} does not exist, creating the directory", themedir);
debug!(
"{} does not exist, creating the directory",
themedir.display()
);
fs::create_dir(&themedir)?;
}
@ -144,7 +146,7 @@ impl BookBuilder {
}
fn build_gitignore(&self) -> Result<()> {
debug!("[*]: Creating .gitignore");
debug!("Creating .gitignore");
let mut f = File::create(self.root.join(".gitignore"))?;
@ -154,7 +156,7 @@ impl BookBuilder {
}
fn create_stub_files(&self) -> Result<()> {
debug!("[*] Creating example book contents");
debug!("Creating example book contents");
let src_dir = self.root.join(&self.config.book.src);
let summary = src_dir.join("SUMMARY.md");
@ -171,7 +173,7 @@ impl BookBuilder {
}
fn create_directory_structure(&self) -> Result<()> {
debug!("[*]: Creating directory tree");
debug!("Creating directory tree");
fs::create_dir_all(&self.root)?;
let src = self.root.join(&self.config.book.src);

View file

@ -21,7 +21,7 @@ use toml::Value;
use utils;
use renderer::{CmdRenderer, HtmlHandlebars, RenderContext, Renderer};
use preprocess::{Preprocessor, LinkPreprocessor, PreprocessorContext};
use preprocess::{LinkPreprocessor, Preprocessor, PreprocessorContext};
use errors::*;
use config::Config;
@ -37,7 +37,7 @@ pub struct MDBook {
renderers: Vec<Box<Renderer>>,
/// List of pre-processors to be run on the book
preprocessors: Vec<Box<Preprocessor>>
preprocessors: Vec<Box<Preprocessor>>,
}
impl MDBook {
@ -57,7 +57,7 @@ impl MDBook {
}
let mut config = if config_location.exists() {
debug!("[*] Loading config from {}", config_location.display());
debug!("Loading config from {}", config_location.display());
Config::from_disk(&config_location)?
} else {
Config::default()
@ -147,7 +147,7 @@ impl MDBook {
/// Tells the renderer to build our book and put it in the build directory.
pub fn build(&self) -> Result<()> {
debug!("[fn]: build");
info!("Book building has started");
let mut preprocessed_book = self.book.clone();
let preprocess_ctx = PreprocessorContext::new(self.root.clone(), self.config.clone());
@ -158,6 +158,7 @@ impl MDBook {
}
for renderer in &self.renderers {
info!("Running the {} backend", renderer.name());
self.run_renderer(&preprocessed_book, renderer.as_ref())?;
}
@ -223,7 +224,7 @@ impl MDBook {
if !ch.path.as_os_str().is_empty() {
let path = self.source_dir().join(&ch.path);
let content = utils::fs::file_to_string(&path)?;
println!("[*]: Testing file: {:?}", path);
info!("Testing file: {:?}", path);
// write preprocessed file to tempdir
let path = temp_dir.path().join(&ch.path);
@ -327,22 +328,19 @@ fn default_preprocessors() -> Vec<Box<Preprocessor>> {
/// Look at the `MDBook` and try to figure out what preprocessors to run.
fn determine_preprocessors(config: &Config) -> Result<Vec<Box<Preprocessor>>> {
let preprocess_list = match config.build.preprocess {
Some(ref p) => p,
// If no preprocessor field is set, default to the LinkPreprocessor. This allows you
// to disable the LinkPreprocessor by setting "preprocess" to an empty list.
None => return Ok(default_preprocessors())
None => return Ok(default_preprocessors()),
};
let mut preprocessors: Vec<Box<Preprocessor>> = Vec::new();
for key in preprocess_list {
match key.as_ref() {
"links" => {
preprocessors.push(Box::new(LinkPreprocessor::new()))
}
_ => bail!("{:?} is not a recognised preprocessor", key),
"links" => preprocessors.push(Box::new(LinkPreprocessor::new())),
_ => bail!("{:?} is not a recognised preprocessor", key),
}
}
@ -431,7 +429,6 @@ mod tests {
preprocess = []
"#;
let cfg = Config::from_str(cfg_str).unwrap();
// make sure we have something in the `output` table
@ -455,7 +452,6 @@ mod tests {
preprocess = ["random"]
"#;
let cfg = Config::from_str(cfg_str).unwrap();
// make sure we have something in the `output` table

View file

@ -240,7 +240,7 @@ impl<'a> SummaryParser<'a> {
fn parse_affix(&mut self, is_prefix: bool) -> Result<Vec<SummaryItem>> {
let mut items = Vec::new();
debug!(
"[*] Parsing {} items",
"Parsing {} items",
if is_prefix { "prefix" } else { "suffix" }
);
@ -362,7 +362,7 @@ impl<'a> SummaryParser<'a> {
}
fn parse_nested_numbered(&mut self, parent: &SectionNumber) -> Result<Vec<SummaryItem>> {
debug!("[*] Parsing numbered chapters at level {}", parent);
debug!("Parsing numbered chapters at level {}", parent);
let mut items = Vec::new();
loop {
@ -406,7 +406,7 @@ impl<'a> SummaryParser<'a> {
let mut number = parent.clone();
number.0.push(num_existing_items as u32 + 1);
trace!(
"[*] Found chapter: {} {} ({})",
"Found chapter: {} {} ({})",
number,
link.name,
link.location.display()
@ -435,7 +435,7 @@ impl<'a> SummaryParser<'a> {
/// Try to parse the title line.
fn parse_title(&mut self) -> Option<String> {
if let Some(Event::Start(Tag::Header(1))) = self.next_event() {
debug!("[*] Found a h1 in the SUMMARY");
debug!("Found a h1 in the SUMMARY");
let tags = collect_events!(self.stream, end Tag::Header(1));
Some(stringify_events(tags))

View file

@ -10,7 +10,7 @@ use regex::{Captures, Regex};
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::io::{Read, Write};
use std::collections::BTreeMap;
use std::collections::HashMap;
@ -53,11 +53,9 @@ impl HtmlHandlebars {
print_content.push_str(&content);
// Update the context with data for this file
let path = ch.path.to_str().ok_or_else(|| {
io::Error::new(io::ErrorKind::Other,
"Could not convert path \
to str")
})?;
let path = ch.path
.to_str()
.chain_err(|| "Could not convert path to str")?;
// "print.html" is used for the print page.
if ch.path == Path::new("print.md") {
@ -82,7 +80,7 @@ impl HtmlHandlebars {
json!(utils::fs::path_to_root(&ch.path)));
// Render the handlebars template with the data
debug!("[*]: Render template");
debug!("Render template");
let rendered = ctx.handlebars.render("index", &ctx.data)?;
let filepath = Path::new(&ch.path).with_extension("html");
@ -95,7 +93,7 @@ impl HtmlHandlebars {
);
// Write to file
info!("[*] Creating {:?} ✓", filepath.display());
debug!("Creating {} ✓", filepath.display());
self.write_file(&ctx.destination, filepath, &rendered.into_bytes())?;
if ctx.is_index {
@ -110,7 +108,7 @@ impl HtmlHandlebars {
/// Create an index.html from the first element in SUMMARY.md
fn render_index(&self, ch: &Chapter, destination: &Path) -> Result<()> {
debug!("[*]: index.html");
debug!("index.html");
let mut content = String::new();
@ -127,8 +125,10 @@ impl HtmlHandlebars {
self.write_file(destination, "index.html", content.as_bytes())?;
info!("[*] Creating index.html from {:?} ✓",
destination.join(&ch.path.with_extension("html")));
debug!(
"Creating index.html from {} ✓",
destination.join(&ch.path.with_extension("html")).display()
);
Ok(())
}
@ -275,7 +275,7 @@ impl Renderer for HtmlHandlebars {
let destination = &ctx.destination;
let book = &ctx.book;
debug!("[fn]: render");
trace!("render");
let mut handlebars = Handlebars::new();
let theme_dir = match html_config.theme {
@ -285,19 +285,13 @@ impl Renderer for HtmlHandlebars {
let theme = theme::Theme::new(theme_dir);
debug!("[*]: Register the index handlebars template");
handlebars.register_template_string(
"index",
String::from_utf8(theme.index.clone())?,
)?;
debug!("Register the index handlebars template");
handlebars.register_template_string("index", String::from_utf8(theme.index.clone())?)?;
debug!("[*]: Register the header handlebars template");
handlebars.register_partial(
"header",
String::from_utf8(theme.header.clone())?,
)?;
debug!("Register the header handlebars template");
handlebars.register_partial("header", String::from_utf8(theme.header.clone())?)?;
debug!("[*]: Register handlebars helpers");
debug!("Register handlebars helpers");
self.register_hbs_helpers(&mut handlebars, &html_config);
let mut data = make_data(&ctx.root, &book, &ctx.config, &html_config)?;
@ -305,7 +299,6 @@ impl Renderer for HtmlHandlebars {
// Print version
let mut print_content = String::new();
debug!("[*]: Check if destination directory exists");
fs::create_dir_all(&destination)
.chain_err(|| "Unexpected error when constructing destination path")?;
@ -327,7 +320,7 @@ impl Renderer for HtmlHandlebars {
}
// Render the handlebars template with the data
debug!("[*]: Render template");
debug!("Render template");
let rendered = handlebars.render("index", &data)?;
@ -336,9 +329,9 @@ impl Renderer for HtmlHandlebars {
&html_config.playpen);
self.write_file(&destination, "print.html", &rendered.into_bytes())?;
info!("[*] Creating print.html ✓");
debug!("Creating print.html ✓");
debug!("[*] Copy static files");
debug!("Copy static files");
self.copy_static_files(&destination, &theme, &html_config)
.chain_err(|| "Unable to copy across static files")?;
self.copy_additional_css_and_js(&html_config, &destination)
@ -352,7 +345,7 @@ impl Renderer for HtmlHandlebars {
}
fn make_data(root: &Path, book: &Book, config: &Config, html_config: &HtmlConfig) -> Result<serde_json::Map<String, serde_json::Value>> {
debug!("[fn]: make_data");
trace!("make_data");
let html = config.html_config().unwrap_or_default();
let mut data = serde_json::Map::new();
@ -430,11 +423,9 @@ fn make_data(root: &Path, book: &Book, config: &Config, html_config: &HtmlConfig
}
chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or_else(|| {
io::Error::new(io::ErrorKind::Other,
"Could not convert path \
to str")
})?;
let path = ch.path
.to_str()
.chain_err(|| "Could not convert path to str")?;
chapter.insert("path".to_owned(), json!(path));
}
BookItem::Separator => {
@ -620,7 +611,6 @@ fn partition_source(s: &str) -> (String, String) {
(before, after)
}
struct RenderItemContext<'a> {
handlebars: &'a Handlebars,
destination: PathBuf,

View file

@ -47,7 +47,7 @@ fn find_chapter(
rc: &mut RenderContext,
target: Target
) -> Result<Option<StringMap>, RenderError> {
debug!("[*]: Get data from context");
debug!("Get data from context");
let chapters = rc.evaluate_absolute("chapters").and_then(|c| {
serde_json::value::from_value::<Vec<StringMap>>(c.clone())
@ -61,7 +61,7 @@ fn find_chapter(
let mut previous: Option<StringMap> = None;
debug!("[*]: Search for chapter");
debug!("Search for chapter");
for item in chapters {
match item.get("path") {
@ -87,7 +87,7 @@ fn render(
rc: &mut RenderContext,
chapter: &StringMap,
) -> Result<(), RenderError> {
debug!("[*]: Creating BTreeMap to inject in context");
trace!("Creating BTreeMap to inject in context");
let mut context = BTreeMap::new();
@ -104,7 +104,7 @@ fn render(
.map(|p| context.insert("link".to_owned(), json!(p.replace("\\", "/"))))
})?;
debug!("[*]: Render template");
trace!("Render template");
_h.template()
.ok_or_else(|| RenderError::new("Error with the handlebars template"))
@ -117,7 +117,7 @@ fn render(
}
pub fn previous(_h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
debug!("[fn]: previous (handlebars helper)");
trace!("previous (handlebars helper)");
if let Some(previous) = find_chapter(rc, Target::Previous)? {
render(_h, r, rc, &previous)?;
@ -127,7 +127,7 @@ pub fn previous(_h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(
}
pub fn next(_h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
debug!("[fn]: next (handlebars helper)");
trace!("next (handlebars helper)");
if let Some(next) = find_chapter(rc, Target::Next)? {
render(_h, r, rc, &next)?;

View file

@ -6,20 +6,12 @@ use std::fs::{self, File};
/// Takes a path to a file and try to read the file into a String
pub fn file_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => {
debug!("[*]: Failed to open {:?}", path);
bail!(e);
}
};
let mut content = String::new();
if let Err(e) = file.read_to_string(&mut content) {
debug!("[*]: Failed to read {:?}", path);
bail!(e);
}
File::open(path)
.chain_err(|| "Unable to open the file")?
.read_to_string(&mut content)
.chain_err(|| "Unable to read the file")?;
Ok(content)
}
@ -48,7 +40,7 @@ pub fn file_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
/// or a [pull-request](https://github.com/rust-lang-nursery/mdBook/pulls) to improve it.
pub fn path_to_root<P: Into<PathBuf>>(path: P) -> String {
debug!("[fn]: path_to_root");
debug!("path_to_root");
// Remove filename and add "../" for every directory
path.into()
@ -56,33 +48,30 @@ pub fn path_to_root<P: Into<PathBuf>>(path: P) -> String {
.expect("")
.components()
.fold(String::new(), |mut s, c| {
match c {
Component::Normal(_) => s.push_str("../"),
_ => {
debug!("[*]: Other path component... {:?}", c);
match c {
Component::Normal(_) => s.push_str("../"),
_ => {
debug!("Other path component... {:?}", c);
}
}
}
s
})
s
})
}
/// This function creates a file and returns it. But before creating the file
/// it checks every directory in the path to see if it exists,
/// and if it does not it will be created.
pub fn create_file(path: &Path) -> Result<File> {
debug!("[fn]: create_file");
debug!("Creating {}", path.display());
// Construct path
if let Some(p) = path.parent() {
debug!("Parent directory is: {:?}", p);
trace!("Parent directory is: {:?}", p);
fs::create_dir_all(p)?;
}
debug!("[*]: Create file: {:?}", path);
File::create(path).map_err(|e| e.into())
}
@ -102,25 +91,29 @@ pub fn remove_dir_content(dir: &Path) -> Result<()> {
Ok(())
}
///
///
/// Copies all files of a directory to another one except the files
/// with the extensions given in the `ext_blacklist` array
pub fn copy_files_except_ext(from: &Path,
to: &Path,
recursive: bool,
ext_blacklist: &[&str])
-> Result<()> {
debug!("[fn] copy_files_except_ext");
pub fn copy_files_except_ext(
from: &Path,
to: &Path,
recursive: bool,
ext_blacklist: &[&str],
) -> Result<()> {
debug!(
"Copying all files from {} to {} (blacklist: {:?})",
from.display(),
to.display(),
ext_blacklist
);
// Check that from and to are different
if from == to {
return Ok(());
}
debug!("[*] Loop");
for entry in fs::read_dir(from)? {
let entry = entry?;
debug!("[*] {:?}", entry.path());
let metadata = entry.metadata()?;
// If the entry is a dir and the recursive option is enabled, call itself
@ -128,17 +121,18 @@ pub fn copy_files_except_ext(from: &Path,
if entry.path() == to.to_path_buf() {
continue;
}
debug!("[*] is dir");
// check if output dir already exists
if !to.join(entry.file_name()).exists() {
fs::create_dir(&to.join(entry.file_name()))?;
}
copy_files_except_ext(&from.join(entry.file_name()),
&to.join(entry.file_name()),
true,
ext_blacklist)?;
copy_files_except_ext(
&from.join(entry.file_name()),
&to.join(entry.file_name()),
true,
ext_blacklist,
)?;
} else if metadata.is_file() {
// Check if it is in the blacklist
if let Some(ext) = entry.path().extension() {
@ -146,31 +140,40 @@ pub fn copy_files_except_ext(from: &Path,
continue;
}
}
debug!("[*] creating path for file: {:?}",
&to.join(entry.path()
.file_name()
.expect("a file should have a file name...")));
debug!(
"creating path for file: {:?}",
&to.join(
entry
.path()
.file_name()
.expect("a file should have a file name...")
)
);
info!("[*] Copying file: {:?}\n to {:?}",
entry.path(),
&to.join(entry.path()
.file_name()
.expect("a file should have a file name...")));
fs::copy(entry.path(),
&to.join(entry.path()
.file_name()
.expect("a file should have a file name...")))?;
debug!(
"Copying {:?} to {:?}",
entry.path(),
&to.join(
entry
.path()
.file_name()
.expect("a file should have a file name...")
)
);
fs::copy(
entry.path(),
&to.join(
entry
.path()
.file_name()
.expect("a file should have a file name..."),
),
)?;
}
}
Ok(())
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// tests
#[cfg(test)]
mod tests {
extern crate tempdir;