require 'yaml'

require 'rubocop/rake_task'
RuboCop::RakeTask.new

namespace 'rubocop' do
  desc 'mikutter 4.1以降に変更されたファイルを .rubocop.blacklist.yml から取り除く'
  task 'unblacklist' do
    yaml = YAML.load_file('.rubocop.blacklist.yml')
    blacklist = yaml.dig('AllCops', 'Exclude').to_set
    excludes = Set[]
    IO.popen('git log --numstat --no-merges --pretty="" 4.1.0..HEAD', 'r') do |rp|
      rp.lazy.map { _1.chomp.split("\t", 3) }.each do |add, del, fn|
        matched = fn.match(/{(\w*) => (\w*)}/)
        if matched
          after = matched.pre_match + matched[2] + matched.post_match
          if blacklist.include?(after) && target?(add, del, after, 'renamed ')
            excludes << after
          end
        elsif blacklist.include?(fn) && target?(add, del, fn)
          excludes << fn
        end
      end
    end
    yaml['AllCops']['Exclude'] =
      yaml['AllCops']['Exclude'].select(&FileTest.method(:exist?)) - excludes.to_a
    File.open('.rubocop.blacklist.yml', 'w') do |wp|
      YAML.dump(yaml, wp)
    end
  end

  def target?(add, del, file_name, hint='')
    if FileTest.exist?(file_name)
      siz = File.open(file_name, 'r') { _1.readlines.size }
      rate = add.to_i.fdiv(siz)
      rate >= 0.5
    else
      true
    end
  end
end
