Class: CodeScanning::SarifFormatter

Inherits:
RuboCop::Formatter::BaseFormatter
  • Object
show all
Defined in:
lib/code_scanning/rubocop/sarif_formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(output, options = {}) ⇒ SarifFormatter

Returns a new instance of SarifFormatter.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/code_scanning/rubocop/sarif_formatter.rb', line 8

def initialize(output, options = {})
  super
  @sarif = {
    "$schema" => "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
    "version" => "2.1.0"
  }
  @rules_map = {}
  @rules = []
  @results = []
  @sarif["runs"] = [
    {
      "tool" => {
        "driver" => {
          "name" => "RuboCop",
          "version" => RuboCop::Version.version,
          "informationUri" => "https://rubocop.org",
          "rules" => @rules
        }
      },
      "results" => @results
    }
  ]
end

Instance Method Details

#file_finished(file, offenses) ⇒ Object



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
# File 'lib/code_scanning/rubocop/sarif_formatter.rb', line 43

def file_finished(file, offenses)
  relative_path = RuboCop::PathUtil.relative_path(file)

  offenses.each do |o|
    rule, rule_index = get_rule(o.cop_name, o.severity)
    @results << {
      "ruleId" => rule.id,
      "ruleIndex" => rule_index,
      "message" => {
        "text" => o.message
      },
      "locations" => [
        {
          "physicalLocation" => {
            "artifactLocation" => {
              "uri" => relative_path,
              "uriBaseId" => "%SRCROOT%",
            },
            "region" => {
              "startLine" => o.line,
              "startColumn" => o.real_column,
              "endColumn" => o.last_column.zero? ? o.real_column : o.last_column
            }
          }
        }
      ]
    }
  end
end

#finished(_inspected_files) ⇒ Object



73
74
75
# File 'lib/code_scanning/rubocop/sarif_formatter.rb', line 73

def finished(_inspected_files)
  output.print(sarif_json)
end

#get_rule(cop_name, severity) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/code_scanning/rubocop/sarif_formatter.rb', line 32

def get_rule(cop_name, severity)
  r = @rules_map[cop_name]
  if r.nil?
    rule = Rule.new(cop_name, severity&.name)
    r = @rules_map[cop_name] = [rule, @rules.size]
    @rules << rule
  end

  r
end

#sarif_jsonObject



77
78
79
# File 'lib/code_scanning/rubocop/sarif_formatter.rb', line 77

def sarif_json
  JSON.pretty_generate(@sarif)
end