Changes for ruby sdk packaging as a gem.
[arvados.git] / sdk / cli / bin / arv
1 #!/usr/bin/env ruby
2
3 # Arvados cli client
4 #
5 # Ward Vandewege <ward@clinicalfuture.com>
6
7 if RUBY_VERSION < '1.9.3' then
8   abort <<-EOS
9 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
10   EOS
11 end
12
13 ENV['ARVADOS_API_VERSION'] ||= 'v1'
14
15 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
16   abort <<-EOS
17 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
18   EOS
19 end
20
21 begin
22   require 'rubygems'
23   require 'google/api_client'
24   require 'json'
25   require 'pp'
26   require 'trollop'
27   require 'andand'
28   require 'oj'
29   require 'active_support/inflector'
30 rescue LoadError
31   abort <<-EOS
32
33 Please install all required gems: 
34
35   gem install google-api-client json trollop andand oj activesupport
36
37   EOS
38 end
39
40 ActiveSupport::Inflector.inflections do |inflect|
41   inflect.irregular 'specimen', 'specimens'
42   inflect.irregular 'human', 'humans'
43 end
44
45 module Kernel
46   def suppress_warnings
47     original_verbosity = $VERBOSE
48     $VERBOSE = nil
49     result = yield
50     $VERBOSE = original_verbosity
51     return result
52   end
53 end
54
55 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
56 if ENV['ARVADOS_API_HOST_INSECURE']
57   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
58 end
59
60 class Google::APIClient
61  def discovery_document(api, version)
62   api = api.to_s
63   return @discovery_documents["#{api}:#{version}"] ||= (begin
64     response = self.execute!(
65       :http_method => :get,
66       :uri => self.discovery_uri(api, version),
67       :authenticated => false
68     )
69     response.body.class == String ? JSON.parse(response.body) : response.body
70   end)
71  end
72 end
73
74 client = Google::APIClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
75 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
76
77 def to_boolean(s)
78   !!(s =~ /^(true|t|yes|y|1)$/i)
79 end
80
81 def parse_arguments(discovery_document)
82   resource_types = Array.new()
83   resource_types << '--help'
84   discovery_document["resources"].each do |k,v|
85     resource_types << k.singularize
86   end
87
88   global_opts = Trollop::options do
89     banner "arvados cli client"
90     opt :dry_run, "Don't actually do anything", :short => "-n"
91     opt :verbose, "Print some things on stderr", :short => "-v"
92     opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
93     opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
94     opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
95     opt :pretty, "Synonym of --human", :short => nil
96     stop_on resource_types
97   end
98   
99   # get the subcommand
100   resource_arg = ARGV.shift
101   if resource_types.include?(resource_arg) and resource_arg != '--help' then
102     # subcommand exists
103     # Now see if the method supplied exists
104     method = ARGV.shift
105     if discovery_document["resources"][resource_arg.pluralize]["methods"].include?(method) then
106       # method exists. Collect arguments.
107       discovered_params = discovery_document["resources"][resource_arg.pluralize]["methods"][method]["parameters"]
108       method_opts = Trollop::options do
109         discovered_params.each do |k,v|
110           opts = Hash.new()
111           opts[:type] = v["type"].to_sym if v.include?("type")
112           if [:datetime, :text, :object].index opts[:type]
113             opts[:type] = :string                       # else trollop bork
114           end
115           opts[:default] = v["default"] if v.include?("default")
116           opts[:default] = v["default"].to_i if opts[:type] == :integer
117           opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
118           opts[:required] = true if v.include?("required") and v["required"]
119           description = ''
120           description = '  ' + v["description"] if v.include?("description")
121           opt k.to_sym, description, opts
122         end
123       end
124       discovered_params.each do |k,v|
125         if v["type"] == "object" and method_opts.has_key? k
126           method_opts[k] = JSON.parse method_opts[k]
127         end
128       end
129     else
130       banner = "\nThis resource type supports the following methods:\n\n"
131       discovery_document["resources"][resource_arg.pluralize]["methods"].each do |k,v|
132         description = ''
133         description = '  ' + v["description"] if v.include?("description")
134         banner += "   #{sprintf("%20s",k)}#{description}\n"
135       end
136       banner += "\n"
137
138       STDERR.puts banner
139   
140       if not method.nil? and method != '--help' then 
141         Trollop::die "Unknown method #{method.to_s} for command #{resource_arg.to_s}"
142       else
143         exit 255
144       end
145
146     end
147     
148   else
149     banner = "\nThis Arvados instance supports the following resource types:\n\n"
150     discovery_document["resources"].each do |k,v|
151       description = ''
152       if discovery_document["schemas"].include?(k.singularize.capitalize) and 
153          discovery_document["schemas"][k.singularize.capitalize].include?('description') then
154         description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
155       end
156       banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
157     end
158     banner += "\n"
159
160     STDERR.puts banner
161
162     if not resource_arg.nil? and resource_arg != '--help' then 
163       Trollop::die "Unknown resource type #{resource_arg.inspect}"
164     else
165       exit 255
166     end
167   end
168
169   return resource_arg.pluralize, method, method_opts, global_opts, ARGV
170 end
171
172 controller, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
173
174 api_method = 'arvados.' + controller + '.' + method
175
176 if global_opts[:dry_run]
177   if global_opts[:verbose]
178     $stderr.puts "#{api_method} #{method_opts.inspect}"
179   end
180   exit
181 end
182
183 result = client.execute :api_method => eval(api_method), :parameters => { :api_token => ENV['ARVADOS_API_TOKEN'] }.merge(method_opts), :authenticated => false
184 results = JSON.parse result.body
185
186 if results["errors"] then
187   abort "Error: #{results["errors"][0]}"
188 end
189
190 if global_opts[:human] or global_opts[:pretty] then
191   puts Oj.dump(results, :indent => 1)
192 elsif global_opts[:json] then
193   puts Oj.dump(results)
194 elsif results["items"] and results["kind"].match /list$/i
195   results['items'].each do |i| puts i['uuid'] end
196 else
197   puts results['uuid']
198 end