chore: Extract generator into google-apis-generator gem (#2143)

This commit is contained in:
Daniel Azuma authored and GitHub committed 2021-01-01 12:29:10 -08:00
1 parent abb3c968fe
commit 1cc46b843e
46 files changed
+533 -41

No files matched your search

+1
View File
@@ -4,6 +4,7 @@ source 'https://rubygems.org'
gemspec
gem 'google-apis-core', path: '../google-apis-core'
gem 'google-apis-generator', path: '../google-apis-generator'
group :development do
gem 'bundler', '>= 1.7'
-226
View File
@@ -1,226 +0,0 @@
#!/usr/bin/env ruby
begin
require 'thor'
rescue LoadError => e
puts "Thor is required. Please install the gem with development dependencies."
exit 1
end
require 'open-uri'
require 'google/apis/discovery_v1'
require 'logger'
require 'psych'
module Google
class ApiGenerator < Thor
def self.exit_on_failure?
true
end
include Thor::Actions
Google::Apis::ClientOptions.default.application_name = "generate-api"
Google::Apis::ClientOptions.default.application_version = Google::Apis::VERSION
Discovery = Google::Apis::DiscoveryV1
desc 'gen OUTDIR', 'Generate ruby API from an API description'
method_options url: :array, file: :array, from_discovery: :boolean, preferred_only: :boolean,
verbose: :boolean, names: :string, names_out: :string, api: :string,
clean: :boolean, spot_check: :boolean
def gen(dir)
ensure_active_support
require 'google/apis/generator'
self.destination_root = dir
Google::Apis.logger.level = Logger::DEBUG if options[:verbose]
count = 0
count += generate_from_url(options[:url]) if options[:url]
count += generate_from_file(options[:file]) if options[:file]
count += generate_specific_apis(options[:api]) if options[:api]
count += generate_from_discovery(preferred_only: options[:preferred_only]) if options[:from_discovery]
count += clean_from_discovery if options[:clean]
create_file(options[:names_out]) { |*| generator.dump_api_names } if count > 0 && options[:names_out]
end
desc 'list', 'List public APIs'
method_options verbose: :boolean, preferred_only: :boolean
def list
Google::Apis.logger.level = Logger::DEBUG if options[:verbose]
discovery_api_list.each do |api|
say sprintf('%s - %s', api.id, api.description).strip unless options[:preferred_only] && !api.preferred?
end
end
no_commands do
def generate_from_url(urls, first_only: false)
count = 0
Array(urls).each do |url|
begin
json = discovery.http(:get, url)
rescue Google::Apis::Error
warn sprintf('Failed request, skipping %s', url)
next
end
generate_api(json)
return 1 if first_only
count += 1
end
count
end
def generate_from_file(files)
Array(files).each do |file|
File.open(file) do |f|
generate_api(f.read)
end
end
Array(files).size
end
def generate_specific_apis(apis)
discovery_apis = discovery_api_list.each_with_object({}) do |api, hash|
hash["#{api.name}.#{api.version}"] = api
end
paused_apis = Array(api_list_config["pause"])
count = 0
Array(apis).each do |name_version|
api = discovery_apis[name_version]
if api.nil?
say "API #{api} is not in the discovery list."
elsif paused_apis.include? name_version
say "Ignoring paused API #{api.name} #{api.version}"
else
discovery_rest_url = "https://raw.githubusercontent.com/googleapis/discovery-artifact-manager/master/discoveries/#{api.name}.#{api.version}.json"
say sprintf('Loading %s, version %s from %s', api.name, api.version, discovery_rest_url)
generate_from_url([discovery_rest_url, api.discovery_rest_url], first_only: true)
count += 1
end
end
count
end
def generate_from_discovery(preferred_only: false)
say 'Fetching API list'
paused_apis = Array(api_list_config["pause"])
count = 0
discovery_api_list.each do |api|
if paused_apis.include? "#{api.name}.#{api.version}"
say "Ignoring paused API #{api.name} #{api.version}"
elsif (preferred_only && !api.preferred?)
say sprintf('Ignoring disoverable API %s', api.id)
else
# The Discovery service may returned cached versions of a Discovery document that are
# not the most recent revision. That means that subsequent requests to the same
# Discovery document URL can return different documents. The
# `discovery-artifact-manager` repo always holds the most recent revision, so it's
# easier to use that document than to force revision checking against the URL returned
# by the Discovery index.
discovery_rest_url = "https://raw.githubusercontent.com/googleapis/discovery-artifact-manager/master/discoveries/#{api.name}.#{api.version}.json"
say sprintf('Loading %s, version %s from %s', api.name, api.version, discovery_rest_url)
generate_from_url([discovery_rest_url, api.discovery_rest_url], first_only: true)
count += 1
end
end
count
end
def clean_from_discovery
count = 0
apis = discovery_api_list.map { |api| "#{api.name.underscore}_#{api.version.tr '.', '_'}" }
return 0 unless File.directory?("#{destination_root}/google/apis")
Dir.chdir("#{destination_root}/google/apis") do
Dir.glob("*.rb").each do |filename|
filename = File.basename(filename, ".rb")
unless apis.include? filename
FileUtils.rm_r filename
FileUtils.rm "#{filename}.rb"
count += 1
end
end
end
count
end
def generate_api(json)
result = generator.render(json)
files = updater.analyze(destination_root, result)
files.each do |file, content|
create_file(file) { |*| content }
end
run_spot_check(result.gem_name) if !files.empty? && options[:spot_check]
end
def run_spot_check(gem_name)
Dir.chdir(File.join(destination_root, gem_name)) do
check_proc = Proc.new do
system("bundle install") or error_and_exit("Failed to install bundle for newly generated library")
system("bundle exec rake ci") or error_and_exit("Failed to run spot check for newly generated library")
end
if defined?(Bundler)
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env(&check_proc)
else
Bundler.with_clean_env(&check_proc)
end
else
check_proc.call
end
end
end
def discovery
@discovery ||= Discovery::DiscoveryService.new
end
def discovery_api_list
@discovery_api_list ||= begin
items = discovery.list_apis.items
excluded = Array(api_list_config["exclude"])
items.delete_if { |item| excluded.include? "#{item.name}.#{item.version}" }
Array(api_list_config["include"]).each do |include_hash|
include_hash.symbolize_keys!
include_item = Discovery::DirectoryList::Item.new(**include_hash)
items << include_item unless items.any? { |item| item.name == include_item.name && item.version == include_item.version }
end
items
end
end
def generator
@generator ||= Google::Apis::Generator.new(api_names: options[:names], api_names_out: options[:names_out])
end
def updater
@updater ||= begin
require 'google/apis/generator/updater'
Google::Apis::Generator::Updater.new
end
end
def api_list_config
@api_list_config ||= Psych.load_file(__dir__ + "/../../api_list_config.yaml")
end
def ensure_active_support
begin
require 'active_support'
require 'active_support/inflector'
require 'active_support/core_ext'
rescue LoadError => e
error_and_exit('ActiveSupport is required. Please run:', 'gem install activesupport')
end
end
def error_and_exit(*messages)
messages.each { |msg| error(msg) }
exit 1
end
end
end
end
Google::ApiGenerator.start(ARGV)
+1 -4
View File
@@ -16,16 +16,13 @@ Gem::Specification.new do |gem|
gem.files = Dir.glob("lib/**/*") +
Dir.glob("generated/**/*.rb") +
Dir.glob("docs/**/*") +
Dir.glob("bin/**/*") +
Dir.glob("*.md") +
[".yardopts", "LICENSE"]
gem.executables = gem.files.grep(%r{^bin/}) { |f| File.basename(f) }
gem.require_paths = %w[lib generated]
gem.required_ruby_version = '>= 2.4'
gem.add_runtime_dependency 'google-apis-core', '~> 0.1'
gem.add_development_dependency 'thor', '~> 0.19'
gem.add_development_dependency 'activesupport', '>= 4.2', '< 5.1'
gem.add_runtime_dependency 'google-apis-generator', '~> 0.1'
end
@@ -1,96 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/discovery_v1'
require 'google/apis/generator/annotator'
require 'google/apis/generator/model'
require 'google/apis/generator/template'
require 'google/apis/generator/version'
require 'active_support/inflector'
require 'yaml'
module Google
module Apis
# Generates ruby classes for APIs from discovery documents
# @private
class Generator
Discovery = Google::Apis::DiscoveryV1
Result = Struct.new :files, :version_path, :changelog_path, :gem_name, :revision
# Load templates
def initialize(api_names: nil, api_names_out: nil)
@names = Google::Apis::Generator::Names.new(api_names_out || File.join(Google::Apis::ROOT, "api_names_out.yaml"),
api_names || File.join(Google::Apis::ROOT, "api_names.yaml"))
@templates = {}
end
# Generates ruby source for an API
#
# @param [String] json
# API Description, as JSON text
# @return [Hash<String,String>]
# Hash of generated files keyed by path
def render(json)
api = parse_description(json)
Annotator.process(api, @names)
context = {
"api" => api,
"generator_version" => Google::Apis::Generator::VERSION
}
base_path = api.gem_name
lib_path = File.join(base_path, "lib")
spec_path = File.join(base_path, "spec")
module_path = File.join(lib_path, ActiveSupport::Inflector.underscore(api.qualified_name))
result = Result.new({},
File.join(module_path, "gem_version.rb"),
File.join(base_path, "CHANGELOG.md"),
api.gem_name,
api.revision)
result.files[File.join(base_path, ".rspec")] = render_template("dot-rspec", context)
result.files[File.join(base_path, ".yardopts")] = render_template("dot-yardopts", context)
result.files[result.changelog_path] = render_template("initial-changelog.md", context)
result.files[File.join(base_path, "Gemfile")] = render_template("gemfile", context)
result.files[File.join(base_path, "#{api.gem_name}.gemspec")] = render_template("gemspec", context)
result.files[File.join(base_path, "LICENSE.md")] = render_template("license.md", context)
result.files[File.join(base_path, "OVERVIEW.md")] = render_template("overview.md", context)
result.files[File.join(base_path, "Rakefile")] = render_template("rakefile", context)
result.files[File.join(lib_path, "#{api.gem_name}.rb")] = render_template("entry-point.rb", context)
result.files[module_path + ".rb"] = render_template("module.rb", context)
result.files[File.join(module_path, "classes.rb")] = render_template("classes.rb", context)
result.files[File.join(module_path, "representations.rb")] = render_template("representations.rb", context)
result.files[File.join(module_path, "service.rb")] = render_template("service.rb", context)
result.files[result.version_path] = render_template("initial-gem_version.rb", context)
result.files[File.join(spec_path, "generated_spec.rb")] = render_template("generated_spec.rb", context)
result
end
def render_template(name, context)
(@templates[name] ||= Template.load(name)).render(context)
end
# Dump mapping of API names
# @return [String] Mapping of paths to ruby names in YAML format
def dump_api_names
@names.dump
end
def parse_description(json)
Discovery::RestDescription::Representation.new(Discovery::RestDescription.new).from_json(json)
end
end
end
end
@@ -1,339 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'logger'
require 'erb'
require 'yaml'
require 'json'
require 'active_support/inflector'
require 'google/apis/core/logging'
require 'google/apis/generator/template'
require 'google/apis/generator/model'
require 'google/apis/generator/helpers'
require 'addressable/uri'
module Google
module Apis
# @private
class Generator
# Helper for picking names for methods, properties, types, etc. Performs various normaliations
# as well as allows for overriding individual names from a configuration file for cases
# where algorithmic approaches produce poor APIs.
class Names
ActiveSupport::Inflector.inflections do |inflections|
inflections.uncountable('send_as', 'as')
inflections.irregular('drive', 'drives')
inflections.irregular('teamdrive', 'teamdrives')
end
include Google::Apis::Core::Logging
include NameHelpers
def initialize(names_out_file_path = nil, names_file_path = nil)
if names_out_file_path && File.file?(names_out_file_path)
logger.info { sprintf('Loading API names from %s', names_out_file_path) }
@names = YAML.load(File.read(names_out_file_path)) || {}
else
@names = {}
end
if names_file_path && File.file?(names_file_path)
logger.info { sprintf('Loading API names from %s', names_file_path) }
@names = @names.merge(YAML.load(File.read(names_file_path)) || {})
end
@path = []
end
def with_path(path)
@path.push(path)
begin
yield
ensure
@path.pop
end
end
def infer_parameter_name
pick_name(normalize_param_name(@path.last))
end
def infer_property_name
pick_name(normalize_property_name(@path.last))
end
def pick_name(alt_name)
preferred_name = @names[key]
if preferred_name && preferred_name == alt_name
# logger.warn { sprintf("Unnecessary name override '%s': %s", key, alt_name) }
elsif preferred_name.nil?
preferred_name = @names[key] = alt_name
end
preferred_name
end
def [](key)
@names[key]
end
def []=(key, value)
@names[key] = value
end
def dump
YAML.dump(Hash[@names.sort])
end
def key
@path.reduce('') { |a, e| a + '/' + e }
end
def option(opt_name)
@names[sprintf('%s?%s', key, opt_name)]
end
# For RPC style methods, pick a name based off the request objects.
# @param [Google::Apis::DiscoveryV1::RestMethod] method
# @param [Boolean] pick_name
# Fragment of the discovery doc describing the method
def infer_method_name_for_rpc(method, pick_name = true)
return nil if method.request.nil?
parts = method.id.split('.')
parts.shift
verb = ActiveSupport::Inflector.underscore(parts.pop)
match = method.request._ref.match(/(.*)(?i:request)/)
return nil if match.nil?
name = ActiveSupport::Inflector.underscore(match[1])
return nil unless name == verb || name.start_with?(verb + '_')
if !parts.empty?
resource_name = ActiveSupport::Inflector.singularize(parts.pop)
resource_name = ActiveSupport::Inflector.underscore(resource_name)
if !name.include?(resource_name)
name = name.split('_').insert(1, resource_name).join('_')
end
end
if pick_name
pick_name(name)
else
name
end
end
# For REST style methods, build a method name from the verb/resource(s) in the method
# id. IDs are in the form <api>.<resource>.<verb>
# @param [Google::Apis::DiscoveryV1::RestMethod] method
# Fragment of the discovery doc describing the method
def infer_method_name_from_id(method)
parts = method.id.split('.')
parts.shift
verb = ActiveSupport::Inflector.underscore(parts.pop)
return verb if parts.empty?
resource_name = ActiveSupport::Inflector.underscore(parts.pop)
if pluralize_method?(verb)
resource_name = ActiveSupport::Inflector.pluralize(resource_name)
else
resource_name = ActiveSupport::Inflector.singularize(resource_name)
end
if parts.empty?
resource_path = resource_name
else
resource_path = parts.map do |p|
p = ActiveSupport::Inflector.singularize(p)
ActiveSupport::Inflector.underscore(p)
end.join('_') + '_' + resource_name
end
method_name = verb.split('_').insert(1, resource_path.split('_')).join('_')
pick_name(method_name)
end
end
# Modifies an API description to support ruby code generation. Primarily does:
# - Ensure all names follow appopriate ruby conventions
# - Maps types to ruby types, classes, and resolves $refs
# - Attempts to simplify names where possible to make APIs more sensible
class Annotator
include NameHelpers
include Google::Apis::Core::Logging
# Prepare the API for the templates.
# @param [Google::Apis::DiscoveryV1::RestDescription] description
# API Description
def self.process(description, api_names = nil)
Annotator.new(description, api_names).annotate_api
end
# @param [Google::Apis::DiscoveryV1::RestDescription] description
# API Description
# @param [Google::Api::Generator::Names] api_names
# Name helper instanace
def initialize(description, api_names = nil)
api_names = Names.new if api_names.nil?
@names = api_names
@rest_description = description
@registered_types = []
@deferred_types = []
@strip_prefixes = []
@all_methods = {}
@dup_method_names_for_rpc = collect_dup_method_names_for_rpc
@path = []
end
def collect_method_names_for_rpc(resource, method_names_for_rpc)
resource.api_methods.each do |_k, v|
# First look for the method name in the `@names` hash. If there's
# no override set, generate it without inserting the generated name
# into the `@names` hash.
method_name_for_rpc = @names[@names.key]
if method_name_for_rpc.nil?
method_name_for_rpc = @names.infer_method_name_for_rpc(v, false)
end
method_names_for_rpc << method_name_for_rpc if method_name_for_rpc
end unless resource.api_methods.nil?
resource.resources.each do |_k, v|
collect_method_names_for_rpc(v, method_names_for_rpc)
end unless resource.resources.nil?
end
def collect_dup_method_names_for_rpc
method_names_for_rpc = []
collect_method_names_for_rpc(@rest_description, method_names_for_rpc)
method_names_for_rpc.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)
end
def annotate_api
@names.with_path(@rest_description.id) do
@strip_prefixes << @rest_description.name
if @rest_description.auth
@rest_description.auth.oauth2.scopes.each do |key, value|
value.constant = constantize_scope(key)
end
end
@rest_description.force_alt_json = @names.option('force_alt_json')
annotate_parameters(@rest_description.parameters)
annotate_resource(@rest_description.name, @rest_description)
@rest_description.schemas.each do |k, v|
annotate_type(k, v, @rest_description)
end unless @rest_description.schemas.nil?
end
resolve_type_references
resolve_variants
end
def annotate_type(name, type, parent)
@names.with_path(name) do
type.name = name
type.path = @names.key
type.generated_name = @names.infer_property_name
if type.type == 'object'
type.generated_class_name = ActiveSupport::Inflector.camelize(type.generated_name)
@registered_types << type
end
type.parent = parent
@deferred_types << type if type._ref
type.properties.each do |k, v|
annotate_type(k, v, type)
end unless type.properties.nil?
if type.additional_properties
type.type = 'hash'
annotate_type(ActiveSupport::Inflector.singularize(type.generated_name), type.additional_properties,
parent)
end
annotate_type(ActiveSupport::Inflector.singularize(type.generated_name), type.items, parent) if type.items
end
end
def annotate_resource(name, resource, parent_resource = nil)
@strip_prefixes << name
resource.parent = parent_resource unless parent_resource.nil?
resource.api_methods.each do |_k, v|
annotate_method(v, resource)
end unless resource.api_methods.nil?
resource.resources.each do |k, v|
annotate_resource(k, v, resource)
end unless resource.resources.nil?
end
def annotate_method(method, parent_resource = nil)
@names.with_path(method.id) do
method.parent = parent_resource
# Grab the method name generated from the request object without
# inserting into, or querying, the names hash.
method_name_for_rpc = @names.infer_method_name_for_rpc(method, false)
# If `method_name_for_rpc` is a duplicate (more than one method in
# the API will generate this name), generate the method name from
# the method ID instead.
if @dup_method_names_for_rpc.include?(method_name_for_rpc)
method.generated_name = @names.infer_method_name_from_id(method)
# Otherwise, proceed as normal.
elsif method_name_for_rpc
method.generated_name = @names.infer_method_name_for_rpc(method)
else
method.generated_name = @names.infer_method_name_from_id(method)
end
check_duplicate_method(method)
annotate_parameters(method.parameters)
end
end
def annotate_parameters(parameters)
parameters.each do |key, value|
@names.with_path(key) do
value.name = key
value.generated_name = @names.infer_parameter_name
@deferred_types << value if value._ref
end
end unless parameters.nil?
end
def resolve_type_references
@deferred_types.each do |type|
if type._ref
ref = @rest_description.schemas[type._ref]
ivars = ref.instance_variables - [:@name, :@generated_name]
(ivars).each do |var|
type.instance_variable_set(var, ref.instance_variable_get(var))
end
end
end
end
def resolve_variants
@deferred_types.each do |type|
if type.variant
type.variant.map.each do |v|
ref = @rest_description.schemas[v._ref]
ref.base_ref = type
ref.discriminant = type.variant.discriminant
ref.discriminant_value = v.type_value
end
end
end
end
def check_duplicate_method(m)
if @all_methods.include?(m.generated_name)
logger.error do
sprintf('Duplicate method %s generated, conflicting paths %s and %s',
m.generated_name, @names.key, @all_methods[m.generated_name])
end
fail 'Duplicate name generated'
end
@all_methods[m.generated_name] = @names.key
end
end
end
end
end
@@ -1,76 +0,0 @@
module Google
module Apis
# @private
class Generator
# Methods for validating & normalizing symbols
module NameHelpers
KEYWORDS = %w(__ENCODING__ def in self __LINE__ defined? module super __FILE__ do next then BEGIN
else nil true END elsif not undef alias end or unless and ensure redo until begin
false rescue when break for retry while case if return yield class command)
PLURAL_METHODS = %w(list search)
# Check to see if the method name should be plauralized
# @return [Boolean]
def pluralize_method?(method_name)
PLURAL_METHODS.include?(method_name)
end
# Check to see if the method is either a keyword or built-in method on object
# @return [Boolean]
def reserved?(name)
keyword?(name) || object_method?(name)
end
# Check to see if the name is a ruby keyword
# @return [Boolean]
def keyword?(name)
KEYWORDS.include?(name)
end
# Check to see if the method already exists on ruby objects
# @return [Boolean]
def object_method?(name)
Object.new.respond_to?(name)
end
# Convert a parameter name to ruby conventions
# @param [String] name
# @return [String] updated param name
def normalize_param_name(name)
name = name.gsub(/\W/, '_')
name = name.gsub(/IPv4/, 'Ipv4')
name = ActiveSupport::Inflector.underscore(name)
if reserved?(name)
logger.warn { sprintf('Found reserved keyword \'%1$s\'', name) }
name += '_'
logger.warn { sprintf('Changed to \'%1$s\'', name) }
end
name
end
# Convert a property name to ruby conventions
# @param [String] name
# @return [String]
def normalize_property_name(name)
name = ActiveSupport::Inflector.underscore(name.gsub(/\W/, '_'))
if object_method?(name)
logger.warn { sprintf('Found reserved property \'%1$s\'', name) }
name += '_prop'
logger.warn { sprintf('Changed to \'%1$s\'', name) }
end
name
end
# Converts a scope string into a ruby constant
# @param [String] url
# Url to convert
# @return [String]
def constantize_scope(url)
scope = Addressable::URI.parse(url).path[1..-1].upcase.gsub(/\W/, '_')
scope = 'AUTH_SCOPE' if scope.nil? || scope.empty?
scope
end
end
end
end
end
@@ -1,195 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'active_support/inflector'
require 'google/apis/discovery_v1'
# Extend the discovery API classes with additional data needed to make
# code generation produce better results
module Google
module Apis
module DiscoveryV1
TYPE_MAP = {
'string' => 'String',
'boolean' => 'Boolean',
'number' => 'Float',
'integer' => 'Fixnum',
'any' => 'Object'
}
class JsonSchema
attr_accessor :name
attr_accessor :generated_name
attr_accessor :generated_class_name
attr_accessor :base_ref
attr_accessor :parent
attr_accessor :discriminant
attr_accessor :discriminant_value
attr_accessor :path
def properties
Hash[(@properties || {}).sort]
end
def qualified_name
parent.qualified_name + '::' + generated_class_name
end
def generated_type
case type
when 'string', 'boolean', 'number', 'integer', 'any'
return 'DateTime' if format == 'date-time'
return 'Date' if format == 'date'
return 'Fixnum' if format == 'int64'
return 'Fixnum' if format == 'uint64'
return TYPE_MAP[type]
when 'array'
if items == self
return sprintf('Array<%s>', qualified_name)
end
return sprintf('Array<%s>', items.generated_type)
when 'hash'
if additional_properties == self
return sprintf('Hash<String,%s>', qualified_name)
end
return sprintf('Hash<String,%s>', additional_properties.generated_type)
when 'object'
return qualified_name
end
end
end
class RestMethod
attr_accessor :generated_name
attr_accessor :parent
def parameters
Hash[(@parameters || {}).sort]
end
def path_parameters
return [] if parameter_order.nil? || parameters.nil?
parameter_order.map { |name| parameters[name] }.select { |param| param.location == 'path' }
end
def query_parameters
return [] if parameters.nil?
parameters.values.select { |param| param.location == 'query' }
end
def required_parameters
return [] if parameter_order.nil? || parameters.nil?
parameter_order.map { |name| parameters[name] }.select { |param| param.location == 'path' || param.required }
end
def optional_query_parameters
query_parameters.select { |param| param.required != true }
end
end
class RestResource
attr_accessor :parent
def api_methods
Hash[(@api_methods || {}).sort]
end
def resources
Hash[(@resources || {}).sort]
end
def all_methods
m = []
m << api_methods.values unless api_methods.nil?
m << resources.map { |_k, r| r.all_methods } unless resources.nil?
m.flatten
end
end
class RestDescription
attr_accessor :force_alt_json
alias_method :force_alt_json?, :force_alt_json
# Don't expose these in the API directly.
PARAMETER_BLACKLIST = %w(alt access_token bearer_token oauth_token pp prettyPrint
$.xgafv callback upload_protocol uploadType)
def version
ActiveSupport::Inflector.camelize(@version.gsub(/\W/, '-')).gsub(/-/, '_')
end
def name
ActiveSupport::Inflector.camelize(@name)
end
def module_name
name + version
end
def qualified_name
sprintf('Google::Apis::%s', module_name)
end
def base_path
ActiveSupport::Inflector.underscore(qualified_name)
end
def gem_name
base_path.tr("/", "-")
end
def service_name
class_name = (canonical_name || name).gsub(/\W/, '')
ActiveSupport::Inflector.camelize(sprintf('%sService', class_name))
end
def api_methods
Hash[(@api_methods || {}).sort]
end
def resources
Hash[(@resources || {}).sort]
end
def all_methods
m = []
m << api_methods.values unless api_methods.nil?
m << resources.map { |_k, r| r.all_methods } unless resources.nil?
m.flatten
end
def parameters
Hash[(@parameters || {}).sort].delete_if { |k, _v| PARAMETER_BLACKLIST.include?(k) }
end
def schemas
Hash[(@schemas || {}).sort]
end
class Auth
class Oauth2
class Scope
attr_accessor :constant
end
def scopes
Hash[(@scopes || {}).sort]
end
end
end
end
end
end
end
@@ -1,124 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'active_support/inflector'
require 'erb'
require 'ostruct'
module Google
module Apis
# @private
class Generator
# Directory containing ERB templates
TEMPLATE_DIR = File.expand_path('../templates', __FILE__)
# Helpers used in ERB templates
module TemplateHelpers
# Get the include path for a ruby module/class
#
# @param [String] module_name
# Fully qualified module/class name
# @return [String]
# Path to file
def to_path(module_name)
ActiveSupport::Inflector.underscore(module_name)
end
# Render a block comment
#
# @param [String] str
# Comment string
# @param [Fixnum] spaces_before
# Number of spaces to indent the comment hash
# @param [Fixnum] spaces_after
# Number of spaces to indent after the comment hash for subsequent lines
# @return [String] formatted comment
def block_comment(str, spaces_before = 0, spaces_after = 0)
return '' if str.nil?
pre = ' ' * spaces_before
post = ' ' * spaces_after
lines = str.gsub(/([{}])/, '`').scan(/.{1,78}(?:\W|$)/).map(&:strip)
lines.join("\n" + pre + '#' + post)
end
# Indent a block of text
#
# @param [String] str
# Content to indent
# @param [Fixnum] spaces
# Number of spaces to indent
# @return [String] formatted content
def indent(str, spaces)
pre = ' ' * spaces
str = pre + str.split(/\n/).join("\n" + pre) + "\n"
return str unless str.strip.empty?
nil
end
# Include a partial inside a template.
#
# @private
# @param [String] partial
# Name of the template
# @param [Hash] context
# Context used to render
# @return [String] rendered content
def include(partial, context)
template = Template.new(sprintf('_%s.tmpl', partial))
template.render(context)
end
end
# Holds local vars/helpers for template rendering
class Context < OpenStruct
include TemplateHelpers
# Get the context for ERB evaluation
# @return [Binding]
def to_binding
binding
end
end
# ERB template for the code generator
class Template
# Loads a template from the template dir. Automatically
# appends the .tmpl suffix
#
# @param [String] template_name
# Name of the template file
def self.load(template_name)
Template.new(sprintf('%s.tmpl', template_name))
end
# @param [String] template_name
# Name of the template file
def initialize(template_name)
file = File.join(TEMPLATE_DIR, template_name)
@erb = ERB.new(File.read(file), nil, '-')
end
# Render the template
#
# @param [Hash] context
# Variables to set when rendering the template
# @return [String] rendered template
def render(context)
ctx = Context.new(context)
@erb.result(ctx.to_binding)
end
end
end
end
end
@@ -1,43 +0,0 @@
<% if cls.type == 'object' || (cls.type == 'hash' && cls.properties.length > 0) -%>
# <%= block_comment(cls.description, 0, 1) %>
class <%= cls.generated_class_name %><% if cls.base_ref %> < <%= cls.base_ref.generated_type %><% end %>
include Google::Apis::Core::Hashable
<% for property in cls.properties.values -%>
# <%= block_comment(property.description, 2, 1) %>
# Corresponds to the JSON property `<%= property.name %>`
<% if property.format == 'byte' -%>
# NOTE: Values are automatically base64 encoded/decoded in the client library.
<% end -%>
# @return [<%= property.generated_type %>]
attr_accessor :<%= property.generated_name %>
<% if property.type == 'boolean' -%>
alias_method :<%= property.generated_name %>?, :<%= property.generated_name %>
<% end -%>
<% end -%>
def initialize(**args)
<% if cls.discriminant -%>
@<%= cls.properties[cls.discriminant].generated_name %> = '<%= cls.discriminant_value %>'
<% end -%>
update!(**args)
end
# Update properties of this object
def update!(**args)
<% for property in cls.properties.values -%>
@<%= property.generated_name %> = args[:<%= property.generated_name %>] if args.key?(:<%= property.generated_name %>)
<% end -%>
end
<% for child_class in cls.properties.values -%>
<% if child_class._ref.nil? -%>
<%= indent(include('class', :cls => child_class, :api => api), 2) -%>
<% end -%>
<% end -%>
end
<% elsif cls.items && cls.items._ref.nil? -%>
<%= include('class', :cls => cls.items, :api => api) -%>
<% elsif cls.additional_properties && cls.additional_properties._ref.nil? -%>
<%= include('class', :cls => cls.additional_properties, :api => api) -%>
<% end -%>
@@ -1,92 +0,0 @@
# <%= block_comment(api_method.description, 0, 1) %>
<% for param in api_method.required_parameters -%>
# @param [<% if param.repeated? %>Array<<%= param.generated_type %>>, <% end %><%= param.generated_type %>] <%= param.generated_name %>
<% if param.description -%>
# <%= block_comment(param.description, 0, 3) %>
<% end -%>
<% end -%>
<% if api_method.request -%>
# @param [<%= api.schemas[api_method.request._ref].generated_type %>] <%= api.schemas[api_method.request._ref].generated_name %>_object
<% end -%>
<% for param in api_method.optional_query_parameters -%>
# @param [<% if param.repeated? %>Array<<%= param.generated_type %>>, <% end %><%= param.generated_type %>] <%= param.generated_name %>
<% if param.description -%>
# <%= block_comment(param.description, 0, 3) %>
<% end -%>
<% end -%>
<% for param in api.parameters.values.reject {|p| p.name == 'key'} -%>
# @param [<% if param.repeated? %>Array<<%= param.generated_type %>>, <% end %><%= param.generated_type %>] <%= param.generated_name %>
<% if param.description -%>
# <%= block_comment(param.description, 0, 3) %>
<% end -%>
<% end -%>
<% if api_method.supports_media_upload? -%>
# @param [IO, String] upload_source
# IO stream or filename containing content to upload
# @param [String] content_type
# Content type of the uploaded content.
<% elsif api_method.supports_media_download? -%>
# @param [IO, String] download_dest
# IO stream or filename to receive content download
<% end -%>
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
<% if api_method.response -%>
# @yieldparam result [<%= api.schemas[api_method.response._ref].generated_type %>] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [<%= api.schemas[api_method.response._ref].generated_type %>]
<% else -%>
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
<% end -%>
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def <%= api_method.generated_name %>(<% for param in api_method.required_parameters %><%= param.generated_name %>, <% end %><% if api_method.request %><%= api.schemas[api_method.request._ref].generated_name %>_object = nil, <% end %><% for param in api_method.optional_query_parameters %><%= param.generated_name %>: nil, <% end %><% for param in api.parameters.values.reject {|p| p.name == 'key'} %><%= param.generated_name %>: nil, <% end %><% if api_method.supports_media_upload? %>upload_source: nil, content_type: nil, <% elsif api_method.supports_media_download? %>download_dest: nil, <% end %>options: nil, &block)
<% if api_method.supports_media_upload? -%>
if upload_source.nil?
command = make_simple_command(:<%= api_method.http_method.downcase %>, '<%= api_method.path %>', options)
else
command = make_upload_command(:<%= api_method.http_method.downcase %>, '<%= api_method.path %>', options)
command.upload_source = upload_source
command.upload_content_type = content_type
end
<% elsif api_method.supports_media_download? -%>
if download_dest.nil?
command = make_simple_command(:<%= api_method.http_method.downcase %>, '<%= api_method.path %>', options)
else
command = make_download_command(:<%= api_method.http_method.downcase %>, '<%= api_method.path %>', options)
command.download_dest = download_dest
end
<% else -%>
command = make_simple_command(:<%= api_method.http_method.downcase %>, '<%= api_method.path %>', options)
<% end -%>
<% if api_method.request -%>
command.request_representation = <%= api.schemas[api_method.request._ref].generated_type %>::Representation
command.request_object = <%= api.schemas[api_method.request._ref].generated_name %>_object
<% end -%>
<% if api_method.response -%>
<% if api.force_alt_json? -%>
command.query['alt'] = 'json'
<% end -%>
command.response_representation = <%= api.schemas[api_method.response._ref].generated_type %>::Representation
command.response_class = <%= api.schemas[api_method.response._ref].generated_type %>
<% end -%>
<% for param in api_method.path_parameters -%>
command.params['<%= param.name %>'] = <%= param.generated_name %> unless <%= param.generated_name %>.nil?
<% end -%>
<% for param in api_method.query_parameters -%>
command.query['<%= param.name %>'] = <%= param.generated_name %> unless <%= param.generated_name %>.nil?
<% end -%>
<% for param in api.parameters.values.reject {|p| p.name == 'key'} -%>
command.query['<%= param.name %>'] = <%= param.generated_name %> unless <%= param.generated_name %>.nil?
<% end -%>
execute_or_queue_command(command, &block)
end
@@ -1,51 +0,0 @@
<% if cls.type == 'object' -%>
class <%= cls.generated_class_name %>
# @private
class Representation < Google::Apis::Core::JsonRepresentation
<% if api.features && api.features.include?('dataWrapper') -%>
self.representation_wrap = lambda { |args| :data if args[:unwrap] == <%= cls.generated_type %> }
<% end -%>
<% if cls.variant -%>
def from_hash(hash, *args)
case hash['<%= cls.variant.discriminant %>']
<% for v in cls.variant.map -%>
<% ref = api.schemas[v._ref] %>
when '<%= v.type_value %>'
<%= ref.generated_type %>::Representation.new(<%= ref.generated_type %>.new).from_hash(hash, *args)
<% end -%>
end
end
def to_hash(*args)
case represented
<% for v in cls.variant.map -%>
<% ref = api.schemas[v._ref] %>
when <%= ref.generated_type %>
<%= ref.generated_type %>::Representation.new(represented).to_hash(*args)
<% end -%>
end
end
<% else -%>
<% for property in cls.properties.values -%>
<% if property.type == 'hash' -%>
hash :<%= property.generated_name %>, as: '<%= property.name %>'<%= include('representation_type', :lead => ', ', :type => property.additional_properties, :api => api) %>
<% elsif property.type == 'array' -%>
collection :<%= property.generated_name %>, as: '<%= property.name %>'<%= include('representation_type', :lead => ', ', :type => property.items, :api => api) %>
<% else -%>
property :<%= property.generated_name %>,<% if ['uint64', 'int64'].include?(property.format) %> :numeric_string => true,<%end%><% if property.format == 'byte' %> :base64 => true,<%end%> as: '<%= property.name %>'<%= include('representation_type', :lead => ', ', :type => property, :api => api) %>
<% end -%>
<% end -%>
<% end -%>
end
<% for child_class in cls.properties.values -%>
<% if child_class._ref.nil? -%>
<%= indent(include('representation', :cls => child_class, :api => api), 2) -%>
<% end -%>
<% end -%>
end
<% elsif cls.items && cls.items._ref.nil? -%>
<%= include('representation', :cls => cls.items, :api => api) -%>
<% elsif cls.additional_properties && cls.additional_properties._ref.nil? -%>
<%= include('representation', :cls => cls.additional_properties, :api => api) -%>
<% end -%>
@@ -1,17 +0,0 @@
<% if cls.type == 'object' -%>
class <%= cls.generated_class_name %>
class Representation < Google::Apis::Core::JsonRepresentation; end
<% for child_class in cls.properties.values -%>
<% if child_class._ref.nil? -%>
<%= indent(include('representation_stub', :cls => child_class), 2) -%>
<% end -%>
<% end -%>
include Google::Apis::Core::JsonObjectSupport
end
<% elsif cls.items && cls.items._ref.nil? -%>
<%= include('representation_stub', :cls => cls.items, :api => api) -%>
<% elsif cls.additional_properties && cls.additional_properties._ref.nil? -%>
<%= include('representation_stub', :cls => cls.additional_properties, :api => api) -%>
<% end -%>
@@ -1,10 +0,0 @@
<% if type.type == 'array' -%>
<%= lead %>:class => Array do
include Representable::JSON::Collection
items<%= include('representation_type', :lead => ' ' , :type => type.items, :api => api) %>
end
<% elsif ['date', 'date-time'].include?(type.format) -%>
<%= lead %>type: <%= type.generated_type %>
<% elsif type.type == 'object' -%>
<%= lead %>class: <%= type.generated_type %>, decorator: <%= type.generated_type %>::Representation
<% end -%>
@@ -1,29 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module <%= api.module_name %>
<% for cls in api.schemas.values.partition(&:variant).flatten -%>
<%= indent(include('class', :cls => cls, :api => api), 6) -%>
<% end -%>
end
end
end
@@ -1,2 +0,0 @@
--color
--format documentation
@@ -1,12 +0,0 @@
--hide-void-return
--no-private
--verbose
--markup-provider=redcarpet
--markup=markdown
--main OVERVIEW.md
lib/<%= api.base_path %>/*.rb
lib/<%= api.base_path %>.rb
-
OVERVIEW.md
CHANGELOG.md
LICENSE.md
@@ -1,15 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "<%= api.base_path %>"
@@ -1,23 +0,0 @@
source 'https://rubygems.org'
gemspec
group :development do
gem "bundler", ">= 1.17"
gem "rake", ">= 12.0"
gem "rspec", "~> 3.9"
gem "opencensus", "~> 0.5"
end
platforms :jruby do
group :development do
gem "jruby-openssl"
end
end
platforms :ruby do
group :development do
gem "yard", "~> 0.9", ">= 0.9.25"
gem "redcarpet", "~> 3.5"
end
end
@@ -1,32 +0,0 @@
require File.expand_path("lib/<%= api.base_path %>/gem_version", __dir__)
Gem::Specification.new do |gem|
gem.name = "<%= api.gem_name %>"
gem.version = <%= api.qualified_name %>::GEM_VERSION
gem.authors = ["Google LLC"]
gem.email = "googleapis-packages@google.com"
gem.summary = "Legacy REST client for <%= api.title %> <%= api.version %>"
gem.description =
"This is the legacy REST client for <%= api.title %> <%= api.version %>." \
" Legacy REST clients are simple Ruby libraries that provide access to" \
" Google services via their HTTP REST API endpoints. These libraries are" \
" generated and updated automatically based on the discovery documents" \
" published by the service, and they handle most concerns such as" \
" authentication, pagination, retry, timeouts, and logging. You can use" \
" this client to access the <%= api.title %>, but note that some" \
" services may provide a separate modern client that is easier to use."
gem.homepage = "https://github.com/google/google-api-ruby-client"
gem.license = "Apache-2.0"
gem.metadata = {
"bug_tracker_uri" => "https://github.com/googleapis/google-api-ruby-client/issues",
"changelog_uri" => "https://github.com/googleapis/google-api-ruby-client/tree/master/generated/<%= api.gem_name %>/CHANGELOG.md",
"documentation_uri" => "https://googleapis.dev/ruby/<%= api.gem_name %>/v#{<%= api.qualified_name %>::GEM_VERSION}",
"source_code_uri" => "https://github.com/googleapis/google-api-ruby-client/tree/master/generated/<%= api.gem_name %>"
}
gem.files = Dir.glob("lib/**/*.rb") + Dir.glob("*.md") + [".yardopts"]
gem.require_paths = ["lib"]
gem.required_ruby_version = '>= 2.4'
gem.add_runtime_dependency "google-apis-core", "~> 0.1"
end
@@ -1,27 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "rspec"
RSpec.describe "<%= api.qualified_name %>" do
# Minimal test just to ensure no syntax errors in generated code
it "should load" do
expect do
require "<%= api.base_path %>"
end.not_to raise_error
expect do
<%= api.qualified_name %>::<%= api.service_name %>.new
end.not_to raise_error
end
end
@@ -1,2 +0,0 @@
# Release history for <%= api.gem_name %>
@@ -1,28 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Apis
module <%= api.module_name %>
# Version of the <%= api.gem_name %> gem
GEM_VERSION = "0.0.0"
# Version of the code generator used to generate this client
GENERATOR_VERSION = "0.0.0"
# Revision of the discovery document this client was generated from
REVISION = "0"
end
end
end
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -1,42 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require '<%= to_path(api.qualified_name) %>/service.rb'
require '<%= to_path(api.qualified_name) %>/classes.rb'
require '<%= to_path(api.qualified_name) %>/representations.rb'
require '<%= to_path(api.qualified_name) %>/gem_version.rb'
module Google
module Apis
# <%= api.title %>
#
# <%= block_comment(api.description, 4, 1) %>
#
<% if api.documentation_link -%>
# @see <%= api.documentation_link %>
<% end -%>
module <%= api.module_name %>
# Version of the <%= api.title %> this client connects to.
# This is NOT the gem version.
VERSION = '<%= api.version %>'
<% if api.auth && api.auth.oauth2 -%>
<% for scope_string, scope in api.auth.oauth2.scopes -%>
# <%= scope.description %>
<%= scope.constant %> = '<%= scope_string %>'
<% end -%>
<% end -%>
end
end
end
@@ -1,96 +0,0 @@
# Legacy REST client for version <%= api.version %> of the <%= api.title %>
This is a simple client library for version <%= api.version %> of the <%= api.title %>. It provides:
* A client object that connects to the HTTP/JSON REST endpoint for the service.
* Ruby objects for data structures related to the service.
* Integration with the googleauth gem for authentication using OAuth, API keys, and service accounts.
* Control of retry, pagination, and timeouts.
Note that although this client library is supported and will continue to be updated to track changes to the service, it is considered legacy. A more modern client may be available for many Google services, especially Cloud Platform services. See the section below titled *Which client should I use?* for more information.
## Getting started
### Before you begin
There are a few setup steps you need to complete before you can use this library:
1. If you don't already have a Google account, [sign up](https://www.google.com/accounts).
2. If you have never created a Google APIs Console project, read about [Managing Projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects) and create a project in the [Google API Console](https://console.cloud.google.com/).
3. Most APIs need to be enabled for your project. [Enable it](https://console.cloud.google.com/apis/library/<%= api.name.downcase %>.googleapis.com) in the console.
### Installation
Add this line to your application's Gemfile:
```ruby
gem '<%= api.gem_name %>', '~> 0.1'
```
And then execute:
```
$ bundle
```
Or install it yourself as:
```
$ gem install <%= api.gem_name %>
```
### Creating a client object
Once the gem is installed, you can load the client code and instantiate a client.
```ruby
# Load the client
require "<%= api.base_path %>"
# Create a client object
client = <%= api.qualified_name %>::<%= api.service_name %>.new
# Authenticate calls
client.authentication = # ... use the googleauth gem to create credentials
```
See the class reference docs for information on the methods you can call from a client.
## Documentation
More detailed descriptions of the Google legacy REST clients are available in two documents.
* The [Usage Guide](https://github.com/googleapis/google-api-ruby-client/blob/master/docs/usage-guide.md) discusses how to make API calls, how to use the provided data structures, and how to work the various features of the client library, including media upload and download, error handling, retries, pagination, and logging.
* The [Auth Guide](https://github.com/googleapis/google-api-ruby-client/blob/master/docs/auth-guide.md) discusses authentication in the client libraries, including API keys, OAuth 2.0, service accounts, and environment variables.
(Note: the above documents are written for the legacy clients in general, and their examples may not reflect the <%= api.name %> service in particular.)
For reference information on specific calls in the <%= api.title %>, see the {<%= api.qualified_name %>::<%= api.service_name %> class reference docs}.
## Which client should I use?
Google provides two types of Ruby API client libraries: **legacy REST clients** and **modern clients**.
This library, `<%= api.gem_name %>`, is a legacy REST client. You can identify legacy clients by their gem names, which are always in the form `google-apis-<servicename>_<serviceversion>`. The legacy REST clients connect to HTTP/JSON REST endpoints and are automatically generated from service discovery documents. They support most API functionality, but their class interfaces are sometimes awkward.
Modern clients are produced by a modern code generator, combined with hand-crafted functionality for some services. Most modern clients connect to high-performance gRPC endpoints, although a few are backed by REST services. Modern clients are available for many Google services, especially Cloud Platform services, but do not yet support all the services covered by the legacy clients.
Gem names for modern clients are often of the form `google-cloud-<service_name>`. (For example, [google-cloud-pubsub](https://rubygems.org/gems/google-cloud-pubsub).) Note that most modern clients also have corresponding "versioned" gems with names like `google-cloud-<service_name>-<version>`. (For example, [google-cloud-pubsub-v1](https://rubygems.org/gems/google-cloud-pubsub-v1).) The "versioned" gems can be used directly, but often provide lower-level interfaces. In most cases, the main gem is recommended.
**For most users, we recommend the modern client, if one is available.** Compared with legacy clients, modern clients are generally much easier to use and more Ruby-like, support more advanced features such as streaming and long-running operations, and often provide much better performance. You may consider using a legacy client instead, if a modern client is not yet available for the service you want to use, or if you are not able to use gRPC on your infrastructure.
The [product documentation](<%= api.documentation_link %>) may provide guidance regarding the preferred client library to use.
## Supported Ruby versions
This library is supported on Ruby 2.5+.
Google provides official support for Ruby versions that are actively supported by Ruby Core -- that is, Ruby versions that are either in normal maintenance or in security maintenance, and not end of life. Currently, this means Ruby 2.5 and later. Older versions of Ruby _may_ still work, but are unsupported and not recommended. See https://www.ruby-lang.org/en/downloads/branches/ for details about the Ruby support schedule.
## License
This library is licensed under Apache 2.0. Full license text is available in the {file:LICENSE.md LICENSE}.
## Support
Please [report bugs at the project on Github](https://github.com/google/google-api-ruby-client/issues). Don't hesitate to [ask questions](http://stackoverflow.com/questions/tagged/google-api-ruby-client) about the client or APIs on [StackOverflow](http://stackoverflow.com).
@@ -1,28 +0,0 @@
require "bundler/gem_tasks"
task :release_gem do
Rake::Task["build"].invoke
Rake::Task["release:rubygem_push"].invoke
end
require 'rake/clean'
CLOBBER.include('coverage', 'doc')
CLEAN.include('.yardoc')
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
begin
require 'yard'
require 'yard/rake/yardoc_task'
YARD::Rake::YardocTask.new do |t|
t.files = ['lib/**/*.rb', 'generated/**/*.rb']
t.options = ['--verbose', '--markup', 'markdown']
end
rescue LoadError
task :yard
puts "YARD not available"
end
task :ci => [:spec, :yard, :build]
task :default => :ci
@@ -1,32 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module <%= api.module_name %>
<% for cls in api.schemas.values.partition(&:variant).flatten -%>
<%= indent(include('representation_stub', :cls => cls), 6) -%>
<% end -%>
<% for cls in api.schemas.values.partition(&:variant).flatten -%>
<%= indent(include('representation', :cls => cls, :api => api), 6) -%>
<% end -%>
end
end
end
@@ -1,63 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module <%= api.module_name %>
# <%= api.title %>
#
# <%= block_comment(api.description, 6, 2) %>
#
# @example
# require '<%= to_path(api.qualified_name) %>'
#
# <%= api.name %> = <%= api.qualified_name %> # Alias the module
# service = <%= api.name %>::<%= api.service_name %>.new
#
<% if api.documentation_link -%>
# @see <%= api.documentation_link %>
<% end -%>
class <%= api.service_name %> < Google::Apis::Core::BaseService
<% for param in api.parameters.values.reject {|p| p.name == 'fields'} -%>
# @return [<%= param.generated_type %>]
# <%= block_comment(param.description, 8, 2) %>
attr_accessor :<%= param.generated_name %>
<% end -%>
def initialize
super('<%= api.root_url %>', '<%= api.service_path %>',
client_name: '<%= api.gem_name %>',
client_version: <%= api.qualified_name %>::GEM_VERSION)
@batch_path = '<%= api.batch_path %>'
end
<% for api_method in api.all_methods -%>
<%= indent(include('method', :api_method => api_method, :api => api), 8) -%>
<% end -%>
protected
def apply_command_defaults(command)
<% for param in api.parameters.values.reject {|p| p.name == 'fields'} -%>
command.query['<%= param.name %>'] = <%= param.generated_name %> unless <%= param.generated_name %>.nil?
<% end -%>
end
end
end
end
end
@@ -1,139 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "gems"
module Google
module Apis
class Generator
# Matches generated files against current files and decides what to update
# @private
class Updater
def initialize
@gems_client = nil
@current_rubygems_versions = {}
end
def analyze(base_dir, generator_result)
modified_files = {}
version_content = changelog_content = nil
generator_result.files.each do |path, content|
full_path = File.join(base_dir, path)
old_content = File.binread(full_path) if File.readable?(full_path)
if path == generator_result.version_path
version_content = old_content || content
elsif path == generator_result.changelog_path
changelog_content = old_content || content
else
modified_files[path] = content unless content == old_content
end
end
unless modified_files.empty?
desired_gem_version = next_rubygems_version(generator_result.gem_name)
version_content, generator_version_change, revision_change =
update_version_content(version_content, desired_gem_version, generator_result.revision)
changelog_content = update_changelog_content(changelog_content, desired_gem_version, generator_version_change, revision_change)
modified_files[generator_result.version_path] = version_content
modified_files[generator_result.changelog_path] = changelog_content
end
modified_files
end
# @private
def gems_client
@gems_client ||= Gems::Client.new
end
# @private
def current_rubygems_version(gem_name)
@current_rubygems_versions[gem_name] ||= begin
gems_client.info(gem_name)["version"]
rescue Gems::NotFound
"0.0.0"
end
end
# @private
def next_rubygems_version(gem_name)
major, minor = current_rubygems_version(gem_name).split(".")
"#{major.to_i}.#{minor.to_i + 1}.0"
end
# @private
def update_version_content(content, desired_gem_version, new_revision)
generator_version_change = revision_change = nil
modified_content = content.dup
modified_content.sub!(/GEM_VERSION = "([\w\.]*)"/) do |*|
"GEM_VERSION = \"#{desired_gem_version}\""
end or raise "gem_version.rb is missing GEM_VERSION"
modified_content.sub!(/GENERATOR_VERSION = "([\w\.]*)"/) do |*|
generator_version_change = Generator::VERSION unless Regexp.last_match[1] == Generator::VERSION
"GENERATOR_VERSION = \"#{Generator::VERSION}\""
end or raise "gem_version.rb is missing GENERATOR_VERSION"
modified_content.sub!(/REVISION = "([\w\.]*)"/) do |*|
revision_change = new_revision unless Regexp.last_match[1] == new_revision
"REVISION = \"#{new_revision}\""
end or raise "gem_version.rb is missing REVISION"
[modified_content, generator_version_change, revision_change]
end
# @private
def update_changelog_content(content, desired_gem_version, generator_version_change, revision_change)
lines = parse_existing_changelog_entry(content, desired_gem_version)
modify_changelog_lines(lines, generator_version_change, revision_change)
entry = assemble_changelog_entry(lines, desired_gem_version)
replace_changelog_entry(content, desired_gem_version, entry)
end
# @private
def parse_existing_changelog_entry(content, desired_gem_version)
quoted_gem_version = Regexp.quote(desired_gem_version)
match = /\n+### v#{quoted_gem_version} \([\d-]+\)\n+((?:[^#][^\n]*\n+)*)(?=#|$)/.match content
return [] unless match
match[1].split("\n")
end
# @private
def modify_changelog_lines(lines, generator_version_change, revision_change)
if generator_version_change
lines.reject! { |line| line =~ /^\* Regenerated using generator version \d[\w\.]+/ }
lines.unshift("* Regenerated using generator version #{generator_version_change}")
end
if revision_change
lines.reject! { |line| line =~ /^\* Regenerated from discovery document revision \d+/ }
lines.unshift("* Regenerated from discovery document revision #{revision_change}")
end
lines << "* Unspecified changes" if lines.empty?
end
# @private
def assemble_changelog_entry(lines, desired_gem_version)
entry_lines = lines.join("\n")
date = Time.now.strftime("%Y-%m-%d")
"\n\n### v#{desired_gem_version} (#{date})\n\n#{entry_lines}\n\n"
end
# @private
def replace_changelog_entry(content, desired_gem_version, entry)
quoted_gem_version = Regexp.quote(desired_gem_version)
modified_content = content.dup
modified_content.sub!(/\n+### v#{quoted_gem_version} \([\d-]+\)\n+(?:[^#][^\n]*\n+)*(?=#|$)/, entry) or
modified_content.sub!(/^(\n*# [^\n]+)\n+(?=#|$)/, "\\1#{entry}") or
raise "CHANGELOG doesn't seem to have the expected header"
modified_content
end
end
end
end
end
@@ -1,21 +0,0 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Apis
class Generator
VERSION = "0.1.0"
end
end
end
-3
View File
@@ -1,3 +0,0 @@
---
"/test:v1/TestAnotherThing": another_thing
-1
View File
@@ -1 +0,0 @@
test
-487
View File
@@ -1,487 +0,0 @@
{
"kind": "discovery#describeItem",
"name": "test",
"version": "v1",
"id": "test:v1",
"description": "Discovery doc API used for testing the code generator",
"basePath": "/test/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "test/v1/",
"batchPath": "batch/test/v1",
"rpcPath": "/rpc",
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/test": {
"description": "View and manage things"
},
"https://www.googleapis.com/auth/test.readonly": {
"description": "View things"
}
}
}
},
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"schemas": {
"Thing": {
"id": "Thing",
"type": "object",
"properties": {
"id": {
"type": "string"
},
"etag": {
"type": "string"
},
"kind": {
"type": "string",
"default": "test#thing"
},
"name": {
"type": "string"
},
"enabled": {
"type": "boolean"
},
"hat": {
"$ref": "Hat"
},
"recursiveHat": {
"$ref": "RecursiveHat"
},
"properties": {
"$ref": "HashLikeThing"
},
"photo": {
"type": "object",
"properties": {
"filename": {
"type": "string"
},
"hash": {
"type": "string"
},
"hashAlgorithm": {
"type": "string"
},
"size": {
"type": "integer"
},
"type": {
"type": "string"
}
}
}
}
},
"Hat": {
"type": "object",
"variant": {
"discriminant": "type",
"map": [
{
"type_value": "topHat",
"$ref": "TopHat"
},
{
"type_value": "baseballHat",
"$ref": "BaseballHat"
}
]
}
},
"RecursiveHat": {
"id": "RecursiveHat",
"type": "object",
"properties": {
"bool": {
"type": "boolean",
"description": "The bool value."
},
"double": {
"type": "number",
"description": "The double value.",
"format": "double"
},
"image": {
"$ref": "Image",
"description": "The image value."
},
"int": {
"type": "integer",
"description": "The int value.",
"format": "int32"
},
"kind": {
"type": "string",
"description": "The kind, fixed to \"test#recursiveHat\".",
"default": "test#recursiveHat"
},
"list": {
"type": "array",
"description": "The list of typed values.",
"items": {
"$ref": "RecursiveHat"
}
},
"string": {
"type": "string",
"description": "The string value."
}
},
"additionalProperties": {
"$ref": "RecursiveHat"
}
},
"TopHat": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"height": {
"type": "number"
}
}
},
"BaseballHat": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"color": {
"type": "string"
}
}
},
"HashLikeThing": {
"id": "HashLikeThing",
"type": "object",
"additionalProperties": {
"type": "string",
"description": "A mapping from export format to URL"
}
},
"TestThing": {
"id": "TestThing",
"type": "object",
"properties" :{}
},
"TestAnotherThing": {
"id": "TestAnotherThing",
"type": "object",
"properties" :{}
},
"ThingList": {
"id": "ThingList",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "The actual list of files.",
"items": {
"$ref": "Thing"
}
},
"kind": {
"type": "string",
"default": "test#thinglist"
}
}
},
"QueryResults": {
"id": "QueryResults",
"type": "object",
"properties": {
"rows": {
"$ref": "Rows"
}
}
},
"Rows": {
"id": "QueryResults",
"type": "array",
"items": {
"type": "object",
"properties": {
"value": {
"type": "string"
}
}
}
}
},
"methods": {
"query": {
"path": "query",
"id": "test.query",
"httpMethod": "GET",
"response": {
"$ref": "QueryResults"
//"$ref": "Rows" TODO: Support naked collections as a return value
},
"parameters": {
"s": {
"type": "string",
"location": "query",
"required": false,
"repeated": false
},
"i": {
"type": "integer",
"location": "query",
"required": false,
"repeated": false,
"minimum": "0",
"maximum": "4294967295",
"default": "20"
},
"n": {
"type": "number",
"location": "query",
"required": false,
"repeated": false
},
"b": {
"type": "boolean",
"location": "query",
"required": false,
"repeated": false
},
"a": {
"type": "any",
"location": "query",
"required": false,
"repeated": false
},
"e": {
"type": "string",
"location": "query",
"required": false,
"repeated": false,
"enum": [
"foo",
"bar"
]
},
"er": {
"type": "string",
"location": "query",
"required": false,
"repeated": true,
"enum": [
"one",
"two",
"three"
]
},
"sr": {
"type": "string",
"location": "query",
"required": false,
"repeated": true,
"pattern": "[a-z]+"
},
"do": {
"type": "string",
"location": "query",
"required": false
}
}
}
},
"resources": {
"things": {
"resources": {
"subthings": {
"methods": {
"list": {
"path": "things",
"id": "test.things.subthings.list",
"httpMethod": "GET",
"parameters": {
"max-results": {
"type": "number",
"location": "query",
"required": false
}
},
"response": {
"$ref": "ThingList"
}
}
}
}
},
"methods": {
"list": {
"path": "things",
"id": "test.things.list",
"httpMethod": "GET",
"parameters": {
"max-results": {
"type": "number",
"location": "query",
"required": false
}
},
"response": {
"$ref": "ThingList"
}
},
"delete": {
"path": "things/{id}",
"id": "test.things.delete",
"httpMethod": "DELETE",
"description": "Delete things",
"parameters": {
"id": {
"location": "path",
"required": true,
"description": "ID of the thing to delete",
"type": "string"
}
},
"parameterOrder": [
"id"
]
},
"get": {
"path": "things/{id}",
"id": "test.things.get",
"httpMethod": "GET",
"description": "Get things",
"supportsMediaDownload": true,
"parameters": {
"id": {
"location": "path",
"required": true,
"description": "ID of the thing to get",
"type": "string"
}
},
"supportsMediaDownload": true,
"parameterOrder": [
"id"
],
"response": {
"$ref": "Thing"
}
},
"create": {
"path": "things",
"id": "test.things.create",
"httpMethod": "POST",
"description": "Create things",
"request": {
"$ref": "Thing"
},
"response": {
"$ref": "Thing"
},
"supportsMediaUpload": true,
"mediaUpload": {
"accept": [
"*/*"
],
"maxSize": "1KB",
"protocols": {
"simple": {
"multipart": true,
"path": "upload/things/{id}"
},
"resumable": {
"multipart": true,
"path": "/resumable/upload/things/{id}"
}
}
}
},
"update": {
"path": "things/{id}",
"id": "test.things.update",
"httpMethod": "PUT",
"description": "Update things",
"parameters": {
"id": {
"location": "path",
"description": "ID of the thing to update",
"type": "string"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Thing"
},
"response": {
"$ref": "Thing"
},
"supportsMediaUpload": true,
"mediaUpload": {
"accept": [
"*/*"
],
"maxSize": "1KB",
"protocols": {
"simple": {
"multipart": true,
"path": "upload/things/{id}"
},
"resumable": {
"multipart": true,
"path": "/resumable/upload/things/{id}"
}
}
}
}
}
}
}
}
@@ -1,347 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/apis/generator'
require 'tmpdir'
require 'fileutils'
# TODO - Naked arrays in method requests/responses
RSpec.describe Google::Apis::Generator do
include TestHelpers
context 'with test API' do
before(:context) do
generator = Google::Apis::Generator.new(api_names: File.join(FIXTURES_DIR, 'files', 'api_names.yaml'))
discovery = File.read(File.join(FIXTURES_DIR, 'files', 'test_api.json'))
generated_files = generator.render(discovery).files
# puts generator.dump_api_names
tempdir = Dir.mktmpdir
generated_files.each do |key, content|
# puts content
path = File.join(tempdir, key)
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write(content)
end
end
$LOAD_PATH.unshift(File.join(tempdir, "google-apis-test_v1", "lib"))
require 'google/apis/test_v1'
end
let(:service) { Google::Apis::TestV1::TestService.new }
context 'with the generated service' do
it 'should set the base URL' do
expect(service.root_url.to_s).to eql('https://www.googleapis.com/')
end
it 'should set the batch path' do
expect(service.batch_path).to eql('batch/test/v1')
end
it 'should define global methods from discovery' do
expect(service.method(:query)).to_not be_nil
end
it 'should define parameters on methods' do
parameters = service.method(:query).parameters.map { |(_k, v)| v }
expect(parameters).to include(:s, :i, :n, :b, :a, :e, :er, :sr)
end
it 'should modify parameter names that are ruby keywords' do
parameters = service.method(:query).parameters.map { |(_k, v)| v }
expect(parameters).to include(:do_)
end
it 'should define global parameters on methods' do
parameters = service.method(:query).parameters.map { |(_k, v)| v }
expect(parameters).to include(:fields, :quota_user, :user_ip)
end
it 'should include standard options & block' do
parameters = service.method(:query).parameters.map { |(_k, v)| v }
expect(parameters).to include(:options, :block)
end
it 'should define AUTH_TEST scope' do
expect(Google::Apis::TestV1::AUTH_TEST).to eql ('https://www.googleapis.com/auth/test')
end
it 'should define AUTH_TEST_READONLY scope' do
expect(Google::Apis::TestV1::AUTH_TEST_READONLY).to eql ('https://www.googleapis.com/auth/test.readonly')
end
context 'when simplifying class names' do
it 'should simplify the TestAnotherThing name' do
expect { Google::Apis::TestV1::AnotherThing.new }.not_to raise_error
end
it 'should not simplify the TestThing name' do
expect { Google::Apis::TestV1::TestThing.new }.not_to raise_error
end
end
context 'with the Thing resource' do
it 'should define the create method`' do
expect(service.method(:create_thing)).to_not be_nil
end
it 'should define the list method`' do
expect(service.method(:list_things)).to_not be_nil
end
it 'should define the get method`' do
expect(service.method(:get_thing)).to_not be_nil
end
it 'should include the download_dest parameter for get_thing' do
parameters = service.method(:get_thing).parameters.map { |(_k, v)| v }
expect(parameters).to include(:download_dest)
end
it 'should define the update method`' do
expect(service.method(:update_thing)).to_not be_nil
end
it 'should include the upload_source parameter for update_thing' do
parameters = service.method(:update_thing).parameters.map { |(_k, v)| v }
expect(parameters).to include(:upload_source)
end
it 'should define subresource methods' do
expect(service.method(:list_thing_subthings)).to_not be_nil
end
context 'With the from_json method' do
let(:json) do
<<EOF
{
"name" : "A thing",
"properties": {
"prop_a" : "value_a"
},
"photo": {
"filename": "image.jpg"
},
"hat": {
"type": "topHat",
"height": 100
}
}
EOF
end
let(:thing) { Google::Apis::TestV1::Thing.from_json(json) }
it 'should return a thing' do
expect(thing).to be_instance_of(Google::Apis::TestV1::Thing)
end
it 'should parse properties' do
expect(thing.name).to eq 'A thing'
end
it 'should parse subtypes' do
expect(thing.photo.filename).to eq "image.jpg"
end
end
context 'With the to_json method' do
let(:thing) do
Google::Apis::TestV1::Thing.new(
name: "A thing",
properties: {
prop_a: "value_a"
},
photo: {
filename: "image.jpg"
},
hat: {
type: "topHat",
height: 100
}
)
end
end
end
context 'with the get_thing method' do
before(:example) do
json = <<EOF
{
"id" : "123",
"name" : "A thing",
"enabled": true,
"properties": {
"prop_a" : "value_a",
"prop_b" : "value_b"
},
"photo": {
"filename": "image.jpg"
},
"hat": {
"type": "baseballHat",
"color": "red"
}
}
EOF
stub_request(:get, 'https://www.googleapis.com/test/v1/things/123')
.to_return(headers: { 'Content-Type' => 'application/json' }, body: json)
end
let(:thing) { service.get_thing('123') }
it 'should return a Thing' do
expect(thing).to be_instance_of(Google::Apis::TestV1::Thing)
end
it 'should set attributes' do
expect(thing.id).to eql '123'
end
it 'should alias boolean methods on Thing' do
expect(thing.enabled?).to be true
end
it 'should return a Hash for properties' do
expect(thing.properties).to be_instance_of(Hash)
end
it 'should set hash elements' do
expect(thing.properties).to include('prop_a' => 'value_a')
end
it 'should return the correct variant type for hat' do
expect(thing.hat).to be_instance_of(Google::Apis::TestV1::BaseballHat)
end
it 'should return the correct variant properties for hat' do
expect(thing.hat.color).to eql 'red'
end
it 'should return a photo' do
expect(thing.photo).to be_instance_of(Google::Apis::TestV1::Thing::Photo)
end
it 'should return photo properties' do
expect(thing.photo.filename).to eql 'image.jpg'
end
end
context 'with the create_thing method' do
before(:example) do
json = <<EOF
{
"id" : "123",
"name" : "A thing",
"properties": {
"prop_a" : "value_a"
},
"photo": {
"filename": "image.jpg"
},
"hat": {
"type": "topHat",
"height": 100
}
}
EOF
stub_request(:post, 'https://www.googleapis.com/test/v1/things')
.to_return(headers: { 'Content-Type' => 'application/json' }, body: json)
end
let(:thing) do
thing = Google::Apis::TestV1::Thing.new(name: 'A thing', properties: { 'prop_a' => 'value_a' })
thing.photo = Google::Apis::TestV1::Thing::Photo.new(filename: 'image.jpg')
thing.hat = Google::Apis::TestV1::TopHat.new(type: 'topHat', height: 100)
service.create_thing(thing)
end
it 'should serialize the thing' do
expected_body = <<EOF
{
"name" : "A thing",
"properties": {
"prop_a" : "value_a"
},
"photo": {
"filename": "image.jpg"
},
"hat": {
"type": "topHat",
"height": 100
}
}
EOF
expect(thing).to be_instance_of(Google::Apis::TestV1::Thing)
expect(a_request(:post, 'https://www.googleapis.com/test/v1/things')
.with { |req| expect(req.body).to be_json_eql(expected_body) }).to have_been_made
end
it 'should an updated id' do
expect(thing.id).to eql '123'
end
end
context 'with the query method' do
before(:example) do
body = %({"rows": [{"value": "hello"}, {"value": "world"}]})
stub_request(:get, 'https://www.googleapis.com/test/v1/query')
.to_return(headers: { 'Content-Type' => 'application/json' }, body: body)
end
it 'should return query results' do
results = service.query
expect(results).to be_instance_of(Google::Apis::TestV1::QueryResults)
end
it 'should return an array for items' do
results = service.query
expect(results.rows).to be_instance_of(Array)
end
it 'should return items of type Row' do
results = service.query
expect(results.rows.first).to be_instance_of(Google::Apis::TestV1::Row)
end
it 'should return values for rows' do
results = service.query
expect(results.rows[1].value).to eql('world')
end
end
end
end
context 'with minimal API description' do
before do
generated_files = Google::Apis::Generator.new.render(
'{ "name": "minimal_api", "id": "minimal_api", "version": "v1" }'
).files
namespace.send(:binding).eval(
generated_files.fetch('google-apis-minimal_api_v1/lib/google/apis/minimal_api_v1/service.rb')
)
end
let(:namespace) { Module.new }
it 'should define service class' do
expect(namespace).to be_const_defined('Google::Apis::MinimalApiV1::MinimalApiService')
end
end
end