A binding to the libmagic library for magic numbers detection using dart:ffi provinding a simple and easy way to identify file types from dart code.
Prerequisites
To fully use this package, you need to have the libmagic
library installed on your system. You can install it using the following commands:
# For Ubuntu/Debian
sudo apt-get install libmagic-dev
# For Fedora
sudo dnf install file-devel
# For Alpine
apk add file-dev
# For MacOS
brew install libmagic
Usage
Add the library to your project by adding the following to your pubspec.yaml
file:
dependencies:
libmagic: ^5.45.0
Then run pub get
to download the library.
import 'dart:ffi';
import 'dart:io';
import 'package:libmagic/libmagic.dart';
void main() {
late final Magic libmagic;
late final magic_t magic;
/// Load the libmagic library from the system
DynamicLibrary? lib;
try {
lib = switch (Platform.operatingSystem) {
'linux' => DynamicLibrary.open('libmagic.so'),
'macos' =>
DynamicLibrary.open('libmagic.dylib'),
'windows' => DynamicLibrary.open('magic1.dll'),
_ => throw Exception('Unsupported platform')
};
} catch (e) {
print('Failed to load libmagic: $e');
}
if (lib == null) {
return;
}
libmagic = Magic(lib);
/// Open the magic database
magic = libmagic.magic_open(MAGIC_NONE);
/// Load the magic database
libmagic.magic_load(magic, nullptr);
/// Get the version of the magic database
final version = libmagic.magic_version();
/// Set the flags for the magic database
final flags = libmagic.magic_setflags(magic, MAGIC_MIME_TYPE);
/// Get the flags for the magic database
final getFlags = libmagic.magic_getflags(magic);
/// Close the magic database
libmagic.magic_close(magic);
}
Update / Generate the bindings
Updating the binding require both the prerequisites and the following steps:
dart pub run ffigen
Versionning scheme
The versionning scheme used in this package is the same as the one used in the libmagic library. The version number is composed of three parts: the major version, the minor version, and the patch version. The version number is in the format x.y.z
where x
is the major version, y
is the minor version, and z
is the patch version.
A +v
is added to the version number to indicate that the version is a custom version and not the original version of the library.
Credit
Libmagic authors
- Måns Rullgård Initial libmagic implementation, and configuration.
- Christos Zoulas API cleanup, error code and allocation handling.