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.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.rip_source(source) ⇒ Object



96
97
98
99
100
101
102
# File 'lib/rubocop/cli.rb', line 96

def self.rip_source(source)
  tokens = Ripper.lex(source.join("\n")).map { |t| Cop::Token.new(*t) }
  sexp = Ripper.sexp(source.join("\n"))
  Cop::Position.make_position_objects(sexp)
  correlations = Cop::Grammar.new(tokens).correlate(sexp)
  [tokens, sexp, correlations]
end

Instance Method Details

#config_from_dotfile(target_file_dir) ⇒ Object

Returns the configuration hash from .rubocop.yml searching upwards in the directory structure starting at the given directory where the inspected file is. If no .rubocop.yml is found there, the user’s home directory is checked.



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

def config_from_dotfile(target_file_dir)
  return unless target_file_dir
  # @configs is a cache that maps directories to
  # configurations. We search for .rubocop.yml only if we haven't
  # already found it for the given directory.
  unless @configs[target_file_dir]
    dir = target_file_dir
    while dir != '/'
      path = File.join(dir, '.rubocop.yml')
      if File.exist?(path)
        @configs[target_file_dir] = YAML.load_file(path)
        break
      end
      dir = File.expand_path('..', dir)
    end
    path = File.join(Dir.home, '.rubocop.yml')
    @configs[target_file_dir] = YAML.load_file(path) if File.exist?(path)
  end
  @configs[target_file_dir]
end

#cops_on_duty(config) ⇒ Object



129
130
131
132
133
134
135
136
137
138
# File 'lib/rubocop/cli.rb', line 129

def cops_on_duty(config)
  cops_on_duty = []

  Cop::Cop.all.each do |cop_klass|
    cop_config = config[cop_klass.name.split('::').last] if config
    cops_on_duty << cop_klass if cop_config.nil? || cop_config['Enabled']
  end

  cops_on_duty
end

#get_rid_of_invalid_byte_sequences(line) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/rubocop/cli.rb', line 88

def get_rid_of_invalid_byte_sequences(line)
  enc = line.encoding.name
  # UTF-16 works better in this algorithm but is not supported in 1.9.2.
  temporary_encoding = (RUBY_VERSION == '1.9.2') ? 'UTF-8' : 'UTF-16'
  line.encode!(temporary_encoding, enc, invalid: :replace, replace: '')
  line.encode!(enc, temporary_encoding)
end

#ruby_files(root = Dir.pwd) ⇒ Array

Finds all Ruby source files under the current or other supplied directory. A Ruby source file is defined as a file with the ‘.rb` extension or a file with no extension that has a ruby shebang line as its first line.

Parameters:

  • root (defaults to: Dir.pwd)

    Root directory under which to search for ruby source files

Returns:

  • (Array)

    Array of filenames



174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/rubocop/cli.rb', line 174

def ruby_files(root = Dir.pwd)
  files = Dir["#{root}/**/*"].reject { |file| FileTest.directory? file }

  rb = []

  rb << files.select { |file| File.extname(file) == '.rb' }
  rb << files.select do |file|
    File.extname(file) == '' &&
    File.open(file) { |f| f.readline } =~ /#!.*ruby/
  end

  rb.flatten
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



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
82
83
84
85
86
# File 'lib/rubocop/cli.rb', line 15

def run(args = ARGV)
  $options = { mode: :default }

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

    opts.on('-d', '--[no-]debug', 'Display debug info') do |d|
      $options[:debug] = d
    end
    opts.on('-e', '--emacs', 'Emacs style output') do
      $options[:mode] = :emacs_style
    end
    opts.on('-c FILE', '--config FILE', 'Configuration file') do |f|
      $options[:config] = YAML.load_file(f)
    end
    opts.on('-s', '--silent', 'Silence summary') do |s|
      $options[:silent] = s
    end
    opts.on('-v', '--version', 'Display version') do
      puts Rubocop::VERSION
      exit(0)
    end
  end.parse!(args)

  cops = Cop::Cop.all
  show_cops_on_duty(cops) if $options[:debug]
  total_offences = 0
  @configs = {}

  target_files(args).each do |file|
    report = Report.create(file, $options[:mode])
    source = File.readlines(file).map do |line|
      get_rid_of_invalid_byte_sequences(line)
      line.chomp
    end

    syntax_cop = Rubocop::Cop::Syntax.new
    syntax_cop.inspect(file, source, nil, nil)

    if syntax_cop.offences.map(&:severity).include?(:error)
      # In case of a syntax error we just report that error and do
      # no more checking in the file.
      report << syntax_cop
      total_offences += syntax_cop.offences.count
    else
      tokens, sexp, correlations = CLI.rip_source(source)
      config = $options[:config] || config_from_dotfile(File.dirname(file))

      cops.each do |cop_klass|
        cop_config = config[cop_klass.name.split('::').last] if config
        if cop_config.nil? || cop_config['Enabled']
          cop_klass.config = cop_config
          cop = cop_klass.new
          cop.correlations = correlations
          cop.inspect(file, source, tokens, sexp)
          total_offences += cop.offences.count
          report << cop if cop.has_report?
        end
      end
    end

    report.display unless report.empty?
  end

  unless $options[:silent]
    print "\n#{target_files(args).count} files inspected, "
    puts "#{total_offences} offences detected"
      .send(total_offences.zero? ? :green : :red)
  end

  return total_offences == 0 ? 0 : 1
end

#show_cops_on_duty(cops) ⇒ Object



140
141
142
143
144
# File 'lib/rubocop/cli.rb', line 140

def show_cops_on_duty(cops)
  puts '== Reporting for duty =='
  cops.each { |c| puts ' * '.yellow + c.to_s.green }
  puts '========================'
end

#target_files(args) ⇒ Array

Generate a list of target files by expanding globing patterns (if any). If args is empty recursively finds all Ruby source files under the current directory

Returns:

  • (Array)

    array of filenames



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/rubocop/cli.rb', line 150

def target_files(args)
  return ruby_files if args.empty?

  files = []

  args.each do |target|
    if File.directory?(target)
      files << ruby_files(target)
    elsif target =~ /\*/
      files << Dir[target]
    else
      files << target
    end
  end

  files.flatten
end