gitlabhq/lib/utils.rb

73 lines
1.7 KiB
Ruby
Raw Normal View History

2011-10-08 23:36:38 +02:00
module Utils
2011-10-20 21:00:00 +02:00
module FileHelper
def binary?(string)
2011-10-20 21:00:00 +02:00
string.each_byte do |x|
x.nonzero? or return true
2011-10-20 21:00:00 +02:00
end
false
end
def image?
mime_type =~ /image/
end
def text?
mime_type =~ /application|text/ && !binary?(data)
end
end
module CharEncode
2011-12-29 04:51:33 +01:00
def encode(content)
content ||= ''
detection = CharlockHolmes::EncodingDetector.detect(content)
if hash = detection
content = CharlockHolmes::Converter.convert(content, hash[:encoding], 'UTF-8') if hash[:encoding]
end
2011-12-29 04:51:33 +01:00
content
end
end
2011-10-20 21:00:00 +02:00
module Colorize
include CharEncode
2011-10-20 21:00:00 +02:00
def colorize
system_colorize(data, name)
2011-10-21 14:35:42 +02:00
end
def system_colorize(data, file_name)
ft = handle_file_type(file_name)
Pygments.highlight(encode(data), :lexer => ft, :options => { :encoding => 'utf-8', :linenos => 'True' })
2011-10-20 21:00:00 +02:00
end
def handle_file_type(file_name, mime_type = nil)
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 21:00:00 +02:00
:ruby
when /(\.py|\.pyw|\.sc|SConstruct|SConscript|\.tac)$/
2011-10-20 21:00:00 +02:00
:python
when /(\.js|\.json)$/
2011-10-20 21:00:00 +02:00
:javascript
when /(\.xml|\.xsl|\.rss|\.xslt|\.xsd|\.wsdl)$/
:xml
when /(\.vm|\.fhtml)$/
:velocity
when /\.sh$/
2011-10-20 21:00:00 +02:00
:bash
when /\.coffee$/
2011-10-20 21:00:00 +02:00
:coffeescript
when /(\.yml|\.yaml)$/
2011-10-20 21:00:00 +02:00
:yaml
when /\.md$/
2011-10-20 21:00:00 +02:00
:minid
else
:text
end
2011-10-08 23:36:38 +02:00
end
end
end