gitlab-org--gitlab-foss/lib/gitlab/highlight.rb

79 lines
2.1 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module Gitlab
class Highlight
TIMEOUT_BACKGROUND = 30.seconds
TIMEOUT_FOREGROUND = 3.seconds
MAXIMUM_TEXT_HIGHLIGHT_SIZE = 1.megabyte
def self.highlight(blob_name, blob_content, language: nil, plain: false)
new(blob_name, blob_content, language: language)
2017-06-21 09:48:12 -04:00
.highlight(blob_content, continue: false, plain: plain)
end
2016-07-10 17:13:06 -04:00
attr_reader :blob_name
def initialize(blob_name, blob_content, language: nil)
@formatter = Rouge::Formatters::HTMLGitlab
@language = language
@blob_name = blob_name
@blob_content = blob_content
end
2016-04-14 06:44:35 -04:00
def highlight(text, continue: true, plain: false)
plain ||= text.length > MAXIMUM_TEXT_HIGHLIGHT_SIZE
2016-07-10 17:13:06 -04:00
highlighted_text = highlight_text(text, continue: continue, plain: plain)
highlighted_text = link_dependencies(text, highlighted_text) if blob_name
highlighted_text
end
def lexer
@lexer ||= custom_language || begin
2016-07-14 15:21:22 -04:00
Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
rescue Rouge::Guesser::Ambiguous => e
e.alternatives.sort_by(&:tag).first
end
end
private
2016-06-21 12:23:42 -04:00
def custom_language
return nil unless @language
2016-06-21 12:23:42 -04:00
Rouge::Lexer.find_fancy(@language)
2016-06-21 12:23:42 -04:00
end
2016-07-10 17:13:06 -04:00
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)
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)
2016-07-10 17:13:06 -04:00
rescue
highlight_plain(text)
end
def timeout_time
Sidekiq.server? ? TIMEOUT_BACKGROUND : TIMEOUT_FOREGROUND
end
2016-07-10 17:13:06 -04:00
def link_dependencies(text, highlighted_text)
Gitlab::DependencyLinker.link(blob_name, text, highlighted_text)
end
end
end