Parent

Methods

Class/Module Index [+]

Quicksearch

Chef::Knife::Search

Public Instance Methods

run() click to toggle source
# File lib/chef/knife/search.rb, line 77
def run
  if config[:query] && @name_args[1]
    ui.error "please specify query as an argument or an option via -q, not both"
    ui.msg opt_parser
    exit 1
  end
  raw_query = config[:query] || @name_args[1]
  if !raw_query || raw_query.empty?
    ui.error "no query specified"
    ui.msg opt_parser
    exit 1
  end

  if name_args[0].nil?
    ui.error "you must specify an item type to search for"
    exit 1
  end

  if name_args[0] == 'node'
    ui.use_presenter Knife::Core::NodePresenter
  end


  q = Chef::Search::Query.new
  query = URI.escape(raw_query,
                     Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

  result_items = []
  result_count = 0

  rows = config[:rows]
  start = config[:start]
  begin
    q.search(@name_args[0], query, config[:sort], start, rows) do |item|
      formatted_item = format_for_display(item)
      if formatted_item.respond_to?(:has_key?) && !formatted_item.has_key?('id')
        formatted_item['id'] = item.has_key?('id') ? item['id'] : item.name
      end
      result_items << formatted_item
      result_count += 1
    end
  rescue Net::HTTPServerException => e
    msg = Chef::JSONCompat.from_json(e.response.body)["error"].first
    ui.error("knife search failed: #{msg}")
    exit 1
  end

  if ui.interchange?
    output({:results => result_count, :rows => result_items})
  else
    ui.msg "#{result_count} items found"
    ui.msg("\n")
    result_items.each do |item|
      output(item)
      ui.msg("\n")
    end
  end
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.