From 126d8ba164b280f03599c03cc58bf73c6287036e Mon Sep 17 00:00:00 2001 From: Claudio Bley Date: Mon, 13 Aug 2018 23:20:53 +0200 Subject: [PATCH] Fix #205: Handle optparse errors gracefully --- lib/colorls/flags.rb | 19 +++++++++++++------ spec/color_ls/flags_spec.rb | 12 ++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/colorls/flags.rb b/lib/colorls/flags.rb index 696097ba..65b7c227 100644 --- a/lib/colorls/flags.rb +++ b/lib/colorls/flags.rb @@ -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 < e + warn "colorls: #{e}\nSee 'colorls --help'." + exit 2 end def set_color_opts diff --git a/spec/color_ls/flags_spec.rb b/spec/color_ls/flags_spec.rb index 5fc4d32b..404826ce 100644 --- a/spec/color_ls/flags_spec.rb +++ b/spec/color_ls/flags_spec.rb @@ -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