Class: PreCommit::Checks::Rubocop

Inherits:
Plugin
  • Object
show all
Defined in:
lib/plugins/pre_commit/checks/rubocop.rb

Constant Summary collapse

WHITELIST =
%w[
  \.gemspec \.jbuilder \.opal \.podspec \.rake \.rb config\.ru
  Berksfile Capfile Cheffile Gemfile Guardfile Podfile
  Rakefile Thorfile Vagabondfile Vagrantfile
]

Instance Attribute Summary

Attributes inherited from Plugin

#config, #pluginator

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Plugin

#initialize, #name

Constructor Details

This class inherits a constructor from PreCommit::Checks::Plugin

Class Method Details

.aliasesObject



14
15
16
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 14

def self.aliases
  [ :rubocop_all, :rubocop_new ]
end

.descriptionObject



63
64
65
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 63

def self.description
  "Runs rubocop to detect errors."
end

.excludesObject



18
19
20
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 18

def self.excludes
  [ :ruby_symbol_hashrocket ]
end

Instance Method Details

#alternate_config_fileObject



59
60
61
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 59

def alternate_config_file
  '.rubocop.yml'
end

#call(staged_files) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 22

def call(staged_files)
  require 'rubocop'
rescue LoadError => e
  $stderr.puts "Could not find rubocop: #{e}"
else
  staged_files = filter_staged_files(staged_files)
  return if staged_files.empty?

  args = config_file_flag + user_supplied_flags + ["--force-exclusion"] + staged_files

  success, captured = capture { ::RuboCop::CLI.new.run(args) == 0 }
  captured unless success
end

#captureObject



41
42
43
44
45
46
47
48
49
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 41

def capture
  $stdout, stdout = StringIO.new, $stdout
  $stderr, stderr = StringIO.new, $stderr
  result = yield
  [result, $stdout.string + $stderr.string]
ensure
  $stdout = stdout
  $stderr = stderr
end

#config_file_flagObject



51
52
53
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 51

def config_file_flag
  config_file ? ['-c', config_file] : []
end

#filter_staged_files(staged_files) ⇒ Object



36
37
38
39
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 36

def filter_staged_files(staged_files)
  expression = Regexp.new(WHITELIST.map { |i| i + "\\Z" }.join("|"))
  staged_files.grep(expression)
end

#user_supplied_flagsObject



55
56
57
# File 'lib/plugins/pre_commit/checks/rubocop.rb', line 55

def user_supplied_flags
  Array(config.get('rubocop.flags')).reject(&:empty?)
end