lib/eco/scripting/arguments.rb in eco-helpers-0.7.1 vs lib/eco/scripting/arguments.rb in eco-helpers-0.7.2
- old
+ new
@@ -1,40 +1,68 @@
module Eco
class Scripting
- module Lib
- def is_modifier?(value)
- value&.start_with?("-")
+ class Arguments
+ include Enumerable
+
+ attr_reader :args
+
+ def initialize(args = ARGV)
+ @args = args
+ @known = {}
end
- def get_arg(key, with_param: false, valid: true)
- return nil if !ARGV.include?(key)
- value = true
- if with_param
- next_i = ARGV.index(key) + 1
- value = ARGV[next_i]
- #puts "modifier argument: #{value}"
- value = nil if valid && is_modifier?(value)
- end
- return value
+ def each(params: {}, &block)
+ return to_enum(:each) unless block
+ @known.values.each(&block)
end
- def get_file(key, required: false, should_exist: true)
- filename = get_arg(key, with_param: true)
- if !filename
- if required
- puts "you need to specify a file '#{key} file'"
- exit
- end
- elsif !(File.exists?(filename) || File.exists?(File.expand_path(filename)))
- if should_exist && required
- puts "file doesn't exist #{filename}"
- exit
- end
+ def add(key, with_param: false)
+ self << Argument.new(key, with_param: with_param)
+ end
+
+ def <<(arg)
+ raise "Expected Argument. Given #{arg.class}" unless arg.is_a?(Argument)
+ if karg = @known[arg.key]
+ #puts "Found already existent option #{arg.key} (with_param: arg.with_param?)"
+ karg.with_param! if arg.with_param?
+ else
+ #puts "Adding unexistent option #{arg.key}"
+ @known[arg.key] = arg
end
+ self
+ end
- filename = File.expand_path(filename) if filename && should_exist
- filename
+ def known?(value)
+ @known.key?(to_key(value))
end
-
+
+ def keys
+ @known.keys
+ end
+
+ def unknown(exclude: [])
+ reduce(args.dup - exclude) do |not_known, arg|
+ arg.args_slice(*not_known)
+ end
+ end
+
+ def any_unkown?(exclude: [])
+ unknown(exclude: exclude).length > 0
+ end
+
+ private
+
+ def to_key(value)
+ case value
+ when String
+ value
+ when Argument
+ value.key
+ else
+ "Missuse: only able to transform to key a String or an Argument. Given #{value.class}"
+ end
+ end
+
+
end
end
end