crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.33k stars 1.61k forks source link

option parser quit on help #8921

Open smalls12 opened 4 years ago

smalls12 commented 4 years ago

Hello,

The OptionParser in the documents is as follows

require "option_parser"

upcase = false
destination = "World"

OptionParser.parse do |parser|
  parser.banner = "Usage: salute [arguments]"
  parser.on("-u", "--upcase", "Upcases the salute") { upcase = true }
  parser.on("-t NAME", "--to=NAME", "Specifies the name to salute") { |name| destination = name }
  parser.on("-h", "--help", "Show this help") { puts parser }
  parser.invalid_option do |flag|
    STDERR.puts "ERROR: #{flag} is not a valid option."
    STDERR.puts parser
    exit(1)
  end
end

destination = destination.upcase if upcase
puts "Hello #{destination}!"

I expected that if you actually used the "-h" or "--help" that the program would display the help and then would end.

However in this example above, the help menu would be printed and the program will continue.

If the program writes a lot of data to the screen, the help menu could be lost until the program ends and then the user scrolls up to see the help.

The solution might be to follow what parser.invalid_option does; something like parser.help.

Could this behavior be added?

Sija commented 4 years ago

It's as easy as doing puts parser; exit...

smalls12 commented 4 years ago

Oh fair enough, I guess that works.

RX14 commented 4 years ago

I think that printing the help message being just OptionParser#to_s is a bit confusing.

straight-shoota commented 4 years ago

The example should have an exit call to demonstrate proper usage.

vlazar commented 4 years ago

@RX14 Are you talking about renaming OptionParser#to_s to something like OptionParser#help or OptionParser#options instead? I can't think of better method name.

vlazar commented 4 years ago

On the second thought maybe parser.print_help replacing puts parser.to_s would do?

smalls12 commented 4 years ago

Maybe related, does the user have to specify the help option? Could it not just be added in the background automatically?