summaryrefslogtreecommitdiff
path: root/lib/gitlab/badge/coverage/report.rb
blob: 390da014a5a332bdf58d2cee64325957d88677a5 (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
68
69
70
71
72
73
74
75
# frozen_string_literal: true

module Gitlab
  module Badge
    module Coverage
      ##
      # Test coverage report badge
      #
      class Report < Badge::Base
        attr_reader :project, :ref, :job, :customization

        def initialize(project, ref, opts: { job: nil })
          @project = project
          @ref = ref
          @job = opts[:job]
          @customization = {
            key_width: opts[:key_width].to_i,
            key_text: opts[:key_text]
          }
        end

        def entity
          'coverage'
        end

        def status
          @coverage ||= raw_coverage
          return unless @coverage

          @coverage.to_f.round(2)
        end

        def metadata
          @metadata ||= Coverage::Metadata.new(self)
        end

        def template
          @template ||= Coverage::Template.new(self)
        end

        private

        def successful_pipeline
          @successful_pipeline ||= @project.ci_pipelines.latest_successful_for_ref(@ref)
        end

        def failed_pipeline
          @failed_pipeline ||= @project.ci_pipelines.latest_failed_for_ref(@ref)
        end

        def running_pipeline
          @running_pipeline ||= @project.ci_pipelines.latest_running_for_ref(@ref)
        end

        def raw_coverage
          latest =
            if @job.present?
              builds = ::Ci::Build
                .in_pipelines([successful_pipeline, running_pipeline, failed_pipeline])
                .latest
                .success
                .for_ref(@ref)
                .by_name(@job)

              builds.max_by(&:created_at)
            else
              successful_pipeline
            end

          latest&.coverage
        end
      end
    end
  end
end