lib/eco/cli/scripting/args_helpers.rb in eco-helpers-2.0.16 vs lib/eco/cli/scripting/args_helpers.rb in eco-helpers-2.0.17

- old
+ new

@@ -1,51 +1,78 @@ module Eco class CLI class Scripting module ArgsHelpers + # @return [Array<String] the command line arguments. def argv @argv || ARGV end def is_modifier?(value) Argument.is_modifier?(value) end + # @return [Arguments] supported known arguments. def arguments @arguments ||= Arguments.new(argv) end + # Registers an argument as a known one. + def known_argument(key, with_param: false) + arguments.add(key, with_param: with_param) + end + + + # Validation to stop the `script` if among `argv` there's any **unknown** argument. def stop_on_unknown!(exclude: [], only_options: false) # validate only those that are options unknown = arguments.unknown(exclude: exclude) if only_options unknown = unknown..select {|arg| is_modifier?(arg)} end unless unknown.empty? - raise "There are unknown options in your command line arguments: #{unknown}" + msg = "There are unknown options in your command line arguments:\n" + msg += "#{unknown}\n" + msg += "Please, remember that use case specific options should come after the use case in the command line.\n" + msg += "Use 'ruby main.rb -org [-usecase] --help -options' for more information" + raise msg end end + # @return [Boolean] if `key` is in the command line. + def arg?(key) + argv.include?(key) + end + + # @return [Integer, nil] the position of `key` in the command line. def get_arg_index(key) - return nil if !argv.include?(key) + return nil if !arg?(key) argv.index(key) end + # @return [Boolean] if `key1` precedes `key2` in the command line. + def arg_order?(key1, key2) + return false unless (k1 = get_arg_index(key1)) && k2 = get_arg_index(key2) + k1 < k2 + end + + # @return [String, Boolean] the argument value if `with_param` or a `Boolean` if not. def get_arg(key, with_param: false, valid: true) # track what a known option looks like - arguments.add(key, with_param: with_param) + known_argument(key, with_param: with_param) return nil unless index = get_arg_index(key) value = true if with_param value = argv[index + 1] #puts "modifier argument: #{value}" value = nil if valid && is_modifier?(value) end return value end + # @return [String] the filename. def get_file(key, required: false, should_exist: true) filename = get_arg(key, with_param: true) if !filename && required puts "You need to specify a file '#{key} file'" exit(1)