Introduced the `BookBuilder`.

- You now use a `BookBuilder` for creating a book directory tree

- This also removes the `--no-create` argument
This commit is contained in:
Michael Bryan 2017-11-18 20:41:04 +08:00
parent cafb8b75e7
commit 47eb4788cb
No known key found for this signature in database
GPG Key ID: E9C602B0D9A998DC
10 changed files with 225 additions and 261 deletions

View File

@ -1,5 +1,5 @@
use std::path::PathBuf;
use clap::{ArgMatches, SubCommand, App};
use clap::{App, ArgMatches, SubCommand};
use mdbook::MDBook;
use mdbook::errors::Result;
use {get_book_dir, open};
@ -10,32 +10,23 @@ pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
.about("Build the book from the markdown files")
.arg_from_usage("-o, --open 'Open the compiled book in a web browser'")
.arg_from_usage(
"-d, --dest-dir=[dest-dir] 'The output directory for your \
book{n}(Defaults to ./book when omitted)'",
)
.arg_from_usage(
"--no-create 'Will not create non-existent files linked from SUMMARY.md (deprecated: use book.toml instead)'",
)
.arg_from_usage(
"[dir] 'A directory for your book{n}(Defaults to Current Directory \
"-d, --dest-dir=[dest-dir] 'The output directory for your book{n}(Defaults to ./book \
when omitted)'",
)
.arg_from_usage(
"[dir] 'A directory for your book{n}(Defaults to Current Directory when omitted)'",
)
}
// Build command implementation
pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir).read_config()?;
let mut book = MDBook::load(&book_dir)?;
if let Some(dest_dir) = args.value_of("dest-dir") {
book.config.build.build_dir = PathBuf::from(dest_dir);
}
// This flag is deprecated in favor of being set via `book.toml`.
if args.is_present("no-create") {
book.config.build.create_missing = false;
}
book.build()?;
if args.is_present("open") {

View File

@ -3,6 +3,7 @@ use std::io::Write;
use clap::{App, ArgMatches, SubCommand};
use mdbook::MDBook;
use mdbook::errors::Result;
use mdbook::config::Config;
use get_book_dir;
// Create clap subcommand arguments
@ -19,45 +20,31 @@ pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
// Init command implementation
pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir);
// Call the function that does the initialization
book.init()?;
let mut builder = MDBook::init(&book_dir);
// If flag `--theme` is present, copy theme to src
if args.is_present("theme") {
// Skip this if `--force` is present
if !args.is_present("force") {
// Print warning
print!("\nCopying the default theme to {:?}", book.get_source());
println!("could potentially overwrite files already present in that directory.");
print!("\nCopying the default theme to {}", builder.config().book.src.display());
println!("This could potentially overwrite files already present in that directory.");
print!("\nAre you sure you want to continue? (y/n) ");
// Read answer from user and exit if it's not 'yes'
if !confirm() {
println!("\nSkipping...\n");
println!("All done, no errors...");
::std::process::exit(0);
if confirm() {
builder.copy_theme(true);
}
}
}
// Call the function that copies the theme
book.copy_theme()?;
println!("\nTheme copied.");
}
// Because of `src/book/mdbook.rs#L37-L39`, `dest` will always start with `root`
let is_dest_inside_root = book.get_destination().starts_with(&book.root);
if !args.is_present("force") && is_dest_inside_root {
println!("\nDo you want a .gitignore to be created? (y/n)");
if confirm() {
book.create_gitignore();
println!("\n.gitignore created.");
}
builder.create_gitignore(true);
}
builder.build()?;
println!("\nAll done, no errors...");
Ok(())

View File

@ -49,7 +49,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
const RELOAD_COMMAND: &'static str = "reload";
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir).read_config()?;
let mut book = MDBook::load(&book_dir)?;
if let Some(dest_dir) = args.value_of("dest-dir") {
book.config.build.build_dir = PathBuf::from(dest_dir);
@ -64,7 +64,8 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
let address = format!("{}:{}", interface, port);
let ws_address = format!("{}:{}", interface, ws_port);
book.livereload = Some(format!(r#"
book.livereload = Some(format!(
r#"
<script type="text/javascript">
var socket = new WebSocket("ws://{}:{}");
socket.onmessage = function (event) {{
@ -94,7 +95,9 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
let broadcaster = ws_server.broadcaster();
std::thread::spawn(move || { ws_server.listen(&*ws_address).unwrap(); });
std::thread::spawn(move || {
ws_server.listen(&*ws_address).unwrap();
});
let serving_url = format!("http://{}", address);
println!("\nServing on: {}", serving_url);

View File

@ -18,7 +18,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
.map(|v| v.collect())
.unwrap_or_default();
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir).read_config()?;
let mut book = MDBook::load(&book_dir)?;
book.test(library_paths)?;

View File

@ -27,7 +27,7 @@ pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
// Watch command implementation
pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir).read_config()?;
let mut book = MDBook::load(&book_dir)?;
if let Some(dest_dir) = args.value_of("dest-dir") {
book.config.build.build_dir = PathBuf::from(dest_dir);

156
src/book/init.rs Normal file
View File

@ -0,0 +1,156 @@
use std::path::PathBuf;
use config::Config;
use super::MDBook;
use errors::*;
/// A helper for setting up a new book and its directory structure.
#[derive(Debug, Clone, PartialEq)]
pub struct BookBuilder {
root: PathBuf,
create_gitignore: bool,
config: Config,
copy_theme: bool,
}
impl BookBuilder {
pub fn new<P: Into<PathBuf>>(root: P) -> BookBuilder {
BookBuilder {
root: root.into(),
create_gitignore: false,
config: Config::default(),
copy_theme: false,
}
}
/// Set the `Config` to be used.
pub fn with_config(&mut self, cfg: Config) -> &mut BookBuilder {
self.config = cfg;
self
}
pub fn copy_theme(&mut self, copy: bool) -> &mut BookBuilder {
self.copy_theme = copy;
self
}
pub fn create_gitignore(&mut self, create: bool) -> &mut BookBuilder {
self.create_gitignore = create;
self
}
pub fn config(&self) -> &Config {
&self.config
}
pub fn build(&self) -> Result<MDBook> {
unimplemented!()
}
}
// contents of old `init()` function:
// debug!("[fn]: init");
// if !self.root.exists() {
// fs::create_dir_all(&self.root).unwrap();
// info!("{:?} created", self.root.display());
// }
// {
// let dest = self.get_destination();
// if !dest.exists() {
// debug!("[*]: {} does not exist, trying to create directory",
// dest.display()); fs::create_dir_all(dest)?;
// }
// let src = self.get_source();
// if !src.exists() {
// debug!("[*]: {} does not exist, trying to create directory",
// src.display()); fs::create_dir_all(&src)?;
// }
// let summary = src.join("SUMMARY.md");
// if !summary.exists() {
// // Summary does not exist, create it
// debug!("[*]: {:?} does not exist, trying to create SUMMARY.md",
// &summary); let mut f = File::create(&summary)?;
// debug!("[*]: Writing to SUMMARY.md");
// writeln!(f, "# Summary")?;
// writeln!(f, "")?;
// writeln!(f, "- [Chapter 1](./chapter_1.md)")?;
// }
// }
// // parse SUMMARY.md, and create the missing item related file
// self.parse_summary()?;
// debug!("[*]: constructing paths for missing files");
// for item in self.iter() {
// debug!("[*]: item: {:?}", item);
// let ch = match *item {
// BookItem::Spacer => continue,
// BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => ch,
// };
// if !ch.path.as_os_str().is_empty() {
// let path = self.get_source().join(&ch.path);
// if !path.exists() {
// if !self.create_missing {
// return Err(
// format!("'{}' referenced from SUMMARY.md does not
// exist.", path.to_string_lossy()).into(), );
// }
// debug!("[*]: {:?} does not exist, trying to create file", path);
// ::std::fs::create_dir_all(path.parent().unwrap())?;
// let mut f = File::create(path)?;
// // debug!("[*]: Writing to {:?}", path);
// writeln!(f, "# {}", ch.name)?;
// }
// }
// }
// debug!("[*]: init done");
// Ok(())
// pub fn copy_theme(&self) -> Result<()> {
// debug!("[fn]: copy_theme");
// let themedir = self.theme_dir();
// if !themedir.exists() {
// debug!("[*]: {:?} does not exist, trying to create directory",
// themedir); fs::create_dir(&themedir)?;
// }
// // index.hbs
// let mut index = File::create(themedir.join("index.hbs"))?;
// index.write_all(theme::INDEX)?;
// // book.css
// let mut css = File::create(themedir.join("book.css"))?;
// css.write_all(theme::CSS)?;
// // favicon.png
// let mut favicon = File::create(themedir.join("favicon.png"))?;
// favicon.write_all(theme::FAVICON)?;
// // book.js
// let mut js = File::create(themedir.join("book.js"))?;
// js.write_all(theme::JS)?;
// // highlight.css
// let mut highlight_css = File::create(themedir.join("highlight.css"))?;
// highlight_css.write_all(theme::HIGHLIGHT_CSS)?;
// // highlight.js
// let mut highlight_js = File::create(themedir.join("highlight.js"))?;
// highlight_js.write_all(theme::HIGHLIGHT_JS)?;
// Ok(())
// }

View File

@ -1,7 +1,9 @@
mod summary;
mod book;
mod init;
pub use self::book::{Book, BookItem, BookItems, Chapter};
pub use self::init::BookBuilder;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
@ -41,59 +43,14 @@ impl MDBook {
let src_dir = book_root.join(&config.book.src);
let book = book::load_book(&src_dir)?;
let md = MDBook {
Ok(MDBook {
root: book_root,
config: config,
book: book,
renderer: Box::new(HtmlHandlebars::new()),
livereload: None,
})
}
}
// /// Create a new `MDBook` struct with root directory `root`
// ///
// /// # Examples
// ///
// /// ```no_run
// /// # extern crate mdbook;
// /// # use mdbook::MDBook;
// /// # #[allow(unused_variables)]
// /// # fn main() {
// /// let book = MDBook::new("root_dir");
// /// # }
// /// ```
// ///
// /// In this example, `root_dir` will be the root directory of our book
// /// and is specified in function of the current working directory
// /// by using a relative path instead of an
// /// absolute path.
// ///
// /// Default directory paths:
// ///
// /// - source: `root/src`
// /// - output: `root/book`
// /// - theme: `root/theme`
// ///
// /// They can both be changed by using [`set_src()`](#method.set_src) and
// /// [`set_dest()`](#method.set_dest)
// pub fn new<P: Into<PathBuf>>(root: P) -> MDBook {
// let root = root.into();
// if !root.exists() || !root.is_dir() {
// warn!("{:?} No directory with that name", root);
// }
// MDBook {
// root: root,
// config: Config::default(),
// content: vec![],
// renderer: Box::new(HtmlHandlebars::new()),
// livereload: None,
// create_missing: true,
// }
// }
/// Returns a flat depth-first iterator over the elements of the book,
/// it returns an [BookItem enum](bookitem.html):
@ -122,13 +79,15 @@ impl MDBook {
/// // etc.
/// # }
/// ```
pub fn iter(&self) -> BookItems {
self.book.iter()
}
/// `init()` creates some boilerplate files and directories
/// to get you started with your book.
/// `init()` gives you a `BookBuilder` which you can use to setup a new book
/// and its accompanying directory structure.
///
/// The `BookBuilder` creates some boilerplate files and directories to get
/// you started with your book.
///
/// ```text
/// book-test/
@ -138,111 +97,13 @@ impl MDBook {
/// └── SUMMARY.md
/// ```
///
/// It uses the paths given as source and output directories
/// and adds a `SUMMARY.md` and a
/// `chapter_1.md` to the source directory.
pub fn init<P: AsRef<Path>>(book_root: P) -> Result<MDBook> {
unimplemented!()
// debug!("[fn]: init");
// if !self.root.exists() {
// fs::create_dir_all(&self.root).unwrap();
// info!("{:?} created", self.root.display());
// }
// {
// let dest = self.get_destination();
// if !dest.exists() {
// debug!("[*]: {} does not exist, trying to create directory",
// dest.display()); fs::create_dir_all(dest)?;
// }
// let src = self.get_source();
// if !src.exists() {
// debug!("[*]: {} does not exist, trying to create directory",
// src.display()); fs::create_dir_all(&src)?;
// }
// let summary = src.join("SUMMARY.md");
// if !summary.exists() {
// // Summary does not exist, create it
// debug!("[*]: {:?} does not exist, trying to create SUMMARY.md",
// &summary); let mut f = File::create(&summary)?;
// debug!("[*]: Writing to SUMMARY.md");
// writeln!(f, "# Summary")?;
// writeln!(f, "")?;
// writeln!(f, "- [Chapter 1](./chapter_1.md)")?;
// }
// }
// // parse SUMMARY.md, and create the missing item related file
// self.parse_summary()?;
// debug!("[*]: constructing paths for missing files");
// for item in self.iter() {
// debug!("[*]: item: {:?}", item);
// let ch = match *item {
// BookItem::Spacer => continue,
// BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => ch,
// };
// if !ch.path.as_os_str().is_empty() {
// let path = self.get_source().join(&ch.path);
// if !path.exists() {
// if !self.create_missing {
// return Err(
// format!("'{}' referenced from SUMMARY.md does not
// exist.", path.to_string_lossy()).into(), );
// }
// debug!("[*]: {:?} does not exist, trying to create file", path);
// ::std::fs::create_dir_all(path.parent().unwrap())?;
// let mut f = File::create(path)?;
// // debug!("[*]: Writing to {:?}", path);
// writeln!(f, "# {}", ch.name)?;
// }
// }
// }
// debug!("[*]: init done");
// Ok(())
/// It uses the path provided as the root directory for your book, then adds
/// in a `src/` directory containing a `SUMMARY.md` and `chapter_1.md` file
/// to get you started.
pub fn init<P: Into<PathBuf>>(book_root: P) -> BookBuilder {
BookBuilder::new(book_root)
}
// pub fn create_gitignore(&self) {
// let gitignore = self.get_gitignore();
// let destination = self.get_destination();
// // Check that the gitignore does not extist and that the destination path
// // begins with the root path
// // We assume tha if it does begin with the root path it is contained
// within. // This assumption
// // will not hold true for paths containing double dots to go back up e.g.
// // `root/../destination`
// if !gitignore.exists() && destination.starts_with(&self.root) {
// let relative = destination
// .strip_prefix(&self.root)
// .expect("Could not strip the root prefix, path is not relative
// to root") .to_str()
// .expect("Could not convert to &str");
// debug!("[*]: {:?} does not exist, trying to create .gitignore",
// gitignore);
// let mut f = File::create(&gitignore).expect("Could not create
// file.");
// debug!("[*]: Writing to .gitignore");
// writeln!(f, "/{}", relative).expect("Could not write to file.");
// }
// }
/// The `build()` method is the one where everything happens.
/// First it parses `SUMMARY.md` to construct the book's structure
/// in the form of a `Vec<BookItem>` and then calls `render()`
@ -258,48 +119,6 @@ impl MDBook {
self.renderer.render(self)
}
pub fn copy_theme(&self) -> Result<()> {
debug!("[fn]: copy_theme");
let themedir = self.theme_dir();
if !themedir.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", themedir);
fs::create_dir(&themedir)?;
}
// index.hbs
let mut index = File::create(themedir.join("index.hbs"))?;
index.write_all(theme::INDEX)?;
// header.hbs
let mut header = File::create(themedir.join("header.hbs"))?;
header.write_all(theme::HEADER)?;
// book.css
let mut css = File::create(themedir.join("book.css"))?;
css.write_all(theme::CSS)?;
// favicon.png
let mut favicon = File::create(themedir.join("favicon.png"))?;
favicon.write_all(theme::FAVICON)?;
// book.js
let mut js = File::create(themedir.join("book.js"))?;
js.write_all(theme::JS)?;
// highlight.css
let mut highlight_css = File::create(themedir.join("highlight.css"))?;
highlight_css.write_all(theme::HIGHLIGHT_CSS)?;
// highlight.js
let mut highlight_js = File::create(themedir.join("highlight.js"))?;
highlight_js.write_all(theme::HIGHLIGHT_JS)?;
Ok(())
}
pub fn write_file<P: AsRef<Path>>(&self, filename: P, content: &[u8]) -> Result<()> {
let path = self.get_destination().join(filename);
@ -385,7 +204,10 @@ impl MDBook {
.output()?;
if !output.status.success() {
bail!(ErrorKind::Subprocess("Rustdoc returned an error".to_string(), output));
bail!(ErrorKind::Subprocess(
"Rustdoc returned an error".to_string(),
output
));
}
}
}

View File

@ -3,6 +3,7 @@ extern crate tempdir;
use std::path::PathBuf;
use mdbook::MDBook;
use mdbook::config::Config;
use tempdir::TempDir;
@ -17,8 +18,7 @@ fn base_mdbook_init_should_create_default_content() {
assert!(!temp.path().join(file).exists());
}
let mut md = MDBook::new(temp.path());
md.init().unwrap();
let md = MDBook::init(temp.path()).build().unwrap();
for file in &created_files {
let target = temp.path().join(file);
@ -35,28 +35,33 @@ fn run_mdbook_init_with_custom_book_and_src_locations() {
let temp = TempDir::new("mdbook").unwrap();
for file in &created_files {
assert!(!temp.path().join(file).exists(),
assert!(
!temp.path().join(file).exists(),
"{} shouldn't exist yet!",
file);
file
);
}
let mut md = MDBook::new(temp.path());
md.config.book.src = PathBuf::from("in");
md.config.build.build_dir = PathBuf::from("out");
let mut cfg = Config::default();
cfg.book.src = PathBuf::from("in");
cfg.build.build_dir = PathBuf::from("out");
md.init().unwrap();
let mut md = MDBook::init(temp.path()).with_config(cfg).build().unwrap();
for file in &created_files {
let target = temp.path().join(file);
assert!(target.exists(), "{} should have been created by `mdbook init`", file);
assert!(
target.exists(),
"{} should have been created by `mdbook init`",
file
);
}
}
#[test]
fn book_toml_isnt_required() {
let temp = TempDir::new("mdbook").unwrap();
let mut md = MDBook::new(temp.path());
md.init().unwrap();
let md = MDBook::init(temp.path()).build().unwrap();
assert!(!temp.path().join("book.toml").exists());

View File

@ -33,7 +33,7 @@ const TOC_SECOND_LEVEL: &[&'static str] = &["1.1. Nested Chapter"];
#[test]
fn build_the_dummy_book() {
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
md.build().unwrap();
}
@ -41,7 +41,7 @@ fn build_the_dummy_book() {
#[test]
fn by_default_mdbook_generates_rendered_content_in_the_book_directory() {
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
assert!(!temp.path().join("book").exists());
md.build().unwrap();
@ -53,7 +53,7 @@ fn by_default_mdbook_generates_rendered_content_in_the_book_directory() {
#[test]
fn make_sure_bottom_level_files_contain_links_to_chapters() {
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
md.build().unwrap();
let dest = temp.path().join("book");
@ -73,7 +73,7 @@ fn make_sure_bottom_level_files_contain_links_to_chapters() {
#[test]
fn check_correct_cross_links_in_nested_dir() {
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
md.build().unwrap();
let first = temp.path().join("book").join("first");
@ -100,7 +100,7 @@ fn check_correct_cross_links_in_nested_dir() {
#[test]
fn rendered_code_has_playpen_stuff() {
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
md.build().unwrap();
let nested = temp.path().join("book/first/nested.html");
@ -121,7 +121,7 @@ fn chapter_content_appears_in_rendered_document() {
("conclusion.html", "Conclusion")];
let temp = DummyBook::new().build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
md.build().unwrap();
let destination = temp.path().join("book");
@ -180,7 +180,7 @@ fn entry_ends_with(entry: &DirEntry, ending: &str) -> bool {
fn root_index_html() -> Result<Document> {
let temp = DummyBook::new().build()
.chain_err(|| "Couldn't create the dummy book")?;
MDBook::new(temp.path()).build()
MDBook::load(temp.path())?.build()
.chain_err(|| "Book building failed")?;
let index_page = temp.path().join("book").join("index.html");
@ -264,7 +264,7 @@ fn create_missing_file_without_config() {
fn create_missing_setup(create_missing: Option<bool>) -> (MDBook, TempDir) {
let temp = DummyBook::new().build().unwrap();
let md = MDBook::new(temp.path());
let md = MDBook::load(temp.path()).unwrap();
let mut file = File::create(temp.path().join("book.toml")).unwrap();
match create_missing {

View File

@ -9,7 +9,7 @@ use mdbook::MDBook;
#[test]
fn mdbook_can_correctly_test_a_passing_book() {
let temp = DummyBook::new().with_passing_test(true).build().unwrap();
let mut md = MDBook::new(temp.path());
let mut md = MDBook::load(temp.path()).unwrap();
assert!(md.test(vec![]).is_ok());
}
@ -17,7 +17,7 @@ fn mdbook_can_correctly_test_a_passing_book() {
#[test]
fn mdbook_detects_book_with_failing_tests() {
let temp = DummyBook::new().with_passing_test(false).build().unwrap();
let mut md: MDBook = MDBook::new(temp.path());
let mut md: MDBook = MDBook::load(temp.path()).unwrap();
assert!(md.test(vec![]).is_err());
}