Crate xdg_mime

source ·
Expand description

xdg_mime allows to look up the MIME type associated to a file name or to the contents of a file, using the Freedesktop.org Shared MIME database specification.

Alongside the MIME type, the shared MIME database contains other ancillary information, like the icon associated to the MIME type; the aliases for a given MIME type; and the various sub-classes of a MIME type.

§Loading the Shared MIME database

The SharedMimeInfo type will automatically load all the instances of shared MIME databases available in the following directories, in this specified order:

  • $XDG_DATA_HOME/mime
    • if XDG_DATA_HOME is unset, this corresponds to $HOME/.local/share/mime
  • $XDG_DATA_DIRS/mime
    • if XDG_DATA_DIRS is unset, this corresponds to /usr/local/share/mime and /usr/share/mime

For more information on the XDG_DATA_HOME and XDG_DATA_DIRS environment variables, see the XDG base directory specification.

The MIME data in each directory will be coalesced into a single database.

§Retrieving the MIME type of a file

If you want to know the MIME type of a file, you typically have two options at your disposal:

The former step does not come with performance penalties, or even requires the file to exist in the first place, but it may return a list of potential matches; the latter can be an arbitrarily expensive operation to perform, but its result is going to be certain. It is recommended to always guess the MIME type from the file name first, and only use content sniffing lazily and, possibly, asynchronously.

§Guessing the MIME type

If you have access to a file name or its contents, it’s possible to use the guess_mime_type method to create a GuessBuilder instance, and populate it with the file name, its contents, or the full path to the file; then, call the guess method to guess the MIME type depending on the available information.

Structs§