tauri_plugin_compmd/
files.rs1use std::fs;
5use std::path::PathBuf;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum Files {
10 Embedded(&'static [(&'static str, &'static [u8])]),
12 Folder(PathBuf),
14}
15
16impl Files {
17 #[must_use]
19 pub fn read(&self, parts: &[&str]) -> Option<Vec<u8>> {
20 match self {
21 Self::Embedded(files) => {
22 let path = parts.join("/");
23 let found = files
24 .binary_search_by(|(name, _)| (*name).cmp(path.as_str()))
25 .ok()?;
26 Some(files[found].1.to_vec())
27 }
28 Self::Folder(folder) => {
29 let file = parts
30 .iter()
31 .fold(folder.clone(), |path, part| path.join(part));
32 if file.is_file() {
33 fs::read(file).ok()
34 } else {
35 None
36 }
37 }
38 }
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 const EMBEDDED: &[(&str, &[u8])] = &[
47 ("chunks/runtime.js", b"export {}"),
48 ("strict.html", b"<!doctype html>"),
49 ];
50
51 #[test]
52 fn an_embedded_file_is_found_by_its_path() {
53 let files = Files::Embedded(EMBEDDED);
54 assert_eq!(
55 files.read(&["strict.html"]),
56 Some(b"<!doctype html>".to_vec())
57 );
58 assert_eq!(
59 files.read(&["chunks", "runtime.js"]),
60 Some(b"export {}".to_vec())
61 );
62 assert_eq!(files.read(&["chunks"]), None);
63 assert_eq!(files.read(&["missing.js"]), None);
64 }
65
66 #[test]
67 fn a_folders_file_is_read_and_a_folder_is_not_a_file() {
68 let folder =
69 std::env::temp_dir().join(format!("compmd-tauri-files-{}", std::process::id()));
70 fs::create_dir_all(folder.join("chunks")).expect("made");
71 fs::write(folder.join("chunks").join("runtime.js"), "export {}").expect("written");
72 let files = Files::Folder(folder.clone());
73 assert_eq!(
74 files.read(&["chunks", "runtime.js"]),
75 Some(b"export {}".to_vec())
76 );
77 assert_eq!(files.read(&["chunks"]), None);
78 assert_eq!(files.read(&["missing.js"]), None);
79 drop(fs::remove_dir_all(folder));
80 }
81}