magic_embed/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(unused_imports)]
3#![deny(missing_docs)]
4//! # `magic-embed`: Compile-time Magic Database Embedding
5//!
6//! A procedural macro crate for embedding compiled [`pure_magic`](https://crates.io/crates/pure-magic) databases directly into your Rust binary.
7//! This crate provides a convenient way to bundle file type detection rules with your application,
8//! eliminating the need for external rule files at runtime.
9//!
10//! ## Features
11//!
12//! * **Compile-time Embedding**: Magic rule files are compiled and embedded during build
13//! * **Zero Runtime Dependencies**: No need to distribute separate rule files
14//! * **Flexible Configuration**: Include/exclude specific rule files or directories
15//! * **Seamless Integration**: Works with the [`pure_magic`](https://crates.io/crates/pure-magic)
16//!
17//! ## Installation
18//!
19//! Add `magic-embed` to your `Cargo.toml`:
20//!
21//! ```toml
22//! [dependencies]
23//! magic-embed = "0.1"  # Replace with the latest version
24//! pure-magic = "0.1"     # Required peer dependency
25//! ```
26//!
27//! ## Usage
28//!
29//! Apply the `#[magic_embed]` attribute to a struct to embed a compiled magic database:
30//!
31//! ```rust
32//! use magic_embed::magic_embed;
33//! use pure_magic::MagicDb;
34//!
35//! #[magic_embed(include=["../../magic-db/src/magdir"], exclude=["../../magic-db/src/magdir/der"])]
36//! struct MyMagicDb;
37//!
38//! fn main() -> Result<(), pure_magic::Error> {
39//!     let db = MyMagicDb::open()?;
40//!     // Use the database as you would with pure_magic
41//!     Ok(())
42//! }
43//! ```
44//!
45//! ## Attributes
46//!
47//! | Attribute | Type       | Required | Description |
48//! |-----------|------------|----------|-------------|
49//! | `include` | String[]   | Yes      | Paths to include in the database (files or directories) |
50//! | `exclude` | String[]   | No       | Paths to exclude from the database |
51//!
52//! ## Complete Example
53//!
54//! ```rust
55//! use magic_embed::magic_embed;
56//! use pure_magic::MagicDb;
57//! use std::fs::File;
58//! use std::env::current_exe;
59//!
60//! #[magic_embed(
61//!     include=["../../magic-db/src/magdir"],
62//!     exclude=["../../magic-db/src/magdir/der"]
63//! )]
64//! struct AppMagicDb;
65//!
66//! fn main() -> Result<(), Box<dyn std::error::Error>> {
67//!     // Open the embedded database
68//!     let db = AppMagicDb::open()?;
69//!
70//!     // Use it to detect file types
71//!     let mut file = File::open(current_exe()?)?;
72//!     let magic = db.first_magic(&mut file, None)?;
73//!
74//!     println!("Detected: {} (MIME: {})", magic.message(), magic.mime_type());
75//!     Ok(())
76//! }
77//! ```
78//!
79//! ## Build Configuration
80//!
81//! To ensure your database is rebuilt when rule files change, create a `build.rs` file:
82//!
83//! ```rust,ignore
84//! // build.rs
85//! fn main() {
86//!     println!("cargo:rerun-if-changed=magic/rules/");
87//! }
88//! ```
89//!
90//! Replace `magic/rules/` with the path to your actual rule files.
91//!
92//! ## How It Works
93//!
94//! 1. **Compile Time**: The macro compiles all specified magic rule files into a binary database
95//! 2. **Embedding**: The compiled database is embedded in your binary as a byte array
96//! 3. **Runtime**: The `open()` method deserializes the embedded database
97//!
98//! ## Performance Considerations
99//!
100//! - The database is compiled only when source files change
101//! - Embedded databases increase binary size but eliminate runtime file I/O
102//! - Database deserialization happens once at runtime when `open()` is called
103//!
104//! ## License
105//!
106//! This project is licensed under the **GPL-3.0 License**.
107
108use std::{
109    collections::{HashMap, HashSet},
110    path::PathBuf,
111};
112
113use proc_macro::TokenStream;
114use pure_magic::{MagicDb, MagicSource};
115use quote::quote;
116use syn::{
117    Expr, ExprArray, ItemStruct, Meta, MetaNameValue, Token, parse::Parser, punctuated::Punctuated,
118};
119
120/// Parser for procedural macro attributes
121///
122/// Processes comma-separated key-value attributes for the `magic_embed` macro.
123struct MetaParser {
124    attr: proc_macro2::TokenStream,
125    metas: HashMap<String, Meta>,
126}
127
128impl MetaParser {
129    /// Creates a new [`MetaParser`] from a token stream
130    ///
131    /// # Arguments
132    ///
133    /// * `attr` - [`proc_macro2::TokenStream`] - Attribute token stream to parse
134    ///
135    /// # Returns
136    ///
137    /// * `Result<Self, syn::Error>` - Parsed metadata or syntax error
138    fn parse_meta(attr: proc_macro2::TokenStream) -> Result<Self, syn::Error> {
139        let mut out = HashMap::new();
140
141        // parser for a comma-separated list of Meta entries
142        let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
143
144        let metas = match parser.parse2(attr.clone()) {
145            Ok(m) => m,
146            Err(e) => return Err(syn::Error::new_spanned(attr, e.to_string())),
147        };
148
149        for meta in metas {
150            out.insert(
151                meta.path()
152                    .get_ident()
153                    .ok_or(syn::Error::new_spanned(
154                        meta.clone(),
155                        "failed to process meta",
156                    ))?
157                    .to_string(),
158                meta,
159            );
160        }
161        Ok(Self {
162            attr: attr.clone(),
163            metas: out,
164        })
165    }
166
167    /// Retrieves a key-value attribute by name
168    ///
169    /// # Arguments
170    ///
171    /// * `key` - `&str` - Name of the attribute to retrieve
172    ///
173    /// # Returns
174    ///
175    /// * `Result<Option<&MetaNameValue>, syn::Error>` - Found attribute or error
176    fn get_key_value(&self, key: &str) -> Result<Option<&MetaNameValue>, syn::Error> {
177        if let Some(meta) = self.metas.get(key) {
178            match meta {
179                Meta::NameValue(m) => return Ok(Some(m)),
180                _ => {
181                    return Err(syn::Error::new_spanned(
182                        &self.attr,
183                        format!("expecting a key value attribute: {key}"),
184                    ));
185                }
186            }
187        }
188        Ok(None)
189    }
190}
191
192/// Converts a [`MetaNameValue`] array expression to a vector of strings
193///
194/// # Arguments
195///
196/// * `nv` - Name-value attribute containing array
197///
198/// # Returns
199///
200/// * `Result<Vec<(proc_macro2::Span, String)>, syn::Error>` - Vector of (span, string) tuples
201fn meta_name_value_to_string_vec(
202    nv: &MetaNameValue,
203) -> Result<Vec<(proc_macro2::Span, String)>, syn::Error> {
204    if let Expr::Array(ExprArray { elems, .. }) = &nv.value {
205        Ok(elems
206            .into_iter()
207            .filter_map(|e| match e {
208                Expr::Lit(syn::ExprLit {
209                    lit: syn::Lit::Str(lit_str),
210                    ..
211                }) => Some((lit_str.span(), lit_str.value())),
212                _ => None,
213            })
214            .collect::<Vec<_>>())
215    } else {
216        Err(syn::Error::new_spanned(
217            &nv.value,
218            "expected an array literal like [\"foo\", \"bar\"]",
219        ))
220    }
221}
222
223fn impl_magic_embed(attr: TokenStream, item: TokenStream) -> Result<TokenStream, syn::Error> {
224    // Parse the input function
225    let input_struct: ItemStruct = syn::parse2(item.into())?;
226    let struct_name = &input_struct.ident;
227    let cs = proc_macro::Span::call_site();
228
229    let Some(source_file) = cs.local_file() else {
230        return Ok(quote! {}.into());
231    };
232
233    let source_dir = source_file.parent().unwrap();
234
235    // convert to proc-macro2 TokenStream for syn helpers
236    let ts2: proc_macro2::TokenStream = attr.into();
237
238    let struct_vis = input_struct.vis;
239
240    let metas = MetaParser::parse_meta(ts2)?;
241
242    let exclude = if let Some(exclude) = metas.get_key_value("exclude")? {
243        meta_name_value_to_string_vec(exclude)?
244            .into_iter()
245            .map(|(s, p)| (s, source_dir.join(p)))
246            .collect()
247    } else {
248        vec![]
249    };
250
251    let include_nv = metas.get_key_value("include")?.ok_or(syn::Error::new(
252        struct_name.span(),
253        "expected  a list of files or directory to include: \"include\" = [\"magdir\"]",
254    ))?;
255
256    let include: Vec<(proc_macro2::Span, PathBuf)> = meta_name_value_to_string_vec(include_nv)?
257        .into_iter()
258        .map(|(s, p)| (s, source_dir.join(p)))
259        .collect();
260
261    // we don't walk rules recursively
262    let mut wo = fs_walk::WalkOptions::new();
263    wo.files().max_depth(0).sort(true);
264
265    let mut db = MagicDb::new();
266
267    let exclude_set: HashSet<PathBuf> = exclude.into_iter().map(|(_, p)| p).collect();
268
269    macro_rules! load_file {
270        ($span: expr, $path: expr) => {
271            let f = MagicSource::open($path).map_err(|e| {
272                syn::Error::new(
273                    $span.clone(),
274                    format!(
275                        "failed to parse magic file={}: {e}",
276                        $path.to_string_lossy()
277                    ),
278                )
279            })?;
280            db.load(f).map_err(|e| {
281                syn::Error::new(
282                    $span.clone(),
283                    format!("database failed to load magic file: {e}"),
284                )
285            })?;
286        };
287    }
288
289    for (s, p) in include.iter() {
290        if p.is_dir() {
291            for rule_file in wo.walk(p) {
292                let rule_file = rule_file
293                    .map_err(|e| syn::Error::new(*s, format!("failed to list rule file: {e}")))?;
294
295                if exclude_set.contains(&rule_file) {
296                    continue;
297                }
298
299                load_file!(s, &rule_file);
300            }
301        } else if p.is_file() {
302            load_file!(s, p);
303        }
304    }
305
306    // Serialize and save database
307    let mut ser = vec![];
308    db.serialize(&mut ser).map_err(|e| {
309        syn::Error::new(
310            struct_name.span(),
311            format!("failed to serialize database: {e}"),
312        )
313    })?;
314
315    // Generate the output: the original function + a print statement
316    let output = quote! {
317        /// This structure exposes an embedded compiled magic database.
318        #struct_vis struct #struct_name;
319
320        impl #struct_name {
321            const DB: &[u8] = &[ #( #ser ),* ];
322
323            /// Opens the embedded magic database and returns a [`pure_magic::MagicDb`]
324            #struct_vis fn open() -> Result<pure_magic::MagicDb, pure_magic::Error> {
325                pure_magic::MagicDb::deserialize(&mut Self::DB.as_ref())
326            }
327        }
328    };
329
330    Ok(output.into())
331}
332
333/// Procedural macro to embed a compiled [`pure_magic::MagicDb`]
334///
335/// This attribute macro compiles magic rule files at program
336/// compile time and embeds them in the binary. The database
337/// will not be automatically rebuilt when rule files change
338/// (c.f. see Note section below).
339///
340/// # Attributes
341///
342/// * `include` - Array of paths to include in the database (required)
343/// * `exclude` - Array of paths to exclude from the database (optional)
344///
345/// # Examples
346///
347/// ```
348/// use magic_embed::magic_embed;
349/// use pure_magic::MagicDb;
350///
351/// #[magic_embed(include=["../../magic-db/src/magdir"], exclude=["../../magic-db/src/magdir/der"])]
352/// struct EmbeddedMagicDb;
353///
354/// let db: MagicDb = EmbeddedMagicDb::open().unwrap();
355/// ```
356///
357/// # Errors
358///
359/// This macro will emit a compile-time error if:
360/// - The `include` attribute is missing
361/// - Specified paths don't exist
362/// - Database compilation fails
363/// - File I/O operations fail
364///
365/// # Note
366///
367/// If you want Cargo to track changes to your rule files (e.g., `magdir/`),
368/// you **must** create a build script in your project. The proc-macro cannot
369/// track these files directly because it embeds only the compiled database,
370/// not the rule files themselves. Add a `build.rs` file like this:
371///
372/// ```ignore
373/// // build.rs
374/// fn main() {
375///     println!("cargo::rerun-if-changed=magdir/");
376/// }
377/// ```
378///
379/// Replace `magdir/` with the path to your rule files.
380#[proc_macro_attribute]
381pub fn magic_embed(attr: TokenStream, item: TokenStream) -> TokenStream {
382    match impl_magic_embed(attr, item) {
383        Ok(ts) => ts,
384        Err(e) => e.to_compile_error().into(),
385    }
386}