Class: Gzr::Command

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Session
Defined in:
lib/gzr/command.rb

Direct Known Subclasses

Gzr::Commands::Attribute::Cat, Gzr::Commands::Attribute::Create, Gzr::Commands::Attribute::GetGroupValue, Gzr::Commands::Attribute::Import, Gzr::Commands::Attribute::Ls, Gzr::Commands::Attribute::Rm, Gzr::Commands::Attribute::SetGroupValue, Gzr::Commands::Connection::Dialects, Gzr::Commands::Connection::Ls, Gzr::Commands::Dashboard::Cat, Gzr::Commands::Dashboard::Import, Gzr::Commands::Dashboard::Mv, Gzr::Commands::Dashboard::Rm, Gzr::Commands::Folder::Cat, Gzr::Commands::Folder::Create, Gzr::Commands::Folder::Export, Gzr::Commands::Folder::Ls, Gzr::Commands::Folder::Rm, Gzr::Commands::Folder::Top, Gzr::Commands::Folder::Tree, Gzr::Commands::Group::Ls, Gzr::Commands::Group::MemberGroups, Gzr::Commands::Group::MemberUsers, Gzr::Commands::Look::Cat, Gzr::Commands::Look::Import, Gzr::Commands::Look::Mv, Gzr::Commands::Look::Rm, Gzr::Commands::Model::Ls, Gzr::Commands::Permissions::Ls, Gzr::Commands::Plan::Cat, Gzr::Commands::Plan::Disable, Gzr::Commands::Plan::Enable, Gzr::Commands::Plan::Failures, Gzr::Commands::Plan::Import, Gzr::Commands::Plan::Ls, Gzr::Commands::Plan::Rm, Gzr::Commands::Plan::RunIt, Gzr::Commands::Query::RunQuery, Gzr::Commands::Role::Cat, Gzr::Commands::Role::GroupAdd, Gzr::Commands::Role::GroupLs, Gzr::Commands::Role::GroupRm, Gzr::Commands::Role::Ls, Gzr::Commands::Role::Rm, Gzr::Commands::Role::UserAdd, Gzr::Commands::Role::UserLs, Gzr::Commands::Role::UserRm, Gzr::Commands::User::Cat, Gzr::Commands::User::Delete, Gzr::Commands::User::Disable, Gzr::Commands::User::Enable, Gzr::Commands::User::Ls, Gzr::Commands::User::Me

Instance Method Summary collapse

Methods included from Session

#build_connection_hash, #login, #logout_all, #pastel, #say_error, #say_ok, #say_warning, #sufficient_version?, #with_session

Constructor Details

#initializeCommand

Returns a new instance of Command.



37
38
39
40
41
# File 'lib/gzr/command.rb', line 37

def initialize
  @sdk = nil
  @access_token_stack = Array.new
  @options = Hash.new
end

Instance Method Details

#all_color_collectionsObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/gzr/command.rb', line 120

def all_color_collections()
  data = nil
  begin
    data = @sdk.all_color_collections().collect { |o| o.to_attrs if o.respond_to?(:to_attrs) }
  rescue NoMethodError => nme
    say_warning "The api endpoint all_color_collections() is not implemented on this Looker instance"
  rescue LookerSDK::NotFound => nf
    say_warning "The current user can't query all color collections"
  rescue LookerSDK::Error => e
    say_error "Error querying all_color_collections()"
    say_error e
    raise
  end
  data
end

#color_collection(collection_id) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/gzr/command.rb', line 154

def color_collection(collection_id)
  data = nil
  begin
    data = @sdk.color_collection(collection_id).to_attrs
  rescue NoMethodError => nme
    say_warning "The api endpoint color_collection(collection_id) is not implemented on this Looker instance"
  rescue LookerSDK::NotFound => nf
    say_warning "The color_collection(#{collection_id}) is not found"
  rescue LookerSDK::Error => e
    say_error "Error querying color_collection(#{collection_id})"
    say_error e
    raise
  end
  data
end

#color_palette_lookup!(obj) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
# File 'lib/gzr/command.rb', line 196

def color_palette_lookup!(obj)
  return nil unless obj.respond_to?(:'has_key?')
  #say_warning("performing color_palette_lookup! on #{JSON.pretty_generate obj}") if @options[:debug]
  palettes = []
  palettes += obj[:categoricalPalettes] if obj[:categoricalPalettes]
  palettes += obj[:sequentialPalettes] if obj[:sequentialPalettes]
  palettes += obj[:divergingPalettes] if obj[:divergingPalettes]
  obj[:palettes]=palettes
  #say_warning("got palettes #{JSON.pretty_generate palettes}") if @options[:debug]
  obj
end

#create_merge_query(merge_query) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/gzr/command.rb', line 95

def create_merge_query(merge_query)
  begin
    data = @sdk.create_merge_query(merge_query)
  rescue NoMethodError => nme
    say_error "The api endpoint create_merge_query() is not implemented on this Looker instance"
    raise
  rescue LookerSDK::Error => e
    say_error "Error creating merge_query(#{JSON.pretty_generate(merge_query)})"
    say_error e
    raise
  end
  data
end

#create_query(query) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gzr/command.rb', line 67

def create_query(query)
  begin
    data = @sdk.create_query(query)
    if !(data.respond_to?(:id))
      raise Gzr::CLI::Error, "create_query(#{JSON.pretty_generate(query)}) returned #{data.inspect}"
    end
  rescue LookerSDK::Error => e
    say_error "Error creating query(#{JSON.pretty_generate(query)})"
    say_error e
    raise
  end
  data
end

#default_color_collectionObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/gzr/command.rb', line 136

def default_color_collection()
  return @dcc if @dcc
  data = nil
  begin
    data = @sdk.default_color_collection().to_attrs
    @dcc = data
  rescue NoMethodError => nme
    say_warning "The api endpoint default_color_collection() is not implemented on this Looker instance"
  rescue LookerSDK::NotFound => nf
    say_warning "The current user can't query the default color collection"
  rescue LookerSDK::Error => e
    say_error "Error querying default_color_collection()"
    say_error e
    raise
  end
  data
end

#executeObject

Execute this command

Raises:

  • (NotImplementedError)


48
49
50
51
52
53
# File 'lib/gzr/command.rb', line 48

def execute(*)
  raise(
    NotImplementedError,
    "#{self.class}##{__method__} must be implemented"
  )
end

#field_expression(name) ⇒ Object

This method will accept a field name in a format like ‘c.e.g’ and convert it into ‘c&.e&.g’, which can be evaluated to get the value of g, or nil if any intermediate value is nil.



387
388
389
390
# File 'lib/gzr/command.rb', line 387

def field_expression(name)
  parts = name.split(/\./)
  parts.join('&.')
end

#field_names(opt_fields) ⇒ Object

This method accepts a string containing a list of fields. The fields can be nested in a format like…

‘a,b,c(d,e(f,g)),h’

representing a structure like

{

a: "val",
b: "val",
c: {
  d: "val",
  e: {
    f: "val",
    g: "val"
  }
},
h: "val"

}

That string will get parsed and yield an array like

a, b, c.d, c.e.f, c.e.g, h


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/gzr/command.rb', line 356

def field_names(opt_fields)
  fields = []
  token_stack = []
  last_token = false
  tokens = opt_fields.split /(\(|,|\))/
  tokens << nil
  tokens.each do |t|
    if t.nil? then
      fields << (token_stack + [last_token]).join('.') if last_token
    elsif t.empty? then
      next
    elsif t == ',' then
      fields << (token_stack + [last_token]).join('.') if last_token
    elsif t == '(' then
      token_stack.push(last_token)
    elsif t == ')' then
      fields << (token_stack + [last_token]).join('.') if last_token
      token_stack.pop
      last_token = false
    else
      last_token = t
    end
  end
  fields
end

#find_color_palette_reference(obj, default_colors = nil, &block) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/gzr/command.rb', line 178

def find_color_palette_reference(obj, default_colors=nil, &block)
  begin
    dcc = default_color_collection()
    if dcc.nil?
      say_warning "You do not have access to query color palettes so these won't be processed."
      return
    end
    @default_colors=color_palette_lookup!(dcc)
    #say_warning("Default colors #{JSON.pretty_generate @default_colors}") if @options[:debug]
  end unless @default_colors

  if obj.respond_to?(:'has_key?') && obj.has_key?(:collection_id) && obj.has_key?(:palette_id)
    yield(obj,@default_colors)
  elsif obj.is_a? Enumerable
    obj.each { |o| find_color_palette_reference(o,@default_colors,&block) }
  end
end

#find_vis_config_reference(obj, &block) ⇒ Object



170
171
172
173
174
175
176
# File 'lib/gzr/command.rb', line 170

def find_vis_config_reference(obj, &block)
  if obj.respond_to?(:'has_key?') && obj.has_key?(:vis_config)
    yield (obj[:vis_config])
  elsif obj.is_a? Enumerable
    obj.each { |o| find_vis_config_reference(o,&block) }
  end
end

#keys_to_keep(operation) ⇒ Object

This method accepts the name of an sdk operation, then finds the parameter for that operation in the data structures from the swagger.json file. The parameter is a json object. Some of the attributes of the json object are read-only, and some are read-write. A few are write-only. The list of read-write and write-only attribute names are returned as an array. That array can be used to take the json document that describes an object and strip out the read-only values, creating a document that can be used to create or update an object.

The pattern typically looks like this…

new_obj_hash = existing_obj_hash.select do |k,v|
  keys_to_keep('create_new_obj').include? k
end


285
286
287
288
# File 'lib/gzr/command.rb', line 285

def keys_to_keep(operation)
  @keys_to_keep_cache ||= {}
  @keys_to_keep_cache[operation] ||= keys_to_keep_internal(operation)
end

#keys_to_keep_internal(operation) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/gzr/command.rb', line 290

def keys_to_keep_internal(operation)
  o = @sdk.operations[operation] || @sdk.operations[operation.to_sym]
  begin
    say_error "Operation #{operation} not found"
    return []
  end unless o

  parameters = o[:info][:parameters].select { |p| p[:in] == "body" && p[:schema] }

  say_warning "Expecting exactly one body parameter with a schema for operation #{operation}" unless parameters.length == 1
  schema_ref = parameters[0][:schema][:$ref].split(/\//)
  key_list = @sdk.swagger[schema_ref[1].to_sym][schema_ref[2].to_sym][:properties].reject { |k,v| v[:readOnly] }.keys
  say_warning "key_list #{operation} -> #{key_list}" if @options[:debug]
  return key_list

end

#merge_query(merge_result_id) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/gzr/command.rb', line 81

def merge_query(merge_result_id)
  data = nil
  begin
    data = @sdk.merge_query(merge_result_id)
  rescue NoMethodError => nme
    say_error "The api endpoint merge_query(#{merge_result_id}) is not implemented on this Looker instance"
  rescue LookerSDK::Error => e
    say_error "Error querying merge_query(#{merge_result_id})"
    say_error e
    raise
  end
  data
end

#pairs(a, b, *args) ⇒ Object

This method will accept two arrays, a and b, and create a third array like [ [a,b], [a,b], [a,b], …]. If either array is longer than the other, additional pairs will be generated with the shorter array padded out with nil values.

Any additional args will be added to each inner array.



400
401
402
403
404
405
406
407
408
409
410
# File 'lib/gzr/command.rb', line 400

def pairs(a, b, *args)
  pair_array = Array.new([a.count,b.count].max) do |i|
    pair = [a.fetch(i,nil),b.fetch(i,nil)]
    pair += args if args
    pair
  end

  return pair_array unless block_given?

  pair_array.collect { |e| yield(e) }
end

#query(query_id) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gzr/command.rb', line 55

def query(query_id)
  data = nil
  begin
    data = @sdk.query(query_id)
  rescue LookerSDK::Error => e
    say_error "Error querying query(#{query_id})"
    say_error e
    raise
  end
  data
end

#render_csv(t) ⇒ Object

The tty-table gem is normally used to output tabular data. This method accepts a Table object as used by the tty-table gem, and generates CSV output. It returns a string with crlf encoding



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/gzr/command.rb', line 312

def render_csv(t)
  io = StringIO.new
  io.puts (
    t.header.collect do |v|
      v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : ""
    end.join(',')
  ) unless @options[:plain]
  t.each do |row|
    next if row === t.header
    io.puts (
      row.collect do |v|
        v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : ""
      end.join(',')
    )
  end
  io.rewind
  io.gets(nil).encode(crlf_newline: true)
end

#rewrite_color_palette!(o, default_colors) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/gzr/command.rb', line 208

def rewrite_color_palette!(o,default_colors)
  cc = nil
  if o[:collection_id] == default_colors[:id]
    o[:collection_default] = true
    cc = default_colors
  else
    o[:collection_default] = false
    #say_ok("looking up color collection by id #{o[:collection_id]}") if @options[:debug]
    cc = color_palette_lookup!(color_collection(o[:collection_id]))
  end
  return unless cc
  #say_warning("got color collection #{JSON.pretty_generate cc}") if @options[:debug]
  o[:collection_label] = cc[:label]
  ps = cc[:palettes].select { |p| p[:id] == o[:palette_id] }
  if ps.length > 0
    p = ps.first
    o[:palette_label] = p[:label]
    o[:palette_type] = p[:type]
    o[:palette_colors] = p[:colors] if p[:colors]
    o[:palette_stops] = p[:stops] if p[:stops]
  end
end

#run_inline_query(query) ⇒ Object



109
110
111
112
113
114
115
116
117
118
# File 'lib/gzr/command.rb', line 109

def run_inline_query(query)
  begin
    data = @sdk.run_inline_query("json",query)
  rescue LookerSDK::Error => e
    say_error "Error running inline_query(#{JSON.pretty_generate(query)})"
    say_error e
    raise
  end
  data
end

#update_color_palette!(o, default_colors, force_default = false) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/gzr/command.rb', line 231

def update_color_palette!(o,default_colors,force_default=false)
  return unless o.has_key?(:collection_label) && o.has_key?(:palette_type)

  cc = default_colors
  if !(force_default && o[:collection_default])
    # look up color collection by id
    #say_warning("attempting to match palette on id #{o[:collection_id]}") if @options[:debug]
    cc = color_palette_lookup!(color_collection(o[:collection_id]))
    if cc.nil?
      # find color collection by name
      #say_warning("no match on id, attempting to match palette on name #{o[:collection_label]}") if @options[:debug]
      ccs = all_color_collections()&.select { |cc| o[:collection_label] == cc[:label]}
      if ccs.nil? || ccs.length == 0
        # no color collection found. Use default.
        say_warning "Color collection #{o[:collection_label]} not found. Using default."
        cc = default_colors
      else
        cc = color_palette_lookup!(ccs.first)
      end
    end
  end
  o[:collection_id] = cc[:id]

  # look up palette by id
  ps = cc[:palettes].select {|p| p[:id] == o[:palette_id]}
  if ps.length == 0
    # find palette by type
    ps = cc[:palettes].select {|p| p[:type] == o[:palette_type]}
    if ps.length > 0
      o[:palette_id] = ps.first[:id]
    else
      # no palette found
      say_warning "Color palette #{o[:palette_type]} not found."
      o.delete(:palette_id)
    end
  end
end