1use mime::Mime;
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::spanned::Spanned;
5use syn::{Attribute, DeriveInput, Expr, Ident, Lit, Meta, parse_macro_input};
6
7use std::fs;
8use std::path::{Path, PathBuf};
9
10#[derive(Debug, Clone, Copy)]
11enum EmbedMode {
12 Bytes,
13 Str,
14 BytesMime,
15}
16
17#[proc_macro_derive(Embed, attributes(dir, mode))]
18pub fn embed(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
19 let input = parse_macro_input!(input as DeriveInput);
20
21 let struct_name = &input.ident;
22
23 let dir_attr = input
24 .attrs
25 .iter()
26 .find(|e| e.path().is_ident("dir"))
27 .expect("No #[dir = \"...\"] attribute found");
28
29 let mode_attr = input.attrs.iter().find(|e| e.path().is_ident("mode"));
30
31 let mode = mode_attr.map(extract_mode).unwrap_or(EmbedMode::Bytes);
32
33 let base_path = PathBuf::from(extract_dir_path(dir_attr));
34 let source_file = PathBuf::from(input.span().unwrap().file());
35
36 let source_dir = if let Some(parent) = source_file.parent() {
37 parent
38 } else {
39 return TokenStream::from(generate_byte_impl(struct_name, Vec::new()));
41 };
42
43 let absolue_path = source_dir.join(&base_path);
44
45 let mut match_arms = Vec::new();
46
47 for entry in collect_files(&absolue_path) {
48 let rel_path = entry
49 .0
50 .strip_prefix(&absolue_path)
51 .unwrap()
52 .to_str()
53 .unwrap()
54 .replace("\\", "/");
55
56 let include_path = base_path.join(&rel_path);
57 let include_string = include_path.to_str().unwrap();
58
59 let arm = match mode {
60 EmbedMode::Bytes => generate_byte_arm(&rel_path, include_string),
61 EmbedMode::Str => generate_str_arm(&rel_path, include_string),
62 EmbedMode::BytesMime => generate_mime_arm(
63 &rel_path,
64 include_string,
65 entry.1.unwrap_or(mime::APPLICATION_OCTET_STREAM),
66 ),
67 };
68
69 match_arms.push(arm);
70 }
71
72 #[allow(unused_mut)]
73 let mut expanded = match mode {
74 EmbedMode::Bytes => generate_byte_impl(struct_name, match_arms),
75 EmbedMode::Str => generate_str_impl(struct_name, match_arms),
76 EmbedMode::BytesMime => generate_mime_impl(struct_name, match_arms),
77 };
78
79 proc_macro::TokenStream::from(expanded)
80}
81
82fn collect_files(dir: &Path) -> Vec<(PathBuf, Option<Mime>)> {
83 let mut files = Vec::new();
84
85 for entry in fs::read_dir(dir).unwrap() {
86 let path = entry.unwrap().path();
87
88 if path.is_file() {
89 let mime_type = mime_guess::from_path(&path);
90 files.push((path, mime_type.first()));
91 } else if path.is_dir() {
92 files.extend(collect_files(&path));
93 }
94 }
95
96 files
97}
98
99fn extract_dir_path(attr: &Attribute) -> String {
100 let meta = match &attr.meta {
101 Meta::NameValue(meta) => meta,
102 _ => panic!("Expected #[dir = \"...\"] as a name-value attribute."),
103 };
104
105 let expr_lit = match &meta.value {
106 Expr::Lit(expr_lit) => expr_lit,
107 _ => panic!("Expected #[dir = \"...\"] with a string literal."),
108 };
109
110 match &expr_lit.lit {
111 Lit::Str(str) => str.value(),
112 _ => panic!("Expected #[dir = \"...\"] to be a string."),
113 }
114}
115
116fn extract_mode(attr: &Attribute) -> EmbedMode {
117 let meta = match &attr.meta {
118 Meta::NameValue(meta) => meta,
119 _ => panic!("Expected #[mode = \"bytes\"|\"str\"|\"mime\"] as a name-value attribute."),
120 };
121
122 let expr_lit = match &meta.value {
123 Expr::Lit(expr_lit) => expr_lit,
124 _ => panic!("Expected #[mode = \"bytes\"|\"str\"|\"mime\"] with a string literal."),
125 };
126
127 match &expr_lit.lit {
128 Lit::Str(str) => match str.value().as_str() {
129 "bytes" => EmbedMode::Bytes,
130 "str" => EmbedMode::Str,
131 "mime" => EmbedMode::BytesMime,
132 other => panic!("Unknown mode: {other}. Use `bytes`,`str` or `mime`."),
133 },
134 _ => panic!("Expected #[mode = \"bytes\"|\"str\"|\"mime\"] to be a string."),
135 }
136}
137
138fn generate_byte_arm(rel: &str, include: &str) -> proc_macro2::TokenStream {
139 quote! {
140 #rel => Some(include_bytes!(#include)),
141 }
142}
143
144fn generate_byte_impl(
145 struct_name: &Ident,
146 match_arms: Vec<proc_macro2::TokenStream>,
147) -> proc_macro2::TokenStream {
148 quote! {
149 impl #struct_name {
150 pub fn get(name: &str) -> Option<&'static [u8]> {
151 match name {
152 #(#match_arms)*
153 _ => None,
154 }
155 }
156 }
157 }
158}
159
160fn generate_str_arm(rel: &str, include: &str) -> proc_macro2::TokenStream {
161 quote! {
162 #rel => Some(include_str!(#include)),
163 }
164}
165
166fn generate_str_impl(
167 struct_name: &Ident,
168 match_arms: Vec<proc_macro2::TokenStream>,
169) -> proc_macro2::TokenStream {
170 quote! {
171 impl #struct_name {
172 pub fn get(name: &str) -> Option<&'static str> {
173 match name {
174 #(#match_arms)*
175 _ => None,
176 }
177 }
178 }
179 }
180}
181
182fn generate_mime_arm(rel: &str, include: &str, mime_type: Mime) -> proc_macro2::TokenStream {
183 let mime_str = mime_type.essence_str();
184 quote! {
185 #rel => Some((include_bytes!(#include),#mime_str)),
186 }
187}
188
189fn generate_mime_impl(
190 struct_name: &Ident,
191 match_arms: Vec<proc_macro2::TokenStream>,
192) -> proc_macro2::TokenStream {
193 quote! {
194 impl #struct_name {
195 pub fn get(name: &str) -> Option<(&'static [u8],&'static str)> {
196 match name {
197 #(#match_arms)*
198 _ => None,
199 }
200 }
201 }
202 }
203}