Skip to main content

memory_serve/build/
code.rs

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