Made the logging a lot quieter by default (#569)
This commit is contained in:
parent
0d146ffa82
commit
5379a0bdf8
|
@ -46,7 +46,7 @@ fn create_missing(src_dir: &Path, summary: &Summary) -> Result<()> {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
debug!("[*] Creating missing file {}", filename.display());
|
debug!("Creating missing file {}", filename.display());
|
||||||
|
|
||||||
let mut f = File::create(&filename)?;
|
let mut f = File::create(&filename)?;
|
||||||
writeln!(f, "# {}", link.name)?;
|
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
|
/// You need to pass in the book's source directory because all the links in
|
||||||
/// `SUMMARY.md` give the chapter locations relative to it.
|
/// `SUMMARY.md` give the chapter locations relative to it.
|
||||||
fn load_book_from_disk<P: AsRef<Path>>(summary: &Summary, src_dir: P) -> Result<Book> {
|
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 src_dir = src_dir.as_ref();
|
||||||
|
|
||||||
let prefix = summary.prefix_chapters.iter();
|
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> {
|
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 src_dir = src_dir.as_ref();
|
||||||
|
|
||||||
let location = if link.location.is_absolute() {
|
let location = if link.location.is_absolute() {
|
||||||
|
|
|
@ -8,7 +8,6 @@ use super::MDBook;
|
||||||
use theme;
|
use theme;
|
||||||
use errors::*;
|
use errors::*;
|
||||||
|
|
||||||
|
|
||||||
/// A helper for setting up a new book and its directory structure.
|
/// A helper for setting up a new book and its directory structure.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct BookBuilder {
|
pub struct BookBuilder {
|
||||||
|
@ -97,7 +96,7 @@ impl BookBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_book_toml(&self) -> Result<()> {
|
fn write_book_toml(&self) -> Result<()> {
|
||||||
debug!("[*] Writing book.toml");
|
debug!("Writing book.toml");
|
||||||
let book_toml = self.root.join("book.toml");
|
let book_toml = self.root.join("book.toml");
|
||||||
let cfg = toml::to_vec(&self.config).chain_err(|| "Unable to serialize the config")?;
|
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<()> {
|
fn copy_across_theme(&self) -> Result<()> {
|
||||||
debug!("[*] Copying theme");
|
debug!("Copying theme");
|
||||||
|
|
||||||
let themedir = self.config
|
let themedir = self.config
|
||||||
.html_config()
|
.html_config()
|
||||||
|
@ -118,7 +117,10 @@ impl BookBuilder {
|
||||||
let themedir = self.root.join(themedir);
|
let themedir = self.root.join(themedir);
|
||||||
|
|
||||||
if !themedir.exists() {
|
if !themedir.exists() {
|
||||||
debug!("[*]: {:?} does not exist, creating the directory", themedir);
|
debug!(
|
||||||
|
"{} does not exist, creating the directory",
|
||||||
|
themedir.display()
|
||||||
|
);
|
||||||
fs::create_dir(&themedir)?;
|
fs::create_dir(&themedir)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -144,7 +146,7 @@ impl BookBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_gitignore(&self) -> Result<()> {
|
fn build_gitignore(&self) -> Result<()> {
|
||||||
debug!("[*]: Creating .gitignore");
|
debug!("Creating .gitignore");
|
||||||
|
|
||||||
let mut f = File::create(self.root.join(".gitignore"))?;
|
let mut f = File::create(self.root.join(".gitignore"))?;
|
||||||
|
|
||||||
|
@ -154,7 +156,7 @@ impl BookBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_stub_files(&self) -> Result<()> {
|
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 src_dir = self.root.join(&self.config.book.src);
|
||||||
|
|
||||||
let summary = src_dir.join("SUMMARY.md");
|
let summary = src_dir.join("SUMMARY.md");
|
||||||
|
@ -171,7 +173,7 @@ impl BookBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_directory_structure(&self) -> Result<()> {
|
fn create_directory_structure(&self) -> Result<()> {
|
||||||
debug!("[*]: Creating directory tree");
|
debug!("Creating directory tree");
|
||||||
fs::create_dir_all(&self.root)?;
|
fs::create_dir_all(&self.root)?;
|
||||||
|
|
||||||
let src = self.root.join(&self.config.book.src);
|
let src = self.root.join(&self.config.book.src);
|
||||||
|
|
|
@ -21,7 +21,7 @@ use toml::Value;
|
||||||
|
|
||||||
use utils;
|
use utils;
|
||||||
use renderer::{CmdRenderer, HtmlHandlebars, RenderContext, Renderer};
|
use renderer::{CmdRenderer, HtmlHandlebars, RenderContext, Renderer};
|
||||||
use preprocess::{Preprocessor, LinkPreprocessor, PreprocessorContext};
|
use preprocess::{LinkPreprocessor, Preprocessor, PreprocessorContext};
|
||||||
use errors::*;
|
use errors::*;
|
||||||
|
|
||||||
use config::Config;
|
use config::Config;
|
||||||
|
@ -37,7 +37,7 @@ pub struct MDBook {
|
||||||
renderers: Vec<Box<Renderer>>,
|
renderers: Vec<Box<Renderer>>,
|
||||||
|
|
||||||
/// List of pre-processors to be run on the book
|
/// List of pre-processors to be run on the book
|
||||||
preprocessors: Vec<Box<Preprocessor>>
|
preprocessors: Vec<Box<Preprocessor>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MDBook {
|
impl MDBook {
|
||||||
|
@ -57,7 +57,7 @@ impl MDBook {
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut config = if config_location.exists() {
|
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)?
|
Config::from_disk(&config_location)?
|
||||||
} else {
|
} else {
|
||||||
Config::default()
|
Config::default()
|
||||||
|
@ -147,7 +147,7 @@ impl MDBook {
|
||||||
|
|
||||||
/// Tells the renderer to build our book and put it in the build directory.
|
/// Tells the renderer to build our book and put it in the build directory.
|
||||||
pub fn build(&self) -> Result<()> {
|
pub fn build(&self) -> Result<()> {
|
||||||
debug!("[fn]: build");
|
info!("Book building has started");
|
||||||
|
|
||||||
let mut preprocessed_book = self.book.clone();
|
let mut preprocessed_book = self.book.clone();
|
||||||
let preprocess_ctx = PreprocessorContext::new(self.root.clone(), self.config.clone());
|
let preprocess_ctx = PreprocessorContext::new(self.root.clone(), self.config.clone());
|
||||||
|
@ -158,6 +158,7 @@ impl MDBook {
|
||||||
}
|
}
|
||||||
|
|
||||||
for renderer in &self.renderers {
|
for renderer in &self.renderers {
|
||||||
|
info!("Running the {} backend", renderer.name());
|
||||||
self.run_renderer(&preprocessed_book, renderer.as_ref())?;
|
self.run_renderer(&preprocessed_book, renderer.as_ref())?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -223,7 +224,7 @@ impl MDBook {
|
||||||
if !ch.path.as_os_str().is_empty() {
|
if !ch.path.as_os_str().is_empty() {
|
||||||
let path = self.source_dir().join(&ch.path);
|
let path = self.source_dir().join(&ch.path);
|
||||||
let content = utils::fs::file_to_string(&path)?;
|
let content = utils::fs::file_to_string(&path)?;
|
||||||
println!("[*]: Testing file: {:?}", path);
|
info!("Testing file: {:?}", path);
|
||||||
|
|
||||||
// write preprocessed file to tempdir
|
// write preprocessed file to tempdir
|
||||||
let path = temp_dir.path().join(&ch.path);
|
let path = temp_dir.path().join(&ch.path);
|
||||||
|
@ -327,21 +328,18 @@ fn default_preprocessors() -> Vec<Box<Preprocessor>> {
|
||||||
|
|
||||||
/// Look at the `MDBook` and try to figure out what preprocessors to run.
|
/// Look at the `MDBook` and try to figure out what preprocessors to run.
|
||||||
fn determine_preprocessors(config: &Config) -> Result<Vec<Box<Preprocessor>>> {
|
fn determine_preprocessors(config: &Config) -> Result<Vec<Box<Preprocessor>>> {
|
||||||
|
|
||||||
let preprocess_list = match config.build.preprocess {
|
let preprocess_list = match config.build.preprocess {
|
||||||
Some(ref p) => p,
|
Some(ref p) => p,
|
||||||
// If no preprocessor field is set, default to the LinkPreprocessor. This allows you
|
// If no preprocessor field is set, default to the LinkPreprocessor. This allows you
|
||||||
// to disable the LinkPreprocessor by setting "preprocess" to an empty list.
|
// 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();
|
let mut preprocessors: Vec<Box<Preprocessor>> = Vec::new();
|
||||||
|
|
||||||
for key in preprocess_list {
|
for key in preprocess_list {
|
||||||
match key.as_ref() {
|
match key.as_ref() {
|
||||||
"links" => {
|
"links" => preprocessors.push(Box::new(LinkPreprocessor::new())),
|
||||||
preprocessors.push(Box::new(LinkPreprocessor::new()))
|
|
||||||
}
|
|
||||||
_ => bail!("{:?} is not a recognised preprocessor", key),
|
_ => bail!("{:?} is not a recognised preprocessor", key),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -431,7 +429,6 @@ mod tests {
|
||||||
preprocess = []
|
preprocess = []
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
|
||||||
let cfg = Config::from_str(cfg_str).unwrap();
|
let cfg = Config::from_str(cfg_str).unwrap();
|
||||||
|
|
||||||
// make sure we have something in the `output` table
|
// make sure we have something in the `output` table
|
||||||
|
@ -455,7 +452,6 @@ mod tests {
|
||||||
preprocess = ["random"]
|
preprocess = ["random"]
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
|
||||||
let cfg = Config::from_str(cfg_str).unwrap();
|
let cfg = Config::from_str(cfg_str).unwrap();
|
||||||
|
|
||||||
// make sure we have something in the `output` table
|
// make sure we have something in the `output` table
|
||||||
|
|
|
@ -240,7 +240,7 @@ impl<'a> SummaryParser<'a> {
|
||||||
fn parse_affix(&mut self, is_prefix: bool) -> Result<Vec<SummaryItem>> {
|
fn parse_affix(&mut self, is_prefix: bool) -> Result<Vec<SummaryItem>> {
|
||||||
let mut items = Vec::new();
|
let mut items = Vec::new();
|
||||||
debug!(
|
debug!(
|
||||||
"[*] Parsing {} items",
|
"Parsing {} items",
|
||||||
if is_prefix { "prefix" } else { "suffix" }
|
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>> {
|
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();
|
let mut items = Vec::new();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
@ -406,7 +406,7 @@ impl<'a> SummaryParser<'a> {
|
||||||
let mut number = parent.clone();
|
let mut number = parent.clone();
|
||||||
number.0.push(num_existing_items as u32 + 1);
|
number.0.push(num_existing_items as u32 + 1);
|
||||||
trace!(
|
trace!(
|
||||||
"[*] Found chapter: {} {} ({})",
|
"Found chapter: {} {} ({})",
|
||||||
number,
|
number,
|
||||||
link.name,
|
link.name,
|
||||||
link.location.display()
|
link.location.display()
|
||||||
|
@ -435,7 +435,7 @@ impl<'a> SummaryParser<'a> {
|
||||||
/// Try to parse the title line.
|
/// Try to parse the title line.
|
||||||
fn parse_title(&mut self) -> Option<String> {
|
fn parse_title(&mut self) -> Option<String> {
|
||||||
if let Some(Event::Start(Tag::Header(1))) = self.next_event() {
|
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));
|
let tags = collect_events!(self.stream, end Tag::Header(1));
|
||||||
Some(stringify_events(tags))
|
Some(stringify_events(tags))
|
||||||
|
|
|
@ -10,7 +10,7 @@ use regex::{Captures, Regex};
|
||||||
#[allow(unused_imports)] use std::ascii::AsciiExt;
|
#[allow(unused_imports)] use std::ascii::AsciiExt;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::fs::{self, File};
|
use std::fs::{self, File};
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
@ -53,11 +53,9 @@ impl 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_else(|| {
|
let path = ch.path
|
||||||
io::Error::new(io::ErrorKind::Other,
|
.to_str()
|
||||||
"Could not convert path \
|
.chain_err(|| "Could not convert path to str")?;
|
||||||
to str")
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// "print.html" is used for the print page.
|
// "print.html" is used for the print page.
|
||||||
if ch.path == Path::new("print.md") {
|
if ch.path == Path::new("print.md") {
|
||||||
|
@ -82,7 +80,7 @@ impl HtmlHandlebars {
|
||||||
json!(utils::fs::path_to_root(&ch.path)));
|
json!(utils::fs::path_to_root(&ch.path)));
|
||||||
|
|
||||||
// Render the handlebars template with the data
|
// Render the handlebars template with the data
|
||||||
debug!("[*]: Render template");
|
debug!("Render template");
|
||||||
let rendered = ctx.handlebars.render("index", &ctx.data)?;
|
let rendered = ctx.handlebars.render("index", &ctx.data)?;
|
||||||
|
|
||||||
let filepath = Path::new(&ch.path).with_extension("html");
|
let filepath = Path::new(&ch.path).with_extension("html");
|
||||||
|
@ -95,7 +93,7 @@ impl HtmlHandlebars {
|
||||||
);
|
);
|
||||||
|
|
||||||
// Write to file
|
// Write to file
|
||||||
info!("[*] Creating {:?} ✓", filepath.display());
|
debug!("Creating {} ✓", filepath.display());
|
||||||
self.write_file(&ctx.destination, filepath, &rendered.into_bytes())?;
|
self.write_file(&ctx.destination, filepath, &rendered.into_bytes())?;
|
||||||
|
|
||||||
if ctx.is_index {
|
if ctx.is_index {
|
||||||
|
@ -110,7 +108,7 @@ impl HtmlHandlebars {
|
||||||
|
|
||||||
/// Create an index.html from the first element in SUMMARY.md
|
/// Create an index.html from the first element in SUMMARY.md
|
||||||
fn render_index(&self, ch: &Chapter, destination: &Path) -> Result<()> {
|
fn render_index(&self, ch: &Chapter, destination: &Path) -> Result<()> {
|
||||||
debug!("[*]: index.html");
|
debug!("index.html");
|
||||||
|
|
||||||
let mut content = String::new();
|
let mut content = String::new();
|
||||||
|
|
||||||
|
@ -127,8 +125,10 @@ impl HtmlHandlebars {
|
||||||
|
|
||||||
self.write_file(destination, "index.html", content.as_bytes())?;
|
self.write_file(destination, "index.html", content.as_bytes())?;
|
||||||
|
|
||||||
info!("[*] Creating index.html from {:?} ✓",
|
debug!(
|
||||||
destination.join(&ch.path.with_extension("html")));
|
"Creating index.html from {} ✓",
|
||||||
|
destination.join(&ch.path.with_extension("html")).display()
|
||||||
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -275,7 +275,7 @@ impl Renderer for HtmlHandlebars {
|
||||||
let destination = &ctx.destination;
|
let destination = &ctx.destination;
|
||||||
let book = &ctx.book;
|
let book = &ctx.book;
|
||||||
|
|
||||||
debug!("[fn]: render");
|
trace!("render");
|
||||||
let mut handlebars = Handlebars::new();
|
let mut handlebars = Handlebars::new();
|
||||||
|
|
||||||
let theme_dir = match html_config.theme {
|
let theme_dir = match html_config.theme {
|
||||||
|
@ -285,19 +285,13 @@ impl Renderer for HtmlHandlebars {
|
||||||
|
|
||||||
let theme = theme::Theme::new(theme_dir);
|
let theme = theme::Theme::new(theme_dir);
|
||||||
|
|
||||||
debug!("[*]: Register the index handlebars template");
|
debug!("Register the index handlebars template");
|
||||||
handlebars.register_template_string(
|
handlebars.register_template_string("index", String::from_utf8(theme.index.clone())?)?;
|
||||||
"index",
|
|
||||||
String::from_utf8(theme.index.clone())?,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
debug!("[*]: Register the header handlebars template");
|
debug!("Register the header handlebars template");
|
||||||
handlebars.register_partial(
|
handlebars.register_partial("header", String::from_utf8(theme.header.clone())?)?;
|
||||||
"header",
|
|
||||||
String::from_utf8(theme.header.clone())?,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
debug!("[*]: Register handlebars helpers");
|
debug!("Register handlebars helpers");
|
||||||
self.register_hbs_helpers(&mut handlebars, &html_config);
|
self.register_hbs_helpers(&mut handlebars, &html_config);
|
||||||
|
|
||||||
let mut data = make_data(&ctx.root, &book, &ctx.config, &html_config)?;
|
let mut data = make_data(&ctx.root, &book, &ctx.config, &html_config)?;
|
||||||
|
@ -305,7 +299,6 @@ impl Renderer for HtmlHandlebars {
|
||||||
// Print version
|
// Print version
|
||||||
let mut print_content = String::new();
|
let mut print_content = String::new();
|
||||||
|
|
||||||
debug!("[*]: Check if destination directory exists");
|
|
||||||
fs::create_dir_all(&destination)
|
fs::create_dir_all(&destination)
|
||||||
.chain_err(|| "Unexpected error when constructing destination path")?;
|
.chain_err(|| "Unexpected error when constructing destination path")?;
|
||||||
|
|
||||||
|
@ -327,7 +320,7 @@ impl Renderer for HtmlHandlebars {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render the handlebars template with the data
|
// Render the handlebars template with the data
|
||||||
debug!("[*]: Render template");
|
debug!("Render template");
|
||||||
|
|
||||||
let rendered = handlebars.render("index", &data)?;
|
let rendered = handlebars.render("index", &data)?;
|
||||||
|
|
||||||
|
@ -336,9 +329,9 @@ impl Renderer for HtmlHandlebars {
|
||||||
&html_config.playpen);
|
&html_config.playpen);
|
||||||
|
|
||||||
self.write_file(&destination, "print.html", &rendered.into_bytes())?;
|
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)
|
self.copy_static_files(&destination, &theme, &html_config)
|
||||||
.chain_err(|| "Unable to copy across static files")?;
|
.chain_err(|| "Unable to copy across static files")?;
|
||||||
self.copy_additional_css_and_js(&html_config, &destination)
|
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>> {
|
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 html = config.html_config().unwrap_or_default();
|
||||||
|
|
||||||
let mut data = serde_json::Map::new();
|
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));
|
chapter.insert("name".to_owned(), json!(ch.name));
|
||||||
let path = ch.path.to_str().ok_or_else(|| {
|
let path = ch.path
|
||||||
io::Error::new(io::ErrorKind::Other,
|
.to_str()
|
||||||
"Could not convert path \
|
.chain_err(|| "Could not convert path to str")?;
|
||||||
to str")
|
|
||||||
})?;
|
|
||||||
chapter.insert("path".to_owned(), json!(path));
|
chapter.insert("path".to_owned(), json!(path));
|
||||||
}
|
}
|
||||||
BookItem::Separator => {
|
BookItem::Separator => {
|
||||||
|
@ -620,7 +611,6 @@ fn partition_source(s: &str) -> (String, String) {
|
||||||
(before, after)
|
(before, after)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
struct RenderItemContext<'a> {
|
struct RenderItemContext<'a> {
|
||||||
handlebars: &'a Handlebars,
|
handlebars: &'a Handlebars,
|
||||||
destination: PathBuf,
|
destination: PathBuf,
|
||||||
|
|
|
@ -47,7 +47,7 @@ fn find_chapter(
|
||||||
rc: &mut RenderContext,
|
rc: &mut RenderContext,
|
||||||
target: Target
|
target: Target
|
||||||
) -> Result<Option<StringMap>, RenderError> {
|
) -> Result<Option<StringMap>, RenderError> {
|
||||||
debug!("[*]: Get data from context");
|
debug!("Get data from context");
|
||||||
|
|
||||||
let chapters = rc.evaluate_absolute("chapters").and_then(|c| {
|
let chapters = rc.evaluate_absolute("chapters").and_then(|c| {
|
||||||
serde_json::value::from_value::<Vec<StringMap>>(c.clone())
|
serde_json::value::from_value::<Vec<StringMap>>(c.clone())
|
||||||
|
@ -61,7 +61,7 @@ fn find_chapter(
|
||||||
|
|
||||||
let mut previous: Option<StringMap> = None;
|
let mut previous: Option<StringMap> = None;
|
||||||
|
|
||||||
debug!("[*]: Search for chapter");
|
debug!("Search for chapter");
|
||||||
|
|
||||||
for item in chapters {
|
for item in chapters {
|
||||||
match item.get("path") {
|
match item.get("path") {
|
||||||
|
@ -87,7 +87,7 @@ fn render(
|
||||||
rc: &mut RenderContext,
|
rc: &mut RenderContext,
|
||||||
chapter: &StringMap,
|
chapter: &StringMap,
|
||||||
) -> Result<(), RenderError> {
|
) -> Result<(), RenderError> {
|
||||||
debug!("[*]: Creating BTreeMap to inject in context");
|
trace!("Creating BTreeMap to inject in context");
|
||||||
|
|
||||||
let mut context = BTreeMap::new();
|
let mut context = BTreeMap::new();
|
||||||
|
|
||||||
|
@ -104,7 +104,7 @@ fn render(
|
||||||
.map(|p| context.insert("link".to_owned(), json!(p.replace("\\", "/"))))
|
.map(|p| context.insert("link".to_owned(), json!(p.replace("\\", "/"))))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
debug!("[*]: Render template");
|
trace!("Render template");
|
||||||
|
|
||||||
_h.template()
|
_h.template()
|
||||||
.ok_or_else(|| RenderError::new("Error with the handlebars 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> {
|
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)? {
|
if let Some(previous) = find_chapter(rc, Target::Previous)? {
|
||||||
render(_h, r, rc, &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> {
|
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)? {
|
if let Some(next) = find_chapter(rc, Target::Next)? {
|
||||||
render(_h, r, rc, &next)?;
|
render(_h, r, rc, &next)?;
|
||||||
|
|
|
@ -6,20 +6,12 @@ use std::fs::{self, File};
|
||||||
/// Takes a path to a file and try to read the file into a String
|
/// 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> {
|
pub fn file_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
|
||||||
let path = path.as_ref();
|
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();
|
let mut content = String::new();
|
||||||
|
File::open(path)
|
||||||
if let Err(e) = file.read_to_string(&mut content) {
|
.chain_err(|| "Unable to open the file")?
|
||||||
debug!("[*]: Failed to read {:?}", path);
|
.read_to_string(&mut content)
|
||||||
bail!(e);
|
.chain_err(|| "Unable to read the file")?;
|
||||||
}
|
|
||||||
|
|
||||||
Ok(content)
|
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.
|
/// 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 {
|
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
|
// Remove filename and add "../" for every directory
|
||||||
|
|
||||||
path.into()
|
path.into()
|
||||||
|
@ -59,30 +51,27 @@ pub fn path_to_root<P: Into<PathBuf>>(path: P) -> String {
|
||||||
match c {
|
match c {
|
||||||
Component::Normal(_) => s.push_str("../"),
|
Component::Normal(_) => s.push_str("../"),
|
||||||
_ => {
|
_ => {
|
||||||
debug!("[*]: Other path component... {:?}", c);
|
debug!("Other path component... {:?}", c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s
|
s
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// This function creates a file and returns it. But before creating the file
|
/// 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,
|
/// it checks every directory in the path to see if it exists,
|
||||||
/// and if it does not it will be created.
|
/// and if it does not it will be created.
|
||||||
|
|
||||||
pub fn create_file(path: &Path) -> Result<File> {
|
pub fn create_file(path: &Path) -> Result<File> {
|
||||||
debug!("[fn]: create_file");
|
debug!("Creating {}", path.display());
|
||||||
|
|
||||||
// Construct path
|
// Construct path
|
||||||
if let Some(p) = path.parent() {
|
if let Some(p) = path.parent() {
|
||||||
debug!("Parent directory is: {:?}", p);
|
trace!("Parent directory is: {:?}", p);
|
||||||
|
|
||||||
fs::create_dir_all(p)?;
|
fs::create_dir_all(p)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("[*]: Create file: {:?}", path);
|
|
||||||
File::create(path).map_err(|e| e.into())
|
File::create(path).map_err(|e| e.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -102,25 +91,29 @@ pub fn remove_dir_content(dir: &Path) -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
///
|
|
||||||
///
|
|
||||||
/// Copies all files of a directory to another one except the files
|
/// Copies all files of a directory to another one except the files
|
||||||
/// with the extensions given in the `ext_blacklist` array
|
/// with the extensions given in the `ext_blacklist` array
|
||||||
|
|
||||||
pub fn copy_files_except_ext(from: &Path,
|
pub fn copy_files_except_ext(
|
||||||
|
from: &Path,
|
||||||
to: &Path,
|
to: &Path,
|
||||||
recursive: bool,
|
recursive: bool,
|
||||||
ext_blacklist: &[&str])
|
ext_blacklist: &[&str],
|
||||||
-> Result<()> {
|
) -> Result<()> {
|
||||||
debug!("[fn] copy_files_except_ext");
|
debug!(
|
||||||
|
"Copying all files from {} to {} (blacklist: {:?})",
|
||||||
|
from.display(),
|
||||||
|
to.display(),
|
||||||
|
ext_blacklist
|
||||||
|
);
|
||||||
|
|
||||||
// Check that from and to are different
|
// Check that from and to are different
|
||||||
if from == to {
|
if from == to {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
debug!("[*] Loop");
|
|
||||||
for entry in fs::read_dir(from)? {
|
for entry in fs::read_dir(from)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
debug!("[*] {:?}", entry.path());
|
|
||||||
let metadata = entry.metadata()?;
|
let metadata = entry.metadata()?;
|
||||||
|
|
||||||
// If the entry is a dir and the recursive option is enabled, call itself
|
// 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() {
|
if entry.path() == to.to_path_buf() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
debug!("[*] is dir");
|
|
||||||
|
|
||||||
// check if output dir already exists
|
// check if output dir already exists
|
||||||
if !to.join(entry.file_name()).exists() {
|
if !to.join(entry.file_name()).exists() {
|
||||||
fs::create_dir(&to.join(entry.file_name()))?;
|
fs::create_dir(&to.join(entry.file_name()))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
copy_files_except_ext(&from.join(entry.file_name()),
|
copy_files_except_ext(
|
||||||
|
&from.join(entry.file_name()),
|
||||||
&to.join(entry.file_name()),
|
&to.join(entry.file_name()),
|
||||||
true,
|
true,
|
||||||
ext_blacklist)?;
|
ext_blacklist,
|
||||||
|
)?;
|
||||||
} else if metadata.is_file() {
|
} else if metadata.is_file() {
|
||||||
// Check if it is in the blacklist
|
// Check if it is in the blacklist
|
||||||
if let Some(ext) = entry.path().extension() {
|
if let Some(ext) = entry.path().extension() {
|
||||||
|
@ -146,31 +140,40 @@ pub fn copy_files_except_ext(from: &Path,
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
debug!("[*] creating path for file: {:?}",
|
debug!(
|
||||||
&to.join(entry.path()
|
"creating path for file: {:?}",
|
||||||
|
&to.join(
|
||||||
|
entry
|
||||||
|
.path()
|
||||||
.file_name()
|
.file_name()
|
||||||
.expect("a file should have a file name...")));
|
.expect("a file should have a file name...")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
info!("[*] Copying file: {:?}\n to {:?}",
|
debug!(
|
||||||
|
"Copying {:?} to {:?}",
|
||||||
entry.path(),
|
entry.path(),
|
||||||
&to.join(entry.path()
|
&to.join(
|
||||||
|
entry
|
||||||
|
.path()
|
||||||
.file_name()
|
.file_name()
|
||||||
.expect("a file should have a file name...")));
|
.expect("a file should have a file name...")
|
||||||
fs::copy(entry.path(),
|
)
|
||||||
&to.join(entry.path()
|
);
|
||||||
|
fs::copy(
|
||||||
|
entry.path(),
|
||||||
|
&to.join(
|
||||||
|
entry
|
||||||
|
.path()
|
||||||
.file_name()
|
.file_name()
|
||||||
.expect("a file should have a file name...")))?;
|
.expect("a file should have a file name..."),
|
||||||
|
),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ------------------------------------------------------------------------------------------------
|
|
||||||
// ------------------------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
// tests
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
extern crate tempdir;
|
extern crate tempdir;
|
||||||
|
|
Loading…
Reference in New Issue