27 releases (14 breaking)

new 0.15.1 Sep 28, 2023
0.14.0 Sep 16, 2023
0.13.0 Aug 18, 2022
0.13.0-alpha.3 Nov 7, 2021
0.2.0 Nov 20, 2014

#89 in Filesystem

Download history 3170/week @ 2023-06-09 2889/week @ 2023-06-16 3163/week @ 2023-06-23 3851/week @ 2023-06-30 4478/week @ 2023-07-07 4193/week @ 2023-07-14 4690/week @ 2023-07-21 6097/week @ 2023-07-28 5059/week @ 2023-08-04 6156/week @ 2023-08-11 5430/week @ 2023-08-18 4968/week @ 2023-08-25 4519/week @ 2023-09-01 4433/week @ 2023-09-08 3041/week @ 2023-09-15 5251/week @ 2023-09-22

18,086 downloads per month
Used in 4 crates

MIT/Apache

33KB
482 lines

rust-magic build status Documentation REUSE status CII Best Practices OpenSSF Scorecard codecov

libmagic bindings for Rust.

Usage

This magic crate is published on the crates.io Rust package registry.

Use cargo add to specify dependencies:

$ cargo add magic

You might be familiar with libmagic's CLI; file:

$ file data/tests/rust-logo-128x128-blk.png
data/tests/rust-logo-128x128-blk.png: PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced

You can implement something similar in Rust with the magic crate (see examples/file-ish.rs):

fn file_example() -> Result<(), magic::MagicError> {
    // Open a new configuration with flags
    let cookie = magic::Cookie::open(magic::CookieFlags::ERROR)?;

    // Load a specific database (so exact text assertion below works regardless of the system's default database)
    cookie.load(&["data/tests/db-images-png"])?;

    let file = "data/tests/rust-logo-128x128-blk.png";

    // Analyze the file
    assert_eq!(cookie.file(file)?, "PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced");

    Ok(())
}
$ cargo run --example file-ish -- data/tests/rust-logo-128x128-blk.png
PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced

Read the magic rustdoc for further examples and info.

MSRV

The Minimum Supported Rust Version (MSRV) is Rust 1.56 or higher.

This version might be changed in the future, but it will be done with a crate version bump.

Requirements

By default, compiling the magic crate will search your system library paths for a shared library version of libmagic to link against. For this to work, you need to install the development version of libmagic in a standard location:

$ # On Debian based Linux systems:
$ sudo apt-get install libmagic1 libmagic-dev

$ # On MacOs:
$ brew install libmagic

$ # On Windows:
$ cargo install cargo-vcpkg
$ cargo vcpkg build

If you're cross-compiling, or need more control over which library is selected, see how to build magic-sys.

License

This project is licensed under either of

at your option.

For further details, see LICENSE.md.

Security

See SECURITY.md.

Contribution

See CONTRIBUTING.md.

Dependencies

~0.5–1MB
~24K SLoC