Struct mdbook::book::MDBook

source ·
pub struct MDBook {
    pub root: PathBuf,
    pub config: Config,
    pub book: Book,
    /* private fields */
}
Expand description

The object used to manage and build a book.

Fields§

§root: PathBuf

The book’s root directory.

§config: Config

The configuration used to tweak now a book is built.

§book: Book

A representation of the book’s contents in memory.

Implementations§

Load a book from its root directory on disk.

Examples found in repository?
src/book/init.rs (line 85)
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    pub fn build(&self) -> Result<MDBook> {
        info!("Creating a new book with stub content");

        self.create_directory_structure()
            .with_context(|| "Unable to create directory structure")?;

        self.create_stub_files()
            .with_context(|| "Unable to create stub files")?;

        if self.create_gitignore {
            self.build_gitignore()
                .with_context(|| "Unable to create .gitignore")?;
        }

        if self.copy_theme {
            self.copy_across_theme()
                .with_context(|| "Unable to copy across the theme")?;
        }

        self.write_book_toml()?;

        match MDBook::load(&self.root) {
            Ok(book) => Ok(book),
            Err(e) => {
                error!("{}", e);

                panic!(
                    "The BookBuilder should always create a valid book. If you are seeing this it \
                     is a bug and should be reported."
                );
            }
        }
    }

Load a book from its root directory using a custom Config.

Examples found in repository?
src/book/mod.rs (line 94)
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    pub fn load<P: Into<PathBuf>>(book_root: P) -> Result<MDBook> {
        let book_root = book_root.into();
        let config_location = book_root.join("book.toml");

        // the book.json file is no longer used, so we should emit a warning to
        // let people know to migrate to book.toml
        if book_root.join("book.json").exists() {
            warn!("It appears you are still using book.json for configuration.");
            warn!("This format is no longer used, so you should migrate to the");
            warn!("book.toml format.");
            warn!("Check the user guide for migration information:");
            warn!("\thttps://rust-lang.github.io/mdBook/format/config.html");
        }

        let mut config = if config_location.exists() {
            debug!("Loading config from {}", config_location.display());
            Config::from_disk(&config_location)?
        } else {
            Config::default()
        };

        config.update_from_env();

        if config
            .html_config()
            .map_or(false, |html| html.google_analytics.is_some())
        {
            warn!(
                "The output.html.google-analytics field has been deprecated; \
                 it will be removed in a future release.\n\
                 Consider placing the appropriate site tag code into the \
                 theme/head.hbs file instead.\n\
                 The tracking code may be found in the Google Analytics Admin page.\n\
               "
            );
        }

        if log_enabled!(log::Level::Trace) {
            for line in format!("Config: {:#?}", config).lines() {
                trace!("{}", line);
            }
        }

        MDBook::load_with_config(book_root, config)
    }

Load a book from its root directory using a custom Config and a custom summary.

Returns a flat depth-first iterator over the elements of the book, it returns a BookItem enum: (section: String, bookitem: &BookItem)

for item in book.iter() {
    match *item {
        BookItem::Chapter(ref chapter) => {},
        BookItem::Separator => {},
        BookItem::PartTitle(ref title) => {}
    }
}

// would print something like this:
// 1. Chapter 1
// 1.1 Sub Chapter
// 1.2 Sub Chapter
// 2. Chapter 2
//
// etc.

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.

book-test/
├── book
└── src
    ├── chapter_1.md
    └── SUMMARY.md

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.

Tells the renderer to build our book and put it in the build directory.

Run the entire build process for a particular Renderer.

Examples found in repository?
src/book/mod.rs (line 193)
189
190
191
192
193
194
195
196
197
    pub fn build(&self) -> Result<()> {
        info!("Book building has started");

        for renderer in &self.renderers {
            self.execute_build_process(&**renderer)?;
        }

        Ok(())
    }

You can change the default renderer to another one by using this method. The only requirement is that your renderer implement the Renderer trait.

Register a Preprocessor to be used when rendering the book.

Run rustdoc tests on the book, linking against the provided libraries.

Run rustdoc tests on a specific chapter of the book, linking against the provided libraries. If chapter is None, all tests will be run.

Examples found in repository?
src/book/mod.rs (line 251)
249
250
251
252
    pub fn test(&mut self, library_paths: Vec<&str>) -> Result<()> {
        // test_chapter with chapter:None will run all tests.
        self.test_chapter(library_paths, None)
    }

The logic for determining where a backend should put its build artefacts.

If there is only 1 renderer, put it in the directory pointed to by the build.build_dir key in Config. If there is more than one then the renderer gets its own directory within the main build dir.

i.e. If there were only one renderer (in this case, the HTML renderer):

  • build/
    • index.html

Otherwise if there are multiple:

  • build/
    • epub/
      • my_awesome_book.epub
    • html/
      • index.html
    • latex/
      • my_awesome_book.tex
Examples found in repository?
src/book/mod.rs (line 216)
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    pub fn execute_build_process(&self, renderer: &dyn Renderer) -> Result<()> {
        let mut preprocessed_book = self.book.clone();
        let preprocess_ctx = PreprocessorContext::new(
            self.root.clone(),
            self.config.clone(),
            renderer.name().to_string(),
        );

        for preprocessor in &self.preprocessors {
            if preprocessor_should_run(&**preprocessor, renderer, &self.config) {
                debug!("Running the {} preprocessor.", preprocessor.name());
                preprocessed_book = preprocessor.run(&preprocess_ctx, preprocessed_book)?;
            }
        }

        let name = renderer.name();
        let build_dir = self.build_dir_for(name);

        let mut render_context = RenderContext::new(
            self.root.clone(),
            preprocessed_book,
            self.config.clone(),
            build_dir,
        );
        render_context
            .chapter_titles
            .extend(preprocess_ctx.chapter_titles.borrow_mut().drain());

        info!("Running the {} backend", renderer.name());
        renderer
            .render(&render_context)
            .with_context(|| "Rendering failed")
    }

Get the directory containing this book’s source files.

Get the directory containing the theme resources for the book.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more