dtk-client 0.5.6.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. checksums.yaml +15 -0
  2. data/Gemfile +5 -0
  3. data/Gemfile_dev +12 -0
  4. data/README.md +78 -0
  5. data/bin/dtk +54 -0
  6. data/bin/dtk-shell +15 -0
  7. data/dtk-client.gemspec +49 -0
  8. data/lib/auxiliary.rb +13 -0
  9. data/lib/bundler_monkey_patch.rb +9 -0
  10. data/lib/client.rb +48 -0
  11. data/lib/command_helper.rb +16 -0
  12. data/lib/command_helpers/git_repo.rb +391 -0
  13. data/lib/command_helpers/jenkins_client/config_xml.rb +271 -0
  14. data/lib/command_helpers/jenkins_client.rb +91 -0
  15. data/lib/command_helpers/service_importer.rb +99 -0
  16. data/lib/command_helpers/service_link.rb +18 -0
  17. data/lib/command_helpers/ssh_processing.rb +43 -0
  18. data/lib/commands/common/thor/assembly_workspace.rb +1089 -0
  19. data/lib/commands/common/thor/clone.rb +39 -0
  20. data/lib/commands/common/thor/common.rb +34 -0
  21. data/lib/commands/common/thor/edit.rb +168 -0
  22. data/lib/commands/common/thor/list_diffs.rb +84 -0
  23. data/lib/commands/common/thor/pull_clone_changes.rb +11 -0
  24. data/lib/commands/common/thor/pull_from_remote.rb +99 -0
  25. data/lib/commands/common/thor/purge_clone.rb +26 -0
  26. data/lib/commands/common/thor/push_clone_changes.rb +45 -0
  27. data/lib/commands/common/thor/push_to_remote.rb +45 -0
  28. data/lib/commands/common/thor/reparse.rb +36 -0
  29. data/lib/commands/common/thor/set_required_params.rb +29 -0
  30. data/lib/commands/common/thor/task_status.rb +81 -0
  31. data/lib/commands/thor/account.rb +213 -0
  32. data/lib/commands/thor/assembly.rb +329 -0
  33. data/lib/commands/thor/attribute.rb +62 -0
  34. data/lib/commands/thor/component.rb +52 -0
  35. data/lib/commands/thor/component_module.rb +829 -0
  36. data/lib/commands/thor/component_template.rb +153 -0
  37. data/lib/commands/thor/dependency.rb +18 -0
  38. data/lib/commands/thor/developer.rb +105 -0
  39. data/lib/commands/thor/dtk.rb +117 -0
  40. data/lib/commands/thor/library.rb +107 -0
  41. data/lib/commands/thor/node.rb +411 -0
  42. data/lib/commands/thor/node_group.rb +211 -0
  43. data/lib/commands/thor/node_template.rb +88 -0
  44. data/lib/commands/thor/project.rb +17 -0
  45. data/lib/commands/thor/provider.rb +155 -0
  46. data/lib/commands/thor/repo.rb +35 -0
  47. data/lib/commands/thor/service.rb +656 -0
  48. data/lib/commands/thor/service_module.rb +806 -0
  49. data/lib/commands/thor/state_change.rb +10 -0
  50. data/lib/commands/thor/target.rb +94 -0
  51. data/lib/commands/thor/task.rb +100 -0
  52. data/lib/commands/thor/utils.rb +4 -0
  53. data/lib/commands/thor/workspace.rb +437 -0
  54. data/lib/commands.rb +40 -0
  55. data/lib/config/cacert.pem +3785 -0
  56. data/lib/config/client.conf.header +18 -0
  57. data/lib/config/configuration.rb +82 -0
  58. data/lib/config/default.conf +14 -0
  59. data/lib/config/disk_cacher.rb +60 -0
  60. data/lib/configurator.rb +92 -0
  61. data/lib/context_router.rb +23 -0
  62. data/lib/core.rb +460 -0
  63. data/lib/domain/git_adapter.rb +221 -0
  64. data/lib/domain/response.rb +234 -0
  65. data/lib/dtk-client/version.rb +3 -0
  66. data/lib/dtk_constants.rb +23 -0
  67. data/lib/dtk_logger.rb +96 -0
  68. data/lib/error.rb +74 -0
  69. data/lib/git-logs/git.log +0 -0
  70. data/lib/parser/adapters/option_parser.rb +53 -0
  71. data/lib/parser/adapters/thor/common_option_defs.rb +12 -0
  72. data/lib/parser/adapters/thor.rb +509 -0
  73. data/lib/require_first.rb +87 -0
  74. data/lib/search_hash.rb +27 -0
  75. data/lib/shell/context.rb +975 -0
  76. data/lib/shell/context_aux.rb +29 -0
  77. data/lib/shell/domain.rb +447 -0
  78. data/lib/shell/header_shell.rb +27 -0
  79. data/lib/shell/help_monkey_patch.rb +221 -0
  80. data/lib/shell/interactive_wizard.rb +233 -0
  81. data/lib/shell/parse_monkey_patch.rb +22 -0
  82. data/lib/shell/status_monitor.rb +105 -0
  83. data/lib/shell.rb +219 -0
  84. data/lib/util/console.rb +143 -0
  85. data/lib/util/dtk_puppet.rb +46 -0
  86. data/lib/util/os_util.rb +265 -0
  87. data/lib/view_processor/augmented_simple_list.rb +27 -0
  88. data/lib/view_processor/hash_pretty_print.rb +106 -0
  89. data/lib/view_processor/simple_list.rb +139 -0
  90. data/lib/view_processor/table_print.rb +277 -0
  91. data/lib/view_processor.rb +112 -0
  92. data/puppet/manifests/init.pp +72 -0
  93. data/puppet/manifests/params.pp +16 -0
  94. data/puppet/r8meta.puppet.yml +18 -0
  95. data/puppet/templates/bash_profile.erb +2 -0
  96. data/puppet/templates/client.conf.erb +1 -0
  97. data/puppet/templates/dtkclient.erb +2 -0
  98. data/spec/assembly_spec.rb +50 -0
  99. data/spec/assembly_template_spec.rb +51 -0
  100. data/spec/component_template_spec.rb +40 -0
  101. data/spec/dependency_spec.rb +6 -0
  102. data/spec/dtk_shell_spec.rb +13 -0
  103. data/spec/dtk_spec.rb +33 -0
  104. data/spec/lib/spec_helper.rb +10 -0
  105. data/spec/lib/spec_thor.rb +105 -0
  106. data/spec/module_spec.rb +35 -0
  107. data/spec/node_spec.rb +43 -0
  108. data/spec/node_template_spec.rb +25 -0
  109. data/spec/project_spec.rb +6 -0
  110. data/spec/repo_spec.rb +7 -0
  111. data/spec/response_spec.rb +52 -0
  112. data/spec/service_spec.rb +41 -0
  113. data/spec/state_change_spec.rb +7 -0
  114. data/spec/table_print_spec.rb +48 -0
  115. data/spec/target_spec.rb +57 -0
  116. data/spec/task_spec.rb +28 -0
  117. data/views/assembly/augmented_simple_list.rb +12 -0
  118. data/views/assembly_template/augmented_simple_list.rb +12 -0
  119. data/views/list_task/augmented_simple_list.rb +12 -0
  120. metadata +351 -0
@@ -0,0 +1,509 @@
1
+ require 'thor'
2
+ require 'thor/group'
3
+ require 'readline'
4
+ require 'colorize'
5
+ require 'digest/sha1'
6
+
7
+ dtk_require("../../shell/interactive_wizard")
8
+ dtk_require("../../util/os_util")
9
+ dtk_require("../../util/console")
10
+ dtk_require_common_commands('thor/task_status')
11
+ dtk_require_from_base("command_helper")
12
+ dtk_require("../../context_router")
13
+
14
+ module DTK
15
+ module Client
16
+ class CommandBaseThor < Thor
17
+ dtk_nested_require('thor','common_option_defs')
18
+
19
+ include CommandBase
20
+ extend CommandBase
21
+ extend TaskStatusMixin
22
+ extend Console
23
+ include CommandHelperMixin
24
+ extend CommonOptionDefsClassMixin
25
+
26
+ @@cached_response = {}
27
+ @@invalidate_map = []
28
+ TIME_DIFF = 60 #second(s)
29
+ EXTENDED_TIMEOUT = 360 #second(s)
30
+ HIDE_FROM_BASE_CONTEXT = "HIDE_FROM_BASE"
31
+
32
+ # thor command specific constants
33
+ ALT_IDENTIFIER_SEPARATOR = ':::'
34
+
35
+ def initialize(args, opts, config)
36
+ @conn = config[:conn]
37
+ super
38
+ end
39
+
40
+ def self.execute_from_cli(conn,method_name,context_params,thor_options,shell_execution=false)
41
+ @@shell_execution = shell_execution
42
+
43
+ # I am sorry!
44
+ if method_name == 'help'
45
+ ret = start([method_name] + context_params.method_arguments,:conn => conn)
46
+ else
47
+ ret = start([method_name, context_params] + (thor_options||[]),:conn => conn)
48
+ end
49
+
50
+ # special case where we have validation reply
51
+ if ret.kind_of?(Response)
52
+ if ret.validation_response?
53
+ ret = action_on_revalidation_response(ret, conn, method_name, context_params, thor_options, shell_execution)
54
+ end
55
+ end
56
+
57
+ ret.kind_of?(Response) ? ret : Response::NoOp.new
58
+ end
59
+
60
+ # TODO: Make sure that server responds with new format of ARGVS
61
+ def self.action_on_revalidation_response(validation_response, conn, method_name, context_params, thor_options, shell_execution)
62
+ puts "[NOTICE] #{validation_response.validation_message}"
63
+ actions = validation_response.validation_actions
64
+
65
+ actions.each_with_index do |action, i|
66
+ if Console.confirmation_prompt("Pre-action '#{action['action']}' needed, execute"+"?")
67
+ # we have hash map with values { :assembly_id => 2123123123, :option_1 => true }
68
+ # we translate to array of values, with action as first element
69
+
70
+ # def self.execute_from_cli(conn,method_name,context_params,options_args,shell_execution=false)
71
+ response = self.execute_from_cli(conn, action['action'], create_context_arguments(action['params']),[],shell_execution)
72
+ # we abort if error happens
73
+ ResponseErrorHandler.check(response)
74
+
75
+ if action['wait_for_complete']
76
+ entity_id, entity_type = action['wait_for_complete']['id'].to_s, action['wait_for_complete']['type']
77
+ puts "Waiting for task to complete ..."
78
+ task_status_aux(entity_id,entity_type,true)
79
+ end
80
+ else
81
+ # validation action are being skipped
82
+ return ""
83
+ end
84
+ end
85
+
86
+ puts "Executing original action: '#{method_name}' ..."
87
+ # if all executed correctly we run original action
88
+ return self.execute_from_cli(conn,method_name, context_params,thor_options,shell_execution)
89
+ end
90
+
91
+ def self.invalidate_entities(*array_of_entites)
92
+ # we handle to cases here
93
+ # n-context invalidation, whole structure
94
+ @@invalidate_map << array_of_entites.join('_').to_sym
95
+
96
+ # last entity
97
+ @@invalidate_map << array_of_entites.last.to_sym
98
+ end
99
+
100
+ # we take current timestamp and compare it to timestamp stored in @@cached_response
101
+ # if difference is greater than TIME_DIFF we send request again, if not we use
102
+ # response from cache
103
+ def self.get_cached_response(entity_name, url, subtype={})
104
+ subtype ||= {}
105
+ current_ts = Time.now.to_i
106
+ cache_id = (subtype.empty? ? :response : generate_cached_id(subtype))
107
+
108
+ # if @@cache_response is empty return true if not than return time difference between
109
+ # current_ts and ts stored in cache
110
+ time_difference = @@cached_response[entity_name].nil? ? true : ((current_ts - @@cached_response[entity_name][:ts]) > TIME_DIFF)
111
+
112
+ if (@@cached_response[entity_name])
113
+ time_difference = true if @@cached_response[entity_name][cache_id].nil?
114
+ end
115
+
116
+ if (time_difference || @@invalidate_map.include?(entity_name))
117
+ response = post rest_url(url), subtype
118
+
119
+ # we do not want to catch is if it is not valid
120
+ if response.nil? || response.empty?
121
+ DtkLogger.instance.debug("Response was nil or empty for that reason we did not cache it.")
122
+ return response
123
+ end
124
+
125
+ if response.ok?
126
+ response_hash = {cache_id => response, :ts => current_ts}
127
+
128
+ @@invalidate_map.delete(entity_name) if @@invalidate_map.include?(entity_name)
129
+
130
+ if @@cached_response[entity_name]
131
+ @@cached_response[entity_name].merge!(response_hash)
132
+ else
133
+ @@cached_response.store(entity_name, response_hash)
134
+ end
135
+ end
136
+ end
137
+
138
+ if @@cached_response[entity_name]
139
+ return @@cached_response[entity_name][cache_id]
140
+ else
141
+ return nil
142
+ end
143
+ end
144
+
145
+ def self.generate_cached_id(subtype)
146
+ values = ''
147
+ # subtype.sort.map do |key,value|
148
+ # removed sort since subtype is hash where keys are symbols,
149
+ # sort method uses the <=> comparison operator to put things into order but
150
+ # symbols don't have a <=> comparison operator in ruby 1.8.7
151
+ subtype.map do |key,value|
152
+ values += value.to_s
153
+ end
154
+
155
+ Digest::SHA1.hexdigest(values)
156
+ end
157
+
158
+ def self.create_context_arguments(params)
159
+ context_params = DTK::Shell::ContextParams.new
160
+ params.each do |k,v|
161
+ context_params.add_context_to_params(k,k,v)
162
+ end
163
+ return context_params
164
+ end
165
+
166
+ def self.list_method_supported?
167
+ return (respond_to?(:validation_list) || respond_to?(:whoami))
168
+ end
169
+
170
+ # returns all task names for given thor class with use friendly names (with '-' instead '_')
171
+ def self.task_names
172
+ all_tasks().map(&:first).collect { |item| item.gsub('_','-')}
173
+ end
174
+
175
+ def self.get_usage_info(entity_name, method)
176
+ # no need for nil checks since task will be found
177
+ # [0] element contains desire usage description
178
+ # [2] element contains method name with '_'
179
+ result = printable_tasks().select { |help_item| help_item[2].gsub('_','-') == method }.flatten[0]
180
+ # we add entity name with dashes
181
+ return result.gsub('dtk', "dtk #{entity_name.gsub('_','-')}")
182
+ end
183
+
184
+ # caches all the taks names for each possible tier and each thor class
185
+ # returnes it, executes only once and only on dtk-shell start
186
+ def self.tiered_task_names
187
+ # cached data
188
+ cached_tasks = {}
189
+
190
+ # get command name from namespace (which is derived by thor from file name)
191
+ command = namespace.split(':').last.gsub('_','-').upcase
192
+
193
+ # first elvel identifier
194
+ command_sym = command.downcase.to_sym
195
+ command_id_sym = (command.downcase + '_wid').to_sym
196
+
197
+ cached_tasks.store(command_sym, [])
198
+ cached_tasks.store(command_id_sym, [])
199
+
200
+ # n-context children
201
+ all_children = []
202
+ children = self.respond_to?(:all_children) ? self.all_children() : nil
203
+ all_children << children unless children.nil?
204
+
205
+ # some commands have multiple n-level contexts
206
+ # e.g. workspace_node_component, workspace_utils and workspace_node_utils
207
+ # we go through all of them and load them to 'all_children'
208
+ multi_context_children = self.respond_to?(:multi_context_children) ? self.multi_context_children() : nil
209
+ if multi_context_children
210
+ multi_context_children.each do |mc|
211
+ all_children << (mc.is_a?(Array) ? mc : multi_context_children)
212
+ end
213
+ end
214
+
215
+ # n-context-override task, special case which
216
+ override_task_obj = self.respond_to?(:override_allowed_methods) ? self.override_allowed_methods.dup : nil
217
+
218
+ # we seperate tier 1 and tier 2 tasks
219
+ all_tasks().each do |task|
220
+ # noralize task name with '-' since it will be displayed to user that way
221
+ task_name = task[0].gsub('_','-')
222
+ usage = task[1].usage
223
+ # we will match those commands that require identifiers (NAME/ID)
224
+ # e.g. ASSEMBLY-NAME/ID list ... => MATCH
225
+ # e.g. [ASSEMBLY-NAME/ID] list ... => MATCH
226
+ matched_data = task[1].usage.match(/\[?#{command}.?(NAME\/ID|ID\/NAME)\]?/)
227
+ matched_alt_identifiers_data = nil
228
+
229
+ # we chance alternate providers
230
+ if respond_to?(:alternate_identifiers)
231
+ alternate_identifiers = self.alternate_identifiers()
232
+
233
+ alternate_identifiers.each do |a_provider|
234
+ if matched_alt_identifiers_data = task[1].usage.match(/\[?#{a_provider}.?(NAME\/ID|ID\/NAME)\]?/)
235
+ command_alt_sym = "#{command}_#{a_provider}".downcase.to_sym
236
+ cached_tasks[command_alt_sym] = cached_tasks.fetch(command_alt_sym,[])
237
+ cached_tasks[command_alt_sym] << task_name
238
+ # when found break
239
+ break
240
+ end
241
+ end
242
+ end
243
+
244
+ # only if not matched alt data found continue with caching of task
245
+ unless matched_alt_identifiers_data
246
+ if matched_data.nil?
247
+ # no match it means it is tier 1 task, tier 1 => dtk:\assembly>
248
+ # using HIDE_FROM_BASE_CONTEXT to hide command from base context (e.g from dtk:/assembly>) ...
249
+ # ... but to be able to use that command in other context
250
+ # (e.g get-netstats removed from dtk:/assembly> but used in dtk:/assembly/assembly_id/utils)
251
+ cached_tasks[command_sym] << task_name unless usage.include?(HIDE_FROM_BASE_CONTEXT)
252
+ else
253
+ # match means it is tier 2 taks, tier 2 => dtk:\assembly\231312345>
254
+ cached_tasks[command_id_sym] << task_name
255
+ # if there are '[' it means it is optinal identifiers so it is tier 1 and tier 2 task
256
+ cached_tasks[command_sym] << task_name if matched_data[0].include?('[')
257
+ end
258
+
259
+ # n-level matching
260
+ all_children.each do |child|
261
+ current_children = []
262
+
263
+ child.each do |c|
264
+ current_children << c.to_s
265
+
266
+ # create entry e.g. assembly_node_id
267
+ child_id_sym = (command.downcase + '_' + current_children.join('_') + '_wid').to_sym
268
+
269
+ # n-context matching
270
+ matched_data = task[1].usage.match(/^\[?#{c.to_s.upcase}.?(NAME\/ID|ID\/NAME|ID|NAME)(\-?PATTERN)?\]?/)
271
+ if matched_data
272
+ cached_tasks[child_id_sym] = cached_tasks.fetch(child_id_sym,[]) << task_name
273
+ end
274
+
275
+ # override method list, we add these methods only once
276
+ if override_task_obj && !override_task_obj.is_completed?(c)
277
+ command_o_tasks, identifier_o_tasks = override_task_obj.get_all_tasks(c)
278
+ child_sym = (command.downcase + '_' + current_children.join('_')).to_sym
279
+
280
+ command_o_tasks.each do |o_task|
281
+ cached_tasks[child_sym] = cached_tasks.fetch(child_sym,[]) << o_task[0]
282
+ end
283
+
284
+ identifier_o_tasks.each do |o_task|
285
+ cached_tasks[child_id_sym] = cached_tasks.fetch(child_id_sym,[]) << o_task[0]
286
+ end
287
+
288
+ override_task_obj.add_to_completed(c)
289
+ end
290
+ end
291
+ end
292
+
293
+ # will leave this commented for now until we check if new code works properly
294
+ # if children
295
+ # current_children = []
296
+ # children.each do |child|
297
+ # current_children << child.to_s
298
+
299
+ # # create entry e.g. assembly_node_id
300
+ # child_id_sym = (command.downcase + '_' + current_children.join('_') + '_wid').to_sym
301
+
302
+ # # n-context matching
303
+ # matched_data = task[1].usage.match(/\[?#{child.to_s.upcase}.?(NAME\/ID|ID\/NAME|ID|NAME)(\-?PATTERN)?\]?/)
304
+ # if matched_data
305
+ # cached_tasks[child_id_sym] = cached_tasks.fetch(child_id_sym,[]) << task_name
306
+ # end
307
+
308
+ # # override method list, we add these methods only once
309
+ # if override_task_obj && !override_task_obj.is_completed?(child)
310
+ # command_o_tasks, identifier_o_tasks = override_task_obj.get_all_tasks(child)
311
+ # child_sym = (command.downcase + '_' + current_children.join('_')).to_sym
312
+
313
+ # command_o_tasks.each do |o_task|
314
+ # cached_tasks[child_sym] = cached_tasks.fetch(child_sym,[]) << o_task[0]
315
+ # end
316
+
317
+ # identifier_o_tasks.each do |o_task|
318
+ # cached_tasks[child_id_sym] = cached_tasks.fetch(child_id_sym,[]) << o_task[0]
319
+ # end
320
+
321
+ # override_task_obj.add_to_completed(child)
322
+ # end
323
+ # end
324
+ # end
325
+
326
+ end
327
+ end
328
+
329
+ # there is always help, and in all cases this is exception to the rule
330
+ cached_tasks[command_id_sym] << 'help'
331
+
332
+ return cached_tasks
333
+ end
334
+
335
+ # we make valid methods to make sure that when context changing
336
+ # we allow change only for valid ID/NAME
337
+ def self.valid_id?(value, conn, context_params)
338
+
339
+ context_list = self.get_identifiers(conn, context_params)
340
+ results = context_list.select { |e| e[:name].eql?(value) || e[:identifier].eql?(value.to_i)}
341
+
342
+ return results.empty? ? nil : results.first
343
+ end
344
+
345
+ def self.get_identifiers(conn, context_params)
346
+ @conn = conn if @conn.nil?
347
+
348
+ # we force raw output
349
+ # options = Thor::CoreExt::HashWithIndifferentAccess.new({'list' => true})
350
+
351
+ 3.downto(1) do
352
+ # get list data from one of the methods
353
+ if respond_to?(:validation_list)
354
+ response = validation_list(context_params)
355
+ else
356
+ clazz, endpoint, opts = whoami()
357
+ response = get_cached_response(clazz, endpoint, opts)
358
+ end
359
+
360
+ unless (response.nil? || response.empty?)
361
+ unless response['data'].nil?
362
+ identifiers = []
363
+ response['data'].each do |element|
364
+ identifiers << { :name => element['display_name'], :identifier => element['id'] }
365
+ end
366
+ return identifiers
367
+ end
368
+ end
369
+ unless response.nil?
370
+ break if response["status"].eql?('ok')
371
+ end
372
+ sleep(1)
373
+ end
374
+
375
+ DtkLogger.instance.warn("[WARNING] We were not able to check cached context, possible errors may occur.")
376
+ return []
377
+ end
378
+
379
+ no_tasks do
380
+
381
+ ##
382
+ # Block that allows users to specify part of the code which is expected to run for longer duration
383
+ #
384
+ def extended_timeout
385
+ puts "Please wait, this could take a few minutes ..."
386
+ old_timeout = ::DTK::Client::Conn.get_timeout()
387
+ ::DTK::Client::Conn.set_timeout(EXTENDED_TIMEOUT)
388
+ result = yield
389
+ ::DTK::Client::Conn.set_timeout(old_timeout)
390
+ result
391
+ end
392
+
393
+ # Method not implemented error
394
+ def not_implemented
395
+ raise DTK::Client::DtkError, "Method NOT IMPLEMENTED!"
396
+ end
397
+
398
+ def raise_validation_error_method_usage(method_name)
399
+ usage_text = self.class.all_tasks[method_name][:usage]
400
+ raise DTK::Client::DtkValidationError, "Invalid method usage, use: #{usage_text}"
401
+ end
402
+
403
+ # returns method name and usage
404
+ def current_method_info
405
+ unless @_initializer[2][:current_task]
406
+ raise DTK::Client::DtkError, "You are using development mode, and you have newer version of Thor gem than specified by dtk-client"
407
+ end
408
+
409
+ return @_initializer[2][:current_task].name, @_initializer[2][:current_task].usage
410
+ end
411
+
412
+ # returns names of the arguments, after the method name
413
+ def method_argument_names
414
+ name, usage = current_method_info
415
+ results = usage.split(name.gsub(/_/,'-')).last || ""
416
+ return results.split(' ')
417
+ end
418
+
419
+ #TODO: can make more efficient by having rest call that returns name from id, rather than using 'list path'
420
+ #entity_id can be a name as well as an id
421
+ def get_name_from_id_helper(entity_id, entity_type=nil,list_command_path=nil, subtype=nil)
422
+ return entity_id unless is_numeric_id?(entity_id)
423
+
424
+ entity_id = entity_id.to_i
425
+ if entity_type.nil?
426
+ entity_type,list_command_path,subtype = self.class.whoami()
427
+ end
428
+
429
+ match = nil
430
+ response = self.class.get_cached_response(entity_type,list_command_path,subtype)
431
+ if response.ok? and response['data']
432
+ match = response['data'].find{|entity|entity_id == entity['id']}
433
+ end
434
+ unless match
435
+ raise DTK::Client::DtkError, "Not able to resolve entity name, please provide #{entity_type} name."
436
+ end
437
+ match['display_name']
438
+ end
439
+
440
+ def is_numeric_id?(possible_id)
441
+ !possible_id.to_s.match(/^[0-9]+$/).nil?
442
+ end
443
+
444
+ # User input prompt
445
+ def user_input(message)
446
+ trap("INT", "SIG_IGN")
447
+ while line = Readline.readline("#{message}: ",true)
448
+ unless line.chomp.empty?
449
+ trap("INT", false)
450
+ return line
451
+ end
452
+ end
453
+ end
454
+
455
+ def get_type_and_raise_error_if_invalid(about, default_about, type_options)
456
+ about ||= default_about
457
+ raise DTK::Client::DtkError, "Not supported type '#{about}' for list for current context level. Possible type options: #{type_options.join(', ')}" unless type_options.include?(about)
458
+ return about, about[0..-2].to_sym
459
+ end
460
+
461
+ # check for delimiter '/', if present returns namespace and name for module/service
462
+ # returns: namespace, name
463
+ def get_namespace_and_name(input_remote_name)
464
+ (input_remote_name||'').include?('/') ? input_remote_name.split('/') : [nil, input_remote_name]
465
+ end
466
+ end
467
+
468
+
469
+ ##
470
+ # This is fix where we wanna exclude basename print when using dtk-shell.
471
+ # Thor has banner method, representing row when help is invoked. As such banner
472
+ # will print out basename first. e.g.
473
+ #
474
+ # dtk-shell assembly list [library|target] # List asssemblies in library or target
475
+ #
476
+ # Basename is derived from name of file, as such can be overriden to serve some other
477
+ # logic.
478
+ #
479
+ def self.basename
480
+ basename = super
481
+ basename = '' if basename == 'dtk-shell'
482
+ return basename
483
+ end
484
+
485
+ desc "help [SUBCOMMAND]", "Describes available subcommands or one specific subcommand"
486
+ def help(*args)
487
+ puts # pretty print
488
+ not_dtk_clazz = true
489
+
490
+ if defined?(DTK::Client::Dtk)
491
+ not_dtk_clazz = !self.class.eql?(DTK::Client::Dtk)
492
+ end
493
+
494
+ # not_dtk_clazz - we don't use subcommand print in case of root DTK class
495
+ # for other classes Assembly, Node, etc. we print subcommand
496
+ # this gives us console output: dtk assembly converge ASSEMBLY-ID
497
+ #
498
+ # @@shell_execution - if we run from shell we don't want subcommand output
499
+ #
500
+
501
+ super(args.empty? ? nil : args.first, not_dtk_clazz && !@@shell_execution)
502
+
503
+ # we will print error in case configuration has reported error
504
+ @conn.print_warning if @conn.connection_error?
505
+ puts # pretty print
506
+ end
507
+ end
508
+ end
509
+ end
@@ -0,0 +1,87 @@
1
+ require File.expand_path('../lib/error', File.dirname(__FILE__))
2
+
3
+ # we leave possibilites that folders user multiple names
4
+ # when somebody takes fresh projects from git it is expected that
5
+ # person will use dtk-common name
6
+ POSSIBLE_COMMON_CORE_FOLDERS = ['dtk-common-repo','dtk-common-core']
7
+
8
+
9
+ def dtk_require(*files_x)
10
+ files = (files_x.first.kind_of?(Array) ? files_x.first : files_x)
11
+ caller_dir = caller.first.gsub(/\/[^\/]+$/,"")
12
+ files.each{|f|require File.expand_path(f,caller_dir)}
13
+ end
14
+
15
+ def dtk_require_from_base(*files_x)
16
+ #different than just calling dtk_require because of change to context give by caller
17
+ dtk_require(*files_x)
18
+ end
19
+
20
+ def dtk_require_common_commands(*files_x)
21
+ dtk_require_from_base(*files_x.map{|f|"commands/common/#{f}"})
22
+ end
23
+
24
+ def dtk_nested_require(dir,*files_x)
25
+ files = (files_x.first.kind_of?(Array) ? files_x.first : files_x)
26
+ caller_dir = caller.first.gsub(/\/[^\/]+$/,"")
27
+
28
+ # invalid command will be send here as such needs to be handled.
29
+ # we will throw DtkClient error as invalid command
30
+ files.each do |f|
31
+ begin
32
+ require File.expand_path("#{dir}/#{f}",caller_dir)
33
+ rescue LoadError => e
34
+ if e.message.include? "#{dir}/#{f}"
35
+ raise DTK::Client::DtkError,"Command '#{f}' not found."
36
+ else
37
+ raise e
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ # this returns true if there is no common folder e.g. dtk-common in parent folder,
44
+ # and gem is installed
45
+ def gem_only_available?()
46
+ return !determine_common_folder() && is_dtk_common_core_gem_installed?
47
+ end
48
+
49
+ def dtk_require_dtk_common_core(common_library)
50
+ # use common folder else common gem
51
+ common_folder = determine_common_folder()
52
+
53
+ if common_folder
54
+ dtk_require("../../" + common_folder + "/lib/#{common_library}")
55
+ elsif is_dtk_common_core_gem_installed?
56
+ # already loaded so do not do anything
57
+ else
58
+ raise DTK::Client::DtkError,"Common directory/gem not found, please make sure that you have cloned dtk-common folder or installed dtk common gem!"
59
+ end
60
+ end
61
+
62
+ private
63
+
64
+ ##
65
+ # Check if dtk-common gem has been installed if so use common gem. If there is no gem
66
+ # logic from dtk_require_dtk_common will try to find commond folder.
67
+ # DEVELOPER NOTE: Uninstall dtk-common gem when changing dtk-common to avoid re-building gem.
68
+ def is_dtk_common_core_gem_installed?
69
+ begin
70
+ # if no exception gem is found
71
+ gem 'dtk-common-core'
72
+ return true
73
+ rescue Gem::LoadError
74
+ return false
75
+ end
76
+ end
77
+
78
+ ##
79
+ # Checks for expected names of dtk-common folder and returns name of existing common folder
80
+ def determine_common_folder
81
+ POSSIBLE_COMMON_CORE_FOLDERS.each do |folder|
82
+ path = File.join(File.dirname(__FILE__),'..','..',folder)
83
+ return folder if File.directory?(path)
84
+ end
85
+
86
+ return nil
87
+ end
@@ -0,0 +1,27 @@
1
+ module DTK
2
+ module Client
3
+ class SearchHash < Hash
4
+ def cols=(cols)
5
+ self.merge!(:columns => cols)
6
+ end
7
+ def filter=(filter)
8
+ self.merge!(:filter => filter)
9
+ end
10
+ def set_order_by!(col,dir="ASC")
11
+ unless %w{ASC DESC}.include?(dir)
12
+ raise Error.new("set order by direction must by 'ASC' or 'DESC'")
13
+ end
14
+ order_by =
15
+ [{
16
+ :field => col,
17
+ :order => dir
18
+ }]
19
+ self.merge!(:order_by => order_by)
20
+ end
21
+
22
+ def post_body_hash()
23
+ {:search => JSON.generate(self)}
24
+ end
25
+ end
26
+ end
27
+ end