2015-12-30 05:52:50 +00:00
|
|
|
module Gitlab
|
|
|
|
module Diff
|
|
|
|
class Highlight
|
2016-01-08 03:37:01 +00:00
|
|
|
attr_reader :diff_file
|
|
|
|
|
|
|
|
delegate :repository, :old_path, :new_path, :old_ref, :new_ref,
|
|
|
|
to: :diff_file, prefix: :diff
|
|
|
|
|
2015-12-31 06:05:52 +00:00
|
|
|
# Apply syntax highlight to provided source code
|
|
|
|
#
|
2016-01-08 03:37:01 +00:00
|
|
|
# diff_file - an instance of Gitlab::Diff::File
|
2015-12-31 06:05:52 +00:00
|
|
|
#
|
|
|
|
# Returns an Array with the processed items.
|
2016-01-08 03:37:01 +00:00
|
|
|
def self.process_diff_lines(diff_file)
|
|
|
|
processor = new(diff_file)
|
2015-12-30 05:52:50 +00:00
|
|
|
processor.highlight
|
|
|
|
end
|
|
|
|
|
2016-01-08 03:37:01 +00:00
|
|
|
def self.process_file(repository, ref, file_name)
|
|
|
|
blob = repository.blob_at(ref, file_name)
|
|
|
|
return [] unless blob
|
|
|
|
|
2016-01-14 14:11:50 +00:00
|
|
|
Gitlab::Highlight.highlight(file_name, blob.data).lines.map!(&:html_safe)
|
2016-01-08 03:37:01 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(diff_file)
|
|
|
|
@diff_file = diff_file
|
|
|
|
@file_name = diff_file.new_path
|
|
|
|
@lines = diff_file.diff_lines
|
2015-12-30 05:52:50 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def highlight
|
2015-12-31 06:05:52 +00:00
|
|
|
return [] if @lines.empty?
|
|
|
|
|
2016-01-12 22:36:08 +00:00
|
|
|
@lines.each_with_index do |line, i|
|
2016-01-14 15:13:35 +00:00
|
|
|
line_prefix = line.text.match(/\A([+-])/) ? $1 : ' '
|
2015-12-31 02:44:12 +00:00
|
|
|
|
|
|
|
# ignore highlighting for "match" lines
|
2016-01-12 22:36:08 +00:00
|
|
|
next if line.type == 'match'
|
2015-12-31 02:44:12 +00:00
|
|
|
|
2016-01-12 22:36:08 +00:00
|
|
|
case line.type
|
2016-01-08 03:37:01 +00:00
|
|
|
when 'new', nil
|
2016-01-12 22:36:08 +00:00
|
|
|
highlighted_line = new_lines[line.new_pos - 1]
|
2016-01-08 03:37:01 +00:00
|
|
|
when 'old'
|
2016-01-12 22:36:08 +00:00
|
|
|
highlighted_line = old_lines[line.old_pos - 1]
|
2016-01-08 03:37:01 +00:00
|
|
|
end
|
2016-01-09 06:55:31 +00:00
|
|
|
|
|
|
|
# Only update text if line is found. This will prevent
|
|
|
|
# issues with submodules given the line only exists in diff content.
|
2016-01-14 15:13:35 +00:00
|
|
|
line.text = highlighted_line.insert(0, line_prefix).html_safe if highlighted_line
|
2015-12-30 05:52:50 +00:00
|
|
|
end
|
|
|
|
|
2015-12-31 06:05:52 +00:00
|
|
|
@lines
|
2015-12-30 05:52:50 +00:00
|
|
|
end
|
|
|
|
|
2016-01-08 03:37:01 +00:00
|
|
|
def old_lines
|
2016-01-14 15:13:35 +00:00
|
|
|
@old_lines ||= self.class.process_file(diff_repository, diff_old_ref, diff_old_path)
|
2016-01-08 03:37:01 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def new_lines
|
2016-01-14 15:13:35 +00:00
|
|
|
@new_lines ||= self.class.process_file(diff_repository, diff_new_ref, diff_new_path)
|
2015-12-30 05:52:50 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|