1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
pub mod bookitem;
pub use self::bookitem::{BookItem, BookItems};
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::process::Command;
use tempdir::TempDir;
use {theme, parse, utils};
use renderer::{Renderer, HtmlHandlebars};
use preprocess;
use errors::*;
use config::BookConfig;
use config::tomlconfig::TomlConfig;
use config::htmlconfig::HtmlConfig;
use config::jsonconfig::JsonConfig;
pub struct MDBook {
config: BookConfig,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
livereload: Option<String>,
pub create_missing: bool,
}
impl MDBook {
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 {
config: BookConfig::new(root),
content: vec![],
renderer: Box::new(HtmlHandlebars::new()),
livereload: None,
create_missing: true,
}
}
pub fn iter(&self) -> BookItems {
BookItems {
items: &self.content[..],
current_index: 0,
stack: Vec::new(),
}
}
pub fn init(&mut self) -> Result<()> {
debug!("[fn]: init");
if !self.config.get_root().exists() {
fs::create_dir_all(&self.config.get_root()).unwrap();
info!("{:?} created", &self.config.get_root());
}
{
if !self.get_destination().exists() {
debug!("[*]: {:?} does not exist, trying to create directory", self.get_destination());
fs::create_dir_all(self.get_destination())?;
}
if !self.config.get_source().exists() {
debug!("[*]: {:?} does not exist, trying to create directory", self.config.get_source());
fs::create_dir_all(self.config.get_source())?;
}
let summary = self.config.get_source().join("SUMMARY.md");
if !summary.exists() {
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)")?;
}
}
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.config.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)?;
writeln!(f, "# {}", ch.name)?;
}
}
}
debug!("[*]: init done");
Ok(())
}
pub fn create_gitignore(&self) {
let gitignore = self.get_gitignore();
let destination = self.config.get_html_config()
.get_destination();
if !gitignore.exists() && destination.starts_with(self.config.get_root()) {
let relative = destination
.strip_prefix(self.config.get_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.");
}
}
pub fn build(&mut self) -> Result<()> {
debug!("[fn]: build");
self.init()?;
utils::fs::remove_dir_content(self.config.get_html_config().get_destination())?;
self.renderer.render(self)
}
pub fn get_gitignore(&self) -> PathBuf {
self.config.get_root().join(".gitignore")
}
pub fn copy_theme(&self) -> Result<()> {
debug!("[fn]: copy_theme");
let themedir = self.config.get_html_config().get_theme();
if !themedir.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", themedir);
fs::create_dir(&themedir)?;
}
let mut index = File::create(&themedir.join("index.hbs"))?;
index.write_all(theme::INDEX)?;
let mut css = File::create(&themedir.join("book.css"))?;
css.write_all(theme::CSS)?;
let mut favicon = File::create(&themedir.join("favicon.png"))?;
favicon.write_all(theme::FAVICON)?;
let mut js = File::create(&themedir.join("book.js"))?;
js.write_all(theme::JS)?;
let mut highlight_css = File::create(&themedir.join("highlight.css"))?;
highlight_css.write_all(theme::HIGHLIGHT_CSS)?;
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);
utils::fs::create_file(&path)?
.write_all(content)
.map_err(|e| e.into())
}
pub fn read_config(mut self) -> Result<Self> {
let toml = self.get_root().join("book.toml");
let json = self.get_root().join("book.json");
if toml.exists() {
let mut file = File::open(toml)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let parsed_config = TomlConfig::from_toml(&content)?;
self.config.fill_from_tomlconfig(parsed_config);
} else if json.exists() {
warn!("The JSON configuration file is deprecated, please use the TOML configuration.");
let mut file = File::open(json)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let parsed_config = JsonConfig::from_json(&content)?;
self.config.fill_from_jsonconfig(parsed_config);
}
Ok(self)
}
pub fn set_renderer(mut self, renderer: Box<Renderer>) -> Self {
self.renderer = renderer;
self
}
pub fn test(&mut self, library_paths: Vec<&str>) -> Result<()> {
self.parse_summary().chain_err(|| "Couldn't parse summary")?;
let library_args: Vec<&str> = (0..library_paths.len()).map(|_| "-L")
.zip(library_paths.into_iter())
.flat_map(|x| vec![x.0, x.1])
.collect();
let temp_dir = TempDir::new("mdbook")?;
for item in self.iter() {
if let BookItem::Chapter(_, ref ch) = *item {
if !ch.path.as_os_str().is_empty() {
let path = self.get_source().join(&ch.path);
let base = path.parent().ok_or_else(
|| String::from("Invalid bookitem path!"),
)?;
let content = utils::fs::file_to_string(&path)?;
let content = preprocess::links::replace_all(&content, base)?;
println!("[*]: Testing file: {:?}", path);
let path = temp_dir.path().join(&ch.path);
let mut tmpf = utils::fs::create_file(&path)?;
tmpf.write_all(content.as_bytes())?;
let output = Command::new("rustdoc").arg(&path).arg("--test").args(&library_args).output()?;
if !output.status.success() {
bail!(ErrorKind::Subprocess("Rustdoc returned an error".to_string(), output));
}
}
}
}
Ok(())
}
pub fn get_root(&self) -> &Path {
self.config.get_root()
}
pub fn with_destination<T: Into<PathBuf>>(mut self, destination: T) -> Self {
let root = self.config.get_root().to_owned();
self.config.get_mut_html_config()
.set_destination(&root, &destination.into());
self
}
pub fn get_destination(&self) -> &Path {
self.config.get_html_config()
.get_destination()
}
pub fn with_source<T: Into<PathBuf>>(mut self, source: T) -> Self {
self.config.set_source(source);
self
}
pub fn get_source(&self) -> &Path {
self.config.get_source()
}
pub fn with_title<T: Into<String>>(mut self, title: T) -> Self {
self.config.set_title(title);
self
}
pub fn get_title(&self) -> &str {
self.config.get_title()
}
pub fn with_description<T: Into<String>>(mut self, description: T) -> Self {
self.config.set_description(description);
self
}
pub fn get_description(&self) -> &str {
self.config.get_description()
}
pub fn set_livereload(&mut self, livereload: String) -> &mut Self {
self.livereload = Some(livereload);
self
}
pub fn unset_livereload(&mut self) -> &Self {
self.livereload = None;
self
}
pub fn get_livereload(&self) -> Option<&String> {
self.livereload.as_ref()
}
pub fn with_theme_path<T: Into<PathBuf>>(mut self, theme_path: T) -> Self {
let root = self.config.get_root().to_owned();
self.config.get_mut_html_config()
.set_theme(&root, &theme_path.into());
self
}
pub fn get_theme_path(&self) -> &Path {
self.config.get_html_config()
.get_theme()
}
pub fn with_curly_quotes(mut self, curly_quotes: bool) -> Self {
self.config.get_mut_html_config()
.set_curly_quotes(curly_quotes);
self
}
pub fn get_curly_quotes(&self) -> bool {
self.config.get_html_config()
.get_curly_quotes()
}
pub fn with_mathjax_support(mut self, mathjax_support: bool) -> Self {
self.config.get_mut_html_config()
.set_mathjax_support(mathjax_support);
self
}
pub fn get_mathjax_support(&self) -> bool {
self.config.get_html_config()
.get_mathjax_support()
}
pub fn get_google_analytics_id(&self) -> Option<String> {
self.config.get_html_config()
.get_google_analytics_id()
}
pub fn has_additional_js(&self) -> bool {
self.config.get_html_config()
.has_additional_js()
}
pub fn get_additional_js(&self) -> &[PathBuf] {
self.config.get_html_config()
.get_additional_js()
}
pub fn has_additional_css(&self) -> bool {
self.config.get_html_config()
.has_additional_css()
}
pub fn get_additional_css(&self) -> &[PathBuf] {
self.config.get_html_config()
.get_additional_css()
}
pub fn get_html_config(&self) -> &HtmlConfig {
self.config.get_html_config()
}
fn parse_summary(&mut self) -> Result<()> {
self.content = parse::construct_bookitems(&self.get_source().join("SUMMARY.md"))?;
Ok(())
}
}