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'
20 ARGV.unshift('--help') if ARGV.empty?
26 # Initialize with default parameter values
29 :command => 'execute',
34 if @argv.first =~ /^[a-z0-9][a-z0-9_-]*$/i
35 self.options[:command] = @argv.shift
37 if @argv.first =~ /^[a-z0-9_-]+\.[a-z0-9_\.-]+$/i
38 self.options[:rpcname] = @argv.shift
46 return self.options[:command]
50 return self.options[:rpcname]
54 @parser ||= OptionParser.new do |opts|
55 opts.banner = "Usage: google-api " +
56 "(execute <rpcname> | [command]) [options] [-- <parameters>]"
58 opts.separator "\nAvailable options:"
61 "--scope <scope>", String, "Set the OAuth scope") do |s|
65 "--client-id <key>", String,
66 "Set the OAuth client id or key") do |k|
67 options[:client_credential_key] = k
70 "--client-secret <secret>", String,
71 "Set the OAuth client secret") do |s|
72 options[:client_credential_secret] = s
75 "--api <name>", String,
76 "Perform discovery on API") do |s|
80 "--api-version <id>", String,
81 "Select api version") do |id|
82 options[:version] = id
85 "--content-type <format>", String,
86 "Content-Type for request") do |f|
87 # Resolve content type shortcuts
90 f = 'application/json'
94 f = 'application/atom+xml'
96 f = 'application/rss+xml'
98 options[:content_type] = f
101 "-u", "--uri <uri>", String,
102 "Sets the URI to perform a request against") do |u|
106 "--discovery-uri <uri>", String,
107 "Sets the URI to perform discovery") do |u|
108 options[:discovery_uri] = u
111 "-m", "--method <method>", String,
112 "Sets the HTTP method to use for the request") do |m|
113 options[:http_method] = m
116 "--requestor-id <email>", String,
117 "Sets the email address of the requestor") do |e|
118 options[:requestor_id] = e
121 opts.on("-v", "--verbose", "Run verbosely") do |v|
122 options[:verbose] = v
124 opts.on("-h", "--help", "Show this message") do
128 opts.on("--version", "Show version") do
129 puts "google-api-client (#{Google::APIClient::VERSION::STRING})"
134 "\nAvailable commands:\n" +
135 " oauth-2-login Log a user into an API with OAuth 2.0\n" +
136 " list List the methods available for an API\n" +
137 " execute Execute a method on the API\n" +
138 " irb Start an interactive client session"
144 self.parser.parse!(self.argv)
145 symbol = self.command.gsub(/-/, "_").to_sym
146 if !COMMANDS.include?(symbol)
147 STDERR.puts("Invalid command: #{self.command}")
155 config_file = File.expand_path('~/.google-api.yaml')
157 if File.exist?(config_file)
158 config = open(config_file, 'r') { |file| YAML.load(file.read) }
162 if config["mechanism"]
163 authorization = config["mechanism"].to_sym
166 client = Google::APIClient.new(
167 :application_name => 'Ruby CLI',
168 :application_version => Google::APIClient::VERSION::STRING,
169 :authorization => authorization)
173 STDERR.puts('OAuth 1 is deprecated. Please reauthorize with OAuth 2.')
174 client.authorization.client_credential_key =
175 config["client_credential_key"]
176 client.authorization.client_credential_secret =
177 config["client_credential_secret"]
178 client.authorization.token_credential_key =
179 config["token_credential_key"]
180 client.authorization.token_credential_secret =
181 config["token_credential_secret"]
183 client.authorization.scope = options[:scope]
184 client.authorization.client_id = config["client_id"]
185 client.authorization.client_secret = config["client_secret"]
186 client.authorization.access_token = config["access_token"]
187 client.authorization.refresh_token = config["refresh_token"]
192 if options[:discovery_uri]
193 if options[:api] && options[:version]
194 client.register_discovery_uri(
195 options[:api], options[:version], options[:discovery_uri]
199 'Cannot register a discovery URI without ' +
200 'specifying an API and version.'
209 def api_version(api_name, version)
212 if client.preferred_version(api_name)
213 v = client.preferred_version(api_name).version
229 require 'signet/oauth_2/client'
231 if !options[:client_credential_key] ||
232 !options[:client_credential_secret]
233 STDERR.puts('No client ID and secret supplied.')
236 if options[:access_token]
238 "mechanism" => "oauth_2",
239 "scope" => options[:scope],
240 "client_id" => options[:client_credential_key],
241 "client_secret" => options[:client_credential_secret],
242 "access_token" => options[:access_token],
243 "refresh_token" => options[:refresh_token]
245 config_file = File.expand_path('~/.google-api.yaml')
246 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
249 flow = Google::APIClient::InstalledAppFlow.new(
250 :port => OAUTH_SERVER_PORT,
251 :client_id => options[:client_credential_key],
252 :client_secret => options[:client_credential_secret],
253 :scope => options[:scope]
256 oauth_client = flow.authorize
259 "mechanism" => "oauth_2",
260 "scope" => options[:scope],
261 "client_id" => oauth_client.client_id,
262 "client_secret" => oauth_client.client_secret,
263 "access_token" => oauth_client.access_token,
264 "refresh_token" => oauth_client.refresh_token
266 config_file = File.expand_path('~/.google-api.yaml')
267 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
274 api_name = options[:api]
276 STDERR.puts('No API name supplied.')
279 #client = Google::APIClient.new(:authorization => nil)
280 if options[:discovery_uri]
281 if options[:api] && options[:version]
282 client.register_discovery_uri(
283 options[:api], options[:version], options[:discovery_uri]
287 'Cannot register a discovery URI without ' +
288 'specifying an API and version.'
293 version = api_version(api_name, options[:version])
294 api = client.discovered_api(api_name, version)
295 rpcnames = api.to_h.keys
296 puts rpcnames.sort.join("\n")
303 # Setup HTTP request data
305 input_streams, _, _ = IO.select([STDIN], [], [], 0)
306 request_body = STDIN.read || '' if input_streams
308 if options[:content_type]
309 headers << ['Content-Type', options[:content_type]]
312 headers << ['Content-Type', 'application/json']
316 # Make request with URI manually specified
317 uri = Addressable::URI.parse(options[:uri])
319 STDERR.puts('URI may not be relative.')
322 if options[:requestor_id]
323 uri.query_values = uri.query_values.merge(
324 'xoauth_requestor_id' => options[:requestor_id]
327 method = options[:http_method]
328 method ||= request_body == '' ? 'GET' : 'POST'
330 response = client.execute(:http_method => method, :uri => uri.to_str,
331 :headers => headers, :body => request_body)
335 # Make request with URI generated from template and parameters
337 STDERR.puts('No rpcname supplied.')
340 api_name = options[:api] || self.rpcname[/^([^\.]+)\./, 1]
341 version = api_version(api_name, options[:version])
342 api = client.discovered_api(api_name, version)
343 method = api.to_h[self.rpcname]
346 "Method #{self.rpcname} does not exist for " +
347 "#{api_name}-#{version}."
351 parameters = self.argv.inject({}) do |accu, pair|
352 name, value = pair.split('=', 2)
356 if options[:requestor_id]
357 parameters['xoauth_requestor_id'] = options[:requestor_id]
360 result = client.execute(
361 :api_method => method,
362 :parameters => parameters,
363 :merged_body => request_body,
366 puts result.response.body
368 rescue ArgumentError => e
376 $client = self.client
377 # Otherwise IRB will misinterpret command-line options
390 Google::APIClient::CLI.new(ARGV).parse!