Skip to main content

memory_serve/build/
code.rs

1use std::path::Path;
2
3use super::{file_asset::FileAsset, list::list_assets};
4
5/// Generate code with metadata and contents for the assets
6pub fn assets_to_code(
7    asset_dir: &str,
8    path: &Path,
9    out_dir: &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    // using a string is faster than using quote ;)
24    let mut code = "&[".to_string();
25
26    for asset in assets {
27        let FileAsset {
28            route,
29            path,
30            etag,
31            content_type,
32            compressed_bytes,
33            should_compress,
34        } = asset;
35
36        let is_compressed = compressed_bytes.is_some();
37
38        let bytes = if !embed {
39            "None".to_string()
40        } else if let Some(compressed_bytes) = compressed_bytes {
41            let file_path = out_dir.join(&etag);
42            std::fs::write(&file_path, compressed_bytes).expect("Unable to write file to out dir.");
43
44            format!("Some(include_bytes!(r\"{}\"))", file_path.to_string_lossy())
45        } else {
46            format!("Some(include_bytes!(r\"{}\"))", path.to_string_lossy())
47        };
48
49        code.push_str(&format!(
50            "
51            memory_serve::Asset {{
52                route: r\"{route}\",
53                path: r{path:?},
54                content_type: \"{content_type}\",
55                etag: \"{etag}\",
56                bytes: {bytes},
57                is_compressed: {is_compressed},
58                should_compress: {should_compress},
59            }},"
60        ));
61    }
62
63    code.push(']');
64
65    code
66}