Skip to content

Commit

Permalink
Fix #205: Handle optparse errors gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
avdv committed Aug 20, 2018
1 parent f78c561 commit 126d8ba
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/colorls/flags.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ def add_general_options(options)
options.on('--hyperlink') { @opts[:hyperlink] = true }
end

def add_help_option(opts)
opts.separator ''
opts.on_tail('-h', '--help', 'prints this help') do
puts @parser
show_examples
exit
end
end

def show_examples
puts <<EXAMPLES.gsub(/^ /, '')
Expand Down Expand Up @@ -146,13 +155,8 @@ def parse_options
add_common_options(opts)
add_sort_options(opts)
add_general_options(opts)
add_help_option(opts)

opts.separator ''
opts.on_tail('-h', '--help', 'prints this help') do
puts @parser
show_examples
exit
end
opts.on_tail('--version', 'show version') do
puts ColorLS::VERSION
exit
Expand All @@ -162,6 +166,9 @@ def parse_options
@parser.parse!(@args)

set_color_opts
rescue OptionParser::ParseError => e
warn "colorls: #{e}\nSee 'colorls --help'."
exit 2
end

def set_color_opts
Expand Down
12 changes: 12 additions & 0 deletions spec/color_ls/flags_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,16 @@ def capture_stdout

it { is_expected.to match(/yaml_sort_checker.rb/) }
end

context 'when passing invalid flags' do
let(:args) { ['--snafu'] }

it 'should issue a warning, hint about `--help` and exit' do
allow(::Kernel).to receive(:warn) do |message|
expect(message).to match "--snafu"
end

expect { subject }.to raise_error(SystemExit).and output(/--help/).to_stderr
end
end
end

0 comments on commit 126d8ba

Please # to comment.