Sha256: 0ad97265f89500fe8c2ebb4eda3fd8c7e5104b29b686ac7539e523e3c65b5d14

Contents?: true

Size: 1.97 KB

Versions: 4

Compression:

Stored size: 1.97 KB

Contents

# frozen_string_literal: true

require_relative 'utils'

class Danger::DangerWCC < Danger::Plugin
  class Todos
    include Utils

    TODO_REGEX = /^\+.*\#.*TODO:?/i
    LINK_REGEX = /\#.*(https?\:\/\/\S+)/i

    def initialize(plugin, options = {})
      @plugin = plugin
      @options = options
    end

    def perform
      find_new_todos.each do |result|
        issue_message(result)
      end
    end

    private

    def issue_message(result)
      if result[:link]
        plugin.message "TODO added in #{result[:file_link]} "\
          "referencing [#{result[:link]}](#{result[:link]})",
          file: result[:file], line: result[:line]
      else
        plugin.warn "TODO added in #{result[:file_link]} - "\
          'is there a card associated with that?',
          file: result[:file], line: result[:line]
      end
    end

    def find_new_todos
      find_in_diff(TODO_REGEX) do |_m, line, _hunk, file, _diff|
        make_violation(file, line)
      end
    end

    def make_violation(file, todo_line)
      link_line_number, link = find_link_in_context(file, todo_line)

      {
        link: link,
        file: file.b_path,
        file_link: @plugin.github.html_link(file.b_path),
        line: max(link_line_number, todo_line.line_number.right),
        warn: link.nil?
      }
    end

    def grab_context_lines(file, line_number)
      contents = File.read(file.b_path)
      # grab the line and the lines immediately before and after it
      contents.lines[max(line_number - 2, 0)..line_number]
    end

    def find_link_in_context(file, line)
      context = grab_context_lines(file, line.line_number.right)
      context.each_with_index do |l, i|
        if m = l.match(LINK_REGEX)
          # line at index 0 in the context array is (line.line_number.right - 1)
          return [line.line_number.right - 1 + i, m.captures[0]]
        end
      end
      nil
    end

    def max(a, b)
      return a if b.nil?
      return b if a.nil?
      a > b ? a : b
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
danger-wcc-0.0.5 lib/wcc/todos.rb
danger-wcc-0.0.4 lib/wcc/todos.rb
danger-wcc-0.0.3 lib/wcc/todos.rb
danger-wcc-0.0.2 lib/wcc/todos.rb