Sha256: 3ed36393d79e96e4aa2e5e3b4791bebfebcd1270c1a5833552cc9883b072aafb

Contents?: true

Size: 1.53 KB

Versions: 35

Compression:

Stored size: 1.53 KB

Contents

module Linguist
  class Shebang
    # 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.
    def self.call(blob, _ = nil)
      Language.find_by_interpreter interpreter(blob.data)
    end

    # Public: Get the interpreter from the shebang
    #
    # Returns a String or nil
    def self.interpreter(data)
      shebang = data.lines.first

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

      s = StringScanner.new(shebang)

      # There was nothing after the #!
      return unless path = s.scan(/^#!\s*\S+/)

      # Keep going
      script = path.split('/').last

      # if /usr/bin/env type shebang then walk the string
      if script == 'env'
        s.scan(/\s+/)
        s.scan(/.*=[^\s]+\s+/) # skip over variable arguments e.g. foo=bar
        script = s.scan(/\S+/)
      end

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

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

      # #! perl -> perl
      script.sub!(/^#!\s*/, '')

      # 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
  end
end

Version data entries

35 entries across 35 versions & 1 rubygems

Version Path
github-linguist-5.3.3 lib/linguist/shebang.rb
github-linguist-5.3.2 lib/linguist/shebang.rb
github-linguist-5.3.1 lib/linguist/shebang.rb
github-linguist-5.3.0 lib/linguist/shebang.rb
github-linguist-5.2.0 lib/linguist/shebang.rb
github-linguist-5.1.0 lib/linguist/shebang.rb
github-linguist-5.0.11 lib/linguist/shebang.rb
github-linguist-5.0.10 lib/linguist/shebang.rb
github-linguist-5.0.9 lib/linguist/shebang.rb
github-linguist-5.0.8 lib/linguist/shebang.rb
github-linguist-5.0.7 lib/linguist/shebang.rb
github-linguist-5.0.6 lib/linguist/shebang.rb
github-linguist-5.0.5 lib/linguist/shebang.rb
github-linguist-5.0.4 lib/linguist/shebang.rb
github-linguist-5.0.3 lib/linguist/shebang.rb
github-linguist-5.0.2 lib/linguist/shebang.rb
github-linguist-5.0.0 lib/linguist/shebang.rb
github-linguist-4.8.18 lib/linguist/shebang.rb
github-linguist-4.8.17 lib/linguist/shebang.rb
github-linguist-4.8.16 lib/linguist/shebang.rb