Class: Linguist::Shebang

Inherits:
Object
  • Object
show all
Defined in:
lib/linguist/shebang.rb

Class Method Summary collapse

Class Method Details

.call(blob, _ = nil) ⇒ Object

Public: Use shebang to detect language of the blob.

blob - An object that quacks like a blob.

Examples

Shebang.call(FileBlob.new("path/to/file"))

Returns an Array with one Language if the blob has a shebang with a valid interpreter, or empty if there is no shebang.



13
14
15
# File 'lib/linguist/shebang.rb', line 13

def self.call(blob, _ = nil)
  Language.find_by_interpreter interpreter(blob.data)
end

.interpreter(data) ⇒ Object

Public: Get the interpreter from the shebang

Returns a String or nil



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/linguist/shebang.rb', line 20

def self.interpreter(data)
  shebang = data.lines.first

  # First line must start with #!
  return unless shebang && shebang.start_with?("#!")

  # Get the parts of the shebang without the #!
  tokens = shebang.sub(/^#!\s*/, '').strip.split(' ')

  # There was nothing after the #!
  return if tokens.empty?

  # Get the name of the interpreter
  script = File.basename(tokens.first)

  # Get next argument if interpreter was /usr/bin/env
  script = tokens[1] if script == 'env'

  # Interpreter was /usr/bin/env with no arguments
  return unless script

  # "python2.6" -> "python2"
  script.sub! /(\.\d+)$/, ''

  # Check for multiline shebang hacks that call `exec`
  if script == 'sh' &&
    data.lines.first(5).any? { |l| l.match(/exec (\w+).+\$0.+\$@/) }
    script = $1
  end

  File.basename(script)
end