5
# The {HelpRenderer} class is responsible for generating a string containing
6
# the help for a given command, intended to be printed on the command line.
9
# Creates a new help renderer for the given command.
11
# @param [Cri::Command] cmd The command to generate the help for
13
# @option params [Boolean] :verbose true if the help output should be
14
# verbose, false otherwise.
15
def initialize(cmd, params={})
17
@is_verbose = params.fetch(:verbose, false)
20
# @return [String] The help text for this command
26
append_description(text)
27
append_subcommands(text)
35
def append_summary(text)
36
return if @cmd.summary.nil?
38
text << "name".formatted_as_title << "\n"
39
text << " #{@cmd.name.formatted_as_command} - #{@cmd.summary}" << "\n"
40
unless @cmd.aliases.empty?
41
text << " aliases: " << @cmd.aliases.map { |a| a.formatted_as_command }.join(' ') << "\n"
45
def append_usage(text)
46
return if @cmd.usage.nil?
48
path = [ @cmd.supercommand ]
49
path.unshift(path[0].supercommand) until path[0].nil?
50
formatted_usage = @cmd.usage.gsub(/^([^\s]+)/) { |m| m.formatted_as_command }
51
full_usage = path[1..-1].map { |c| c.name.formatted_as_command + ' ' }.join + formatted_usage
54
text << "usage".formatted_as_title << "\n"
55
text << full_usage.wrap_and_indent(78, 4) << "\n"
58
def append_description(text)
59
return if @cmd.description.nil?
62
text << "description".formatted_as_title << "\n"
63
text << @cmd.description.wrap_and_indent(78, 4) + "\n"
66
def append_subcommands(text)
67
return if @cmd.subcommands.empty?
70
text << (@cmd.supercommand ? 'subcommands' : 'commands').formatted_as_title
73
shown_subcommands = @cmd.subcommands.select { |c| !c.hidden? || @is_verbose }
74
length = shown_subcommands.map { |c| c.name.formatted_as_command.size }.max
77
shown_subcommands.sort_by { |cmd| cmd.name }.each do |cmd|
78
text << sprintf(" %-#{length+4}s %s\n",
79
cmd.name.formatted_as_command,
85
diff = @cmd.subcommands.size - shown_subcommands.size
89
text << " (1 hidden command omitted; show it with --verbose)\n"
91
text << " (#{diff} hidden commands omitted; show them with --verbose)\n"
96
def append_options(text)
97
groups = { 'options' => @cmd.option_definitions }
99
groups["options for #{@cmd.supercommand.name}"] = @cmd.supercommand.global_option_definitions
101
length = groups.values.inject(&:+).map { |o| o[:long].to_s.size }.max
102
groups.keys.sort.each do |name|
104
append_option_group(text, name, defs, length)
108
def append_option_group(text, name, defs, length)
109
return if defs.empty?
112
text << "#{name}".formatted_as_title
115
ordered_defs = defs.sort_by { |x| x[:short] || x[:long] }
116
ordered_defs.each do |opt_def|
117
text << format_opt_def(opt_def, length)
118
text << opt_def[:desc] << "\n"
122
def format_opt_def(opt_def, length)
124
" %-2s %-#{length+6}s",
125
opt_def[:short] ? ('-' + opt_def[:short]) : '',
126
opt_def[:long] ? ('--' + opt_def[:long]) : '')
127
opt_text.formatted_as_option