summaryrefslogtreecommitdiff
path: root/app/components/diffs/stats_component.rb
blob: 55589c7b0153874276bf3968cb09bcaa339a0244 (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
62
63
64
65
66
67
# frozen_string_literal: true

module Diffs
  class StatsComponent < BaseComponent
    attr_reader :diff_files

    def initialize(diff_files:)
      @diff_files = diff_files
      @changed ||= diff_files.size
      @added   ||= diff_files.sum(&:added_lines)
      @removed ||= diff_files.sum(&:removed_lines)
    end

    def diff_files_data
      diffs_map = @diff_files.map do |f|
        {
            href: "##{helpers.hexdigest(f.file_path)}",
            title: f.new_path,
            name: f.file_path,
            path: diff_file_path_text(f),
            icon: diff_file_changed_icon(f),
            iconColor: "#{diff_file_changed_icon_color(f)}",
            added: f.added_lines,
            removed: f.removed_lines
        }
      end

      Gitlab::Json.dump(diffs_map)
    end

    # Disabled undercoverage reports for this method
    # as it returns a false positive on the last line,
    # which is covered in the tests
    #
    # Issue: https://gitlab.com/gitlab-org/gitlab/-/issues/357381
    #
    # :nocov:
    def diff_file_path_text(diff_file, max: 60)
      path = diff_file.new_path

      return path unless path.size > max && max > 3

      "...#{path[-(max - 3)..]}"
    end
    # :nocov:

    private

    def diff_file_changed_icon(diff_file)
      if diff_file.deleted_file?
        "file-deletion"
      elsif diff_file.new_file?
        "file-addition"
      else
        "file-modified"
      end
    end

    def diff_file_changed_icon_color(diff_file)
      if diff_file.deleted_file?
        "danger"
      elsif diff_file.new_file?
        "success"
      end
    end
  end
end