davetron5000 / gli

Make awesome command-line applications the easy way
http://davetron5000.github.io/gli
Apache License 2.0
1.26k stars 102 forks source link

local switch -v taken as global version switch but "version unknown" #274

Open yashi opened 6 years ago

yashi commented 6 years ago

Hi,

when I run the following code, I get

$ bundle exec ruby ./ecm.rb bar -v
ecm: version unknown
error: ecm: version unknown

It doesn't even print the defined version number. I was expecting to see error: Unknown option -v. Is this a bug?

It prints the version number if you put -v before the sub-command, as I expected:

$ bundle exec ruby ./ecm.rb -v bar
ecm.rb version 0.0.1

If a sub-command knows -v, you get it as a local option, as I expected:

$ bundle exec ruby ./ecm.rb foo -v
globals: {"version"=>false, :version=>false, "help"=>false, :help=>false}
options: {"v"=>true, :v=>true}
#!/usr/bin/env ruby

require 'gli'
include GLI::App

program_desc 'A Command to test'
version '0.0.1'

subcommand_option_handling :normal
arguments :strict

desc 'foo command'
command :foo do |c|
  c.desc 'Verbose'
  c.switch :v

  c.action do |global_options, options, args|
    puts "globals: #{global_options}"
    puts "options: #{options}"
  end
end

desc 'bar command'
command :bar do |c|
  c.action do |global_options, options, args|
    puts "globals: #{global_options}"
    puts "options: #{options}"
  end
end

exit run(ARGV)
davetron5000 commented 6 years ago

Hmm, this does seem like a bug.

davetron5000 commented 1 month ago

This may not be easily fixable. The problem is that GLI is using the standard library OptionParser under the hood. It hard-codes --version and interprets -v as --version. What's happening is that when you run bundle exec ruby ./ecm.rb bar -v, since bar does not accept -v, that is getting passed to the OptionParser as --version, which uses OptionParser's internal version that GLI doesn't use.

That's all fine, except that OptionParser is calling exit instead of raising an exception.

I'm leaving this open as documentation, but I'm not sure how to fix it.