summaryrefslogtreecommitdiff
path: root/lib/slop.rb
blob: 658ef7aff8f650387281a18af669dd1dac502d3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
require 'slop/options'
require 'slop/option'

class Slop
  include Enumerable

  # Raised when an option expects an argument and none is given
  class MissingArgumentError < RuntimeError; end

  # Raised when an option specifies the `:match` attribute and this
  # options argument does not match this regexp
  class InvalidArgumentError < RuntimeError; end

  # Raised when the `:strict` option is enabled and an unknown
  # or unspecified option is used
  class InvalidOptionError < RuntimeError; end

  # @return [String] The current version string
  VERSION = '1.4.1'

  # Parses the items from a CLI format into a friendly object.
  #
  # @param [Array] items Items to parse into options.
  # @example Specifying three options to parse:
  #  opts = Slops.parse do
  #    on :v, :verbose, 'Enable verbose mode'
  #    on :n, :name,    'Your name'
  #    on :a, :age,     'Your age'
  #  end
  #  -------
  #  program.rb --verbose -n 'Emily' -a 25
  # @return [Slop] Returns an instance of Slop.
  def self.parse(items=ARGV, options={}, &block)
    initialize_and_parse(items, false, options, &block)
  end

  # Identical to {Slop.parse}, but removes parsed options from the original Array.
  #
  # @return [Slop] Returns an instance of Slop.
  def self.parse!(items=ARGV, options={}, &block)
    initialize_and_parse(items, true, options, &block)
  end

  # @return [Options]
  attr_reader :options

  # @return [Hash]
  attr_reader :commands

  attr_writer :banner
  attr_accessor :longest_flag

  # @param [Hash] options
  # @option opts [Boolean] :help Automatically add the `help` option
  # @option opts [Boolean] :strict Strict mode raises when a non listed
  #   option is found, false by default
  # @option opts [Boolean] :multiple_switches Allows `-abc` to be processed
  #   as the options 'a', 'b', 'c' and will force their argument values to
  #   true. By default Slop with parse this as 'a' with the argument 'bc'
  def initialize(*opts, &block)
    sloptions = {}
    sloptions.merge! opts.pop if opts.last.is_a? Hash
    @banner = opts.shift if opts[0].respond_to?(:to_str)
    opts.each { |o| sloptions[o] = true }

    @options = Options.new
    @commands = {}
    @longest_flag = 0
    @strict = sloptions[:strict]
    @invalid_options = []
    @multiple_switches = sloptions[:multiple_switches]
    @on_empty = sloptions[:on_empty]
    @sloptions = sloptions

    if block_given?
      block.arity == 1 ? yield(self) : instance_eval(&block)
    end

    if sloptions[:help]
      on :h, :help, 'Print this help message', :tail => true do
        puts help
        exit
      end
    end
  end

  # Set or return banner text.
  #
  # @param [String] text Displayed banner text.
  # @example
  #   opts = Slop.parse do
  #     banner "Usage - ruby foo.rb [arguments]"
  #   end
  # @return [String] Returns current banner.
  def banner(text=nil)
    @banner = text if text
    @banner
  end

  # Parse a list of options, leaving the original Array unchanged.
  #
  # @param items
  def parse(items=ARGV, &block)
    parse_items items, &block
  end

  # Parse a list of options, removing parsed options from the original Array.
  #
  # @param items
  def parse!(items=ARGV, &block)
    parse_items items, true, &block
  end

  # Enumerable interface
  def each
    return enum_for(:each) unless block_given?
    @options.each { |option| yield option }
  end

  # Return the value of an option via the subscript operator.
  #
  # @param [Symbol] key Option symbol.
  # @example
  #   opts[:name] #=> "Emily"
  # @return [Object] Returns the value associated with that option.
  def [](key)
    option = @options[key]
    option.argument_value if option
  end

  # Specify an option with a short or long version, description and type.
  #
  # @param [*] args Option configuration.
  # @option args [Symbol, String] :short_flag Short option name.
  # @option args [Symbol, String] :long_flag Full option name.
  # @option args [String] :description Option description for use in Slop#help
  # @option args [Boolean] :argument Specifies whether a required option or not.
  # @option args [Hash] :options Optional option configurations.
  # @example
  #   opts = Slop.parse do
  #     on :n, :name, 'Your username', true # Required argument
  #     on :a, :age,  'Your age (optional)', :optional => true
  #     on :g, :gender, 'Your gender', :optional => false
  #     on :V, :verbose, 'Run in verbose mode', :default => true
  #     on :P, :people, 'Your friends', true, :as => Array
  #     on :h, :help, 'Print this help screen' do
  #       puts help
  #     end
  #   end
  # @return [Slop::Option]
  def option(*args, &block)
    options = args.pop if args.last.is_a?(Hash)
    options ||= {}

    short, long, desc, arg = clean_options(args)
    option = Option.new(self, short, long, desc, arg, options, &block)
    @options << option

    option
  end
  alias :opt :option
  alias :on :option


  # Namespace options depending on what command is executed
  #
  # @param [Symbol, String] label
  # @param [Hash] options
  # @example
  #   opts = Slop.new do
  #     command :create do
  #       on :v, :verbose
  #     end
  #   end
  #
  #   # ARGV is `create -v`
  #   opts.commands[:create].verbose? #=> true
  # @return [Slop] a new instance of Slop namespaced to +label+
  def command(label, options={}, &block)
    if @commands[label]
      raise ArgumentError, "command `#{label}` already exists"
    end

    options = @sloptions.merge(options)
    slop = Slop.new(options)
    @commands[label] = slop

    if block_given?
      block.arity == 1 ? yield(slop) : slop.instance_eval(&block)
    end

    slop
  end

  # Add an object to be called when Slop has no values to parse
  #
  # @param [Object, nil] proc The object (which can be anything
  #   responding to :call)
  # @example
  #   Slop.parse do
  #     on_empty { puts 'No argument given!' }
  #   end
  def on_empty(obj=nil, &block)
    @on_empty ||= (obj || block)
  end
  alias :on_empty= :on_empty

  # Returns the parsed list into a option/value hash.
  #
  # @example
  #   opts.to_hash #=> { 'name' => 'Emily' }
  #
  #   # symbols!
  #   opts.to_hash(true) #=> { :name => 'Emily' }
  # @return [Hash]
  def to_hash(symbols=false)
    @options.to_hash(symbols)
  end
  alias :to_h :to_hash

  # Allows you to check whether an option was specified in the parsed list.
  #
  # @example
  #   #== ruby foo.rb -v
  #   opts.verbose? #=> true
  #   opts.name?    #=> false
  # @return [Boolean] Whether the desired option was specified.
  def method_missing(meth, *args, &block)
    super unless meth.to_s =~ /\?\z/
    !!self[meth.to_s.chomp '?']
  end

  # Returns the banner followed by available options listed on the next line.
  #
  # @example
  #  opts = Slop.parse do
  #    banner "Usage - ruby foo.rb [arguments]"
  #    on :v, :verbose, "Enable verbose mode"
  #  end
  #  puts opts
  # @return [String] Help text.
  def to_s
    banner = "#{@banner}\n" if @banner
    (banner || '') + options.to_help
  end
  alias :help :to_s

  private

  class << self
    private

    def initialize_and_parse(items, delete, options, &block)
      if items.is_a?(Hash) && options.empty?
        options = items
        items = ARGV
      end

      slop = new(options, &block)
      delete ? slop.parse!(items) : slop.parse(items)
      slop
    end
  end

  def parse_items(items, delete=false, &block)
    if items.empty? && @on_empty.respond_to?(:call)
      @on_empty.call self
      return
    end

    return if execute_command(items, delete)

    trash = []

    items.each_with_index do |item, index|
      item = item.to_s
      flag = item.sub(/^--?/, '')
      option = @options[flag]

      unless option
        case item
        when /\A-[^-]/
          if @multiple_switches
            enable_multiple_switches(item)
            next
          else
            flag, argument = flag.split('', 2)
            option = @options[flag]
          end
        when /\A--([^=]+)=(.+)\z/
          option = @options[$1]
          argument = $2
        when /\A--no-(.+)\z/
          option = @options[$1]
          option.force_argument_value(false) if option
        end
      end

      if option
        trash << item
        next if option.forced?
        option.argument_value = true

        if option.expects_argument? || option.accepts_optional_argument?
          argument ||= items.at(index + 1)
          check_valid_argument!(option, argument)
          trash << argument

          if argument
            check_matching_argument!(option, argument)
            option.argument_value = argument
            option.callback.call option.argument_value if option.callback
          else
            option.argument_value = nil
            check_optional_argument!(option, flag)
          end
        elsif option.callback
          option.callback.call nil
        end
      else
        check_invalid_option!(item, flag)
        block.call(item) if block_given? && !trash.include?(item)
      end
    end

    items.delete_if { |item| trash.include? item } if delete
    raise_if_invalid_options!
    items
  end

  def check_valid_argument!(option, argument)
    if !option.accepts_optional_argument? && argument =~ /\A--?.+\z/
      raise MissingArgumentError,
        "'#{option.key}' expects an argument, none given"
    end
  end

  def check_matching_argument!(option, argument)
    if option.match && !argument.match(option.match)
      raise InvalidArgumentError,
        "'#{argument}' does not match #{option.match.inspect}"
    end
  end

  def check_optional_argument!(option, flag)
    if option.accepts_optional_argument?
      option.callback.call nil if option.callback
    else
      raise MissingArgumentError,
        "'#{flag}' expects an argument, none given"
    end
  end

  def check_invalid_option!(item, flag)
    @invalid_options << flag if item[/\A--?/] && @strict
  end

  def raise_if_invalid_options!
    return if !@strict || @invalid_options.empty?
    message = "Unknown option"
    message << 's' if @invalid_options.size > 1
    message << ' -- ' << @invalid_options.map { |o| "'#{o}'" }.join(', ')
    raise InvalidOptionError, message
  end

  def enable_multiple_switches(item)
    item[1..-1].split('').each do |switch|
      if option = @options[switch]
        if option.expects_argument?
          raise MissingArgumentError,
            "'-#{switch}' expects an argument, used in multiple_switch context"
        else
          option.argument_value = true
        end
      else
        if @strict
          raise InvalidOptionError, "Unknown option '-#{switch}'"
        end
      end
    end
  end

  def execute_command(items, delete)
    command = items[0]
    command = @commands.find { |cmd| cmd == command.to_s }
    if @commands.key?(command)
      items.shift
      opts = @commands[command]
      delete ? opts.parse!(items) : opts.parse(items)
      true
    end
  end

  def clean_options(args)
    options = []

    short = args.first.to_s.sub(/\A--?/, '')
    if short.size == 1
      options.push short
      args.shift
    else
      options.push nil
    end

    long = args.first
    boolean = [true, false].include?(long)
    if !boolean && long.to_s =~ /\A(?:--?)?[a-zA-Z0-9_-]+\z/
      options.push args.shift.to_s.sub(/\A--?/, '')
    else
      options.push nil
    end

    options.push args.first.respond_to?(:to_sym) ? args.shift : nil
    options.push args.shift ? true : false # force true/false
  end
end