Class: Rubocop::TargetFinder

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

Overview

This class finds target files to inspect by scanning directory tree and picking ruby files.

Instance Method Summary collapse

Constructor Details

#initialize(config_store, debug = false) ⇒ TargetFinder

Returns a new instance of TargetFinder.



7
8
9
10
# File 'lib/rubocop/target_finder.rb', line 7

def initialize(config_store, debug = false)
  @config_store = config_store
  @debug = debug
end

Instance Method Details

#find(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 file paths



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubocop/target_finder.rb', line 16

def find(args)
  return target_files_in_dir if args.empty?

  files = []

  args.uniq.each do |arg|
    if File.directory?(arg)
      files += target_files_in_dir(arg.chomp(File::SEPARATOR))
    elsif arg.include?('*')
      files += Dir[arg]
    else
      files << arg
    end
  end

  files.map { |f| File.expand_path(f) }.uniq
end

#ruby_executable?(file) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
60
61
62
63
64
# File 'lib/rubocop/target_finder.rb', line 57

def ruby_executable?(file)
  return false unless File.extname(file).empty?
  first_line = File.open(file) { |f| f.readline }
  first_line =~ /#!.*ruby/
rescue EOFError, ArgumentError => e
  warn "Unprocessable file #{file}: #{e.class}, #{e.message}" if @debug
  false
end

#target_files_in_dir(base_dir = 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. It is possible to specify includes and excludes using the config file, so you can include other Ruby files like Rakefiles and gemspecs.

Parameters:

  • base_dir (defaults to: Dir.pwd)

    Root directory under which to search for ruby source files

Returns:

  • (Array)

    Array of filenames



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/target_finder.rb', line 43

def target_files_in_dir(base_dir = Dir.pwd)
  files = Dir["#{base_dir}/**/*"].select { |path| FileTest.file?(path) }

  target_files = files.select do |file|
    config = @config_store.for(file)
    next false if config.file_to_exclude?(file)
    next true if File.extname(file) == '.rb'
    next true if ruby_executable?(file)
    config.file_to_include?(file)
  end

  target_files.uniq
end