chore: Generator creates separate libraries (#2136)

This commit is contained in:
Daniel Azuma authored and GitHub committed 2020-12-31 14:55:59 -08:00
1 parent a6a5b6071e
commit 6b972afb60
29 files changed
+2124 -35

No files matched your search

+26 -5
View File
@@ -28,7 +28,8 @@ module Google
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
verbose: :boolean, names: :string, names_out: :string, api: :string,
clean: :boolean, spot_check: :boolean
def gen(dir)
ensure_active_support
require 'google/apis/generator'
@@ -129,6 +130,7 @@ module Google
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")
@@ -143,10 +145,19 @@ module Google
end
def generate_api(json)
files = generator.render(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
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
end
def discovery
@@ -171,6 +182,13 @@ module Google
@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
@@ -181,11 +199,14 @@ module Google
require 'active_support/inflector'
require 'active_support/core_ext'
rescue LoadError => e
error 'ActiveSupport is required, please run:'
error 'gem install activesupport'
exit 1
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
+39 -14
View File
@@ -16,6 +16,7 @@ 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'
@@ -26,14 +27,13 @@ module Google
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'))
@module_template = Template.load('module.rb')
@service_template = Template.load('service.rb')
@classes_template = Template.load('classes.rb')
@representations_template = Template.load('representations.rb')
@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
@@ -45,16 +45,41 @@ module Google
def render(json)
api = parse_description(json)
Annotator.process(api, @names)
base_path = ActiveSupport::Inflector.underscore(api.qualified_name)
context = {
'api' => api
"api" => api,
"generator_version" => Google::Apis::Generator::VERSION
}
files = {}
files[base_path + '.rb'] = @module_template.render(context)
files[File.join(base_path, 'service.rb')] = @service_template.render(context)
files[File.join(base_path, 'classes.rb')] = @classes_template.render(context)
files[File.join(base_path, 'representations.rb')] = @representations_template.render(context)
files
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
@@ -142,6 +142,14 @@ module Google
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))
@@ -1,4 +1,4 @@
# Copyright 2015 Google Inc.
# 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.
@@ -0,0 +1,2 @@
--color
--format documentation
@@ -0,0 +1,13 @@
--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
@@ -0,0 +1,15 @@
# 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 %>"
@@ -0,0 +1,46 @@
source 'https://rubygems.org'
gemspec
gem "google-apis-core", path: "../../google-apis-core"
group :development do
gem 'bundler', '>= 1.7'
gem 'rake', '~> 11.2'
gem 'rspec', '~> 3.1'
gem 'json_spec', '~> 1.1'
gem 'webmock', '~> 2.1'
gem 'simplecov', '~> 0.12'
gem 'coveralls', '~> 0.8'
gem 'rubocop', '~> 0.49.0'
gem 'launchy', '~> 2.4'
gem 'dotenv', '~> 2.0'
gem 'fakefs', '~> 0.6', require: "fakefs/safe"
gem 'google-id-token', '~> 1.3'
gem 'os', '~> 0.9'
gem 'rmail', '~> 1.1'
gem 'redis', '~> 3.2'
gem 'logging', '~> 2.2'
gem 'opencensus', '~> 0.4'
gem 'httparty'
end
platforms :jruby do
group :development do
gem 'jruby-openssl'
end
end
platforms :ruby do
group :development do
gem 'yard', '~> 0.9', '>= 0.9.11'
gem 'redcarpet', '~> 3.2'
gem 'github-markup', '~> 1.3'
gem 'pry-doc', '~> 0.8'
gem 'pry-byebug', '~> 3.2'
end
end
if ENV['RAILS_VERSION']
gem 'rails', ENV['RAILS_VERSION']
end
@@ -0,0 +1,32 @@
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.0"
end
@@ -0,0 +1,27 @@
# 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
@@ -0,0 +1,2 @@
# Release history for <%= api.gem_name %>
@@ -0,0 +1,28 @@
# 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
@@ -0,0 +1,202 @@
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,4 +1,4 @@
# Copyright 2015 Google Inc.
# 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.
@@ -15,6 +15,7 @@
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
@@ -26,8 +27,9 @@ module Google
# @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 %>'
REVISION = '<%= api.revision %>'
<% if api.auth && api.auth.oauth2 -%>
<% for scope_string, scope in api.auth.oauth2.scopes -%>
@@ -0,0 +1,96 @@
# 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).
@@ -0,0 +1,25 @@
require "bundler/gem_tasks"
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
puts "YARD not available"
end
task :ci => [:spec, :yard, :build]
task :default => :ci
@@ -1,4 +1,4 @@
# Copyright 2015 Google Inc.
# 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.
@@ -1,4 +1,4 @@
# Copyright 2015 Google Inc.
# 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.
@@ -0,0 +1,139 @@
# 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
@@ -0,0 +1,21 @@
# 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
@@ -26,7 +26,7 @@ RSpec.describe Google::Apis::Generator 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)
generated_files = generator.render(discovery).files
# puts generator.dump_api_names
tempdir = Dir.mktmpdir
generated_files.each do |key, content|
@@ -37,7 +37,7 @@ RSpec.describe Google::Apis::Generator do
f.write(content)
end
end
$LOAD_PATH.unshift(tempdir)
$LOAD_PATH.unshift(File.join(tempdir, "google-apis-test_v1", "lib"))
require 'google/apis/test_v1'
end
@@ -331,10 +331,10 @@ EOF
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/service.rb')
generated_files.fetch('google-apis-minimal_api_v1/lib/google/apis/minimal_api_v1/service.rb')
)
end