davetron5000 / gli

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

pre block - error: precondtions failed #321

Closed noraj closed 21 hours ago

noraj commented 3 weeks ago

When I do something like that

    pre do |global_options, _command, _options, _args|
      Paint.mode = 0 unless global_options[:color]
    end

or even like that

    pre do |global_options, _command, _options, _args|
      puts "test"
    end

I get the error error: precondtions failed.

So that my code can continue and to avoid the failure, I have to add a truthy (true, 1, etc.) return value.

    pre do |global_options, _command, _options, _args|
      Paint.mode = 0 unless global_options[:color]
      true
    end

If the output of the last command in the pre block returns nil or false (but not 0) it fails.

It's what explained here: https://www.rubydoc.info/gems/gli/2.21.1/GLI/App#pre-instance_method

Define a block to run after command line arguments are parsed but before any command is run. If this block raises an exception the command specified will not be executed. The block will receive the global-options,command,options, and arguments If this block evaluates to true, the program will proceed; otherwise the program will end immediately and exit nonzero

I wonder why this behavior was chosen, it's not really handy in many cases.

davetron5000 commented 3 weeks ago

The thinking was that I didn't want exceptions to be the only way to bail out, so it seemed logical to also use the "truthiness" concept in Ruby, i.e. nil and false both evaluate to false in an conditional.

You could do an around block, but you'd have to call .call:

around do |global,_command,_options,_args,code|
  Paint.mode = 0 unless global_options[:color]
  code.call
end
davetron5000 commented 21 hours ago

Closing as this is intended and documented behavior (even though I understand it's not ideal for your use case)

noraj commented 5 hours ago

Thank you for your explanation.