BigW Consortium Gitlab

highlight.rb 1.52 KB
Newer Older
1 2
module Gitlab
  class Highlight
3 4
    def self.highlight(blob_name, blob_content, repository: nil, plain: false)
      new(blob_name, blob_content, repository: repository).
5
        highlight(blob_content, continue: false, plain: plain)
6 7
    end

8 9 10 11
    def self.highlight_lines(repository, ref, file_name)
      blob = repository.blob_at(ref, file_name)
      return [] unless blob

12
      blob.load_all_data!(repository)
13
      highlight(file_name, blob.data, repository: repository).lines.map!(&:html_safe)
14 15
    end

16
    def initialize(blob_name, blob_content, repository: nil)
17
      @formatter = Rouge::Formatters::HTMLGitlab.new
18
      @repository = repository
19
      @blob_name = blob_name
20
      @blob_content = blob_content
21 22
    end

23 24
    def highlight(text, continue: true, plain: false)
      if plain
25
        hl_lexer = Rouge::Lexers::PlainText
26
        continue = false
27 28
      else
        hl_lexer = self.lexer
29
      end
30

31
      @formatter.format(hl_lexer.lex(text, continue: continue)).html_safe
32 33
    rescue
      @formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
34 35
    end

36 37
    def lexer
      @lexer ||= custom_language || begin
38 39
        Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
      rescue Rouge::Guesser::Ambiguous => e
40 41 42 43
        e.alternatives.sort_by(&:tag).first
      end
    end

44 45
    private

46
    def custom_language
47
      language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
48

49
      return nil unless language_name
50

51
      Rouge::Lexer.find_fancy(language_name)
52
    end
53 54
  end
end