From 2e3f3d030945b661fa78e254762dc33825593c32 Mon Sep 17 00:00:00 2001 From: William Woodruff Date: Fri, 29 Sep 2017 18:31:28 -0400 Subject: [PATCH] Support for required options This commit introduces support for required options, which are options that cause the parser to raise a `MissingRequiredOption` exception if not present. Options can be marked as required by passing `required: true` in their configuration, and any errors caused by missing required options can be suppressed via `suppress_errors: true`. --- lib/slop/error.rb | 5 +++++ lib/slop/option.rb | 1 + lib/slop/parser.rb | 7 +++++++ test/error_test.rb | 14 ++++++++++++++ 4 files changed, 27 insertions(+) diff --git a/lib/slop/error.rb b/lib/slop/error.rb index b02de3b8..e0246458 100644 --- a/lib/slop/error.rb +++ b/lib/slop/error.rb @@ -32,4 +32,9 @@ def initialize(msg, flag) @flag = flag end end + + # Raised when a required option is *not* parsed. + # Suppress with the `suppress_errors` config option. + class MissingRequiredOption < Error + end end diff --git a/lib/slop/option.rb b/lib/slop/option.rb index b8533aeb..b2e5f9b0 100644 --- a/lib/slop/option.rb +++ b/lib/slop/option.rb @@ -4,6 +4,7 @@ class Option help: true, tail: false, underscore_flags: true, + required: false, } # An Array of flags this option matches. diff --git a/lib/slop/parser.rb b/lib/slop/parser.rb index 3cba82b7..32cf3d8a 100644 --- a/lib/slop/parser.rb +++ b/lib/slop/parser.rb @@ -80,6 +80,13 @@ def parse(strings) @arguments += ignored_args + unused_options.each do |o| + if o.config[:required] && !suppress_errors? + pretty_flags = o.flags.map { |f| "`#{f}'" }.join(", ") + raise MissingRequiredOption, "missing required option #{pretty_flags}" + end + end + Result.new(self).tap do |result| used_options.each { |o| o.finish(result) } end diff --git a/test/error_test.rb b/test/error_test.rb index 2f7730b6..d9c71ab7 100644 --- a/test/error_test.rb +++ b/test/error_test.rb @@ -49,3 +49,17 @@ opts.parse %w(--foo) end end + +describe Slop::MissingRequiredOption do + it "raises when a required option is missing" do + opts = Slop::Options.new + opts.string "-n", "--name", required: true + assert_raises(Slop::MissingRequiredOption) { opts.parse [] } + end + + it "does not raise when errors are suppressed" do + opts = Slop::Options.new(suppress_errors: true) + opts.string "-n", "--name", required: true + opts.parse [] + end +end