lib/gitlab/cli_helpers.rb in gitlab-3.4.0 vs lib/gitlab/cli_helpers.rb in gitlab-3.5.0
- old
+ new
@@ -1,7 +1,9 @@
require 'yaml'
+require 'json'
+
class Gitlab::CLI
# Defines methods related to CLI output and formatting.
module Helpers
extend self
@@ -97,20 +99,33 @@
else # probably just an error msg
puts data
end
end
+ def output_json(cmd, args, data)
+ if data.empty?
+ puts '{}'
+ else
+ hash_result = case data
+ when Gitlab::ObjectifiedHash
+ record_hash([data], cmd, args, true)
+ when Array
+ record_hash(data, cmd, args)
+ else
+ { :cmd => cmd, :data => data, :args => args }
+ end
+ puts JSON.pretty_generate(hash_result)
+ end
+ end
+
# Table to display records.
#
# @return [Terminal::Table]
def record_table(data, cmd, args)
return 'No data' if data.empty?
- arr = data.map(&:to_h)
- keys = arr.first.keys.sort {|x, y| x.to_s <=> y.to_s }
- keys = keys & required_fields(args) if required_fields(args).any?
- keys = keys - excluded_fields(args)
+ arr, keys = get_keys(args, data)
table do |t|
t.title = "Gitlab.#{cmd} #{args.join(', ')}"
t.headings = keys
@@ -132,10 +147,58 @@
t.add_separator unless arr.size - 1 == index
end
end
end
+ # Renders the result of given commands and arguments into a Hash
+ #
+ # @param [Array] data Resultset from the API call
+ # @param [String] cmd The command passed to the API
+ # @param [Array] args Options passed to the API call
+ # @param [bool] single_value If set to true, a single result should be returned
+ # @return [Hash] Result hash
+ def record_hash(data, cmd, args, single_value = false)
+ if data.empty?
+ result = nil
+ else
+ arr, keys = get_keys(args, data)
+ result = []
+ arr.each do |hash|
+ row = {}
+
+ keys.each do |key|
+ case hash[key]
+ when Hash
+ row[key] = 'Hash'
+ when nil
+ row[key] = nil
+ else
+ row[key] = hash[key]
+ end
+ end
+
+ result.push row
+ end
+ result = result[0] if single_value && result.count > 0
+ end
+
+ {
+ :cmd => "Gitlab.#{cmd} #{args.join(', ')}".strip,
+ :result => result
+ }
+
+ end
+
+ # Helper function to get rows and keys from data returned from API call
+ def get_keys(args, data)
+ arr = data.map(&:to_h)
+ keys = arr.first.keys.sort { |x, y| x.to_s <=> y.to_s }
+ keys = keys & required_fields(args) if required_fields(args).any?
+ keys = keys - excluded_fields(args)
+ return arr, keys
+ end
+
# Helper function to call Gitlab commands with args.
def gitlab_helper(cmd, args = [])
begin
data = args.any? ? Gitlab.send(cmd, *args) : Gitlab.send(cmd)
rescue => e
@@ -160,20 +223,16 @@
end
hash
end
- # Run YAML::load on each arg.
- # @return [Array]
- def yaml_load_arguments!(args)
- args.map! do |arg|
- begin
- arg = YAML::load(arg)
- rescue Psych::SyntaxError
- raise "error: Argument is not valid YAML syntax: #{arg}"
- end
-
- arg
+ # YAML::load on a single argument
+ def yaml_load(arg)
+ begin
+ yaml = YAML::load(arg)
+ rescue Psych::SyntaxError
+ raise "error: Argument is not valid YAML syntax: #{arg}"
end
+ yaml
end
end
end