Support selective highlighting of lines

Instead of highlighting all lines when not all of them
are needed, only highlight from the beginning up to
the specified limit.

The `BlobPresenter#highlight` method has been updated
to support `to` param. This param will be used to limit
the content to be highlighted.
This commit is contained in:
Patrick Bajao 2019-09-02 11:19:32 +08:00
parent 60adc14473
commit bf230da05d
4 changed files with 38 additions and 7 deletions

View File

@ -3,12 +3,12 @@
class BlobPresenter < Gitlab::View::Presenter::Delegated
presents :blob
def highlight(plain: nil)
def highlight(to: nil, plain: nil)
load_all_blob_data
Gitlab::Highlight.highlight(
blob.path,
blob.data,
limited_blob_data(to: to),
language: blob.language_from_gitattributes,
plain: plain
)
@ -23,4 +23,18 @@ class BlobPresenter < Gitlab::View::Presenter::Delegated
def load_all_blob_data
blob.load_all_data! if blob.respond_to?(:load_all_data!)
end
def limited_blob_data(to: nil)
return blob.data if to.blank?
# Even though we don't need all the lines at the start of the file (e.g
# viewing the middle part of a file), they still need to be highlighted
# to ensure that the succeeding lines can be formatted correctly (e.g.
# multi-line comments).
all_lines[0..to - 1].join
end
def all_lines
@all_lines ||= blob.data.lines
end
end

View File

@ -26,8 +26,6 @@ module Blobs
# so we can accurately show the rest of the diff when unfolding.
load_all_blob_data
@all_lines = blob.data.lines
handle_full_or_end!
end
@ -46,7 +44,7 @@ module Blobs
def lines
strong_memoize(:lines) do
limit(highlight.lines).map(&:html_safe)
limit(highlight(to: to).lines).map(&:html_safe)
end
end
@ -76,7 +74,7 @@ module Blobs
def all_lines_size
strong_memoize(:all_lines_size) do
@all_lines.size
all_lines.size
end
end
@ -101,7 +99,7 @@ module Blobs
def limited_blob_lines
strong_memoize(:limited_blob_lines) do
limit(@all_lines)
limit(all_lines)
end
end

View File

@ -0,0 +1,5 @@
---
title: Support selective highlighting of lines
merge_request: 32514
author:
type: performance

View File

@ -39,6 +39,20 @@ describe BlobPresenter, :seed_helper do
subject.highlight(plain: true)
end
context '"to" param is present' do
before do
allow(git_blob)
.to receive(:data)
.and_return("line one\nline two\nline 3")
end
it 'returns limited highlighted content' do
expect(Gitlab::Highlight).to receive(:highlight).with('files/ruby/regex.rb', "line one\n", plain: nil, language: nil)
subject.highlight(to: 1)
end
end
context 'gitlab-language contains a match' do
before do
allow(blob).to receive(:language_from_gitattributes).and_return('ruby')