debian-mirror-gitlab/lib/gitlab/highlight.rb

64 lines
1.8 KiB
Ruby
Raw Normal View History

2016-01-29 22:53:50 +05:30
module Gitlab
class Highlight
2016-08-24 12:49:21 +05:30
def self.highlight(blob_name, blob_content, repository: nil, plain: false)
2017-09-10 17:25:29 +05:30
new(blob_name, blob_content, repository: repository)
.highlight(blob_content, continue: false, plain: plain)
2016-01-29 22:53:50 +05:30
end
2017-09-10 17:25:29 +05:30
attr_reader :blob_name
2016-01-29 22:53:50 +05:30
2016-08-24 12:49:21 +05:30
def initialize(blob_name, blob_content, repository: nil)
2017-08-17 22:00:37 +05:30
@formatter = Rouge::Formatters::HTMLGitlab
2016-08-24 12:49:21 +05:30
@repository = repository
@blob_name = blob_name
@blob_content = blob_content
2016-01-29 22:53:50 +05:30
end
2016-06-02 11:05:42 +05:30
def highlight(text, continue: true, plain: false)
2017-09-10 17:25:29 +05:30
highlighted_text = highlight_text(text, continue: continue, plain: plain)
highlighted_text = link_dependencies(text, highlighted_text) if blob_name
highlighted_text
2016-01-29 22:53:50 +05:30
end
2016-08-24 12:49:21 +05:30
def lexer
@lexer ||= custom_language || begin
Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
rescue Rouge::Guesser::Ambiguous => e
e.alternatives.sort_by(&:tag).first
end
end
2016-01-29 22:53:50 +05:30
private
2016-08-24 12:49:21 +05:30
def custom_language
language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
return nil unless language_name
2016-01-29 22:53:50 +05:30
2016-08-24 12:49:21 +05:30
Rouge::Lexer.find_fancy(language_name)
2016-01-29 22:53:50 +05:30
end
2017-09-10 17:25:29 +05:30
def highlight_text(text, continue: true, plain: false)
if plain
highlight_plain(text)
else
highlight_rich(text, continue: continue)
end
end
def highlight_plain(text)
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
end
def highlight_rich(text, continue: true)
@formatter.format(lexer.lex(text, continue: continue), tag: lexer.tag).html_safe
rescue
highlight_plain(text)
end
def link_dependencies(text, highlighted_text)
Gitlab::DependencyLinker.link(blob_name, text, highlighted_text)
end
2016-01-29 22:53:50 +05:30
end
end