2986: Cleaned up arv cli help to be more helpful and consistent. refs #1667.
[arvados.git] / sdk / cli / bin / arv
index 3955c945766204696679a64b4577e51fb6beb4b5..13a0d9de3c0d40797d91b1c616dbac41e766b714 100755 (executable)
@@ -4,13 +4,15 @@
 #
 # Ward Vandewege <ward@clinicalfuture.com>
 
+require 'fileutils'
+
 if RUBY_VERSION < '1.9.3' then
   abort <<-EOS
 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
   EOS
 end
 
-# read authentication data from ~/.config/arvados if present
+# read authentication data from arvados configuration file if present
 lineno = 0
 config_file = File.expand_path('~/.config/arvados/settings.conf')
 if File.exist? config_file then
@@ -30,23 +32,28 @@ if File.exist? config_file then
   end
 end
 
+subcommands = %w(keep pipeline tag ws)
+
 case ARGV[0]
 when 'keep'
   ARGV.shift
   @sub = ARGV.shift
-  if ['get', 'put'].index @sub then
+  if ['get', 'put', 'ls', 'normalize'].index @sub then
     # Native Arvados
     exec `which arv-#{@sub}`.strip, *ARGV
-  elsif ['ls', 'less', 'check'].index @sub then
+  elsif ['less', 'check'].index @sub then
     # wh* shims
     exec `which wh#{@sub}`.strip, *ARGV
+  elsif @sub == 'docker'
+    exec `which arv-keepdocker`.strip, *ARGV
   else
     puts "Usage: \n" +
       "#{$0} keep ls\n" +
       "#{$0} keep get\n" +
       "#{$0} keep put\n" +
       "#{$0} keep less\n" +
-      "#{$0} keep check\n"
+      "#{$0} keep check\n" +
+      "#{$0} keep docker\n"
   end
   abort
 when 'pipeline'
@@ -63,6 +70,9 @@ when 'pipeline'
 when 'tag'
   ARGV.shift
   exec `which arv-tag`.strip, *ARGV
+when 'ws'
+  ARGV.shift
+  exec `which arv-ws`.strip, *ARGV
 end
 
 ENV['ARVADOS_API_VERSION'] ||= 'v1'
@@ -87,7 +97,7 @@ begin
 rescue LoadError
   abort <<-EOS
 
-Please install all required gems: 
+Please install all required gems:
 
   gem install activesupport andand curb google-api-client json oj trollop
 
@@ -116,15 +126,23 @@ end
 
 class Google::APIClient
  def discovery_document(api, version)
-  api = api.to_s
-  return @discovery_documents["#{api}:#{version}"] ||= (begin
-    response = self.execute!(
-      :http_method => :get,
-      :uri => self.discovery_uri(api, version),
-      :authenticated => false
-    )
-    response.body.class == String ? JSON.parse(response.body) : response.body
-  end)
+   api = api.to_s
+   return @discovery_documents["#{api}:#{version}"] ||=
+     begin
+       # fetch new API discovery doc if stale
+       cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
+       if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
+         response = self.execute!(:http_method => :get,
+                                  :uri => self.discovery_uri(api, version),
+                                  :authenticated => false)
+         FileUtils.makedirs(File.dirname cached_doc)
+         File.open(cached_doc, 'w') do |f|
+           f.puts response.body
+         end
+       end
+
+       File.open(cached_doc) { |f| JSON.load f }
+     end
  end
 end
 
@@ -138,16 +156,27 @@ class ArvadosClient < Google::APIClient
   end
 end
 
-client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
-arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
+begin
+  client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
+  arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
+rescue Exception => e
+  puts "Failed to connect to Arvados API server: #{e}"
+  exit 1
+end
 
 def to_boolean(s)
   !!(s =~ /^(true|t|yes|y|1)$/i)
 end
 
+def head_banner
+  "Arvados command line client\n"
+end
+
 def help_methods(discovery_document, resource, method=nil)
-  banner = "\n"
-  banner += "The #{resource} resource type supports the following methods:"
+  banner = head_banner
+  banner += "Usage: arv #{resource} [method] [--parameters]\n"
+  banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
+  banner += "The #{resource} resource supports the following methods:"
   banner += "\n\n"
   discovery_document["resources"][resource.pluralize]["methods"].
     each do |k,v|
@@ -160,44 +189,36 @@ def help_methods(discovery_document, resource, method=nil)
   end
   banner += "\n"
   STDERR.puts banner
-  
-  if not method.nil? and method != '--help' then 
+
+  if not method.nil? and method != '--help' and method != '-h' then
     Trollop::die ("Unknown method #{method.inspect} " +
                   "for resource #{resource.inspect}")
   end
   exit 255
 end
 
-def help_resources(discovery_document, resource)
-  banner = "\n"
-  banner += "This Arvados instance supports the following resource types:"
-  banner += "\n\n"
-  discovery_document["resources"].each do |k,v|
-    description = ''
-    resource_info = discovery_document["schemas"][k.singularize.capitalize]
-    if resource_info and resource_info.include?('description')
-      # add only the first line of the discovery doc description
-      description = '  ' + resource_info["description"].split("\n").first.chomp
-    end
-    banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
-  end
-  banner += "\n"
-  STDERR.puts banner
+def help_resources(option_parser, discovery_document, resource)
+  option_parser.educate
 
-  if not resource.nil? and resource != '--help' then 
+  if not resource.nil? and resource != '--help' then
     Trollop::die "Unknown resource type #{resource.inspect}"
   end
   exit 255
 end
 
-def parse_arguments(discovery_document)
+def parse_arguments(discovery_document, subcommands)
   resource_types = Array.new()
   discovery_document["resources"].each do |k,v|
     resource_types << k.singularize
   end
 
-  global_opts = Trollop::options do
-    banner "arv: the Arvados CLI tool"
+  option_parser = Trollop::Parser.new do
+    version __FILE__
+    banner head_banner
+    banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
+    banner ""
+    banner "Available flags:"
+
     opt :dry_run, "Don't actually do anything", :short => "-n"
     opt :verbose, "Print some things on stderr"
     opt :format,
@@ -206,10 +227,26 @@ def parse_arguments(discovery_document)
         :default => 'json'
     opt :short, "Return only UUIDs (equivalent to --format=uuid)"
     opt :resources, "Display list of resources known to this Arvados instance."
+
+    banner ""
+    banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
+    banner ""
+    banner "Available subcommands: #{subcommands.join(', ')}"
+    banner ""
+
+    banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
+
+    banner ""
+    banner "Additional options:"
+
     conflicts :short, :format
     stop_on resource_types
   end
 
+  global_opts = Trollop::with_standard_exception_handling option_parser do
+    o = option_parser.parse ARGV
+  end
+
   unless %w(json yaml uuid).include?(global_opts[:format])
     $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
     $stderr.puts "Use #{$0} --help for more information."
@@ -222,7 +259,7 @@ def parse_arguments(discovery_document)
 
   resource = ARGV.shift
   if global_opts[:resources] or not resource_types.include?(resource)
-    help_resources(discovery_document, resource)
+    help_resources(option_parser, discovery_document, resource)
   end
 
   method = ARGV.shift
@@ -235,6 +272,11 @@ def parse_arguments(discovery_document)
     ["resources"][resource.pluralize]\
     ["methods"][method]["parameters"]
   method_opts = Trollop::options do
+    banner head_banner
+    banner "Usage: arv #{resource} #{method} [--parameters]"
+    banner ""
+    banner "This method supports the following parameters:"
+    banner ""
     discovered_params.each do |k,v|
       opts = Hash.new()
       opts[:type] = v["type"].to_sym if v.include?("type")
@@ -249,6 +291,7 @@ def parse_arguments(discovery_document)
       description = '  ' + v["description"] if v.include?("description")
       opt k.to_sym, description, opts
     end
+
     body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
     if body_object and discovered_params[resource].nil?
       is_required = true
@@ -259,7 +302,6 @@ def parse_arguments(discovery_document)
         required: is_required,
         type: :string
       }
-      discovered_params[resource.to_sym] = body_object
     end
   end
 
@@ -274,7 +316,8 @@ def parse_arguments(discovery_document)
   return resource, method, method_opts, global_opts, ARGV
 end
 
-resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
+# Parse arguments here
+resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
 controller = resource_schema.pluralize
 
 api_method = 'arvados.' + controller + '.' + method
@@ -286,20 +329,18 @@ if global_opts[:dry_run]
   exit
 end
 
-request_parameters = {}.merge(method_opts)
+request_parameters = {_profile:true}.merge(method_opts)
 resource_body = request_parameters.delete(resource_schema.to_sym)
 if resource_body
   request_body = {
     resource_schema => resource_body
   }
 else
-  request_body = {}
+  request_body = nil
 end
 
 case api_method
 when
-  'arvados.users.event_stream',
-  'arvados.jobs.log_stream',
   'arvados.jobs.log_tail_follow'
 
   # Special case for methods that respond with data streams rather
@@ -310,7 +351,7 @@ when
     curl.headers['Accept'] = 'text/plain'
     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
     if ENV['ARVADOS_API_HOST_INSECURE']
-      curl.ssl_verify_peer = false 
+      curl.ssl_verify_peer = false
       curl.ssl_verify_host = false
     end
     if global_opts[:verbose]
@@ -320,12 +361,13 @@ when
   end
   exit 0
 else
-  request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
-  request_body[:_profile] = true
   result = client.execute(:api_method => eval(api_method),
                           :parameters => request_parameters,
                           :body => request_body,
-                          :authenticated => false)
+                          :authenticated => false,
+                          :headers => {
+                            authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
+                          })
 end
 
 begin
@@ -354,5 +396,3 @@ else
     puts results['uuid']
   end
 end
-
-