3 bin_dir = File.expand_path("..", __FILE__)
4 lib_dir = File.expand_path("../lib", bin_dir)
6 $LOAD_PATH.unshift(lib_dir)
9 OAUTH_SERVER_PORT = 12736
14 require 'faraday/utils'
16 require 'google/api_client/version'
17 require 'google/api_client'
18 require 'google/api_client/auth/installed_app'
21 ARGV.unshift('--help') if ARGV.empty?
27 # Initialize with default parameter values
30 :command => 'execute',
35 if @argv.first =~ /^[a-z0-9][a-z0-9_-]*$/i
36 self.options[:command] = @argv.shift
38 if @argv.first =~ /^[a-z0-9_-]+\.[a-z0-9_\.-]+$/i
39 self.options[:rpcname] = @argv.shift
47 return self.options[:command]
51 return self.options[:rpcname]
55 @parser ||= OptionParser.new do |opts|
56 opts.banner = "Usage: google-api " +
57 "(execute <rpcname> | [command]) [options] [-- <parameters>]"
59 opts.separator "\nAvailable options:"
62 "--scope <scope>", String, "Set the OAuth scope") do |s|
66 "--client-id <key>", String,
67 "Set the OAuth client id or key") do |k|
68 options[:client_credential_key] = k
71 "--client-secret <secret>", String,
72 "Set the OAuth client secret") do |s|
73 options[:client_credential_secret] = s
76 "--api <name>", String,
77 "Perform discovery on API") do |s|
81 "--api-version <id>", String,
82 "Select api version") do |id|
83 options[:version] = id
86 "--content-type <format>", String,
87 "Content-Type for request") do |f|
88 # Resolve content type shortcuts
91 f = 'application/json'
95 f = 'application/atom+xml'
97 f = 'application/rss+xml'
99 options[:content_type] = f
102 "-u", "--uri <uri>", String,
103 "Sets the URI to perform a request against") do |u|
107 "--discovery-uri <uri>", String,
108 "Sets the URI to perform discovery") do |u|
109 options[:discovery_uri] = u
112 "-m", "--method <method>", String,
113 "Sets the HTTP method to use for the request") do |m|
114 options[:http_method] = m
117 "--requestor-id <email>", String,
118 "Sets the email address of the requestor") do |e|
119 options[:requestor_id] = e
122 opts.on("-v", "--verbose", "Run verbosely") do |v|
123 options[:verbose] = v
125 opts.on("-h", "--help", "Show this message") do
129 opts.on("--version", "Show version") do
130 puts "google-api-client (#{Google::APIClient::VERSION::STRING})"
135 "\nAvailable commands:\n" +
136 " oauth-2-login Log a user into an API with OAuth 2.0\n" +
137 " list List the methods available for an API\n" +
138 " execute Execute a method on the API\n" +
139 " irb Start an interactive client session"
145 self.parser.parse!(self.argv)
146 symbol = self.command.gsub(/-/, "_").to_sym
147 if !COMMANDS.include?(symbol)
148 STDERR.puts("Invalid command: #{self.command}")
156 config_file = File.expand_path('~/.google-api.yaml')
158 if File.exist?(config_file)
159 config = open(config_file, 'r') { |file| YAML.load(file.read) }
163 if config["mechanism"]
164 authorization = config["mechanism"].to_sym
167 client = Google::APIClient.new(
168 :application_name => 'Ruby CLI',
169 :application_version => Google::APIClient::VERSION::STRING,
170 :authorization => authorization)
174 STDERR.puts('OAuth 1 is deprecated. Please reauthorize with OAuth 2.')
175 client.authorization.client_credential_key =
176 config["client_credential_key"]
177 client.authorization.client_credential_secret =
178 config["client_credential_secret"]
179 client.authorization.token_credential_key =
180 config["token_credential_key"]
181 client.authorization.token_credential_secret =
182 config["token_credential_secret"]
184 client.authorization.scope = options[:scope]
185 client.authorization.client_id = config["client_id"]
186 client.authorization.client_secret = config["client_secret"]
187 client.authorization.access_token = config["access_token"]
188 client.authorization.refresh_token = config["refresh_token"]
193 if options[:discovery_uri]
194 if options[:api] && options[:version]
195 client.register_discovery_uri(
196 options[:api], options[:version], options[:discovery_uri]
200 'Cannot register a discovery URI without ' +
201 'specifying an API and version.'
210 def api_version(api_name, version)
213 if client.preferred_version(api_name)
214 v = client.preferred_version(api_name).version
230 require 'signet/oauth_2/client'
232 if !options[:client_credential_key] ||
233 !options[:client_credential_secret]
234 STDERR.puts('No client ID and secret supplied.')
237 if options[:access_token]
239 "mechanism" => "oauth_2",
240 "scope" => options[:scope],
241 "client_id" => options[:client_credential_key],
242 "client_secret" => options[:client_credential_secret],
243 "access_token" => options[:access_token],
244 "refresh_token" => options[:refresh_token]
246 config_file = File.expand_path('~/.google-api.yaml')
247 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
250 flow = Google::APIClient::InstalledAppFlow.new(
251 :port => OAUTH_SERVER_PORT,
252 :client_id => options[:client_credential_key],
253 :client_secret => options[:client_credential_secret],
254 :scope => options[:scope]
257 oauth_client = flow.authorize
260 "mechanism" => "oauth_2",
261 "scope" => options[:scope],
262 "client_id" => oauth_client.client_id,
263 "client_secret" => oauth_client.client_secret,
264 "access_token" => oauth_client.access_token,
265 "refresh_token" => oauth_client.refresh_token
267 config_file = File.expand_path('~/.google-api.yaml')
268 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
275 api_name = options[:api]
277 STDERR.puts('No API name supplied.')
280 #client = Google::APIClient.new(:authorization => nil)
281 if options[:discovery_uri]
282 if options[:api] && options[:version]
283 client.register_discovery_uri(
284 options[:api], options[:version], options[:discovery_uri]
288 'Cannot register a discovery URI without ' +
289 'specifying an API and version.'
294 version = api_version(api_name, options[:version])
295 api = client.discovered_api(api_name, version)
296 rpcnames = api.to_h.keys
297 puts rpcnames.sort.join("\n")
304 # Setup HTTP request data
306 input_streams, _, _ = IO.select([STDIN], [], [], 0)
307 request_body = STDIN.read || '' if input_streams
309 if options[:content_type]
310 headers << ['Content-Type', options[:content_type]]
313 headers << ['Content-Type', 'application/json']
317 # Make request with URI manually specified
318 uri = Addressable::URI.parse(options[:uri])
320 STDERR.puts('URI may not be relative.')
323 if options[:requestor_id]
324 uri.query_values = uri.query_values.merge(
325 'xoauth_requestor_id' => options[:requestor_id]
328 method = options[:http_method]
329 method ||= request_body == '' ? 'GET' : 'POST'
331 response = client.execute(:http_method => method, :uri => uri.to_str,
332 :headers => headers, :body => request_body)
336 # Make request with URI generated from template and parameters
338 STDERR.puts('No rpcname supplied.')
341 api_name = options[:api] || self.rpcname[/^([^\.]+)\./, 1]
342 version = api_version(api_name, options[:version])
343 api = client.discovered_api(api_name, version)
344 method = api.to_h[self.rpcname]
347 "Method #{self.rpcname} does not exist for " +
348 "#{api_name}-#{version}."
352 parameters = self.argv.inject({}) do |accu, pair|
353 name, value = pair.split('=', 2)
357 if options[:requestor_id]
358 parameters['xoauth_requestor_id'] = options[:requestor_id]
361 result = client.execute(
362 :api_method => method,
363 :parameters => parameters,
364 :merged_body => request_body,
367 puts result.response.body
369 rescue ArgumentError => e
377 $client = self.client
378 # Otherwise IRB will misinterpret command-line options
391 Google::APIClient::CLI.new(ARGV).parse!