30 releases (15 breaking)

0.16.2 Oct 5, 2023
0.16.0 Sep 30, 2023
0.13.0 Aug 18, 2022
0.13.0-alpha.3 Nov 7, 2021
0.2.0 Nov 20, 2014

#72 in Filesystem

Download history 1358/week @ 2023-12-23 2212/week @ 2023-12-30 2255/week @ 2024-01-06 3560/week @ 2024-01-13 3399/week @ 2024-01-20 2053/week @ 2024-01-27 1652/week @ 2024-02-03 2447/week @ 2024-02-10 2776/week @ 2024-02-17 3274/week @ 2024-02-24 1967/week @ 2024-03-02 3393/week @ 2024-03-09 2994/week @ 2024-03-16 3059/week @ 2024-03-23 3152/week @ 2024-03-30 2935/week @ 2024-04-06

12,531 downloads per month
Used in 8 crates (7 directly)

MIT/Apache

63KB
670 lines

High-level bindings for libmagic

About

This crate provides bindings for the libmagic C library, which recognizes the type of data contained in a file (or buffer) and can give you a textual description, a MIME type and the usual file extensions.

Usage

// only for Rust Edition 2018, see https://doc.rust-lang.org/edition-guide/rust-2021/prelude.html
use std::convert::TryInto;

fn file_example() -> Result<(), Box<dyn std::error::Error>> {
    // Open a new configuration with flags
    let cookie = magic::Cookie::open(magic::cookie::Flags::ERROR)?;

    // Load a specific database
    // (so exact test text assertion below works regardless of the system's default database version)
    let database = ["data/tests/db-images-png"].try_into()?;
    // You can instead load the default database
    //let database = Default::default();

    let cookie = cookie.load(&database)?;

    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(())
}

Check the crate rustdoc for more details.

Repository

The project's repository is github.com/robo9k/rust-magic

It contains the latest in-development version of the magic crate (might not be published to crates.io yet),
more examples how to use the magic crate
as well as issues and discussions.

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 (via the magic-sys crate) 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.

Dependencies

~0.4–1MB
~22K SLoC