rename projects
[arvados.git] / sdk / cli / wh
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 rescue LoadError
28   abort <<-EOS
29
30 Please install all required gems: 
31
32   google-api-client
33   json
34   trollop
35
36   EOS
37 end
38
39 module Kernel
40   def suppress_warnings
41     original_verbosity = $VERBOSE
42     $VERBOSE = nil
43     result = yield
44     $VERBOSE = original_verbosity
45     return result
46   end
47 end
48
49 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
50 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
51
52 class Google::APIClient
53  def discovery_document(api, version)
54   api = api.to_s
55   return @discovery_documents["#{api}:#{version}"] ||= (begin
56     response = self.execute!(
57       :http_method => :get,
58       :uri => self.discovery_uri(api, version),
59       :authenticated => false
60     )
61     response.body.class == String ? JSON.parse(response.body) : response.body
62   end)
63  end
64 end
65
66 client = Google::APIClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'wh-cli', :application_version => '1.0')
67 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
68
69 def to_boolean(s)
70   !!(s =~ /^(true|t|yes|y|1)$/i)
71 end
72
73 def parse_arguments(discovery_document)
74   sub_commands = Array.new()
75   sub_commands << '--help'
76   discovery_document["resources"].each do |k,v|
77     sub_commands << k
78   end
79
80   global_opts = Trollop::options do
81     banner "arvados cli client"
82     opt :dry_run, "Don't actually do anything", :short => "-n"
83     stop_on sub_commands
84   end
85   
86   # get the subcommand
87   cmd = ARGV.shift
88   cmd = cmd.pluralize unless cmd.nil?
89   if sub_commands.include?(cmd) and cmd != '--help' then
90     # subcommand exists
91     # Now see if the method supplied exists
92     method = ARGV.shift 
93     if discovery_document["resources"][cmd]["methods"].include?(method) then
94       # method exists. Collect arguments.
95       discovered_params = discovery_document["resources"][cmd]["methods"][method]["parameters"]
96       method_opts = Trollop::options do
97         discovered_params.each do |k,v|
98           opts = Hash.new()
99           opts[:type] = v["type"].to_sym if v.include?("type")
100           if [:datetime, :text, :object].index opts[:type]
101             opts[:type] = :string                       # else trollop bork
102           end
103           opts[:default] = v["default"] if v.include?("default")
104           opts[:default] = v["default"].to_i if opts[:type] == :integer
105           opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
106           opts[:required] = true if v.include?("required") and v["required"]
107           description = ''
108           description = '  ' + v["description"] if v.include?("description")
109           opt k.to_sym, description, opts
110         end
111         opt :json, "Return the raw json received from the API server", :short => "-j"
112         opt :jsonhuman, "Return the raw json received from the API server, formatted for human consumption", :short => "-h"
113       end
114       discovered_params.each do |k,v|
115         if v["type"] == "object" and method_opts.has_key? k
116           method_opts[k] = JSON.parse method_opts[k]
117         end
118       end
119     else
120       banner = "\nThis api command supports the following methods:\n\n"
121       discovery_document["resources"][cmd]["methods"].each do |k,v|
122         description = ''
123         description = '  ' + v["description"] if v.include?("description")
124         banner += "   #{sprintf("%20s",k)}#{description}\n"
125       end
126       banner += "\n"
127
128       STDERR.puts banner
129   
130       if not method.nil? and method != '--help' then 
131         Trollop::die "Unknown method #{method.to_s} for command #{cmd.to_s}"
132       else
133         exit 255
134       end
135
136     end
137     
138   else
139     banner = "\nThis Arvados cluster supports the following api commands:\n\n"
140     discovery_document["resources"].each do |k,v|
141       description = ''
142       if discovery_document["schemas"].include?(k.singularize.capitalize) and 
143          discovery_document["schemas"][k.singularize.capitalize].include?('description') then
144         description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
145       end
146       banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
147     end
148     banner += "\n"
149
150     STDERR.puts banner
151
152     if not cmd.nil? and cmd != '--help' then 
153       Trollop::die "Unknown command #{cmd.inspect}"
154     else
155       exit 255
156     end
157   end
158
159   return cmd, method, method_opts, ARGV
160 end
161
162 cmd, method, method_opts, remaining_opts = parse_arguments(arvados.discovery_document)
163
164 api_method = 'arvados.' + cmd + '.' + method
165
166 m_o = method_opts.reject {|key,value| key =~ /_given$|^json$|^jsonhuman$|^help$/ or value == nil }
167
168 result = client.execute :api_method => eval(api_method), :parameters => { :api_token => ENV['ARVADOS_API_TOKEN'] }.merge(m_o), :authenticated => false
169 results = JSON.parse result.body
170
171 if results["errors"] then
172   abort "Error: #{results["errors"][0]}"
173 end
174
175 if method_opts[:json] then
176   puts results.to_s
177 elsif method_opts[:jsonhuman] then
178   puts results.pretty_inspect()
179 elsif results["items"] and results["kind"].match /list$/i
180   results['items'].each do |i| puts i['uuid'] end
181 else
182   puts results['uuid']
183 end