memory_serve_core/
code.rs1use std::{env, path::Path};
2
3use crate::{asset::Asset, list::list_assets};
4
5pub fn assets_to_code(
7 asset_dir: &str,
8 path: &Path,
9 out_dir: Option<&Path>,
10 embed: bool,
11 log: fn(&str),
12) -> String {
13 log(&format!("Loading static assets from {asset_dir}"));
14
15 if embed {
16 log("Embedding assets into binary");
17 } else {
18 log("Not embedding assets into binary, assets will load dynamically");
19 }
20
21 let assets = list_assets(path, embed, log);
22
23 let mut code = "&[".to_string();
25
26 for asset in assets {
27 let Asset {
28 route,
29 path,
30 etag,
31 content_type,
32 compressed_bytes,
33 } = asset;
34
35 let is_compressed = compressed_bytes.is_some();
36
37 let bytes = if !embed {
38 "None".to_string()
39 } else if let Some(compressed_bytes) = &compressed_bytes {
40 let file_path = if let Some(out_dir) = out_dir {
41 Path::new(&out_dir).join(&etag)
42 } else {
43 let tmp_dir = env::temp_dir();
44
45 Path::new(&tmp_dir).join(&etag)
46 };
47
48 std::fs::write(&file_path, compressed_bytes).expect("Unable to write file to out dir.");
49
50 format!("Some(include_bytes!(r\"{}\"))", file_path.to_string_lossy())
51 } else {
52 format!("Some(include_bytes!(r\"{}\"))", path.to_string_lossy())
53 };
54
55 code.push_str(&format!(
56 "
57 memory_serve::Asset {{
58 route: r\"{route}\",
59 path: r{path:?},
60 content_type: \"{content_type}\",
61 etag: \"{etag}\",
62 bytes: {bytes},
63 is_compressed: {is_compressed},
64 }},"
65 ));
66 }
67
68 code.push(']');
69
70 code
71}