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

Cannot get `true` to work as a default switch value #286

Closed sd-trailhead-james closed 5 years ago

sd-trailhead-james commented 5 years ago

Let's say I have a global :verbose switch. I want it to have a default value of true so that the app operates in verbose mode by default. Users can then specify --no-verbose to disable/decrease verbosity.

I have attempted to represent that desired behavior with the following code, but the default value for the switch is false. Running the app without the switch results in false. Running it with --verbose results in true, and running it with --no-verbose results in false. So when the switch is present, the behavior is as desired, but I can't get the default value of true to work as desired. How can I get the switch to be true by default when the user omits the switch?

#!/usr/bin/env ruby

require "gli"

class Test
  extend GLI::App

  desc "A 'verbose' switch defaulting to true"
  switch [:verbose], default: true

  desc "Test command"
  command :test do |c|
    c.action do |global_opts, _opts, _args|
      puts "Verbose mode = #{global_opts[:verbose]}"
      puts
    end
  end
end

puts "default run - expect to receive 'true'"
Test.run(%w(test))  # <-- this one prints 'false' for some reason

puts "run with --verbose - expect to receive 'true'"
Test.run(%w(--verbose test))

puts "run with --no-verbose - expect to receive 'false'"
Test.run(%w(--no-verbose test))
davetron5000 commented 5 years ago

This is a bit confusing, but you have to use default_value. the switch command won’t complain about unknown flags, so it happily accepts default, even though it’s not recognized.

sd-trailhead-james commented 5 years ago

Thanks, @davetron5000! That was indeed all it was.