lib/sonar/cli/cli.rb in sonar-client-0.0.1 vs lib/sonar/cli/cli.rb in sonar-client-0.0.2
- old
+ new
@@ -6,41 +6,66 @@
module Sonar
class CLI < Thor
class_option 'profile', aliases: '-P', type: :string, default: File.join(File.expand_path('~'), Sonar::RCFile::FILENAME),
desc: 'Path to Sonar RC file', banner: 'FILE'
+ class_option 'format', type: :string, desc: 'Flat JSON or pretty printed [flat/pretty]'
def initialize(*)
- @rcfile = Sonar::RCFile.instance.load_file
- @client = Sonar::Client.new(email: @rcfile["email"], access_token: @rcfile["access_token"], api_url: @rcfile["api_url"])
+ @config = Sonar::RCFile.instance.load_file
+ @client = Sonar::Client.new(email: @config["email"], access_token: @config["access_token"], api_url: @config["api_url"])
super
end
desc 'profile', 'Display the current profile from sonar.rc'
def profile
- ap @rcfile
+ ap @config
end
- desc 'usage', 'Display API usage for current user.'
+ desc 'usage', 'Display API usage for current user'
def usage
ap @client.usage
end
- desc 'search [QUERY TYPE] [QUERY TERM]', 'Search anything from Sonar.'
+ desc 'search [QUERY TYPE] [QUERY TERM]', 'Search anything from Sonars'
+ method_option 'record_limit', type: :numeric, aliases: '-n', desc: 'Maximum number of records to fetch'
def search(type, term)
@query = {}
@query[type.to_sym] = term
- ap @client.search(@query)
+ @query[:limit] = options['record_limit']
+ @client.search(@query).each do |data|
+ print_json(data, options['format'])
+ end
end
- desc 'types', 'List all Sonar query types.'
+ desc 'types', 'List all Sonar query types'
def types
ap Search::QUERY_TYPES_MAP
end
- desc 'config', 'Update Sonar config file'
+ desc 'config', 'Sonar config file location'
def config
# TODO: add a way to set config
puts "Your config file is located at #{RCFile.instance.path}"
+ end
+
+ private
+
+ def print_json(json, format)
+ case format
+ when 'pretty'
+ ap(json)
+ else
+ # TODO: use a faster JSON generator?
+ puts(json.to_json)
+ end
+ end
+
+ # Merge Thor options with those stored in sonar.rc file
+ # where all default options are set.
+ def options
+ original_options = super
+ user_defaults = @config
+ user_defaults.merge(original_options)
end
end
end