Debian Codegraph @

guide/src/for_developers/backends.md

raw
1 # Alternative backends
2
3 A "backend" is simply a program which `mdbook` will invoke during the book
4 rendering process. This program is passed a JSON representation of the book and
5 configuration information via `stdin`. Once the backend receives this
6 information it is free to do whatever it wants.
7
8 See [Configuring Renderers](../format/configuration/renderers.md) for more information about using backends.
9
10 The community has developed several backends.
11 See the [Third Party Plugins] wiki page for a list of available backends.
12
13 ## Setting up
14
15 This page will step you through creating your own alternative backend in the form
16 of a simple word counting program. Although it will be written in Rust, there's
17 no reason why it couldn't be accomplished using something like Python or Ruby.
18
19 First you'll want to create a new binary program and add `mdbook-renderer` as a
20 dependency.
21
22 ```shell
23 $ cargo new --bin mdbook-wordcount
24 $ cd mdbook-wordcount
25 $ cargo add mdbook-renderer
26 ```
27
28 When our `mdbook-wordcount` plugin is invoked, `mdbook` will send it a JSON
29 version of [`RenderContext`] via our plugin's `stdin`. For convenience, there's
30 a [`RenderContext::from_json()`] constructor which will load a `RenderContext`.
31
32 This is all the boilerplate necessary for our backend to load the book.
33
34 ```rust
35 // src/main.rs
36 use std::io;
37 use mdbook_renderer::RenderContext;
38
39 fn main() {
40 let mut stdin = io::stdin();
41 let ctx = RenderContext::from_json(&mut stdin).unwrap();
42 }
43 ```
44
45 > **Note:** The `RenderContext` contains a `version` field. This lets backends
46 > figure out whether they are compatible with the version of `mdbook` it's being
47 > called by. This `version` comes directly from the corresponding field in
48 > `mdbook`'s `Cargo.toml`.
49 >
50 > It is recommended that backends use the [`semver`] crate to inspect this field
51 > and emit a warning if there may be a compatibility issue.
52
53 ## Inspecting the book
54
55 Now our backend has a copy of the book, lets count how many words are in each
56 chapter!
57
58 Because the `RenderContext` contains a [`Book`] field (`book`), and a `Book` has
59 the [`Book::iter()`] method for iterating over all items in a `Book`, this step
60 turns out to be just as easy as the first.
61
62 ```rust
63
64 fn main() {
65 let mut stdin = io::stdin();
66 let ctx = RenderContext::from_json(&mut stdin).unwrap();
67
68 for item in ctx.book.iter() {
69 if let BookItem::Chapter(ref ch) = *item {
70 let num_words = count_words(ch);
71 println!("{}: {}", ch.name, num_words);
72 }
73 }
74 }
75
76 fn count_words(ch: &Chapter) -> usize {
77 ch.content.split_whitespace().count()
78 }
79 ```
80
81
82 ## Enabling the backend
83
84 Now we've got the basics running, we want to actually use it. First, install the
85 program.
86
87 ```shell
88 $ cargo install --path .
89 ```
90
91 Then `cd` to the particular book you'd like to count the words of and update its
92 `book.toml` file.
93
94 ```diff
95 [book]
96 title = "mdBook Documentation"
97 description = "Create book from markdown files. Like Gitbook but implemented in Rust"
98 authors = ["Mathieu David", "Michael-F-Bryan"]
99
100 + [output.html]
101
102 + [output.wordcount]
103 ```
104
105 When it loads a book into memory, `mdbook` will inspect your `book.toml` file to
106 try and figure out which backends to use by looking for all `output.*` tables.
107 If none are provided it'll fall back to using the default HTML renderer.
108
109 Notably, this means if you want to add your own custom backend you'll also need
110 to make sure to add the HTML backend, even if its table just stays empty.
111
112 Now you just need to build your book like normal, and everything should *Just
113 Work*.
114
115 ```shell
116 $ mdbook build
117 ...
118 2018-01-16 07:31:15 [INFO] (mdbook::renderer): Invoking the "mdbook-wordcount" renderer
119 mdBook: 126
120 Command Line Tool: 224
121 init: 283
122 build: 145
123 watch: 146
124 serve: 292
125 test: 139
126 Format: 30
127 SUMMARY.md: 259
128 Configuration: 784
129 Theme: 304
130 index.hbs: 447
131 Syntax highlighting: 314
132 MathJax Support: 153
133 Rust code specific features: 148
134 For Developers: 788
135 Alternative Backends: 710
136 Contributors: 85
137 ```
138
139 The reason we didn't need to specify the full name/path of our `wordcount`
140 backend is because `mdbook` will try to *infer* the program's name via
141 convention. The executable for the `foo` backend is typically called
142 `mdbook-foo`, with an associated `[output.foo]` entry in the `book.toml`. To
143 explicitly tell `mdbook` what command to invoke (it may require command-line
144 arguments or be an interpreted script), you can use the `command` field.
145
146 ```diff
147 [book]
148 title = "mdBook Documentation"
149 description = "Create book from markdown files. Like Gitbook but implemented in Rust"
150 authors = ["Mathieu David", "Michael-F-Bryan"]
151
152 [output.html]
153
154 [output.wordcount]
155 + command = "python /path/to/wordcount.py"
156 ```
157
158
159 ## Configuration
160
161 Now imagine you don't want to count the number of words on a particular chapter
162 (it might be generated text/code, etc). The canonical way to do this is via the
163 usual `book.toml` configuration file by adding items to your `[output.foo]`
164 table.
165
166 The `Config` can be treated roughly as a nested hashmap which lets you call
167 methods like `get()` to access the config's contents, with a
168 `get_deserialized()` convenience method for retrieving a value and automatically
169 deserializing to some arbitrary type `T`.
170
171 To implement this, we'll create our own serializable `WordcountConfig` struct
172 which will encapsulate all configuration for this backend.
173
174 First add `serde` and `serde_derive` to your `Cargo.toml`,
175
176 ```
177 $ cargo add serde serde_derive
178 ```
179
180 And then you can create the config struct,
181
182 ```rust
183 use serde_derive::{Serialize, Deserialize};
184
185 ...
186
187 #[derive(Debug, Default, Serialize, Deserialize)]
188 #[serde(default, rename_all = "kebab-case")]
189 pub struct WordcountConfig {
190 pub ignores: Vec<String>,
191 }
192 ```
193
194 Now we just need to deserialize the `WordcountConfig` from our `RenderContext`
195 and then add a check to make sure we skip ignored chapters.
196
197 ```diff
198 fn main() {
199 let mut stdin = io::stdin();
200 let ctx = RenderContext::from_json(&mut stdin).unwrap();
201 + let cfg: WordcountConfig = ctx.config
202 + .get_deserialized("output.wordcount")
203 + .unwrap_or_default();
204
205 for item in ctx.book.iter() {
206 if let BookItem::Chapter(ref ch) = *item {
207 + if cfg.ignores.contains(&ch.name) {
208 + continue;
209 + }
210 +
211 let num_words = count_words(ch);
212 println!("{}: {}", ch.name, num_words);
213 }
214 }
215 }
216 ```
217
218
219 ## Output and signalling failure
220
221 While it's nice to print word counts to the terminal when a book is built, it
222 might also be a good idea to output them to a file somewhere. `mdbook` tells a
223 backend where it should place any generated output via the `destination` field
224 in [`RenderContext`].
225
226 ```diff
227 + use std::fs::{self, File};
228 + use std::io::{self, Write};
229 - use std::io;
230 use mdbook::renderer::RenderContext;
231 use mdbook::book::{BookItem, Chapter};
232
233 fn main() {
234 ...
235
236 + let _ = fs::create_dir_all(&ctx.destination);
237 + let mut f = File::create(ctx.destination.join("wordcounts.txt")).unwrap();
238 +
239 for item in ctx.book.iter() {
240 if let BookItem::Chapter(ref ch) = *item {
241 ...
242
243 let num_words = count_words(ch);
244 println!("{}: {}", ch.name, num_words);
245 + writeln!(f, "{}: {}", ch.name, num_words).unwrap();
246 }
247 }
248 }
249 ```
250
251 > **Note:** There is no guarantee that the destination directory exists or is
252 > empty (`mdbook` may leave the previous contents to let backends do caching),
253 > so it's always a good idea to create it with `fs::create_dir_all()`.
254 >
255 > If the destination directory already exists, don't assume it will be empty.
256 > To allow backends to cache the results from previous runs, `mdbook` may leave
257 > old content in the directory.
258
259 There's always the possibility that an error will occur while processing a book
260 (just look at all the `unwrap()`'s we've written already), so `mdbook` will
261 interpret a non-zero exit code as a rendering failure.
262
263 For example, if we wanted to make sure all chapters have an *even* number of
264 words, erroring out if an odd number is encountered, then you may do something
265 like this:
266
267 ```diff
268 + use std::process;
269 ...
270
271 fn main() {
272 ...
273
274 for item in ctx.book.iter() {
275 if let BookItem::Chapter(ref ch) = *item {
276 ...
277
278 let num_words = count_words(ch);
279 println!("{}: {}", ch.name, num_words);
280 writeln!(f, "{}: {}", ch.name, num_words).unwrap();
281
282 + if cfg.deny_odds && num_words % 2 == 1 {
283 + eprintln!("{} has an odd number of words!", ch.name);
284 + process::exit(1);
285 + }
286 }
287 }
288 }
289
290 #[derive(Debug, Default, Serialize, Deserialize)]
291 #[serde(default, rename_all = "kebab-case")]
292 pub struct WordcountConfig {
293 pub ignores: Vec<String>,
294 + pub deny_odds: bool,
295 }
296 ```
297
298 Now, if we reinstall the backend and build a book,
299
300 ```shell
301 $ cargo install --path . --force
302 $ mdbook build /path/to/book
303 ...
304 2018-01-16 21:21:39 [INFO] (mdbook::renderer): Invoking the "wordcount" renderer
305 mdBook: 126
306 Command Line Tool: 224
307 init: 283
308 init has an odd number of words!
309 2018-01-16 21:21:39 [ERROR] (mdbook::renderer): Renderer exited with non-zero return code.
310 2018-01-16 21:21:39 [ERROR] (mdbook::utils): Error: Rendering failed
311 2018-01-16 21:21:39 [ERROR] (mdbook::utils): Caused By: The "mdbook-wordcount" renderer failed
312 ```
313
314 As you've probably already noticed, output from the plugin's subprocess is
315 immediately passed through to the user. It is encouraged for plugins to follow
316 the "rule of silence" and only generate output when necessary (e.g. an error in
317 generation or a warning).
318
319 All environment variables are passed through to the backend, allowing you to use
320 the usual `MDBOOK_LOG` to control logging verbosity.
321
322 ## Wrapping up
323
324 Although contrived, hopefully this example was enough to show how you'd create
325 an alternative backend for `mdbook`. If you feel it's missing something, don't
326 hesitate to create an issue in the [issue tracker] so we can improve the user
327 guide.
328
329 The existing backends mentioned towards the start of this chapter should serve
330 as a good example of how it's done in real life, so feel free to skim through
331 the source code or ask questions.
332
333
334 [Third Party Plugins]: https://github.com/rust-lang/mdBook/wiki/Third-party-plugins
335 [`RenderContext`]: https://docs.rs/mdbook-renderer/latest/mdbook_renderer/struct.RenderContext.html
336 [`RenderContext::from_json()`]: https://docs.rs/mdbook-renderer/latest/mdbook_renderer/struct.RenderContext.html#method.from_json
337 [`semver`]: https://crates.io/crates/semver
338 [`Book`]: https://docs.rs/mdbook-renderer/latest/mdbook_renderer/book/struct.Book.html
339 [`Book::iter()`]: https://docs.rs/mdbook-renderer/latest/mdbook_renderer/book/struct.Book.html#method.iter
340 [`Config`]: https://docs.rs/mdbook-renderer/latest/mdbook_renderer/config/struct.Config.html
341 [issue tracker]: https://github.com/rust-lang/mdBook/issues