Class: Rubocop::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cli.rb

Overview

The CLI is a class responsible of handling all the command line interface logic.

Constant Summary collapse

DEFAULT_FORMATTER =
'progress'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



18
19
20
21
22
# File 'lib/rubocop/cli.rb', line 18

def initialize
  @errors = []
  @options = {}
  @config_store = ConfigStore.new
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



14
15
16
# File 'lib/rubocop/cli.rb', line 14

def options
  @options
end

#wants_to_quitObject Also known as: wants_to_quit?

If set true while running, RuboCop will abort processing and exit gracefully.



13
14
15
# File 'lib/rubocop/cli.rb', line 13

def wants_to_quit
  @wants_to_quit
end

Instance Method Details

#convert_deprecated_options(args) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
# File 'lib/rubocop/cli.rb', line 229

def convert_deprecated_options(args)
  args.map! do |arg|
    case arg
    when '-e', '--emacs'
      deprecate("#{arg} option", '--format emacs', '1.0.0')
      %w(--format emacs)
    else
      arg
    end
  end.flatten!
end

#display_error_summary(errors) ⇒ Object



250
251
252
253
254
255
256
257
258
259
# File 'lib/rubocop/cli.rb', line 250

def display_error_summary(errors)
  return if errors.empty?
  plural = errors.count > 1 ? 's' : ''
  warn "\n#{errors.count} error#{plural} occurred:".color(:red)
  errors.each { |error| warn error }
  warn 'Errors are usually caused by RuboCop bugs.'
  warn 'Please, report your problems to RuboCop\'s issue tracker.'
  warn 'Mention the following information in the issue report:'
  warn Rubocop::Version.version(true)
end

#ignore_dropped_options(args) ⇒ Object

rubocop:enable MethodLength



219
220
221
222
223
224
225
226
227
# File 'lib/rubocop/cli.rb', line 219

def ignore_dropped_options(args)
  # Currently we don't make -s/--silent option raise error
  # since those are mostly used by external tools.
  rejected = args.reject! { |a| %w(-s --silent).include?(a) }
  if rejected
    warn '-s/--silent options is dropped. ' +
         '`emacs` and `files` formatters no longer display summary.'
  end
end

#inspect_file(file) ⇒ Object



84
85
86
87
88
89
90
# File 'lib/rubocop/cli.rb', line 84

def inspect_file(file)
  config = @config_store.for(file)
  team = Cop::Team.new(mobilized_cop_classes, config, @options)
  offences = team.inspect_file(file)
  @errors.concat(team.errors)
  offences
end

#mobilized_cop_classesObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/rubocop/cli.rb', line 66

def mobilized_cop_classes
  @mobilized_cop_classes ||= begin
    cop_classes = Cop::Cop.all

    if @options[:only]
      cop_classes.select! { |c| c.cop_name == @options[:only] }
    else
      # filter out Rails cops unless requested
      cop_classes.reject!(&:rails?) unless @options[:rails]

      # filter out style cops when --lint is passed
      cop_classes.select!(&:lint?) if @options[:lint]
    end

    cop_classes
  end
end

#parse_options(args) ⇒ Object

rubocop:disable MethodLength



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rubocop/cli.rb', line 135

def parse_options(args)
  ignore_dropped_options(args)
  convert_deprecated_options(args)

  OptionParser.new do |opts|
    opts.banner = 'Usage: rubocop [options] [file1, file2, ...]'

    opts.on('-d', '--debug', 'Display debug info.') do |d|
      @options[:debug] = d
    end
    opts.on('-c', '--config FILE', 'Specify configuration file.') do |f|
      @options[:config] = f
      @config_store.set_options_config(@options[:config])
    end
    opts.on('--only COP', 'Run just one cop.') do |s|
      @options[:only] = s
      validate_only_option
    end
    opts.on('--auto-gen-config',
            'Generate a configuration file acting as a',
            'TODO list.') do
      @options[:auto_gen_config] = true
      @options[:formatters] = [
        [DEFAULT_FORMATTER],
        [Formatter::DisabledConfigFormatter, Config::AUTO_GENERATED_FILE]
      ]
      validate_auto_gen_config_option(args)
    end
    opts.on('--show-cops',
            'Shows cops and their config for the',
            'current directory.') do
      print_available_cops
      exit(0)
    end
    opts.on('-f', '--format FORMATTER',
            'Choose an output formatter. This option',
            'can be specified multiple times to enable',
            'multiple formatters at the same time.',
            '  [p]rogress (default)',
            '  [s]imple',
            '  [c]lang',
            '  [e]macs',
            '  [j]son',
            '  [f]iles',
            '  [o]ffences',
            '  custom formatter class name') do |key|
      @options[:formatters] ||= []
      @options[:formatters] << [key]
    end
    opts.on('-o', '--out FILE',
            'Write output to a file instead of STDOUT.',
            'This option applies to the previously',
            'specified --format, or the default format',
            'if no format is specified.') do |path|
      @options[:formatters] ||= [[DEFAULT_FORMATTER]]
      @options[:formatters].last << path
    end
    opts.on('-r', '--require FILE', 'Require Ruby file.') do |f|
      require f
    end
    opts.on('-R', '--rails', 'Run extra Rails cops.') do |r|
      @options[:rails] = r
    end
    opts.on('-l', '--lint', 'Run only lint cops.') do |l|
      @options[:lint] = l
    end
    opts.on('-a', '--auto-correct', 'Auto-correct offences.') do |a|
      @options[:autocorrect] = a
    end
    opts.on('-n', '--no-color', 'Disable color output.') do |s|
      Sickill::Rainbow.enabled = false
    end
    opts.on('-v', '--version', 'Display version.') do
      puts Rubocop::Version.version(false)
      exit(0)
    end
    opts.on('-V', '--verbose-version', 'Display verbose version.') do
      puts Rubocop::Version.version(true)
      exit(0)
    end
  end.parse!(args)
end


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/rubocop/cli.rb', line 113

def print_available_cops
  cops = Cop::Cop.all
  puts "Available cops (#{cops.length}) + config for #{Dir.pwd.to_s}: "
  dirconf = @config_store.for(Dir.pwd.to_s)
  cops.types.sort!.each do |type|
    coptypes = cops.with_type(type).sort_by!(&:cop_name)
    puts "Type '#{type.to_s.capitalize}' (#{coptypes.size}):"
    coptypes.each do |cop|
      puts " - #{cop.cop_name}"
      cnf = dirconf.for_cop(cop).dup
      print_conf_option('Description',
                        cnf.delete('Description') { 'None' })
      cnf.each { |k, v| print_conf_option(k, v) }
    end
  end
end


130
131
132
# File 'lib/rubocop/cli.rb', line 130

def print_conf_option(option, value)
  puts  "    - #{option}: #{value}"
end

#run(args = ARGV) ⇒ Fixnum

Entry point for the application logic. Here we do the command line arguments processing and inspect the target files

Returns:

  • (Fixnum)

    UNIX exit code



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
# File 'lib/rubocop/cli.rb', line 28

def run(args = ARGV)
  trap_interrupt

  parse_options(args)

  Config.debug = @options[:debug]

  target_files = target_finder.find(args)
  target_files.each(&:freeze).freeze
  inspected_files = []
  any_failed = false

  formatter_set.started(target_files)

  target_files.each do |file|
    break if wants_to_quit?

    puts "Scanning #{file}" if @options[:debug]
    formatter_set.file_started(file, {})

    offences = inspect_file(file)

    any_failed = true unless offences.empty?
    inspected_files << file
    formatter_set.file_finished(file, offences.freeze)
  end

  formatter_set.finished(inspected_files.freeze)
  formatter_set.close_output_files

  display_error_summary(@errors)

  !any_failed && !wants_to_quit ? 0 : 1
rescue => e
  $stderr.puts e.message
  return 1
end

#trap_interruptObject



241
242
243
244
245
246
247
248
# File 'lib/rubocop/cli.rb', line 241

def trap_interrupt
  Signal.trap('INT') do
    exit!(1) if wants_to_quit?
    self.wants_to_quit = true
    $stderr.puts
    $stderr.puts 'Exiting... Interrupt again to exit immediately.'
  end
end

#validate_auto_gen_config_option(args) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rubocop/cli.rb', line 98

def validate_auto_gen_config_option(args)
  if args.any?
    fail ArgumentError,
         '--auto-gen-config can not be combined with any other arguments.'
  end

  target_finder.find(args).each do |file|
    config = @config_store.for(file)
    if @options[:auto_gen_config] && config.contains_auto_generated_config
      fail "Remove #{Config::AUTO_GENERATED_FILE} from the current " +
        'configuration before generating it again.'
    end
  end
end

#validate_only_optionObject



92
93
94
95
96
# File 'lib/rubocop/cli.rb', line 92

def validate_only_option
  if Cop::Cop.all.none? { |c| c.cop_name == @options[:only] }
    fail ArgumentError, "Unrecognized cop name: #{@options[:only]}."
  end
end