Skip to content

Commit

Permalink
Fixes passing --help to subcommand
Browse files Browse the repository at this point in the history
Avoid OptionParser to short-circuit `--help` and return immediately by
setting a flag for it and evaluating at the end of the processing of
unknown options.

This is only done for the CLI invocation and is not part of Shards
module (as the help and usage options are only available in this
context).
  • Loading branch information
luislavena committed May 20, 2024
1 parent 776a7c0 commit 5a6dc6c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 10 additions & 0 deletions spec/integration/subcommand_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ describe "subcommand" do
output.should contain(%(args: ["--no-color", "--verbose", "--unknown", "other", "argument"]))
end
end

it "correctly forwards '--help' option to subcommand" do
create_shard("dummy", "0.1.0")
create_executable "dummy", "bin/shards-dummy", %(print "args: "; print ARGV)

with_path(git_path("dummy/bin")) do
output = run("shards dummy --help")
output.should contain(%(args: ["--help"]))
end
end
end

private def with_path(path)
Expand Down
8 changes: 7 additions & 1 deletion src/cli.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ require "option_parser"
require "./commands/*"

module Shards
class_property? display_help : Bool = false

def self.display_help_and_exit(opts)
puts <<-HELP
shards [<options>...] [<command>]
Expand Down Expand Up @@ -53,7 +55,7 @@ module Shards
opts.on("--ignore-crystal-version", "Has no effect. Kept for compatibility, to be removed in the future.") { }
opts.on("-v", "--verbose", "Increase the log verbosity, printing all debug statements.") { self.set_debug_log_level }
opts.on("-q", "--quiet", "Decrease the log verbosity, printing only warnings and errors.") { self.set_warning_log_level }
opts.on("-h", "--help", "Print usage synopsis.") { self.display_help_and_exit(opts) }
opts.on("-h", "--help", "Print usage synopsis.") { self.display_help = true }

opts.unknown_args do |args, options|
case args[0]? || DEFAULT_COMMAND
Expand Down Expand Up @@ -107,6 +109,10 @@ module Shards
end
end

if display_help?
display_help_and_exit(opts)
end

exit
end
end
Expand Down

0 comments on commit 5a6dc6c

Please sign in to comment.