2011-10-08 17:36:38 -04:00
|
|
|
module Utils
|
2011-10-20 15:00:00 -04:00
|
|
|
module FileHelper
|
2011-10-26 09:46:25 -04:00
|
|
|
def binary?(string)
|
2011-10-20 15:00:00 -04:00
|
|
|
string.each_byte do |x|
|
2011-10-26 09:46:25 -04:00
|
|
|
x.nonzero? or return true
|
2011-10-20 15:00:00 -04:00
|
|
|
end
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def image?
|
|
|
|
mime_type =~ /image/
|
|
|
|
end
|
|
|
|
|
|
|
|
def text?
|
|
|
|
mime_type =~ /application|text/ && !binary?(data)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-11-28 04:46:41 -05:00
|
|
|
module CharEncode
|
|
|
|
def encode(string)
|
|
|
|
cd = CharDet.detect(string)
|
|
|
|
if cd.confidence > 0.6
|
|
|
|
string.force_encoding(cd.encoding)
|
|
|
|
end
|
|
|
|
string.encode("utf-8", :undef => :replace, :replace => "?", :invalid => :replace)
|
2011-12-01 02:59:49 -05:00
|
|
|
rescue
|
|
|
|
"Invalid code encoding"
|
2011-11-28 04:46:41 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-10-20 15:00:00 -04:00
|
|
|
module Colorize
|
2011-11-28 04:46:41 -05:00
|
|
|
include CharEncode
|
2011-10-20 15:00:00 -04:00
|
|
|
def colorize
|
2011-11-30 02:05:37 -05:00
|
|
|
system_colorize(data, name)
|
2011-10-21 08:35:42 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def system_colorize(data, file_name)
|
|
|
|
ft = handle_file_type(file_name)
|
2011-11-30 02:05:37 -05:00
|
|
|
Pygments.highlight(encode(data), :lexer => ft, :options => { :encoding => 'utf-8', :linenos => 'True' })
|
2011-10-20 15:00:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def handle_file_type(file_name, mime_type = nil)
|
2011-12-05 05:21:44 -05:00
|
|
|
case file_name
|
|
|
|
when /(\.pl|\.scala|\.java|\.haml|\.jade|\.scaml|\.html|\.sass|\.scss|\.php|\.erb)$/
|
|
|
|
$1[1..-1].to_sym
|
|
|
|
when /(\.c|\.h|\.idc)$/
|
|
|
|
:c
|
|
|
|
when /(\.cpp|\.hpp|\.c++|\.h++|\.cc|\.hh|\.cxx|\.hxx)$/
|
|
|
|
:cpp
|
|
|
|
when /(\.rb|\.ru|\.rake|Rakefile|\.gemspec|\.rbx|Gemfile)$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:ruby
|
2011-12-05 05:21:44 -05:00
|
|
|
when /(\.py|\.pyw|\.sc|SConstruct|SConscript|\.tac)$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:python
|
2011-12-05 05:21:44 -05:00
|
|
|
when /(\.js|\.json)$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:javascript
|
2011-12-05 05:21:44 -05:00
|
|
|
when /(\.xml|\.xsl|\.rss|\.xslt|\.xsd|\.wsdl)$/
|
|
|
|
:xml
|
|
|
|
when /(\.vm|\.fhtml)$/
|
|
|
|
:velocity
|
|
|
|
when /\.sh$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:bash
|
2011-12-05 05:21:44 -05:00
|
|
|
when /\.coffee$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:coffeescript
|
2011-12-05 05:21:44 -05:00
|
|
|
when /(\.yml|\.yaml)$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:yaml
|
2011-12-05 05:21:44 -05:00
|
|
|
when /\.md$/
|
2011-10-20 15:00:00 -04:00
|
|
|
:minid
|
|
|
|
else
|
|
|
|
:text
|
|
|
|
end
|
2011-10-08 17:36:38 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|