summaryrefslogtreecommitdiff
path: root/lib/gitlab/blame.rb
blob: e210c18e3d1da53fc907511094b9d04e920ca029 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true

module Gitlab
  class Blame
    attr_accessor :blob, :commit, :range

    def initialize(blob, commit, range: nil)
      @blob = blob
      @commit = commit
      @range = range
    end

    def first_line
      range&.first || 1
    end

    def groups(highlight: true)
      prev_sha = nil
      groups = []
      current_group = nil

      i = first_line - 1
      blame.each do |commit, line, previous_path|
        commit = Commit.new(commit, project)
        commit.lazy_author # preload author

        if prev_sha != commit.sha
          groups << current_group if current_group
          current_group = { commit: commit, lines: [], previous_path: previous_path }
        end

        current_group[:lines] << (highlight ? highlighted_lines[i].html_safe : line)

        prev_sha = commit.sha
        i += 1
      end
      groups << current_group if current_group

      groups
    end

    private

    def blame
      @blame ||= Gitlab::Git::Blame.new(repository, @commit.id, @blob.path, range: range)
    end

    def highlighted_lines
      @blob.load_all_data!
      @highlighted_lines ||= @blob.present.highlight.lines
    end

    def project
      commit.project
    end

    def repository
      project.repository
    end
  end
end