commander-rb / commander

The complete solution for Ruby command-line executables
MIT License
821 stars 74 forks source link

--[no-]blah style flags fail when used with `global_option` #27

Closed mfurtak closed 8 years ago

mfurtak commented 8 years ago

There seems to be a problem when using '--[no-]blah' style flags as part of a global_option. Specifically, the flag appears to not be accounted for during bookkeeping in remove_global_options.

The following test program exhibits the problem:

#!/usr/bin/env ruby

require 'rubygems'
require 'commander'

class MyApplication
  include Commander::Methods

  def run
    runner = Commander::Runner.instance

    program :name, 'Foo Bar'
    program :version, '1.0.0'
    program :description, 'Stupid command that prints foo or bar.'

    command :foo do |c|
      c.syntax = 'foobar foo'
      c.description = 'Displays foo'
      c.when_called do |args, options|
        puts 'Command goes foo'
        puts 'Wow!' if $exclaim
      end
    end

    global_option('-e', '--[no-]exclaim', 'Whether not to exclaim') do |val| 
      $exclaim = val
      puts "$exclaim is: #{$exclaim}"
    end

    runner.parse_global_options

    puts "ARGV before global options removed: #{ARGV}"

    runner.remove_global_options(runner.options, ARGV)

    puts "ARGV after global options removed: #{ARGV}"

    run!
  end
end

MyApplication.new.run if $0 == __FILE__

When run with ./commander_example.rb foo --exclaim, the result is:

$exclaim is: true
ARGV before global options removed: ["foo", "--exclaim"]
ARGV after global options removed: ["foo", "--exclaim"]
$exclaim is: true
invalid option: --exclaim

When run with ./commander_example.rb foo --no-exclaim the result is:

$exclaim is: false
ARGV before global options removed: ["foo", "--no-exclaim"]
ARGV after global options removed: ["foo", "--no-exclaim"]
$exclaim is: false
invalid option: --no-exclaim

When run with ./commander_example.rb foo -e the result is:

$exclaim is: true
ARGV before global options removed: ["foo", "-e"]
ARGV after global options removed: ["foo"]
Command goes foo
Wow!

edit: Corrected the bug description, my test program, produced output, and provided one more example

mfurtak commented 8 years ago

Fixed in #28