Debian Codegraph @

crates/mdbook-driver/src/load.rs

raw
1 use anyhow::{Context, Result};
2 use mdbook_core::book::{Book, BookItem, Chapter};
3 use mdbook_core::config::BuildConfig;
4 use mdbook_core::utils::{escape_html, fs};
5 use mdbook_summary::{Link, Summary, SummaryItem, parse_summary};
6 use std::path::Path;
7 use tracing::debug;
8
9 /// Load a book into memory from its `src/` directory.
10 pub(crate) fn load_book<P: AsRef<Path>>(src_dir: P, cfg: &BuildConfig) -> Result<Book> {
11 let src_dir = src_dir.as_ref();
12 let summary_md = src_dir.join("SUMMARY.md");
13
14 let summary_content = fs::read_to_string(&summary_md)?;
15 let summary = parse_summary(&summary_content)
16 .with_context(|| format!("Summary parsing failed for file={summary_md:?}"))?;
17
18 if cfg.create_missing {
19 create_missing(src_dir, &summary).with_context(|| "Unable to create missing chapters")?;
20 }
21
22 load_book_from_disk(&summary, src_dir)
23 }
24
25 fn create_missing(src_dir: &Path, summary: &Summary) -> Result<()> {
26 let mut items: Vec<_> = summary
27 .prefix_chapters
28 .iter()
29 .chain(summary.numbered_chapters.iter())
30 .chain(summary.suffix_chapters.iter())
31 .collect();
32
33 while let Some(next) = items.pop() {
34 if let SummaryItem::Link(ref link) = *next {
35 if let Some(ref location) = link.location {
36 let filename = src_dir.join(location);
37 if !filename.exists() {
38 if let Some(parent) = filename.parent() {
39 if !parent.exists() {
40 fs::create_dir_all(parent)?;
41 }
42 }
43 debug!("Creating missing file {}", filename.display());
44 let title = escape_html(&link.name);
45 fs::write(&filename, format!("# {title}\n"))?;
46 }
47 }
48
49 items.extend(&link.nested_items);
50 }
51 }
52
53 Ok(())
54 }
55
56 /// Use the provided `Summary` to load a `Book` from disk.
57 ///
58 /// You need to pass in the book's source directory because all the links in
59 /// `SUMMARY.md` give the chapter locations relative to it.
60 pub(crate) fn load_book_from_disk<P: AsRef<Path>>(summary: &Summary, src_dir: P) -> Result<Book> {
61 debug!("Loading the book from disk");
62 let src_dir = src_dir.as_ref();
63
64 let prefix = summary.prefix_chapters.iter();
65 let numbered = summary.numbered_chapters.iter();
66 let suffix = summary.suffix_chapters.iter();
67
68 let summary_items = prefix.chain(numbered).chain(suffix);
69
70 let mut chapters = Vec::new();
71
72 for summary_item in summary_items {
73 let chapter = load_summary_item(summary_item, src_dir, Vec::new())?;
74 chapters.push(chapter);
75 }
76
77 Ok(Book::new_with_items(chapters))
78 }
79
80 fn load_summary_item<P: AsRef<Path> + Clone>(
81 item: &SummaryItem,
82 src_dir: P,
83 parent_names: Vec<String>,
84 ) -> Result<BookItem> {
85 match item {
86 SummaryItem::Separator => Ok(BookItem::Separator),
87 SummaryItem::Link(link) => load_chapter(link, src_dir, parent_names).map(BookItem::Chapter),
88 SummaryItem::PartTitle(title) => Ok(BookItem::PartTitle(title.clone())),
89 _ => panic!("SummaryItem {item:?} not covered"),
90 }
91 }
92
93 fn load_chapter<P: AsRef<Path>>(
94 link: &Link,
95 src_dir: P,
96 parent_names: Vec<String>,
97 ) -> Result<Chapter> {
98 let src_dir = src_dir.as_ref();
99
100 let mut ch = if let Some(ref link_location) = link.location {
101 debug!("Loading {} ({})", link.name, link_location.display());
102
103 let location = if link_location.is_absolute() {
104 link_location.clone()
105 } else {
106 src_dir.join(link_location)
107 };
108
109 let mut content = std::fs::read_to_string(&location)
110 .with_context(|| format!("failed to read chapter `{}`", link_location.display()))?;
111
112 if content.as_bytes().starts_with(b"\xef\xbb\xbf") {
113 content.replace_range(..3, "");
114 }
115
116 let stripped = location
117 .strip_prefix(src_dir)
118 .expect("Chapters are always inside a book");
119
120 Chapter::new(&link.name, content, stripped, parent_names.clone())
121 } else {
122 Chapter::new_draft(&link.name, parent_names.clone())
123 };
124
125 let mut sub_item_parents = parent_names;
126
127 ch.number = link.number.clone();
128
129 sub_item_parents.push(link.name.clone());
130 let sub_items = link
131 .nested_items
132 .iter()
133 .map(|i| load_summary_item(i, src_dir, sub_item_parents.clone()))
134 .collect::<Result<Vec<_>>>()?;
135
136 ch.sub_items = sub_items;
137
138 Ok(ch)
139 }
140
141 #[cfg(test)]
142 mod tests {
143 use super::*;
144 use mdbook_core::book::SectionNumber;
145 use std::path::PathBuf;
146 use tempfile::{Builder as TempFileBuilder, TempDir};
147
148 const DUMMY_SRC: &str = "
149 # Dummy Chapter
150
151 this is some dummy text.
152
153 And here is some \
154 more text.
155 ";
156
157 /// Create a dummy `Link` in a temporary directory.
158 fn dummy_link() -> (Link, TempDir) {
159 let temp = TempFileBuilder::new().prefix("book").tempdir().unwrap();
160
161 let chapter_path = temp.path().join("chapter_1.md");
162 fs::write(&chapter_path, DUMMY_SRC).unwrap();
163
164 let link = Link::new("Chapter 1", chapter_path);
165
166 (link, temp)
167 }
168
169 /// Create a nested `Link` written to a temporary directory.
170 fn nested_links() -> (Link, TempDir) {
171 let (mut root, temp_dir) = dummy_link();
172
173 let second_path = temp_dir.path().join("second.md");
174 fs::write(&second_path, "Hello World!").unwrap();
175
176 let mut second = Link::new("Nested Chapter 1", &second_path);
177 second.number = Some(SectionNumber::new([1, 2]));
178
179 root.nested_items.push(second.clone().into());
180 root.nested_items.push(SummaryItem::Separator);
181 root.nested_items.push(second.into());
182
183 (root, temp_dir)
184 }
185
186 #[test]
187 fn load_a_single_chapter_from_disk() {
188 let (link, temp_dir) = dummy_link();
189 let should_be = Chapter::new(
190 "Chapter 1",
191 DUMMY_SRC.to_string(),
192 "chapter_1.md",
193 Vec::new(),
194 );
195
196 let got = load_chapter(&link, temp_dir.path(), Vec::new()).unwrap();
197 assert_eq!(got, should_be);
198 }
199
200 #[test]
201 fn load_a_single_chapter_with_utf8_bom_from_disk() {
202 let temp_dir = TempFileBuilder::new().prefix("book").tempdir().unwrap();
203
204 let chapter_path = temp_dir.path().join("chapter_1.md");
205 fs::write(&chapter_path, format!("\u{feff}{DUMMY_SRC}")).unwrap();
206
207 let link = Link::new("Chapter 1", chapter_path);
208
209 let should_be = Chapter::new(
210 "Chapter 1",
211 DUMMY_SRC.to_string(),
212 "chapter_1.md",
213 Vec::new(),
214 );
215
216 let got = load_chapter(&link, temp_dir.path(), Vec::new()).unwrap();
217 assert_eq!(got, should_be);
218 }
219
220 #[test]
221 fn cant_load_a_nonexistent_chapter() {
222 let link = Link::new("Chapter 1", "/foo/bar/baz.md");
223
224 let got = load_chapter(&link, "", Vec::new());
225 assert!(got.is_err());
226 }
227
228 #[test]
229 fn load_recursive_link_with_separators() {
230 let (root, temp) = nested_links();
231
232 let mut nested = Chapter::new(
233 "Nested Chapter 1",
234 String::from("Hello World!"),
235 "second.md",
236 vec![String::from("Chapter 1")],
237 );
238 nested.number = Some(SectionNumber::new([1, 2]));
239 let mut chapter =
240 Chapter::new("Chapter 1", String::from(DUMMY_SRC), "chapter_1.md", vec![]);
241 chapter.sub_items = vec![
242 BookItem::Chapter(nested.clone()),
243 BookItem::Separator,
244 BookItem::Chapter(nested),
245 ];
246 let should_be = BookItem::Chapter(chapter);
247
248 let got = load_summary_item(&SummaryItem::Link(root), temp.path(), Vec::new()).unwrap();
249 assert_eq!(got, should_be);
250 }
251
252 #[test]
253 fn load_a_book_with_a_single_chapter() {
254 let (link, temp) = dummy_link();
255 let mut summary = Summary::default();
256 summary.numbered_chapters = vec![SummaryItem::Link(link)];
257 let chapter = Chapter::new(
258 "Chapter 1",
259 String::from(DUMMY_SRC),
260 PathBuf::from("chapter_1.md"),
261 vec![],
262 );
263 let items = vec![BookItem::Chapter(chapter)];
264 let should_be = Book::new_with_items(items);
265
266 let got = load_book_from_disk(&summary, temp.path()).unwrap();
267
268 assert_eq!(got, should_be);
269 }
270
271 #[test]
272 fn cant_load_chapters_with_an_empty_path() {
273 let (_, temp) = dummy_link();
274 let mut summary = Summary::default();
275 let link = Link::new("Empty", "");
276 summary.numbered_chapters = vec![SummaryItem::Link(link)];
277 let got = load_book_from_disk(&summary, temp.path());
278 assert!(got.is_err());
279 }
280
281 #[test]
282 fn cant_load_chapters_when_the_link_is_a_directory() {
283 let (_, temp) = dummy_link();
284 let dir = temp.path().join("nested");
285 fs::create_dir_all(&dir).unwrap();
286
287 let mut summary = Summary::default();
288 let link = Link::new("nested", dir);
289 summary.numbered_chapters = vec![SummaryItem::Link(link)];
290
291 let got = load_book_from_disk(&summary, temp.path());
292 assert!(got.is_err());
293 }
294
295 #[test]
296 fn cant_open_summary_md() {
297 let cfg = BuildConfig::default();
298 let temp_dir = TempFileBuilder::new().prefix("book").tempdir().unwrap();
299
300 let got = load_book(&temp_dir, &cfg);
301 assert!(got.is_err());
302 let error_message = got.err().unwrap().to_string();
303 let expected = format!(
304 r#"failed to read `{}`"#,
305 temp_dir.path().join("SUMMARY.md").display()
306 );
307 assert_eq!(error_message, expected);
308 }
309 }