class CodeScanning::SarifFormatter

Public Class Methods

new(output, options = {}) click to toggle source
Calls superclass method
# 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", "rules" => @rules }
      },
      "results" => @results
    }
  ]
end

Public Instance Methods

file_finished(file, offenses) click to toggle source
# File lib/code_scanning/rubocop/sarif_formatter.rb, line 38
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%",
              "index" => 0
            },
            "region" => {
              "startLine" => o.line,
              "startColumn" => o.real_column,
              "endColumn" => o.last_column.zero? ? o.real_column : o.last_column
            }
          }
        }
      ],
      "partialFingerprints" => {
        # This will be computed by the upload action for now
      }
    }
  end
end
finished(_inspected_files) click to toggle source
# File lib/code_scanning/rubocop/sarif_formatter.rb, line 72
def finished(_inspected_files)
  output.print(sarif_json)
end
get_rule(cop_name, severity) click to toggle source
# File lib/code_scanning/rubocop/sarif_formatter.rb, line 27
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_json() click to toggle source
# File lib/code_scanning/rubocop/sarif_formatter.rb, line 76
def sarif_json
  JSON.pretty_generate(@sarif)
end