lib/sonar/cli/cli.rb in sonar-client-0.0.3 vs lib/sonar/cli/cli.rb in sonar-client-0.0.4
- old
+ new
@@ -6,11 +6,11 @@
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]'
+ class_option 'format', type: :string, desc: 'Flat JSON, JSON lines, or pretty printed [flat/lines/pretty]'
def initialize(*)
@config = Sonar::RCFile.instance.load_file
@client = Sonar::Client.new(email: @config["email"], access_token: @config["access_token"], api_url: @config["api_url"])
super
@@ -30,12 +30,18 @@
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
@query[:limit] = options['record_limit']
- @client.search(@query).each do |data|
- print_json(cleanup_data(data), options['format'])
+ resp = @client.search(@query)
+
+ if resp.is_a?(Sonar::Request::RequestIterator)
+ resp.each do |data|
+ print_json(cleanup_data(data), options['format'])
+ end
+ else
+ print_json(cleanup_data(resp), options['format'])
end
end
desc 'types', 'List all Sonar query types'
def types
@@ -52,42 +58,44 @@
def print_json(json, format)
case format
when 'pretty'
ap(json)
+ when 'lines'
+ if json.has_key?('collection')
+ json['collection'].each { |l| puts l.to_json }
+ else
+ puts 'Could not parse the response into lines.'
+ end
else
# TODO: use a faster JSON generator?
puts(json.to_json)
end
end
# Clean up whitespace and parse JSON values in responses
def cleanup_data(data)
- ndata = {}
- if data[0] != 'collection'
- return data
- end
-
- ncoll = []
-
- data[1].each do |item|
- nitem = {}
+ return data unless data.is_a?(Hash) && data.has_key?('collection')
+ data['collection'].each do |item|
item.each_pair do |k,v|
-
# Purge whitespace within values
- nval = v.kind_of?(::String) ? v.strip : v
- nkey = k.strip
+ v.is_a?(::String) ? v.strip! : v
# Parse JSON values
- if nval && nval.index('{') == 0
- nval = JSON.parse(nval) rescue nval
+ if v.is_a?(Array)
+ v.map! do |e|
+ e = safe_parse_json(e)
+ end
+ else
+ v = safe_parse_json(v)
end
-
- nitem[nkey] = nval
end
- ncoll << nitem
end
- [ data[0], ncoll ]
+ data
+ end
+
+ def safe_parse_json(s)
+ JSON.parse(s) rescue s
end
# Merge Thor options with those stored in sonar.rc file
# where all default options are set.
def options