Skip to content

Commit

Permalink
Refactor to replace Kernel.#exit with custom error (rubocop#5386)
Browse files Browse the repository at this point in the history
Handle exit status consistently in `RuboCop::CLI#run` method.
  • Loading branch information
ybiquitous authored and bbatsov committed Jan 4, 2018
1 parent 27af3c7 commit ccdee9e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
7 changes: 5 additions & 2 deletions lib/rubocop/cli.rb
Expand Up @@ -29,13 +29,16 @@ def initialize
# @param args [Array<String>] command line arguments
# @return [Integer] UNIX exit code
#
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def run(args = ARGV)
@options, paths = Options.new.parse(args)
validate_options_vs_config
act_on_options
apply_default_formatter
execute_runners(paths)
rescue RuboCop::ConfigNotFoundError => e
warn e.message
return e.status
rescue RuboCop::Error => e
warn Rainbow("Error: #{e.message}").red
return 2
Expand All @@ -49,7 +52,7 @@ def run(args = ARGV)
warn e.backtrace
return 2
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize

def trap_interrupt(runner)
Signal.trap('INT') do
Expand Down
15 changes: 12 additions & 3 deletions lib/rubocop/config_loader.rb
Expand Up @@ -4,6 +4,16 @@
require 'pathname'

module RuboCop
# Raised when a RuboCop configuration file is not found.
class ConfigNotFoundError < Error
attr_reader :status

def initialize(path, status)
super("Configuration file not found: #{path}")
@status = status
end
end

# This class represents the configuration of the RuboCop application
# and all its cops. A Config is associated with a YAML configuration
# file from which it was read. Several different Configs can be used
Expand Down Expand Up @@ -167,9 +177,8 @@ def load_yaml_configuration(absolute_path)
# found" error.
def read_file(absolute_path)
IO.read(absolute_path, encoding: Encoding::UTF_8)
rescue Errno::ENOENT
warn(format('Configuration file not found: %s', absolute_path))
exit(Errno::ENOENT::Errno)
rescue Errno::ENOENT => e
raise ConfigNotFoundError.new(absolute_path, e.errno)
end

def yaml_safe_load(yaml_code, filename)
Expand Down
9 changes: 4 additions & 5 deletions spec/rubocop/config_loader_spec.rb
Expand Up @@ -827,11 +827,10 @@ def cop_enabled?(cop_class)

it 'prints a friendly (concise) message to stderr and exits' do
expect { load_file }.to(
output(/Configuration file not found/).to_stderr.and(
raise_error(SystemExit) do |e|
expect(e.status).to(eq(Errno::ENOENT::Errno))
end
)
raise_error(RuboCop::ConfigNotFoundError) do |e|
expect(e.status).to(eq(Errno::ENOENT::Errno))
expect(e.message).to(match(/\AConfiguration file not found: .+\z/))
end
)
end
end
Expand Down

0 comments on commit ccdee9e

Please sign in to comment.