pub fn load_magic_file(path: &Path) -> Result<Vec<MagicRule>, ParseError>Expand description
Loads magic rules from a file or directory, automatically detecting the format.
This is the unified entry point for loading magic rules from the filesystem. It automatically detects whether the path points to a text magic file, a directory containing magic files, or a binary compiled magic file, and dispatches to the appropriate handler.
§Format Detection and Handling
The function uses detect_format() to determine the file type and handles each
format as follows:
- Text format: Reads the file contents and parses using
super::parse_text_magic_file() - Directory format: Loads all magic files from the directory using
load_magic_directory() - Binary format: Returns an error with guidance to use the
--use-builtinoption
§Arguments
path- Path to a magic file or directory. Can be absolute or relative.
§Returns
Returns Ok(Vec<MagicRule>) containing all successfully parsed magic rules. For
directories, rules from all files are merged in alphabetical order by filename.
§Errors
This function returns a ParseError in the following cases:
- File not found: The specified path does not exist
- Unsupported format: The file is a binary compiled magic file (
.mgc) - Parse errors: The magic file contains syntax errors or invalid rules
- I/O errors: File system errors during reading (permissions, disk errors, etc.)
§Examples
§Loading a text magic file
use libmagic_rs::parser::load_magic_file;
use std::path::Path;
let rules = load_magic_file(Path::new("/usr/share/misc/magic"))?;
println!("Loaded {} magic rules", rules.len());§Loading a directory of magic files
use libmagic_rs::parser::load_magic_file;
use std::path::Path;
let rules = load_magic_file(Path::new("/usr/share/misc/magic.d"))?;
println!("Loaded {} rules from directory", rules.len());§Handling binary format errors
use libmagic_rs::parser::load_magic_file;
use std::path::Path;
match load_magic_file(Path::new("/usr/share/misc/magic.mgc")) {
Ok(rules) => println!("Loaded {} rules", rules.len()),
Err(e) => {
eprintln!("Error loading magic file: {}", e);
eprintln!("Hint: Use --use-builtin for binary files");
}
}§Security
This function delegates to super::parse_text_magic_file() or load_magic_directory()
based on format detection. Security considerations are handled by those functions:
- Rule hierarchy depth is bounded during parsing
- Invalid syntax is rejected with descriptive errors
- Binary
.mgcfiles are rejected (not parsed)
Note: File size limits and memory exhaustion protection are not currently implemented. Large magic files will be loaded entirely into memory.
§See Also
detect_format()- Format detection logicsuper::parse_text_magic_file()- Text file parserload_magic_directory()- Directory loader