slop-3.4.7/0000755000004100000410000000000012253312312012524 5ustar www-datawww-dataslop-3.4.7/Rakefile0000644000004100000410000000110612253312312014167 0ustar www-datawww-databegin require 'bundler/gem_tasks' rescue LoadError end require 'rake/testtask' Rake::TestTask.new do |t| t.libs << 'test' t.test_files = Dir['test/*_test.rb'] end # begin # require 'rdoc/task' # # requires sdoc and horo gems # RDoc::Task.new do |rdoc| # rdoc.title = 'Slop API Documentation' # rdoc.rdoc_dir = 'doc' # rdoc.options << '-f' << 'sdoc' # rdoc.options << '-T' << 'rails' # rdoc.options << '-e' << 'UTF-8' # rdoc.options << '-g' # rdoc.rdoc_files.include('lib/**/*.rb') # end # rescue LoadError # end task :default => :test slop-3.4.7/Gemfile0000644000004100000410000000004612253312312014017 0ustar www-datawww-datasource "https://rubygems.org" gemspecslop-3.4.7/.travis.yml0000644000004100000410000000025012253312312014632 0ustar www-datawww-datarvm: - 1.8.7 - 1.9.2 - 1.9.3 - ruby-head - jruby-18mode - jruby-19mode - rbx-18mode notifications: email: on_success: change on_failure: always slop-3.4.7/lib/0000755000004100000410000000000012253312312013272 5ustar www-datawww-dataslop-3.4.7/lib/slop/0000755000004100000410000000000012253312312014247 5ustar www-datawww-dataslop-3.4.7/lib/slop/commands.rb0000644000004100000410000001266512253312312016407 0ustar www-datawww-dataclass Slop class Commands include Enumerable attr_reader :config, :commands, :arguments attr_writer :banner # Create a new instance of Slop::Commands and optionally build # Slop instances via a block. Any configuration options used in # this method will be the default configuration options sent to # each Slop object created. # # config - An optional configuration Hash. # block - Optional block used to define commands. # # Examples: # # commands = Slop::Commands.new do # on :new do # on '-o', '--outdir=', 'The output directory' # on '-v', '--verbose', 'Enable verbose mode' # end # # on :generate do # on '--assets', 'Generate assets', :default => true # end # # global do # on '-D', '--debug', 'Enable debug mode', :default => false # end # end # # commands[:new].class #=> Slop # commands.parse # def initialize(config = {}, &block) @config = config @commands = {} @banner = nil @triggered_command = nil warn "[DEPRECATED] Slop::Commands is deprecated and will be removed in "\ "Slop version 4. Check out http://leejarvis.github.io/slop/#commands for "\ "a new implementation of commands." if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end end # Optionally set the banner for this command help output. # # banner - The String text to set the banner. # # Returns the String banner if one is set. def banner(banner = nil) @banner = banner if banner @banner end # Add a Slop instance for a specific command. # # command - A String or Symbol key used to identify this command. # config - A Hash of configuration options to pass to Slop. # block - An optional block used to pass options to Slop. # # Returns the newly created Slop instance mapped to command. def on(command, config = {}, &block) commands[command.to_s] = Slop.new(@config.merge(config), &block) end # Add a Slop instance used when no other commands exist. # # config - A Hash of configuration options to pass to Slop. # block - An optional block used to pass options to Slop. # # Returns the newly created Slop instance mapped to default. def default(config = {}, &block) on('default', config, &block) end # Add a global Slop instance. # # config - A Hash of configuration options to pass to Slop. # block - An optional block used to pass options to Slop. # # Returns the newly created Slop instance mapped to global. def global(config = {}, &block) on('global', config, &block) end # Fetch the instance of Slop tied to a command. # # key - The String or Symbol key used to locate this command. # # Returns the Slop instance if this key is found, nil otherwise. def [](key) commands[key.to_s] end alias get [] # Check for a command presence. # # Examples: # # cmds.parse %w( foo ) # cmds.present?(:foo) #=> true # cmds.present?(:bar) #=> false # # Returns true if the given key is present in the parsed arguments. def present?(key) key.to_s == @triggered_command end # Enumerable interface. def each(&block) @commands.each(&block) end # Parse a list of items. # # items - The Array of items to parse. # # Returns the original Array of items. def parse(items = ARGV) parse! items.dup items end # Parse a list of items, removing any options or option arguments found. # # items - The Array of items to parse. # # Returns the original Array of items with options removed. def parse!(items = ARGV) if opts = commands[items[0].to_s] @triggered_command = items.shift execute_arguments! items opts.parse! items execute_global_opts! items else if opts = commands['default'] opts.parse! items else if config[:strict] && items[0] raise InvalidCommandError, "Unknown command `#{items[0]}`" end end execute_global_opts! items end items end # Returns a nested Hash with Slop options and values. See Slop#to_hash. def to_hash Hash[commands.map { |k, v| [k.to_sym, v.to_hash] }] end # Returns the help String. def to_s defaults = commands.delete('default') globals = commands.delete('global') helps = commands.reject { |_, v| v.options.none? } if globals && globals.options.any? helps.merge!('Global options' => globals.to_s) end if defaults && defaults.options.any? helps.merge!('Other options' => defaults.to_s) end banner = @banner ? "#{@banner}\n" : "" banner + helps.map { |key, opts| " #{key}\n#{opts}" }.join("\n\n") end alias help to_s # Returns the inspection String. def inspect "#" end private # Returns nothing. def execute_arguments!(items) @arguments = items.take_while { |arg| !arg.start_with?('-') } items.shift @arguments.size end # Returns nothing. def execute_global_opts!(items) if global_opts = commands['global'] global_opts.parse! items end end end end slop-3.4.7/lib/slop/option.rb0000644000004100000410000001350512253312312016110 0ustar www-datawww-dataclass Slop class Option # The default Hash of configuration options this class uses. DEFAULT_OPTIONS = { :argument => false, :optional_argument => false, :tail => false, :default => nil, :callback => nil, :delimiter => ',', :limit => 0, :match => nil, :optional => true, :required => false, :as => String, :autocreated => false } attr_reader :short, :long, :description, :config, :types attr_accessor :count, :argument_in_value # Incapsulate internal option information, mainly used to store # option specific configuration data, most of the meat of this # class is found in the #value method. # # slop - The instance of Slop tied to this Option. # short - The String or Symbol short flag. # long - The String or Symbol long flag. # description - The String description text. # config - A Hash of configuration options. # block - An optional block used as a callback. def initialize(slop, short, long, description, config = {}, &block) @slop = slop @short = short @long = long @description = description @config = DEFAULT_OPTIONS.merge(config) @count = 0 @callback = block_given? ? block : config[:callback] @value = nil @types = { :string => proc { |v| v.to_s }, :symbol => proc { |v| v.to_sym }, :integer => proc { |v| value_to_integer(v) }, :float => proc { |v| value_to_float(v) }, :range => proc { |v| value_to_range(v) }, :count => proc { |v| @count } } if long && long.size > @slop.config[:longest_flag] @slop.config[:longest_flag] = long.size end @config.each_key do |key| predicate = :"#{key}?" unless self.class.method_defined? predicate self.class.__send__(:define_method, predicate) { !!@config[key] } end end end # Returns true if this option expects an argument. def expects_argument? config[:argument] && config[:argument] != :optional end # Returns true if this option accepts an optional argument. def accepts_optional_argument? config[:optional_argument] || config[:argument] == :optional end # Returns the String flag of this option. Preferring the long flag. def key long || short end # Call this options callback if one exists, and it responds to call(). # # Returns nothing. def call(*objects) @callback.call(*objects) if @callback.respond_to?(:call) end # Set the new argument value for this option. # # We use this setter method to handle concatenating lists. That is, # when an array type is specified and used more than once, values from # both options will be grouped together and flattened into a single array. def value=(new_value) if config[:as].to_s.downcase == 'array' @value ||= [] if new_value.respond_to?(:split) @value.concat new_value.split(config[:delimiter], config[:limit]) end else @value = new_value end end # Fetch the argument value for this option. # # Returns the Object once any type conversions have taken place. def value value = @value.nil? ? config[:default] : @value if [true, false, nil].include?(value) && config[:as].to_s != 'count' return value end type = config[:as] if type.respond_to?(:call) type.call(value) else if callable = types[type.to_s.downcase.to_sym] callable.call(value) else value end end end # Returns the help String for this option. def to_s return config[:help] if config[:help].respond_to?(:to_str) out = " #{short ? "-#{short}, " : ' ' * 4}" if long out << "--#{long}" size = long.size diff = @slop.config[:longest_flag] - size out << (' ' * (diff + 6)) else out << (' ' * (@slop.config[:longest_flag] + 8)) end "#{out}#{description}" end alias help to_s # Returns the String inspection text. def inspect "# false, :help => false, :banner => nil, :ignore_case => false, :autocreate => false, :arguments => false, :optional_arguments => false, :multiple_switches => true, :longest_flag => 0 } class << self # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Examples: # # Slop.parse(ARGV, :help => true) do # on '-n', '--name', 'Your username', :argument => true # end # # Returns a new instance of Slop. def parse(items = ARGV, config = {}, &block) parse! items.dup, config, &block end # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Returns a new instance of Slop. def parse!(items = ARGV, config = {}, &block) config, items = items, ARGV if items.is_a?(Hash) && config.empty? slop = new config, &block slop.parse! items slop end # Build a Slop object from a option specification. # # This allows you to design your options via a simple String rather # than programatically. Do note though that with this method, you're # unable to pass any advanced options to the on() method when creating # options. # # string - The optspec String # config - A Hash of configuration options to pass to Slop.new # # Examples: # # opts = Slop.optspec(<<-SPEC) # ruby foo.rb [options] # --- # n,name= Your name # a,age= Your age # A,auth Sign in with auth # p,passcode= Your secret pass code # SPEC # # opts.fetch_option(:name).description #=> "Your name" # # Returns a new instance of Slop. def optspec(string, config = {}) warn "[DEPRECATED] `Slop.optspec` is deprecated and will be removed in version 4" config[:banner], optspec = string.split(/^--+$/, 2) if string[/^--+$/] lines = optspec.split("\n").reject(&:empty?) opts = Slop.new(config) lines.each do |line| opt, description = line.split(' ', 2) short, long = opt.split(',').map { |s| s.sub(/\A--?/, '') } opt = opts.on(short, long, description) if long && long.end_with?('=') long.sub!(/\=$/, '') opt.config[:argument] = true end end opts end end # The Hash of configuration options for this Slop instance. attr_reader :config # The Array of Slop::Option objects tied to this Slop instance. attr_reader :options # The Hash of sub-commands for this Slop instance. attr_reader :commands # Create a new instance of Slop and optionally build options via a block. # # config - A Hash of configuration options. # block - An optional block used to specify options. def initialize(config = {}, &block) @config = DEFAULT_OPTIONS.merge(config) @options = [] @commands = {} @trash = [] @triggered_options = [] @unknown_options = [] @callbacks = {} @separators = {} @runner = nil @command = config.delete(:command) if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end if config[:help] on('-h', '--help', 'Display this help message.', :tail => true) do puts help exit end end end # Is strict mode enabled? # # Returns true if strict mode is enabled, false otherwise. def strict? config[:strict] end # Set the banner. # # banner - The String to set the banner. def banner=(banner) config[:banner] = banner end # Get or set the banner. # # banner - The String to set the banner. # # Returns the banner String. def banner(banner = nil) config[:banner] = banner if banner config[:banner] end # Set the description (used for commands). # # desc - The String to set the description. def description=(desc) config[:description] = desc end # Get or set the description (used for commands). # # desc - The String to set the description. # # Returns the description String. def description(desc = nil) config[:description] = desc if desc config[:description] end # Add a new command. # # command - The Symbol or String used to identify this command. # options - A Hash of configuration options (see Slop::new) # # Returns a new instance of Slop mapped to this command. def command(command, options = {}, &block) options = @config.merge(options) @commands[command.to_s] = Slop.new(options.merge(:command => command.to_s), &block) end # Parse a list of items, executing and gathering options along the way. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items. def parse(items = ARGV, &block) parse! items.dup, &block items end # Parse a list of items, executing and gathering options along the way. # unlike parse() this method will remove any options and option arguments # from the original Array. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items with options removed. def parse!(items = ARGV, &block) if items.empty? && @callbacks[:empty] @callbacks[:empty].each { |cb| cb.call(self) } return items end # reset the trash so it doesn't carry over if you parse multiple # times with the same instance @trash.clear if cmd = @commands[items[0]] items.shift return cmd.parse! items end items.each_with_index do |item, index| @trash << index && break if item == '--' autocreate(items, index) if config[:autocreate] process_item(items, index, &block) unless @trash.include?(index) end items.reject!.with_index { |item, index| @trash.include?(index) } missing_options = options.select { |opt| opt.required? && opt.count < 1 } if missing_options.any? raise MissingOptionError, "Missing required option(s): #{missing_options.map(&:key).join(', ')}" end if @unknown_options.any? raise InvalidOptionError, "Unknown options #{@unknown_options.join(', ')}" end if @triggered_options.empty? && @callbacks[:no_options] @callbacks[:no_options].each { |cb| cb.call(self) } end if @runner.respond_to?(:call) @runner.call(self, items) unless config[:help] and present?(:help) end items end # Add an Option. # # objects - An Array with an optional Hash as the last element. # # Examples: # # on '-u', '--username=', 'Your username' # on :v, :verbose, 'Enable verbose mode' # # Returns the created instance of Slop::Option. def on(*objects, &block) option = build_option(objects, &block) original = options.find do |o| o.long and o.long == option.long or o.short and o.short == option.short end options.delete(original) if original options << option option end alias option on alias opt on # Fetch an options argument value. # # key - The Symbol or String option short or long flag. # # Returns the Object value for this option, or nil. def [](key) option = fetch_option(key) option.value if option end alias get [] # Returns a new Hash with option flags as keys and option values as values. # # include_commands - If true, merge options from all sub-commands. def to_hash(include_commands = false) hash = Hash[options.map { |opt| [opt.key.to_sym, opt.value] }] if include_commands @commands.each { |cmd, opts| hash.merge!(cmd.to_sym => opts.to_hash) } end hash end alias to_h to_hash # Enumerable interface. Yields each Slop::Option. def each(&block) options.each(&block) end # Specify code to be executed when these options are parsed. # # callable - An object responding to a call method. # # yields - The instance of Slop parsing these options # An Array of unparsed arguments # # Example: # # Slop.parse do # on :v, :verbose # # run do |opts, args| # puts "Arguments: #{args.inspect}" if opts.verbose? # end # end def run(callable = nil, &block) @runner = callable || block unless @runner.respond_to?(:call) raise ArgumentError, "You must specify a callable object or a block to #run" end end # Check for an options presence. # # Examples: # # opts.parse %w( --foo ) # opts.present?(:foo) #=> true # opts.present?(:bar) #=> false # # Returns true if all of the keys are present in the parsed arguments. def present?(*keys) keys.all? { |key| (opt = fetch_option(key)) && opt.count > 0 } end # Override this method so we can check if an option? method exists. # # Returns true if this option key exists in our list of options. def respond_to_missing?(method_name, include_private = false) options.any? { |o| o.key == method_name.to_s.chop } || super end # Fetch a list of options which were missing from the parsed list. # # Examples: # # opts = Slop.new do # on :n, :name= # on :p, :password= # end # # opts.parse %w[ --name Lee ] # opts.missing #=> ['password'] # # Returns an Array of Strings representing missing options. def missing (options - @triggered_options).map(&:key) end # Fetch a Slop::Option object. # # key - The Symbol or String option key. # # Examples: # # opts.on(:foo, 'Something fooey', :argument => :optional) # opt = opts.fetch_option(:foo) # opt.class #=> Slop::Option # opt.accepts_optional_argument? #=> true # # Returns an Option or nil if none were found. def fetch_option(key) options.find { |option| [option.long, option.short].include?(clean(key)) } end # Fetch a Slop object associated with this command. # # command - The String or Symbol name of the command. # # Examples: # # opts.command :foo do # on :v, :verbose, 'Enable verbose mode' # end # # # ruby run.rb foo -v # opts.fetch_command(:foo).verbose? #=> true def fetch_command(command) @commands[command.to_s] end # Add a callback. # # label - The Symbol identifier to attach this callback. # # Returns nothing. def add_callback(label, &block) (@callbacks[label] ||= []) << block end # Add string separators between options. # # text - The String text to print. def separator(text) if @separators[options.size] @separators[options.size] << "\n#{text}" else @separators[options.size] = text end end # Print a handy Slop help string. # # Returns the banner followed by available option help strings. def to_s heads = options.reject(&:tail?) tails = (options - heads) opts = (heads + tails).select(&:help).map(&:to_s) optstr = opts.each_with_index.map { |o, i| (str = @separators[i + 1]) ? [o, str].join("\n") : o }.join("\n") if @commands.any? optstr << "\n" if !optstr.empty? optstr << "\nAvailable commands:\n\n" optstr << commands_to_help optstr << "\n\nSee ` --help` for more information on a specific command." end banner = config[:banner] if banner.nil? banner = "Usage: #{File.basename($0, '.*')}" banner << " #{@command}" if @command banner << " [command]" if @commands.any? banner << " [options]" end if banner "#{banner}\n#{@separators[0] ? "#{@separators[0]}\n" : ''}#{optstr}" else optstr end end alias help to_s private # Convenience method for present?(:option). # # Examples: # # opts.parse %( --verbose ) # opts.verbose? #=> true # opts.other? #=> false # # Returns true if this option is present. If this method does not end # with a ? character it will instead call super(). def method_missing(method, *args, &block) meth = method.to_s if meth.end_with?('?') meth.chop! present?(meth) || present?(meth.gsub('_', '-')) else super end end # Process a list item, figure out if it's an option, execute any # callbacks, assign any option arguments, and do some sanity checks. # # items - The Array of items to process. # index - The current Integer index of the item we want to process. # block - An optional block which when passed will yield non options. # # Returns nothing. def process_item(items, index, &block) return unless item = items[index] option, argument = extract_option(item) if item.start_with?('-') if option option.count += 1 unless item.start_with?('--no-') option.count += 1 if option.key[0, 3] == "no-" @trash << index @triggered_options << option if option.expects_argument? argument ||= items.at(index + 1) if !argument || argument =~ /\A--?[a-zA-Z][a-zA-Z0-9_-]*\z/ raise MissingArgumentError, "#{option.key} expects an argument" end execute_option(option, argument, index, item) elsif option.accepts_optional_argument? argument ||= items.at(index + 1) if argument && argument =~ /\A([^\-?]|-\d)+/ execute_option(option, argument, index, item) else option.call(nil) end elsif config[:multiple_switches] && argument execute_multiple_switches(option, argument, items, index) else option.value = option.count > 0 option.call(nil) end else @unknown_options << item if strict? && item =~ /\A--?/ block.call(item) if block && !@trash.include?(index) end end # Execute an option, firing off callbacks and assigning arguments. # # option - The Slop::Option object found by #process_item. # argument - The argument Object to assign to this option. # index - The current Integer index of the object we're processing. # item - The optional String item we're processing. # # Returns nothing. def execute_option(option, argument, index, item = nil) if !option if config[:multiple_switches] && strict? raise InvalidOptionError, "Unknown option -#{item}" end return end if argument unless item && item.end_with?("=#{argument}") @trash << index + 1 unless option.argument_in_value end option.value = argument else option.value = option.count > 0 end if option.match? && !argument.match(option.config[:match]) raise InvalidArgumentError, "#{argument} is an invalid argument" end option.call(option.value) end # Execute a `-abc` type option where a, b and c are all options. This # method is only executed if the multiple_switches argument is true. # # option - The first Option object. # argument - The argument to this option. (Split into multiple Options). # items - The Array of items currently being parsed. # index - The index of the current item being processed. # # Returns nothing. def execute_multiple_switches(option, argument, items, index) execute_option(option, nil, index) flags = argument.split('') flags.each do |key| if opt = fetch_option(key) opt.count += 1 if (opt.expects_argument? || opt.accepts_optional_argument?) && (flags[-1] == opt.key) && (val = items[index+1]) execute_option(opt, val, index, key) else execute_option(opt, nil, index, key) end else raise InvalidOptionError, "Unknown option -#{key}" if strict? end end end # Extract an option from a flag. # # flag - The flag key used to extract an option. # # Returns an Array of [option, argument]. def extract_option(flag) option = fetch_option(flag) option ||= fetch_option(flag.downcase) if config[:ignore_case] option ||= fetch_option(flag.gsub(/([^-])-/, '\1_')) unless option case flag when /\A--?([^=]+)=(.+)\z/, /\A-([a-zA-Z])(.+)\z/, /\A--no-(.+)\z/ option, argument = fetch_option($1), ($2 || false) option.argument_in_value = true if option end end [option, argument] end # Autocreate an option on the fly. See the :autocreate Slop config option. # # items - The Array of items we're parsing. # index - The current Integer index for the item we're processing. # # Returns nothing. def autocreate(items, index) flag = items[index] if !fetch_option(flag) && !@trash.include?(index) option = build_option(Array(flag)) argument = items[index + 1] option.config[:argument] = (argument && argument !~ /\A--?/) option.config[:autocreated] = true options << option end end # Build an option from a list of objects. # # objects - An Array of objects used to build this option. # # Returns a new instance of Slop::Option. def build_option(objects, &block) config = {} config[:argument] = true if @config[:arguments] config[:optional_argument] = true if @config[:optional_arguments] if objects.last.is_a?(Hash) config.merge!(objects.pop) end short = extract_short_flag(objects, config) long = extract_long_flag(objects, config) desc = objects.shift if objects[0].respond_to?(:to_str) Option.new(self, short, long, desc, config, &block) end def extract_short_flag(objects, config) flag = objects[0].to_s if flag =~ /\A-?\w=?\z/ config[:argument] ||= flag.end_with?('=') objects.shift flag.delete('-=') end end # Extract the long flag from an item. # # objects - The Array of objects passed from #build_option. # config - The Hash of configuration options built in #build_option. def extract_long_flag(objects, config) flag = objects.first.to_s if flag =~ /\A(?:--?)?[a-zA-Z0-9][a-zA-Z0-9_.-]+\=?\??\z/ config[:argument] ||= true if flag.end_with?('=') config[:optional_argument] = true if flag.end_with?('=?') objects.shift clean(flag).sub(/\=\??\z/, '') end end # Remove any leading -- characters from a string. # # object - The Object we want to cast to a String and clean. # # Returns the newly cleaned String with leading -- characters removed. def clean(object) object.to_s.sub(/\A--?/, '') end def commands_to_help padding = 0 @commands.each { |c, _| padding = c.size if c.size > padding } @commands.map do |cmd, opts| " #{cmd}#{' ' * (padding - cmd.size)} #{opts.description}" end.join("\n") end end slop-3.4.7/metadata.yml0000644000004100000410000000370112253312312015030 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: slop version: !ruby/object:Gem::Version version: 3.4.7 platform: ruby authors: - Lee Jarvis autorequire: bindir: bin cert_chain: [] date: 2013-11-14 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: minitest requirement: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 5.0.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 5.0.0 description: A simple DSL for gathering options and parsing the command line email: ljjarvis@gmail.com executables: [] extensions: [] extra_rdoc_files: [] files: - .gitignore - .travis.yml - CHANGES.md - Gemfile - LICENSE - README.md - Rakefile - lib/slop.rb - lib/slop/commands.rb - lib/slop/option.rb - slop.gemspec - test/commands_test.rb - test/helper.rb - test/option_test.rb - test/slop_test.rb homepage: http://github.com/leejarvis/slop licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: 1.8.7 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.0.2 signing_key: specification_version: 4 summary: Simple Lightweight Option Parsing test_files: - test/commands_test.rb - test/helper.rb - test/option_test.rb - test/slop_test.rb slop-3.4.7/slop.gemspec0000644000004100000410000000113312253312312015044 0ustar www-datawww-dataGem::Specification.new do |s| s.name = 'slop' s.version = '3.4.7' s.summary = 'Simple Lightweight Option Parsing' s.description = 'A simple DSL for gathering options and parsing the command line' s.author = 'Lee Jarvis' s.email = 'ljjarvis@gmail.com' s.homepage = 'http://github.com/leejarvis/slop' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- test/*`.split("\n") s.license = 'MIT' s.required_ruby_version = '>= 1.8.7' s.add_development_dependency 'rake' s.add_development_dependency 'minitest', '~> 5.0.0' end slop-3.4.7/test/0000755000004100000410000000000012253312312013503 5ustar www-datawww-dataslop-3.4.7/test/helper.rb0000644000004100000410000000033212253312312015305 0ustar www-datawww-data$VERBOSE = true require 'slop' require 'minitest/autorun' require 'stringio' class TestCase < Minitest::Test def self.test(name, &block) define_method("test_#{name.gsub(/\W/, '_')}", &block) if block end endslop-3.4.7/test/option_test.rb0000644000004100000410000001076212253312312016405 0ustar www-datawww-datarequire 'helper' class OptionTest < TestCase def option(*args, &block) Slop.new.on(*args, &block) end def option_with_argument(*args, &block) options = args.shift slop = Slop.new option = slop.opt(*args) slop.parse(options) slop.options.find {|opt| opt.key == option.key } end def option_value(*args, &block) option_with_argument(*args, &block).value end test "expects_argument?" do assert option(:f=).expects_argument? assert option(:foo=).expects_argument? assert option(:foo, :argument => true).expects_argument? end test "accepts_optional_argument?" do refute option(:f=).accepts_optional_argument? assert option(:f=, :argument => :optional).accepts_optional_argument? assert option(:f, :optional_argument => true).accepts_optional_argument? end test "key" do assert_equal 'foo', option(:foo).key assert_equal 'foo', option(:f, :foo).key assert_equal 'f', option(:f).key end test "call" do foo = nil option(:f, :callback => proc { foo = "bar" }).call assert_equal "bar", foo option(:f) { foo = "baz" }.call assert_equal "baz", foo option(:f) { |o| assert_equal 1, o }.call(1) end # type casting test "proc/custom type cast" do assert_equal 1, option_value(%w'-f 1', :f=, :as => proc {|x| x.to_i }) assert_equal "oof", option_value(%w'-f foo', :f=, :as => proc {|x| x.reverse }) end test "integer type cast" do opts = Slop.new opts.on :f=, :as => Integer opts.parse %w'-f 1' assert_equal 1, opts[:f] opts = Slop.new(:strict => true) { on :r=, :as => Integer } assert_raises(Slop::InvalidArgumentError) { opts.parse %w/-r abc/ } end test "float type cast" do opts = Slop.new(:strict => true) { on :r=, :as => Float } assert_raises(Slop::InvalidArgumentError) { opts.parse %w/-r abc/ } end test "symbol type cast" do assert_equal :foo, option_value(%w'-f foo', :f=, :as => Symbol) end test "range type cast" do assert_equal((1..10), option_value(%w/-r 1..10/, :r=, :as => Range)) assert_equal((1..10), option_value(%w/-r 1-10/, :r=, :as => Range)) assert_equal((1..10), option_value(%w/-r 1,10/, :r=, :as => Range)) assert_equal((1...10), option_value(%w/-r 1...10/, :r=, :as => Range)) assert_equal((-1..10), option_value(%w/-r -1..10/, :r=, :as => Range)) assert_equal((1..-10), option_value(%w/-r 1..-10/, :r=, :as => Range)) assert_equal((1..1), option_value(%w/-r 1/, :r=, :as => Range)) assert_equal((-1..10), option_value(%w/-r -1..10/, :r, :as => Range, :optional_argument => true)) opts = Slop.new(:strict => true) { on :r=, :as => Range } assert_raises(Slop::InvalidArgumentError) { opts.parse %w/-r abc/ } end test "array type cast" do assert_equal %w/lee john bill/, option_value(%w/-p lee,john,bill/, :p=, :as => Array) assert_equal %w/lee john bill jeff jill/, option_value(%w/-p lee,john,bill -p jeff,jill/, :p=, :as => Array) assert_equal %w/lee john bill/, option_value(%w/-p lee:john:bill/, :p=, :as => Array, :delimiter => ':') assert_equal %w/lee john,bill/, option_value(%w/-p lee,john,bill/, :p=, :as => Array, :limit => 2) assert_equal %w/lee john:bill/, option_value(%w/-p lee:john:bill/, :p=, :as => Array, :limit => 2, :delimiter => ':') end test "adding custom types" do opts = Slop.new opt = opts.on :f=, :as => :reverse opt.types[:reverse] = proc { |v| v.reverse } opts.parse %w'-f bar' assert_equal 'rab', opt.value end test "count type" do assert_equal 3, option_value(%w/-c -c -c/, :c, :as => :count) assert_equal 0, option_value(%w/-a -b -z/, :c, :as => :count) assert_equal 3, option_value(%w/-vvv/, :v, :as => :count) end # end type casting tests test "using a default value as fallback" do opts = Slop.new opts.on :f, :argument => :optional, :default => 'foo' opts.parse %w'-f' assert_equal 'foo', opts[:f] end test "printing options" do slop = Slop.new slop.opt :n, :name=, 'Your name' slop.opt :age=, 'Your age' slop.opt :V, 'Display the version' assert_equal " -n, --name Your name", slop.fetch_option(:name).to_s assert_equal " --age Your age", slop.fetch_option(:age).to_s assert_equal " -V, Display the version", slop.fetch_option(:V).help end test "overwriting the help text" do slop = Slop.new slop.on :foo, :help => ' -f, --foo SOMETHING FOOEY' assert_equal ' -f, --foo SOMETHING FOOEY', slop.fetch_option(:foo).help end end slop-3.4.7/test/commands_test.rb0000644000004100000410000000075412253312312016676 0ustar www-datawww-datarequire 'helper' class CommandsTest < TestCase def setup @opts = Slop.new do |o| o.on :v, :version o.command :add do |add| add.on :v, 'verbose mode' end end end test "parse! removes the command AND its options" do items = %w'add -v' @opts.parse! items assert_equal [], items end test "parse does not remove the command or its options" do items = %w'add -v' @opts.parse items assert_equal ['add', '-v'], items end end slop-3.4.7/test/slop_test.rb0000644000004100000410000003372012253312312016051 0ustar www-datawww-datarequire 'helper' class SlopTest < TestCase def build_option(*args) opt = Slop.new.send(:build_option, args) config = opt.config.reject { |k, v| v == Slop::Option::DEFAULT_OPTIONS[k] } [opt.short, opt.long, opt.description, config] end def temp_argv(items) old_argv = ARGV.clone ARGV.replace items yield ensure ARGV.replace old_argv end def temp_stdout $stdout = StringIO.new yield $stdout.string ensure $stdout = STDOUT end test "includes Enumerable" do assert_includes Slop.included_modules, Enumerable end test "enumerates Slop::Option objects in #each" do Slop.new { on :f; on :b; }.each { |o| assert_kind_of Slop::Option, o } end test "build_option" do assert_equal ['f', nil, nil, {}], build_option(:f) assert_equal [nil, 'foo', nil, {}], build_option(:foo) assert_equal ['f', nil, 'Some description', {}], build_option(:f, 'Some description') assert_equal ['f', 'foo', nil, {}], build_option(:f, :foo) assert_equal [nil, '1.8', 'Use v. 1.8', {}], build_option('--1.8', 'Use v. 1.8') # with arguments assert_equal ['f', nil, nil, {:argument=>true}], build_option('f=') assert_equal [nil, 'foo', nil, {:argument=>true}], build_option('foo=') assert_equal [nil, 'foo', nil, {:optional_argument=>true}], build_option('foo=?') end test "parsing option=value" do slop = Slop.new { on :foo= } slop.parse %w' --foo=bar ' assert_equal 'bar', slop[:foo] slop = Slop.new(:multiple_switches => false) { on :f=; on :b= } slop.parse %w' -fabc -bdef ' assert_equal 'abc', slop[:f] assert_equal 'def', slop[:b] end test "fetch_option" do slop = Slop.new opt1 = slop.on :f, :foo opt2 = slop.on :bar assert_equal opt1, slop.fetch_option(:foo) assert_equal opt1, slop.fetch_option(:f) assert_equal opt2, slop.fetch_option(:bar) assert_equal opt2, slop.fetch_option('--bar') assert_nil slop.fetch_option(:baz) end test "default all options to take arguments" do slop = Slop.new(:arguments => true) opt1 = slop.on :foo opt2 = slop.on :bar, :argument => false assert opt1.expects_argument? refute opt2.expects_argument? end test "extract_option" do slop = Slop.new extract = proc { |flag| slop.send(:extract_option, flag) } slop.on :opt= assert_kind_of Array, extract['--foo'] assert_equal 'bar', extract['--foo=bar'][1] assert_equal 'bar', extract['-f=bar'][1] assert_nil extract['--foo'][0] assert_kind_of Slop::Option, extract['--opt'][0] assert_equal false, extract['--no-opt'][1] end test "non-options yielded to parse()" do foo = nil slop = Slop.new slop.parse ['foo'] do |x| foo = x end assert_equal 'foo', foo end test "::parse returns a Slop object" do assert_kind_of Slop, Slop.parse([]) end test "parse" do slop = Slop.new assert_equal ['foo'], slop.parse(%w'foo') assert_equal ['foo'], slop.parse!(%w'foo') end test "parse!" do slop = Slop.new { on :foo= } assert_equal [], slop.parse!(%w'--foo bar') slop = Slop.new { on :baz } assert_equal ['etc'], slop.parse!(%w'--baz etc') end test "new() accepts a hash of configuration options" do slop = Slop.new(:foo => :bar) assert_equal :bar, slop.config[:foo] end test "defaulting to ARGV" do temp_argv(%w/--name lee/) do opts = Slop.parse { on :name= } assert_equal 'lee', opts[:name] end end test "automatically adding the help option" do slop = Slop.new :help => true refute_empty slop.options assert_equal 'Display this help message.', slop.options.first.description end test "default help exits" do temp_stdout do slop = Slop.new :help => true assert_raises SystemExit do slop.parse %w/--help/ end end end test ":arguments and :optional_arguments config options" do slop = Slop.new(:arguments => true) { on :foo } assert slop.fetch_option(:foo).expects_argument? slop = Slop.new(:optional_arguments => true) { on :foo } assert slop.fetch_option(:foo).accepts_optional_argument? end test "yielding non-options when a block is passed to parse()" do items = [] opts = Slop.new { on :name= } opts.parse(%w/--name lee a b c/) { |v| items << v } assert_equal ['a', 'b', 'c'], items end test "on empty callback" do opts = Slop.new foo = nil opts.add_callback(:empty) { foo = "bar" } opts.parse [] assert_equal "bar", foo end test "on no_options callback" do opts = Slop.new foo = nil opts.add_callback(:no_options) { foo = "bar" } opts.parse %w( --foo --bar etc hello ) assert_equal "bar", foo end test "to_hash()" do opts = Slop.new { on :foo=; on :bar; on :baz; on :zip } opts.parse(%w'--foo hello --no-bar --baz') assert_equal({ :foo => 'hello', :bar => false, :baz => true, :zip => nil }, opts.to_hash) end test "missing() returning all missing option keys" do opts = Slop.new { on :foo; on :bar } opts.parse %w'--foo' assert_equal ['bar'], opts.missing end test "autocreating options" do opts = Slop.new :autocreate => true opts.parse %w[ --foo bar --baz ] assert opts.fetch_option(:foo).expects_argument? assert opts.fetch_option(:foo).autocreated? assert_equal 'bar', opts.fetch_option(:foo).value refute opts.fetch_option(:baz).expects_argument? assert_equal nil, opts.fetch_option(:bar) opts = Slop.new :autocreate => true do on :f, :foo= end opts.parse %w[ --foo bar --baz stuff ] assert_equal 'bar', opts[:foo] assert_equal 'stuff', opts[:baz] end test "option terminator" do opts = Slop.new { on :foo= } items = %w' foo -- --foo bar ' opts.parse! items assert_equal %w' foo --foo bar ', items end test "raising an InvalidArgumentError when the argument doesn't match" do opts = Slop.new { on :foo=, :match => /^[a-z]+$/ } assert_raises(Slop::InvalidArgumentError) { opts.parse %w' --foo b4r '} end test "raising a MissingArgumentError when the option expects an argument" do opts = Slop.new { on :foo= } assert_raises(Slop::MissingArgumentError) { opts.parse %w' --foo '} end test "raising a MissingOptionError when a required option is missing" do opts = Slop.new { on :foo, :required => true } assert_raises(Slop::MissingOptionError) { opts.parse %w'' } end test "raising InvalidOptionError when strict mode is enabled and an unknown option appears" do opts = Slop.new :strict => true assert_raises(Slop::InvalidOptionError) { opts.parse %w'--foo' } assert_raises(Slop::InvalidOptionError) { opts.parse %w'-fabc' } end test "raising InvalidOptionError for multiple short options" do opts = Slop.new :strict => true opts.on :L assert_raises(Slop::InvalidOptionError) { opts.parse %w'-Ly' } # but not with no strict mode! opts = Slop.new opts.on :L assert opts.parse %w'-Ly' end test "multiple_switches is enabled by default" do opts = Slop.new { on :f; on :b } opts.parse %w[ -fb ] assert opts.present?(:f) assert opts.present?(:b) end test "multiple_switches disabled" do opts = Slop.new(:multiple_switches => false) { on :f= } opts.parse %w[ -fabc123 ] assert_equal 'abc123', opts[:f] end test "muiltiple_switches should not trash arguments" do opts = Slop.new{ on :f; on :b } args = opts.parse!(%w'-fb foo') assert_equal %w'foo', args end test "multiple options should still accept trailing arguments" do opts = Slop.new { on :a; on :b= } opts.parse %w'-ab foo' assert_equal 'foo', opts[:b] end test "setting/getting the banner" do opts = Slop.new :banner => 'foo' assert_equal 'foo', opts.banner opts = Slop.new opts.banner 'foo' assert_equal 'foo', opts.banner opts = Slop.new opts.banner = 'foo' assert_equal 'foo', opts.banner end test "get/[] fetching an options argument value" do opts = Slop.new { on :foo=; on :bar; on :baz } opts.parse %w' --foo hello --bar ' assert_equal 'hello', opts[:foo] assert_equal true, opts[:bar] assert_nil opts[:baz] end test "checking for an options presence" do opts = Slop.new { on :foo; on :bar } opts.parse %w' --foo ' assert opts.present?(:foo) refute opts.present?(:bar) end test "ignoring case" do opts = Slop.new { on :foo } opts.parse %w' --FOO bar ' assert_nil opts[:foo] opts = Slop.new(:ignore_case => true) { on :foo= } opts.parse %w' --FOO bar ' assert_equal 'bar', opts[:foo] end test "supporting dash" do opts = Slop.new { on :foo_bar= } opts.parse %w' --foo-bar baz ' assert_equal 'baz', opts[:foo_bar] assert opts.foo_bar? end test "supporting underscore" do opts = Slop.new { on :foo_bar= } opts.parse %w' --foo_bar baz ' assert_equal 'baz', opts[:foo_bar] assert opts.foo_bar? end # test "parsing an optspec and building options" do # optspec = <<-SPEC # ruby foo.rb [options] # -- # v,verbose enable verbose mode # q,quiet enable quiet mode # n,name= set your name # p,pass=? set your password # SPEC # opts = Slop.optspec(optspec.gsub(/^\s+/, '')) # opts.parse %w[ --verbose --name Lee ] # assert_equal 'Lee', opts[:name] # assert opts.present?(:verbose) # assert_equal 'enable quiet mode', opts.fetch_option(:quiet).description # assert opts.fetch_option(:pass).accepts_optional_argument? # end test "ensure negative integers are not processed as options" do items = %w(-1) Slop.parse!(items) assert_equal %w(-1), items end test "separators" do opts = Slop.new(:banner => false) do on :foo separator "hello" separator "world" on :bar end assert_equal " --foo \nhello\nworld\n --bar ", opts.help opts = Slop.new do banner "foo" separator "bar" end assert_equal "foo\nbar\n", opts.help end test "printing help with :help => true" do temp_stdout do |string| opts = Slop.new(:help => true, :banner => false) assert_raises SystemExit do opts.parse %w( --help ) end assert_equal " -h, --help Display this help message.\n", string end temp_stdout do |string| opts = Slop.new(:help => true) assert_raises SystemExit do opts.parse %w( --help ) end assert_equal "Usage: rake_test_loader [options]\n -h, --help Display this help message.\n", string end end test "fallback to substituting - for _ when using