From cd3defda427f261ec7bb1924d0a77f799c48f755 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Thu, 27 Nov 2014 12:44:55 -0500 Subject: [PATCH] Simplify shebang detection --- lib/linguist/shebang.rb | 42 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/lib/linguist/shebang.rb b/lib/linguist/shebang.rb index 52933e2b..b0152326 100644 --- a/lib/linguist/shebang.rb +++ b/lib/linguist/shebang.rb @@ -5,45 +5,31 @@ module Linguist Language.find_by_interpreter(new(blob.data).interpreter) end - attr_reader :data - def initialize(data) - @data = data + @lines = data.lines end def interpreter - lines = data.lines.to_a + return unless match = /^#! ?(.*)$/.match(@lines.first) - if lines.any? && (match = lines[0].match(/(.+)\n?/)) && (bang = match[0]) =~ /^#!/ - bang.sub!(/^#! /, '#!') - tokens = bang.split(' ') - pieces = tokens.first.split('/') + tokens = match[0].split(' ') + script = tokens.first.split('/').last - if pieces.size > 1 - script = pieces.last - else - script = pieces.first.sub('#!', '') - end + script = tokens[1] if script == 'env' - script = script == 'env' ? tokens[1] : script + # If script has an invalid shebang, we might get here + return unless script - # If script has an invalid shebang, we might get here - return unless script + # "python2.6" -> "python2" + script.sub! $1, '' if script =~ /(\.\d+)$/ - # "python2.6" -> "python2" - script.sub! $1, '' if script =~ /(\.\d+)$/ - - # Check for multiline shebang hacks that call `exec` - if script == 'sh' && - lines[0...5].any? { |l| l.match(/exec (\w+).+\$0.+\$@/) } - script = $1 - end - - File.basename(script) - else - nil + # Check for multiline shebang hacks that call `exec` + if script == 'sh' && + @lines[0...5].any? { |l| l.match(/exec (\w+).+\$0.+\$@/) } + script = $1 end + File.basename(script) end end end