class FileMagic

Constants

DEFAULT_MAGIC
FLAGS_BY_INT

Map flag values to their names (Integer => :name).

FLAGS_BY_SYM

Map flag names to their values (:name => Integer).

MAGIC_APPLE
MAGIC_CHECK
MAGIC_COMPRESS
MAGIC_COMPRESS_TRANSP
MAGIC_CONTINUE
MAGIC_DEBUG
MAGIC_DEVICES
MAGIC_ERROR
MAGIC_EXTENSION
MAGIC_MIME
MAGIC_MIME_ENCODING
MAGIC_MIME_TYPE
MAGIC_NODESC
MAGIC_NONE
MAGIC_NO_CHECK_APPTYPE
MAGIC_NO_CHECK_ASCII
MAGIC_NO_CHECK_BUILTIN

defined in b5be901 (2010-01-28, 5.05), but broken until 38e0136 (2013-08-15, 5.15)

MAGIC_NO_CHECK_CDF
MAGIC_NO_CHECK_COMPRESS
MAGIC_NO_CHECK_ELF
MAGIC_NO_CHECK_ENCODING
MAGIC_NO_CHECK_FORTRAN
MAGIC_NO_CHECK_SOFT
MAGIC_NO_CHECK_TAR
MAGIC_NO_CHECK_TEXT
MAGIC_NO_CHECK_TOKENS
MAGIC_NO_CHECK_TROFF
MAGIC_PRESERVE_ATIME
MAGIC_RAW
MAGIC_VERSION
SIMPLE_RE

Extract “simple” MIME type.

VERSION

Attributes

simplified[W]

Public Class Methods

clear!() click to toggle source

Clear our instance cache.

# File lib/filemagic.rb, line 84
def clear!
  @fm.each_value(&:close).clear
end
flags(p1) click to toggle source

Converts flags to integer

static VALUE
rb_magic_flags(VALUE klass, VALUE flags) {
  VALUE map = rb_const_get(cFileMagic, rb_intern("FLAGS_BY_SYM")), f, g;
  int i = MAGIC_NONE, j;

  if (TYPE(flags) != T_ARRAY) {
    rb_raise(rb_eTypeError,
      "wrong argument type %s (expected Array)",
      rb_obj_classname(flags));
  }

  for (j = 0; j < RARRAY_LEN(flags); j++) {
    f = rb_ary_entry(flags, j);

    switch (TYPE(f)) {
      case T_SYMBOL:
        if (RTEST(g = rb_hash_aref(map, f))) {
          f = g;
          /* fall through */
        }
        else {
          f = rb_funcall(f, rb_intern("inspect"), 0);
          rb_raise(rb_eArgError, "%s: %s",
            NIL_P(g) ? "no such flag" : "flag not available",
            StringValueCStr(f));

          break;
        }
      case T_FIXNUM:
        i |= NUM2INT(f);
        break;
      default:
        rb_raise(rb_eTypeError,
          "wrong argument type %s (expected Fixnum or Symbol)",
          rb_obj_classname(f));
    }
  }

  return INT2FIX(i);
}
fm(*flags) click to toggle source

Provide a “magic singleton”.

# File lib/filemagic.rb, line 73
def fm(*flags)
  options = flags.last.is_a?(Hash) ? flags.pop : {}

  if fm = @fm[key = [flags = flags(flags), options]]
    return fm unless fm.closed?
  end

  @fm[key] = new(flags, options)
end
library_version() click to toggle source

Returns the magic version

static VALUE
rb_magic_version(VALUE klass) {
  char version[8] = "0";
#ifdef HAVE_MAGIC_VERSION
  RB_MAGIC_SET_VERSION(magic_version() / 100, magic_version() % 100)
#endif
  return rb_str_new2(version);
}
magic_version(default = MAGIC_VERSION) click to toggle source
# File lib/filemagic.rb, line 109
def magic_version(default = MAGIC_VERSION)
  default != '0' ? default :
    user_magic_version ||
    auto_magic_version ||
    [default, 'unknown']
end
mime(*flags, &block) click to toggle source

Just a short-cut to open with the mime flag set.

# File lib/filemagic.rb, line 105
def mime(*flags, &block)
  open(:mime, *flags, &block)
end
new(*args) click to toggle source

::new

static VALUE
rb_magic_new(int argc, VALUE *argv, VALUE klass) {
  VALUE obj, args[2];
  magic_t ms;

  if (rb_block_given_p()) {
    rb_warn(
      "FileMagic.new() does not take a block; use FileMagic.open() instead");
  }

  if (argc > 0 && TYPE(args[1] = argv[argc - 1]) == T_HASH) {
    argc--;
  }
  else {
    args[1] = rb_hash_new();
  }

  args[0] = rb_magic_flags(klass, rb_ary_new4(argc, argv));

  if ((ms = magic_open(NUM2INT(args[0]))) == NULL) {
    rb_raise(rb_FileMagicError,
      "failed to initialize magic cookie (%d)", errno || -1);
  }

  if (magic_load(ms, NULL) == -1) {
    rb_raise(rb_FileMagicError,
      "failed to load database: %s", magic_error(ms));
  }

  obj = Data_Wrap_Struct(klass, 0, rb_magic_free, ms);
  rb_obj_call_init(obj, 2, args);

  return obj;
}
open(*flags) { |fm| ... } click to toggle source

Just like new, but takes an optional block, in which case close is called at the end and the value of the block is returned.

# File lib/filemagic.rb, line 90
def open(*flags)
  fm = new(*flags)

  if block_given?
    begin
      yield fm
    ensure
      fm.close
    end
  else
    fm
  end
end
path() click to toggle source

Returns the magic path

static VALUE
rb_magic_getpath(VALUE klass) {
  const char *path = magic_getpath(NULL, 0);
  return path != NULL ? rb_str_new2(path) : Qnil;
}

Private Class Methods

auto_magic_version() click to toggle source
# File lib/filemagic.rb, line 122
def auto_magic_version
  require 'nuggets/file/which'

  if cmd = File.which_command([
    'dpkg-query -f \${Version}\ -W libmagic-dev',
    'file -v'
  ])
    [%x{#{cmd}}[/\d+\.\d+/], 'auto-detected']
  end
rescue LoadError
end
user_magic_version(key = 'MAGIC_VERSION') click to toggle source
# File lib/filemagic.rb, line 118
def user_magic_version(key = 'MAGIC_VERSION')
  [ENV[key], 'user-specified'] if ENV[key]
end

Public Instance Methods

close() click to toggle source

Frees resources allocated

static VALUE
rb_magic_close(VALUE self) {
  magic_t ms;

  if (RTEST(rb_magic_closed_p(self))) {
    return Qnil;
  }

  GetMagicSet(self, ms);
  rb_magic_free(ms);

  /* This keeps rb_magic_free from trying to free closed objects */
  DATA_PTR(self) = NULL;

  rb_iv_set(self, "closed", Qtrue);

  return Qnil;
}
closed?() click to toggle source
static VALUE
rb_magic_closed_p(VALUE self) {
  return rb_attr_get(self, rb_intern("closed"));
}
fd(fd) click to toggle source
# File lib/filemagic.rb, line 149
def fd(fd)
  descriptor(fd.respond_to?(:fileno) ? fd.fileno : fd)
end
flags() click to toggle source

Get the flags as array of symbols

static VALUE
rb_magic_getflags(VALUE self) {
  VALUE ary = rb_ary_new();
  VALUE map = rb_const_get(cFileMagic, rb_intern("FLAGS_BY_INT"));
  int i = NUM2INT(rb_attr_get(self, rb_intern("iflags"))), j = 0;

  while ((i -= j) > 0) {
    j = pow(2, (int)(log(i) / log(2)));
    rb_ary_unshift(ary, rb_hash_aref(map, INT2FIX(j)));
  }

  return ary;
}
flags=(p1) click to toggle source

Set flags on the ms object

static VALUE
rb_magic_setflags(VALUE self, VALUE flags) {
  magic_t ms;

  GetMagicSet(self, ms);

  rb_iv_set(self, "iflags",
    flags = rb_magic_flags(CLASS_OF(self), rb_Array(flags)));

  return INT2FIX(magic_setflags(ms, NUM2INT(flags)));
}
inspect() click to toggle source
Calls superclass method
# File lib/filemagic.rb, line 153
def inspect
  super.insert(-2, closed? ? ' (closed)' : '')
end
io(io, length = 8, rewind = false) click to toggle source
# File lib/filemagic.rb, line 142
def io(io, length = 8, rewind = false)
  pos = io.pos if rewind
  buffer(io.read(length))
ensure
  io.pos = pos if pos
end
simplified?() click to toggle source
# File lib/filemagic.rb, line 138
def simplified?
  @simplified
end