Usage of short options without =

This commit is contained in:
Denis Knauf 2021-12-08 00:17:37 +01:00
parent ffd24c02f8
commit d2158e08ea
2 changed files with 8 additions and 6 deletions

View file

@ -6,13 +6,15 @@ require 'dencli'
cli = DenCli.new :example, "This is an example for generate a DenCli-API" cli = DenCli.new :example, "This is an example for generate a DenCli-API"
cli.cmd( :args, "Expects and prints given arguments", cli.cmd( :args, "Expects and prints given arguments",
&lambda {|a, b, c:, d:, e:| &lambda {|a, b, c:, d:, e:, f:, g:|
p a: a, b: b, c: c, d: d, e: e p a: a, b: b, c: c, d: d, e: e
}). }).
opt( :c, '-c=ForC', "Option c"). opt( :c, '-c=ForC', "Option c").
opt( :d, '-d=ForD', "Option d", default: "something"). opt( :d, '-dForD', "Option d", default: "something").
opt( :e, '-e', "Toggle e", default: false). opt( :e, '-e', "Toggle e", default: false).
opt( :f, '--[no-]f', "Toggle f", default: false) opt( :f, '--[no-]f', "Toggle f", default: false).
opt( :g, '--long-option=sth', "Long option, no short option", default: "nothing").
opt( :h, '-hsth', "No long option, only short option", default: "nothing")
cli.cmd( :example, "I have an example command") { STDERR.puts "This is an example" } cli.cmd( :example, "I have an example command") { STDERR.puts "This is an example" }
cli.cmd( :help, "", aliases: [nil, '-h', '--help'], &lambda {|*args, full:| cli.cmd( :help, "", aliases: [nil, '-h', '--help'], &lambda {|*args, full:|

View file

@ -72,7 +72,7 @@ class DenCli::CMD
def _usage output def _usage output
output << full_cmd.join( ' ') output << full_cmd.join( ' ')
@options.each do |_, o| @options.each do |_, o|
s = "#{o.short||o.long}#{o.val ? ?= : ''}#{o.val}" s = "#{o.short||o.long}#{(!o.short && o.val) ? ?= : ''}#{o.val}"
output << (o.required? ? " #{s}" : " [#{s}]") output << (o.required? ? " #{s}" : " [#{s}]")
end end
if @exe.lambda? if @exe.lambda?
@ -161,9 +161,9 @@ class DenCli::CMD
@long, @val = $1, $2 || @val @long, @val = $1, $2 || @val
when /\A(--[^=]+)\z/ when /\A(--[^=]+)\z/
@long, @val = $1, nil @long, @val = $1, nil
when /\A(-[^=-]+)=(.+)\z/ when /\A(-[^=-])=?(.+)\z/
@short, @val = $1, $2 || @val @short, @val = $1, $2 || @val
when /\A(-[^=-]+)\z/ when /\A(-[^=-])\z/
@short, @val = $1, nil @short, @val = $1, nil
else else
raise ArgumentError, "Unexpected format for option: #{opt.inspect}" raise ArgumentError, "Unexpected format for option: #{opt.inspect}"