Module: Gitlab::CLI::Helpers

Extended by:
Helpers
Included in:
Gitlab::CLI, Helpers, Help, Shell
Defined in:
lib/gitlab/cli_helpers.rb

Overview

Defines methods related to CLI output and formatting.

Instance Method Summary collapse

Instance Method Details

#actionsArray

Returns actions available to CLI & Shell

Returns:

  • (Array)

13
14
15
# File 'lib/gitlab/cli_helpers.rb', line 13

def actions
  @actions ||= Gitlab.actions
end

#clientGitlab::Client

Returns Gitlab::Client instance

Returns:


20
21
22
# File 'lib/gitlab/cli_helpers.rb', line 20

def client
  @client ||= Gitlab::Client.new(endpoint: (Gitlab.endpoint || ''))
end

#confirm_command(cmd) ⇒ String

Confirms command with a desctructive action.

Returns:

  • (String)

69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/gitlab/cli_helpers.rb', line 69

def confirm_command(cmd)
  return unless cmd.start_with?('remove_', 'delete_')

  puts 'Are you sure? (y/n)'

  if %w(y yes).include?($stdin.gets.to_s.strip.downcase)
    puts 'Proceeding..'
  else
    puts 'Command aborted.'
    exit(1)
  end
end

#excluded_fields(args) ⇒ Array

Returns filtered excluded fields.

Returns:

  • (Array)

50
51
52
53
54
55
56
# File 'lib/gitlab/cli_helpers.rb', line 50

def excluded_fields(args)
  if args.any? && args.last.is_a?(String) && args.last.start_with?('--except=')
    args.last.gsub('--except=', '').split(',')
  else
    []
  end
end

#get_keys(args, data) ⇒ Object

Helper function to get rows and keys from data returned from API call


196
197
198
199
200
201
202
# File 'lib/gitlab/cli_helpers.rb', line 196

def get_keys(args, data)
  arr = data.map(&:to_h)
  keys = arr.first.keys.sort_by(&:to_s)
  keys &= required_fields(args) if required_fields(args).any?
  keys -= excluded_fields(args)
  [arr, keys]
end

#gitlab_helper(cmd, args = []) ⇒ Object

Helper function to call Gitlab commands with args.


205
206
207
208
209
210
211
212
213
214
# File 'lib/gitlab/cli_helpers.rb', line 205

def gitlab_helper(cmd, args=[])
  begin
    data = args.any? ? Gitlab.send(cmd, *args) : Gitlab.send(cmd)
  rescue => e
    puts e.message
    yield if block_given?
  end

  data
end

#help(cmd = nil, &block) ⇒ String

Gets defined help for a specific command/action.

Returns:

  • (String)

85
86
87
88
89
90
91
# File 'lib/gitlab/cli_helpers.rb', line 85

def help(cmd=nil, &block)
  if cmd.nil? || Gitlab::Help.help_map.key?(cmd)
    Gitlab::Help.actions_table(cmd)
  else
    Gitlab::Help.get_help(cmd, &block)
  end
end

#method_ownersArray<Hash>

Returns method names and their owners

Returns:

  • (Array<Hash>)

27
28
29
30
31
32
33
34
# File 'lib/gitlab/cli_helpers.rb', line 27

def method_owners
  @method_owners ||= actions.map do |action|
    {
      name: action.to_s,
      owner: client.method(action).owner.to_s
    }
  end
end

#output_json(cmd, args, data) ⇒ Object


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/gitlab/cli_helpers.rb', line 105

def output_json(cmd, args, data)
  if data.respond_to?(:empty?) && data.empty?
    puts '{}'
  else
    hash_result = case data
                  when Gitlab::ObjectifiedHash, Gitlab::FileResponse
                    record_hash([data], cmd, args, true)
                  when Gitlab::PaginatedResponse
                    record_hash(data, cmd, args)
                  else
                    { cmd: cmd, data: data, args: args }
                  end
    puts JSON.pretty_generate(hash_result)
  end
end

#output_table(cmd, args, data) ⇒ Object

Outputs a nicely formatted table or error msg.


94
95
96
97
98
99
100
101
102
103
# File 'lib/gitlab/cli_helpers.rb', line 94

def output_table(cmd, args, data)
  case data
  when Gitlab::ObjectifiedHash, Gitlab::FileResponse
    puts record_table([data], cmd, args)
  when Gitlab::PaginatedResponse
    puts record_table(data, cmd, args)
  else # probably just an error msg
    puts data
  end
end

#record_hash(data, cmd, args, single_value = false) ⇒ Hash

Renders the result of given commands and arguments into a Hash

Parameters:

  • data (Array)

    Resultset from the API call

  • cmd (String)

    The command passed to the API

  • args (Array)

    Options passed to the API call

  • single_value (bool) (defaults to: false)

    If set to true, a single result should be returned

Returns:

  • (Hash)

    Result hash


162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/gitlab/cli_helpers.rb', line 162

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 StringIO
          row[key] = Base64.encode64(hash[key].read)
        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

#record_table(data, cmd, args) ⇒ Terminal::Table

Table to display records.

Returns:

  • (Terminal::Table)

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/gitlab/cli_helpers.rb', line 124

def record_table(data, cmd, args)
  return 'No data' if data.empty?

  arr, keys = get_keys(args, data)

  table do |t|
    t.title = "Gitlab.#{cmd} #{args.join(', ')}"
    t.headings = keys

    arr.each_with_index do |hash, index|
      values = []

      keys.each do |key|
        case value = hash[key]
        when Hash
          value = value.key?('id') ? value['id'] : 'Hash'
        when StringIO
          value = 'File'
        when nil
          value = 'null'
        end

        values << value
      end

      t.add_row values
      t.add_separator unless arr.size - 1 == index
    end
  end
end

#required_fields(args) ⇒ Array

Returns filtered required fields.

Returns:

  • (Array)

39
40
41
42
43
44
45
# File 'lib/gitlab/cli_helpers.rb', line 39

def required_fields(args)
  if args.any? && args.last.is_a?(String) && args.last.start_with?('--only=')
    args.last.gsub('--only=', '').split(',')
  else
    []
  end
end

#symbolize_keys(hash) ⇒ Hash

Convert a hash (recursively) to use symbol hash keys

Returns:

  • (Hash)

218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/gitlab/cli_helpers.rb', line 218

def symbolize_keys(hash)
  if hash.is_a?(Hash)
    hash = hash.each_with_object({}) do |(key, value), newhash|
      begin
        newhash[key.to_sym] = symbolize_keys(value)
      rescue NoMethodError
        raise "Error: cannot convert hash key to symbol: #{key}"
      end
    end
  end

  hash
end

#valid_command?(cmd) ⇒ Boolean

Confirms command is valid.

Returns:

  • (Boolean)

61
62
63
64
# File 'lib/gitlab/cli_helpers.rb', line 61

def valid_command?(cmd)
  command = cmd.is_a?(Symbol) ? cmd : cmd.to_sym
  Gitlab.actions.include?(command)
end

#yaml_load(arg) ⇒ Object

YAML::load on a single argument


233
234
235
236
237
# File 'lib/gitlab/cli_helpers.rb', line 233

def yaml_load(arg)
  YAML.safe_load(arg)
rescue Psych::SyntaxError
  raise "Error: Argument is not valid YAML syntax: #{arg}"
end