pub fn load_magic_directory(
dir_path: &Path,
) -> Result<Vec<MagicRule>, ParseError>Expand description
Loads and parses all magic files from a directory, merging them into a single rule set.
This function reads all regular files in the specified directory, parses each as a magic file,
and combines the resulting rules into a single Vec<MagicRule>. Files are processed in
alphabetical order by filename to ensure deterministic results.
§Error Handling Strategy
This function distinguishes between critical and non-critical errors:
-
Critical errors (I/O failures, directory access issues, encoding problems): These cause immediate failure and return a
ParseError. The function stops processing and propagates the error to the caller. -
Non-critical errors (individual file parse failures): These are logged to stderr with a warning message and the file is skipped. Processing continues with remaining files.
§Behavior
- Subdirectories are skipped (not recursively processed)
- Symbolic links are skipped
- Empty directories return an empty rules vector
- Files are processed in alphabetical order by filename
- All successfully parsed rules are merged in order
§Examples
Loading a directory of magic files:
use libmagic_rs::parser::load_magic_directory;
use std::path::Path;
let rules = load_magic_directory(Path::new("/usr/share/file/magic.d"))?;
println!("Loaded {} rules from directory", rules.len());Creating a Magdir-style directory structure:
use libmagic_rs::parser::load_magic_directory;
use std::path::Path;
// Directory structure:
// magic.d/
// ├── 01-elf
// ├── 02-archive
// └── 03-text
let rules = load_magic_directory(Path::new("./magic.d"))?;
// Rules from all three files are merged in alphabetical order§Errors
Returns ParseError if:
- The directory does not exist or cannot be accessed
- Directory entries cannot be read
- A file cannot be read due to I/O errors
- A file contains invalid UTF-8 encoding
§Panics
This function does not panic under normal operation.