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

79 lines
2.1 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2016-01-29 22:53:50 +05:30
module Gitlab
class Highlight
2018-11-08 19:23:39 +05:30
TIMEOUT_BACKGROUND = 30.seconds
TIMEOUT_FOREGROUND = 3.seconds
2018-12-13 13:39:08 +05:30
MAXIMUM_TEXT_HIGHLIGHT_SIZE = 1.megabyte
2018-11-08 19:23:39 +05:30
2018-12-13 13:39:08 +05:30
def self.highlight(blob_name, blob_content, language: nil, plain: false)
new(blob_name, blob_content, language: language)
2017-09-10 17:25:29 +05:30
.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
2018-12-13 13:39:08 +05:30
def initialize(blob_name, blob_content, language: nil)
2017-08-17 22:00:37 +05:30
@formatter = Rouge::Formatters::HTMLGitlab
2018-12-13 13:39:08 +05:30
@language = language
2016-08-24 12:49:21 +05:30
@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)
2018-12-13 13:39:08 +05:30
plain ||= text.length > MAXIMUM_TEXT_HIGHLIGHT_SIZE
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
2019-07-07 11:18:12 +05:30
return unless @language
2016-01-29 22:53:50 +05:30
2018-12-13 13:39:08 +05:30
Rouge::Lexer.find_fancy(@language)
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)
2018-11-08 19:23:39 +05:30
tag = lexer.tag
tokens = lexer.lex(text, continue: continue)
Timeout.timeout(timeout_time) { @formatter.format(tokens, tag: tag).html_safe }
rescue Timeout::Error => e
Gitlab::Sentry.track_exception(e)
highlight_plain(text)
2017-09-10 17:25:29 +05:30
rescue
highlight_plain(text)
end
2018-11-08 19:23:39 +05:30
def timeout_time
Sidekiq.server? ? TIMEOUT_BACKGROUND : TIMEOUT_FOREGROUND
end
2017-09-10 17:25:29 +05:30
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