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
pub mod bookitem;
pub use self::bookitem::{BookItem, BookItems};
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::Write;
use std::process::Command;
use tempdir::TempDir;
use {parse, theme, utils};
use renderer::{HtmlHandlebars, Renderer};
use preprocess;
use errors::*;
use config::Config;
pub struct MDBook {
pub root: PathBuf,
pub config: Config,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
pub livereload: Option<String>,
}
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 {
root: root,
config: Config::default(),
content: vec![],
renderer: Box::new(HtmlHandlebars::new()),
livereload: None,
}
}
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.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() {
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.get_source().join(&ch.path);
if !path.exists() {
if !self.config.build.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.get_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.");
}
}
pub fn build(&mut self) -> Result<()> {
debug!("[fn]: build");
self.init()?;
utils::fs::remove_dir_content(&self.get_destination())?;
self.renderer.render(self)
}
pub fn get_gitignore(&self) -> PathBuf {
self.root.join(".gitignore")
}
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)?;
}
let mut index = File::create(themedir.join("index.hbs"))?;
index.write_all(theme::INDEX)?;
let mut header = File::create(themedir.join("header.hbs"))?;
header.write_all(theme::HEADER)?;
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 config_path = self.root.join("book.toml");
if config_path.exists() {
debug!("[*] Loading the config from {}", config_path.display());
self.config = Config::from_disk(&config_path)?;
} else {
self.config = Config::default();
}
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(())
}
fn parse_summary(&mut self) -> Result<()> {
let summary = self.get_source().join("SUMMARY.md");
self.content = parse::construct_bookitems(&summary)?;
Ok(())
}
pub fn get_destination(&self) -> PathBuf {
self.root.join(&self.config.build.build_dir)
}
pub fn get_source(&self) -> PathBuf {
self.root.join(&self.config.book.src)
}
pub fn theme_dir(&self) -> PathBuf {
match self.config.html_config().and_then(|h| h.theme) {
Some(d) => self.root.join(d),
None => self.root.join("theme"),
}
}
}