Module: CodeRay::FileType

Defined in:
lib/coderay/helpers/file_type.rb

Overview

FileType

A simple filetype recognizer.

Copyright © 2006 by murphy (Kornelius Kalnbach) <murphy rubychan de>

License

LGPL / ask the author

Version

0.1 (2005-09-01)

Documentation

# determine the type of the given
 lang = FileType[ARGV.first]

 # return :plaintext if the file type is unknown
 lang = FileType.fetch ARGV.first, :plaintext

 # try the shebang line, too
 lang = FileType.fetch ARGV.first, :plaintext, true

Constant Summary collapse

UnknownFileType =
Class.new Exception
TypeFromExt =
{
  'rb' => :ruby,
  'rbw' => :ruby,
  'rake' => :ruby,
  'mab' => :ruby,
  'cpp' => :c,
  'c' => :c,
  'h' => :c,
  'java' => :java,
  'js' => :java_script,
  'json' => :json,
  'diff' => :diff,
  'patch' => :diff,
  'css' => :css,
  'xml' => :xml,
  'htm' => :html,
  'html' => :html,
  'xhtml' => :xhtml,
  'raydebug' => :debug,
  'rhtml' => :rhtml,
  'html.erb' => :rhtml,
  'ss' => :scheme,
  'sch' => :scheme,
  'yaml' => :yaml,
  'yml' => :yaml,
}
TypeFromShebang =
/\b(?:ruby|perl|python|sh)\b/
TypeFromName =
{
  'Rakefile' => :ruby,
  'Rantfile' => :ruby,
}

Class Method Summary collapse

Class Method Details

.[](filename, read_shebang = false) ⇒ Object

Try to determine the file type of the file.

filename is a relative or absolute path to a file.

The file itself is only accessed when read_shebang is set to true. That means you can get filetypes from files that don’t exist.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/coderay/helpers/file_type.rb', line 35

def [] filename, read_shebang = false
  name = File.basename filename
  ext = File.extname(name).sub(/^\./, '')  # from last dot, delete the leading dot
  ext2 = filename[/\.(.*)/, 1]  # from first dot

  type =
    TypeFromExt[ext.downcase] ||
    (TypeFromExt[ext2.downcase] if ext2) ||
    TypeFromName[name] ||
    TypeFromName[name.downcase]
  type ||= shebang(filename) if read_shebang

  type
end

.fetch(filename, default = nil, read_shebang = false) ⇒ Object

This works like Hash#fetch.

If the filetype cannot be found, the default value is returned.



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/coderay/helpers/file_type.rb', line 68

def fetch filename, default = nil, read_shebang = false
  if default and block_given?
    warn 'block supersedes default value argument'
  end

  unless type = self[filename, read_shebang]
    return yield if block_given?
    return default if default
    raise UnknownFileType, 'Could not determine type of %p.' % filename
  end
  type
end

.shebang(filename) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/coderay/helpers/file_type.rb', line 50

def shebang filename
  begin
    File.open filename, 'r' do |f|
      if first_line = f.gets
        if type = first_line[TypeFromShebang]
          type.to_sym
        end
      end
    end
  rescue IOError
    nil
  end
end