summaryrefslogtreecommitdiff
path: root/rubocop/todo_dir.rb
blob: 4aca4454a069ea51d10e6629bd4940fcecb92b67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true

require 'fileutils'
require 'active_support/inflector/inflections'

module RuboCop
  # Helper class to manage file access to RuboCop TODOs in .rubocop_todo directory.
  class TodoDir
    DEFAULT_TODO_DIR = File.expand_path('../.rubocop_todo', __dir__)

    # Suffix to indicate TODOs being inspected right now.
    SUFFIX_INSPECT = '.inspect'

    attr_reader :directory

    def initialize(directory, inflector: ActiveSupport::Inflector)
      @directory = directory
      @inflector = inflector
    end

    def read(cop_name, suffix = nil)
      read_suffixed(cop_name)
    end

    def write(cop_name, content)
      path = path_for(cop_name)

      FileUtils.mkdir_p(File.dirname(path))
      File.write(path, content)

      path
    end

    def inspect(cop_name)
      path = path_for(cop_name)

      if File.exist?(path)
        FileUtils.mv(path, "#{path}#{SUFFIX_INSPECT}")
        true
      else
        false
      end
    end

    def inspect_all
      pattern = File.join(@directory, '**/*.yml')

      Dir.glob(pattern).count do |path|
        FileUtils.mv(path, "#{path}#{SUFFIX_INSPECT}")
      end
    end

    def list_inspect
      pattern = File.join(@directory, "**/*.yml.inspect")

      Dir.glob(pattern)
    end

    def delete_inspected
      pattern = File.join(@directory, '**/*.yml.inspect')

      Dir.glob(pattern).count do |path|
        File.delete(path)
      end
    end

    private

    def read_suffixed(cop_name, suffix = nil)
      path = path_for(cop_name, suffix)

      File.read(path) if File.exist?(path)
    end

    def path_for(cop_name, suffix = nil)
      todo_path = "#{@inflector.underscore(cop_name)}.yml#{suffix}"

      File.join(@directory, todo_path)
    end
  end
end