1use lazy_regex::regex;
2use log::warn;
3use mdbook::book::{Book, BookItem};
4use mdbook::errors::*;
5use mdbook::preprocess::{Preprocessor, PreprocessorContext};
6use regex::Captures;
7use std::path::Path;
8
9#[derive(Default)]
12pub struct ReadmePreprocessor;
13
14impl ReadmePreprocessor {
15 pub fn new() -> Self {
17 ReadmePreprocessor
18 }
19}
20
21impl Preprocessor for ReadmePreprocessor {
22 fn name(&self) -> &str {
23 "readme"
24 }
25
26 fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
27 let readme_link_re = regex!(r"(?i)\[(.*?)\]\(<?README(?:(?:\.md)|(?:\.markdown))>?\)");
28
29 let source_dir = ctx.root.join(&ctx.config.book.src);
30 book.for_each_mut(|section: &mut BookItem| {
31 if let BookItem::Chapter(ref mut ch) = *section {
32 if let Some(ref mut path) = ch.path {
33 if is_readme_file(&path) {
34 let mut index_md = source_dir.join(path.with_file_name("index.md"));
35 if index_md.exists() {
36 warn_readme_name_conflict(&path, &&mut index_md);
37 }
38 path.set_file_name("index.md");
39 } else {
40 ch.content = readme_link_re
41 .replace_all(&ch.content, |caps: &Captures| {
42 format!("[{}](index.md)", &caps[1])
43 })
44 .to_string();
45 }
46 }
47 }
48 });
49
50 Ok(book)
51 }
52}
53
54fn warn_readme_name_conflict<P: AsRef<Path>>(readme_path: P, index_path: P) {
55 let file_name = readme_path.as_ref().file_name().unwrap_or_default();
56 let parent_dir = index_path
57 .as_ref()
58 .parent()
59 .unwrap_or_else(|| index_path.as_ref());
60 warn!(
61 "It seems that there are both {:?} and index.md under \"{}\".",
62 file_name,
63 parent_dir.display()
64 );
65 warn!(
66 "mdbook converts {:?} into index.html by default. It may cause",
67 file_name
68 );
69 warn!("unexpected behavior if putting both files under the same directory.");
70 warn!("To solve the warning, try to rearrange the book structure or disable");
71 warn!("\"index\" preprocessor to stop the conversion.");
72}
73
74fn is_readme_file<P: AsRef<Path>>(path: P) -> bool {
75 regex!(r"(?i)^readme$").is_match(
76 path.as_ref()
77 .file_stem()
78 .and_then(std::ffi::OsStr::to_str)
79 .unwrap_or_default(),
80 )
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
88 fn file_stem_exactly_matches_readme_case_insensitively() {
89 let path = "path/to/Readme.md";
90 assert!(is_readme_file(path));
91
92 let path = "path/to/README.md";
93 assert!(is_readme_file(path));
94
95 let path = "path/to/rEaDmE.md";
96 assert!(is_readme_file(path));
97
98 let path = "path/to/README.markdown";
99 assert!(is_readme_file(path));
100
101 let path = "path/to/README";
102 assert!(is_readme_file(path));
103
104 let path = "path/to/README-README.md";
105 assert!(!is_readme_file(path));
106 }
107}