Building simplicidade.org: notes, projects, and occasional rants

LibMagic regexp error 17

Got the following error using File::LibMagic (uses libmagic):

error calling magic_file: line 163: regex error 17, (illegal byte sequence)

This is usually caused by two separate issues:

  • first, you are probably using an old version of libmagic. Version 5.17 had problems for me, but a brew upgrade libmagic updated to 5.25;
  • second, libmagic is very sensible to ENV’s LC_CTYPE and LC_LANG. Set both temporarily to C.

One or both of this two actions will need to be used to solve the issue.

More information on this ticket: https://trac.macports.org/ticket/38771.

I wrote a small utility function that takes care of all the details of figuring out the mime_type of a file:

sub mime_type {
  my ($path, $default) = @_;

  return $default unless eval { require File::LibMagic };
  $path = $path->stringify if blessed($path); ## Path::Tiny support

  ## We need the ENV's to avoid https://trac.macports.org/ticket/38771
  local $ENV{LC_CTYPE} = 'C';
  local $ENV{LANG}     = 'C';
  state $fm = File::LibMagic->new;
  my $info = $fm->info_from_filename($path);

  return $info->{mime_type} if $info and $info->{mime_type};
  return $default;
}