Method: RHC::CommandRunner#run_help

Defined in:
lib/rhc/command_runner.rb

#run_help(args = [], options = nil) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/rhc/command_runner.rb', line 132

def run_help(args=[], options=nil)
  args.delete_if{ |a| a.start_with? '-' }
  unless args[0] == 'commands'
    variations = (1..args.length).reverse_each.map{ |n| args[0,n].join('-') }
    cmd = variations.find{ |cmd| command_exists?(cmd) }
  end

  if args.empty?
    say help_formatter.render
    0
  else
    if cmd.nil?
      matches = (variations || ['']).inject(nil) do |candidates, term|
        term = term.downcase
        keys = commands.keys.map(&:downcase)
        prefix, keys = keys.partition{ |n| n.start_with? term }
        inline, keys = keys.partition{ |n| n.include? term }
        break [term, prefix, inline] unless prefix.empty? && inline.empty?
      end

      unless matches
        RHC::Helpers.error "The command '#{program :name} #{provided_arguments.join(' ')}' is not recognized.\n"
        say "See '#{program :name} help' for a list of valid commands."
        return 1
      end

      candidates = (matches[1] + matches[2]).map{ |n| commands[n] }.uniq.sort_by{ |c| c.name }
      if candidates.length == 1
        cmd = candidates.first.name
      else
        RHC::Helpers.pager
        RHC::Helpers.say matches[0] != '' ? "Showing commands matching '#{matches[0]}'" : "Showing all commands"
        candidates.reverse.each do |command|
          RHC::Helpers.paragraph do
            aliases = (commands.map{ |(k,v)| k if command == v }.compact - [command.name]).map{ |s| "'#{s}'"}
            aliases[0] = "(also #{aliases[0]}" if aliases[0]
            aliases[-1] << ')' if aliases[0]

            RHC::Helpers.header [RHC::Helpers.color(command.name, :cyan), *aliases.join(', ')]
            say command.description || command.summary
          end
        end
        return 1
      end
    end

    RHC::Helpers.pager
    command = command(cmd)
    help_bindings = CommandHelpBindings.new command, commands, self
    say help_formatter.render_command help_bindings
    0
  end
end