Skip to main content

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    spanned::Spanned,
119};
120
121/// Parser for procedural macro attributes
122///
123/// Processes comma-separated key-value attributes for the `magic_embed` macro.
124struct MetaParser {
125    attr: proc_macro2::TokenStream,
126    metas: HashMap<String, Meta>,
127}
128
129impl MetaParser {
130    /// Creates a new [`MetaParser`] from a token stream
131    ///
132    /// # Arguments
133    ///
134    /// * `attr` - [`proc_macro2::TokenStream`] - Attribute token stream to parse
135    ///
136    /// # Returns
137    ///
138    /// * `Result<Self, syn::Error>` - Parsed metadata or syntax error
139    fn parse_meta(attr: proc_macro2::TokenStream) -> Result<Self, syn::Error> {
140        let mut out = HashMap::new();
141
142        // parser for a comma-separated list of Meta entries
143        let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
144
145        let metas = match parser.parse2(attr.clone()) {
146            Ok(m) => m,
147            Err(e) => return Err(syn::Error::new_spanned(attr, e.to_string())),
148        };
149
150        for meta in metas {
151            out.insert(
152                meta.path()
153                    .get_ident()
154                    .ok_or(syn::Error::new_spanned(
155                        meta.clone(),
156                        "failed to process meta",
157                    ))?
158                    .to_string(),
159                meta,
160            );
161        }
162        Ok(Self {
163            attr: attr.clone(),
164            metas: out,
165        })
166    }
167
168    /// Retrieves a key-value attribute by name
169    ///
170    /// # Arguments
171    ///
172    /// * `key` - `&str` - Name of the attribute to retrieve
173    ///
174    /// # Returns
175    ///
176    /// * `Result<Option<&MetaNameValue>, syn::Error>` - Found attribute or error
177    fn get_key_value(&self, key: &str) -> Result<Option<&MetaNameValue>, syn::Error> {
178        if let Some(meta) = self.metas.get(key) {
179            match meta {
180                Meta::NameValue(m) => return Ok(Some(m)),
181                _ => {
182                    return Err(syn::Error::new_spanned(
183                        &self.attr,
184                        format!("expecting a key value attribute: {key}"),
185                    ));
186                }
187            }
188        }
189        Ok(None)
190    }
191}
192
193/// Converts a [`MetaNameValue`] array expression to a vector of strings
194///
195/// # Arguments
196///
197/// * `nv` - Name-value attribute containing array
198///
199/// # Returns
200///
201/// * `Result<Vec<(proc_macro2::Span, String)>, syn::Error>` - Vector of (span, string) tuples
202fn meta_name_value_to_string_vec(
203    nv: &MetaNameValue,
204) -> Result<Vec<(proc_macro2::Span, String)>, syn::Error> {
205    if let Expr::Array(ExprArray { elems, .. }) = &nv.value {
206        Ok(elems
207            .into_iter()
208            .filter_map(|e| match e {
209                Expr::Lit(syn::ExprLit {
210                    lit: syn::Lit::Str(lit_str),
211                    ..
212                }) => Some((lit_str.span(), lit_str.value())),
213                _ => None,
214            })
215            .collect::<Vec<_>>())
216    } else {
217        Err(syn::Error::new_spanned(
218            &nv.value,
219            "expected an array literal like [\"foo\", \"bar\"]",
220        ))
221    }
222}
223
224fn impl_magic_embed(attr: TokenStream, item: TokenStream) -> Result<TokenStream, syn::Error> {
225    // Parse the input function
226    let input_struct: ItemStruct = syn::parse2(item.into())?;
227    let struct_name = &input_struct.ident;
228    let cs = proc_macro::Span::call_site();
229
230    let Some(source_file) = cs.local_file() else {
231        return Ok(quote! {}.into());
232    };
233
234    let source_dir = source_file.parent().unwrap();
235
236    // convert to proc-macro2 TokenStream for syn helpers
237    let ts2: proc_macro2::TokenStream = attr.into();
238
239    let struct_vis = input_struct.vis;
240
241    let metas = MetaParser::parse_meta(ts2)?;
242
243    let exclude = if let Some(exclude) = metas.get_key_value("exclude")? {
244        meta_name_value_to_string_vec(exclude)?
245            .into_iter()
246            .map(|(s, p)| (s, source_dir.join(p)))
247            .collect()
248    } else {
249        vec![]
250    };
251
252    let include_nv = metas.get_key_value("include")?.ok_or(syn::Error::new(
253        struct_name.span(),
254        "expected  a list of files or directory to include: \"include\" = [\"magdir\"]",
255    ))?;
256
257    let include: Vec<(proc_macro2::Span, PathBuf)> = meta_name_value_to_string_vec(include_nv)?
258        .into_iter()
259        .map(|(s, p)| (s, source_dir.join(p)))
260        .collect();
261
262    // we don't walk rules recursively
263    let mut wo = fs_walk::WalkOptions::new();
264    wo.files().max_depth(0).sort(true);
265
266    let mut db = MagicDb::new();
267
268    let exclude_set: HashSet<PathBuf> = exclude.into_iter().map(|(_, p)| p).collect();
269
270    macro_rules! load_file {
271        ($span: expr, $path: expr) => {
272            MagicSource::open($path).map_err(|e| {
273                syn::Error::new(
274                    $span.clone(),
275                    format!(
276                        "failed to parse magic file={}: {e}",
277                        $path.to_string_lossy()
278                    ),
279                )
280            })?
281        };
282    }
283
284    let mut rules = vec![];
285    for (s, p) in include.iter() {
286        if p.is_dir() {
287            for rule_file in wo.walk(p) {
288                let rule_file = rule_file
289                    .map_err(|e| syn::Error::new(*s, format!("failed to list rule file: {e}")))?;
290
291                if exclude_set.contains(&rule_file) {
292                    continue;
293                }
294
295                rules.push(load_file!(s, &rule_file));
296            }
297        } else if p.is_file() {
298            rules.push(load_file!(s, p));
299        }
300    }
301
302    db.load_bulk(rules.into_iter());
303    db.verify().map_err(|e| {
304        syn::Error::new(include_nv.span(), format!("inconsistent database: {e}"))
305    })?;
306
307    // Serialize and save database
308    let mut ser = vec![];
309    db.serialize(&mut ser).map_err(|e| {
310        syn::Error::new(
311            struct_name.span(),
312            format!("failed to serialize database: {e}"),
313        )
314    })?;
315
316    // Generate the output: the original function + a print statement
317    let output = quote! {
318        /// This structure exposes an embedded compiled magic database.
319        #struct_vis struct #struct_name;
320
321        impl #struct_name {
322            const DB: &[u8] = &[ #( #ser ),* ];
323
324            /// Opens the embedded magic database and returns a [`pure_magic::MagicDb`]
325            #struct_vis fn open() -> Result<pure_magic::MagicDb, pure_magic::Error> {
326                pure_magic::MagicDb::deserialize(&mut Self::DB.as_ref())
327            }
328        }
329    };
330
331    Ok(output.into())
332}
333
334/// Procedural macro to embed a compiled [`pure_magic::MagicDb`]
335///
336/// This attribute macro compiles magic rule files at program
337/// compile time and embeds them in the binary. The database
338/// will not be automatically rebuilt when rule files change
339/// (c.f. see Note section below).
340///
341/// # Attributes
342///
343/// * `include` - Array of paths to include in the database (required)
344/// * `exclude` - Array of paths to exclude from the database (optional)
345///
346/// # Examples
347///
348/// ```
349/// use magic_embed::magic_embed;
350/// use pure_magic::MagicDb;
351///
352/// #[magic_embed(include=["../../magic-db/src/magdir"], exclude=["../../magic-db/src/magdir/der"])]
353/// struct EmbeddedMagicDb;
354///
355/// let db: MagicDb = EmbeddedMagicDb::open().unwrap();
356/// ```
357///
358/// # Errors
359///
360/// This macro will emit a compile-time error if:
361/// - The `include` attribute is missing
362/// - Specified paths don't exist
363/// - Database compilation fails
364/// - File I/O operations fail
365///
366/// # Note
367///
368/// If you want Cargo to track changes to your rule files (e.g., `magdir/`),
369/// you **must** create a build script in your project. The proc-macro cannot
370/// track these files directly because it embeds only the compiled database,
371/// not the rule files themselves. Add a `build.rs` file like this:
372///
373/// ```ignore
374/// // build.rs
375/// fn main() {
376///     println!("cargo::rerun-if-changed=magdir/");
377/// }
378/// ```
379///
380/// Replace `magdir/` with the path to your rule files.
381#[proc_macro_attribute]
382pub fn magic_embed(attr: TokenStream, item: TokenStream) -> TokenStream {
383    match impl_magic_embed(attr, item) {
384        Ok(ts) => ts,
385        Err(e) => e.to_compile_error().into(),
386    }
387}