Debian Codegraph @

crates/mdbook-html/src/html_handlebars/static_files.rs

raw ◀ ▶
1 Debian patch touch this file
1 //! Support for writing static files.
2
3 use super::helpers::resources::ResourceHelper;
4 use crate::theme::{self, Theme, playground_editor};
5 use anyhow::{Context, Result};
6 use mdbook_core::config::HtmlConfig;
7 use mdbook_core::static_regex;
8 use mdbook_core::utils::fs;
9 use std::borrow::Cow;
10 use std::collections::HashMap;
11 use std::path::{Path, PathBuf};
12 use tracing::debug;
13
14 /// Map static files to their final names and contents.
15 ///
16 /// It performs [fingerprinting], if you call the `hash_files` method.
17 /// If hash-files is turned off, then the files will not be renamed.
18 /// It also writes files to their final destination, when `write_files` is called,
19 /// and interprets the `{{ resource }}` directives to allow assets to name each other.
20 ///
21 /// [fingerprinting]: https://guides.rubyonrails.org/asset_pipeline.html#fingerprinting-versioning-with-digest-based-urls
22 pub(super) struct StaticFiles {
23 static_files: Vec<StaticFile>,
24 hash_map: HashMap<String, String>,
25 }
26
27 enum StaticFile {
28 Builtin {
29 data: Vec<u8>,
30 filename: String,
31 },
32 Additional {
33 input_location: PathBuf,
34 filename: String,
35 },
36 }
37
38 impl StaticFiles {
39 pub(super) fn new(theme: &Theme, html_config: &HtmlConfig, root: &Path) -> Result<StaticFiles> {
40 let static_files = Vec::new();
41 let mut this = StaticFiles {
42 hash_map: HashMap::new(),
43 static_files,
44 };
45
46 this.add_builtin("book.js", &theme.js);
47 this.add_builtin("css/general.css", &theme.general_css);
48 this.add_builtin("css/chrome.css", &theme.chrome_css);
49 if html_config.print.enable {
50 this.add_builtin("css/print.css", &theme.print_css);
51 }
52 this.add_builtin("css/variables.css", &theme.variables_css);
53 if let Some(contents) = &theme.favicon_png {
54 this.add_builtin("favicon.png", contents);
55 }
56 if let Some(contents) = &theme.favicon_svg {
57 this.add_builtin("favicon.svg", contents);
58 }
59 this.add_builtin("highlight.css", &theme.highlight_css);
60 this.add_builtin("tomorrow-night.css", &theme.tomorrow_night_css);
61 this.add_builtin("ayu-highlight.css", &theme.ayu_highlight_css);
62 this.add_builtin("highlight.js", &theme.highlight_js);
63 this.add_builtin("clipboard.min.js", &theme.clipboard_js);
•64 #[cfg(any())] if theme.fonts_css.is_none() {
65 this.add_builtin("fonts/fonts.css", theme::fonts::CSS);
66 for (file_name, contents) in theme::fonts::LICENSES.iter() {
67 this.add_builtin(file_name, contents);
68 }
69 for (file_name, contents) in theme::fonts::OPEN_SANS.iter() {
70 this.add_builtin(file_name, contents);
71 }
72 this.add_builtin(
73 theme::fonts::SOURCE_CODE_PRO.0,
74 theme::fonts::SOURCE_CODE_PRO.1,
75 );
76 } else if let Some(fonts_css) = &theme.fonts_css {
77 if !fonts_css.is_empty() {
78 this.add_builtin("fonts/fonts.css", fonts_css);
79 }
80 }
81
82 let playground_config = &html_config.playground;
83
84 // Ace is a very large dependency, so only load it when requested
85 if playground_config.editable && playground_config.copy_js {
86 // Load the editor
87 this.add_builtin("editor.js", playground_editor::JS);
88 this.add_builtin("ace.js", playground_editor::ACE_JS);
89 this.add_builtin("mode-rust.js", playground_editor::MODE_RUST_JS);
90 this.add_builtin("theme-dawn.js", playground_editor::THEME_DAWN_JS);
91 this.add_builtin(
92 "theme-tomorrow_night.js",
93 playground_editor::THEME_TOMORROW_NIGHT_JS,
94 );
95 }
96
97 let custom_files = html_config
98 .additional_css
99 .iter()
100 .chain(html_config.additional_js.iter());
101
102 for custom_file in custom_files {
103 let input_location = root.join(custom_file);
104
105 this.static_files.push(StaticFile::Additional {
106 input_location,
107 filename: custom_file
108 .to_str()
109 .with_context(|| "resource file names must be valid utf8")?
110 .to_owned(),
111 });
112 }
113
114 for input_location in theme.font_files.iter().cloned() {
115 let filename = Path::new("fonts")
116 .join(input_location.file_name().unwrap())
117 .to_str()
118 .with_context(|| "resource file names must be valid utf8")?
119 .to_owned();
120 this.static_files.push(StaticFile::Additional {
121 input_location,
122 filename,
123 });
124 }
125
126 Ok(this)
127 }
128
129 pub(super) fn add_builtin(&mut self, filename: &str, data: &[u8]) {
130 self.static_files.push(StaticFile::Builtin {
131 filename: filename.to_owned(),
132 data: data.to_owned(),
133 });
134 }
135
136 /// Updates this [`StaticFiles`] to hash the contents for determining the
137 /// filename for each resource.
138 pub(super) fn hash_files(&mut self) -> Result<()> {
139 use sha2::{Digest, Sha256};
140 use std::io::Read;
141 for static_file in &mut self.static_files {
142 match static_file {
143 &mut StaticFile::Builtin {
144 ref mut filename,
145 ref data,
146 } => {
147 let mut parts = filename.splitn(2, '.');
148 let parts = parts.next().and_then(|p| Some((p, parts.next()?)));
149 if let Some((name, suffix)) = parts {
150 if name != "" && suffix != "" && suffix != "txt" {
151 let hex = hex::encode(&Sha256::digest(data)[..4]);
152 let new_filename = format!("{}-{}.{}", name, hex, suffix);
153 self.hash_map.insert(filename.clone(), new_filename.clone());
154 *filename = new_filename;
155 }
156 }
157 }
158 &mut StaticFile::Additional {
159 ref mut filename,
160 ref input_location,
161 } => {
162 let mut parts = filename.splitn(2, '.');
163 let parts = parts.next().and_then(|p| Some((p, parts.next()?)));
164 if let Some((name, suffix)) = parts {
165 if name != "" && suffix != "" {
166 let mut digest = Sha256::new();
167 let mut input_file =
168 std::fs::File::open(input_location).with_context(|| {
169 format!("failed to open `{filename}` for hashing")
170 })?;
171 let mut buf = vec![0; 1024];
172 loop {
173 let amt = input_file
174 .read(&mut buf)
175 .with_context(|| "read static file for hashing")?;
176 if amt == 0 {
177 break;
178 };
179 digest.update(&buf[..amt]);
180 }
181 let hex = hex::encode(&digest.finalize()[..4]);
182 let new_filename = format!("{}-{}.{}", name, hex, suffix);
183 self.hash_map.insert(filename.clone(), new_filename.clone());
184 *filename = new_filename;
185 }
186 }
187 }
188 }
189 }
190 Ok(())
191 }
192
193 pub(super) fn write_files(self, destination: &Path) -> Result<ResourceHelper> {
194 use regex::bytes::Captures;
195 // The `{{ resource "name" }}` directive in static resources look like
196 // handlebars syntax, even if they technically aren't.
197 static_regex!(RESOURCE, bytes, r#"\{\{ resource "([^"]+)" \}\}"#);
198 fn replace_all<'a>(
199 hash_map: &HashMap<String, String>,
200 data: &'a [u8],
201 filename: &str,
202 ) -> Cow<'a, [u8]> {
203 RESOURCE.replace_all(data, move |captures: &Captures<'_>| {
204 let name = captures
205 .get(1)
206 .expect("capture 1 in resource regex")
207 .as_bytes();
208 let name = std::str::from_utf8(name).expect("resource name with invalid utf8");
209 let resource_filename = hash_map.get(name).map(|s| &s[..]).unwrap_or(name);
210 let path_to_root = fs::path_to_root(filename);
211 format!("{}{}", path_to_root, resource_filename)
212 .as_bytes()
213 .to_owned()
214 })
215 }
216 for static_file in &self.static_files {
217 match static_file {
218 StaticFile::Builtin { filename, data } => {
219 debug!("Writing builtin -> {}", filename);
220 let data = if filename.ends_with(".css") || filename.ends_with(".js") {
221 replace_all(&self.hash_map, data, filename)
222 } else {
223 Cow::Borrowed(&data[..])
224 };
225 let path = destination.join(filename);
226 fs::write(path, &data)?;
227 }
228 StaticFile::Additional {
229 input_location,
230 filename,
231 } => {
232 let output_location = destination.join(filename);
233 debug!(
234 "Copying {} -> {}",
235 input_location.display(),
236 output_location.display()
237 );
238 if let Some(parent) = output_location.parent() {
239 fs::create_dir_all(parent)
240 .with_context(|| format!("Unable to create {}", parent.display()))?;
241 }
242 if filename.ends_with(".css") || filename.ends_with(".js") {
243 let data = fs::read_to_string(input_location)?;
244 let data = replace_all(&self.hash_map, data.as_bytes(), filename);
245 let path = destination.join(filename);
246 fs::write(path, &data)?;
247 } else {
248 std::fs::copy(input_location, &output_location).with_context(|| {
249 format!(
250 "Unable to copy {} to {}",
251 input_location.display(),
252 output_location.display()
253 )
254 })?;
255 }
256 }
257 }
258 }
259 let hash_map = self.hash_map;
260 Ok(ResourceHelper { hash_map })
261 }
262 }
263
264 #[cfg(test)]
265 mod tests {
266 use super::*;
267 use crate::theme::Theme;
268 use mdbook_core::config::HtmlConfig;
269 use mdbook_core::utils::fs;
270 use tempfile::TempDir;
271
272 #[test]
273 fn test_write_directive() {
274 let theme = Theme {
275 index: Vec::new(),
276 head: Vec::new(),
277 redirect: Vec::new(),
278 header: Vec::new(),
279 chrome_css: Vec::new(),
280 general_css: Vec::new(),
281 print_css: Vec::new(),
282 variables_css: Vec::new(),
283 favicon_png: Some(Vec::new()),
284 favicon_svg: Some(Vec::new()),
285 js: Vec::new(),
286 highlight_css: Vec::new(),
287 tomorrow_night_css: Vec::new(),
288 ayu_highlight_css: Vec::new(),
289 highlight_js: Vec::new(),
290 clipboard_js: Vec::new(),
291 toc_js: Vec::new(),
292 toc_html: Vec::new(),
293 fonts_css: None,
294 font_files: Vec::new(),
295 };
296 let temp_dir = TempDir::with_prefix("mdbook-").unwrap();
297 let reference_js = Path::new("static-files-test-case-reference.js");
298 let mut html_config = HtmlConfig::default();
299 html_config.additional_js.push(reference_js.to_owned());
300 fs::write(
301 temp_dir.path().join(reference_js),
302 br#"{{ resource "book.js" }}"#,
303 )
304 .unwrap();
305 let mut static_files = StaticFiles::new(&theme, &html_config, temp_dir.path()).unwrap();
306 static_files.hash_files().unwrap();
307 static_files.write_files(temp_dir.path()).unwrap();
308 // custom JS winds up referencing book.js
309 let reference_js_content = fs::read_to_string(
310 temp_dir
311 .path()
312 .join("static-files-test-case-reference-635c9cdc.js"),
313 )
314 .unwrap();
315 assert_eq!("book-e3b0c442.js", reference_js_content);
316 // book.js winds up empty
317 let book_js_content = fs::read_to_string(temp_dir.path().join("book-e3b0c442.js")).unwrap();
318 assert_eq!("", book_js_content);
319 }
320 }