class CC::Analyzer::SourceExtractor

Constants

InvalidLocation

Attributes

source[R]

Public Class Methods

new(source) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 6
def initialize(source)
  @source = source
end

Public Instance Methods

extract(location) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 10
def extract(location)
  validate_location(location)

  if (lines = location["lines"])
    extract_from_lines(lines)
  elsif (positions = location["positions"])
    extract_from_positions(positions)
  end
end

Private Instance Methods

convert_to_offsets(positions) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 50
def convert_to_offsets(positions)
  positions.each_with_object({}) do |(key, value), memo|
    memo[key] =
      if value.key?("offset")
        value
      else
        {
          "offset" => to_offset(value["line"] - 1, value["column"] - 1),
        }
      end
  end
end
extract_from_lines(lines) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 31
def extract_from_lines(lines)
  begin_index = lines.fetch("begin") - 1
  end_index = lines.fetch("end") - 1
  range = (begin_index..end_index)

  source.each_line.with_object("").with_index do |(source_line, memo), index|
    memo << source_line if range.include?(index)
  end
end
extract_from_positions(positions) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 41
def extract_from_positions(positions)
  positions = convert_to_offsets(positions)
  begin_offset = positions.fetch("begin").fetch("offset")
  end_offset = positions.fetch("end").fetch("offset")
  length = end_offset - begin_offset

  source[begin_offset, length + 1]
end
to_offset(line, column, offset = 0) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 63
def to_offset(line, column, offset = 0)
  source.each_line.with_index do |source_line, index|
    offset +=
      if line == index
        column
      else
        source_line.length
      end

    break if index >= line
  end

  offset
end
validate_location(location) click to toggle source
# File lib/cc/analyzer/source_extractor.rb, line 24
def validate_location(location)
  validator = IssueValidations::LocationFormatValidation::Validator.new(location)
  unless validator.valid?
    raise InvalidLocation, validator.message
  end
end