From e8c09e91d5e72b50b4e70b3425ef6a485fc4df43 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 18 Jun 2011 20:09:11 -0500 Subject: [PATCH] Add find lexer by mimetype --- lib/linguist/lexer.rb | 30 +++++++++++++++++++++++++++--- test/test_lexer.rb | 13 +++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/lib/linguist/lexer.rb b/lib/linguist/lexer.rb index cd853afa..ab7260d0 100644 --- a/lib/linguist/lexer.rb +++ b/lib/linguist/lexer.rb @@ -9,9 +9,10 @@ module Linguist # filenames - Filename globs (*.js) # mimetypes - Mime types (application/javascript) class Lexer < Struct.new(:name, :aliases, :filenames, :mimetypes) - @lexers = [] - @name_index = {} - @alias_index = {} + @lexers = [] + @name_index = {} + @alias_index = {} + @mimetypes_index = {} # Internal: Test if system has Pygments # @@ -58,6 +59,20 @@ module Linguist @alias_index[name] end + # Public: Look up Lexer by one of it's mime types. + # + # type - A mime type String. + # + # Examples + # + # Lexer.find_by_mimetype('application/x-ruby') + # # => # + # + # Returns the Lexer or nil if none was found. + def self.find_by_mimetype(type) + @mimetypes_index[type] + end + # Public: Look up Lexer by name or alias. # # name - A case-insensitive String name or alias @@ -132,6 +147,15 @@ module Linguist @alias_index[name] = lexer end + + lexer.mimetypes.each do |type| + # All Lexer mimetypes should be unique. Warn if there is a duplicate. + if @mimetypes_index.key?(name) + warn "Duplicate mimetype: #{name}" + end + + @mimetypes_index[type] = lexer + end end end end diff --git a/test/test_lexer.rb b/test/test_lexer.rb index 06e335f2..897a26d0 100644 --- a/test/test_lexer.rb +++ b/test/test_lexer.rb @@ -32,6 +32,19 @@ class TestLexer < Test::Unit::TestCase end end + def test_find_by_mimetype + assert_equal Lexer['Ruby'], Lexer.find_by_mimetype('text/x-ruby') + assert_equal Lexer['Ruby'], Lexer.find_by_mimetype('application/x-ruby') + end + + def test_find_all_by_mimetype + Lexer.all.each do |lexer| + lexer.mimetypes.each do |type| + assert_equal lexer, Lexer.find_by_mimetype(type) + end + end + end + def test_name assert_equal 'Ruby', Lexer['Ruby'].name assert_equal 'Python', Lexer['Python'].name