pax_global_header00006660000000000000000000000064145442261750014524gustar00rootroot0000000000000052 comment=ec01f60bb739b646a7f53a3c796e1b68555c093b ruby-google-cloud-core-1.6.1/000077500000000000000000000000001454422617500160165ustar00rootroot00000000000000ruby-google-cloud-core-1.6.1/.yardopts000066400000000000000000000002551454422617500176660ustar00rootroot00000000000000--no-private --title=Google Cloud Core --markup markdown --markup-provider redcarpet ./lib/**/*.rb - README.md AUTHENTICATION.md CONTRIBUTING.md CODE_OF_CONDUCT.md LICENSE ruby-google-cloud-core-1.6.1/AUTHENTICATION.md000066400000000000000000000040321454422617500204560ustar00rootroot00000000000000## With `google-cloud-ruby` With `google-cloud-ruby` it's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. ### Google Cloud Platform environments While running on Google Cloud Platform (GCP), including Google Compute Engine (GCE), Google Kubernetes Engine (GKE), Google App Engine (GAE), Google Cloud Functions (GCF) and Cloud Run, no extra work is needed. The **Project ID** and **Credentials** and are discovered automatically. Code should be written as if already authenticated. ### Project and Credential Lookup The google-cloud library aims to make authentication as simple as possible, and provides several mechanisms to configure your system without providing **Project ID** and **Service Account Credentials** directly in code. **Project ID** is discovered in the following order: 1. Specify project ID in code 2. Discover project ID in environment variables 3. Discover GCE project ID **Credentials** are discovered in the following order: 1. Specify credentials in code 2. Discover credentials path in environment variables 3. Discover credentials JSON in environment variables 4. Discover credentials file in the Cloud SDK's path 5. Discover GCE credentials ### Environment Variables The **Project ID** and **Credentials JSON** can be placed in environment variables instead of declaring them directly in code. Each service has its own environment variable, allowing for different service accounts to be used for different services. The path to the **Credentials JSON** file can be stored in the environment variable, or the **Credentials JSON** itself can be stored for environments such as Docker containers where writing files is difficult or not encouraged. Here are the environment variables (in the order they are checked) for project ID: 1. `GOOGLE_CLOUD_PROJECT` Here are the environment variables (in the order they are checked) for credentials: 1. `GOOGLE_CLOUD_KEYFILE` - Path to JSON file 2. `GOOGLE_CLOUD_KEYFILE_JSON` - JSON contents ruby-google-cloud-core-1.6.1/CODE_OF_CONDUCT.md000066400000000000000000000036771454422617500206320ustar00rootroot00000000000000# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) ruby-google-cloud-core-1.6.1/CONTRIBUTING.md000066400000000000000000000104331454422617500202500ustar00rootroot00000000000000# Contributing to Google Cloud 1. **Sign one of the contributor license agreements below.** 2. Fork the repo, develop and test your code changes. 3. Send a pull request. ## Contributor License Agreements Before we can accept your pull requests you'll need to sign a Contributor License Agreement (CLA): - **If you are an individual writing original source code** and **you own the intellectual property**, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). - **If you work for a company that wants to allow you to contribute your work**, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). You can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests. ## Setup In order to use the google-cloud console and run the project's tests, there is a small amount of setup: 1. Install Ruby. google-cloud requires Ruby 2.5+. You may choose to manage your Ruby and gem installations with [RVM](https://rvm.io/), [rbenv](https://github.com/rbenv/rbenv), or [chruby](https://github.com/postmodern/chruby). 2. Install [Bundler](http://bundler.io/). ```sh $ gem install bundler ``` 3. Install the top-level project dependencies. ```sh $ bundle install ``` 4. Install the Google Cloud dependencies. ```sh $ cd google-cloud-core/ $ bundle install ``` ## Console In order to run code interactively, you can automatically load google-cloud and its dependencies in IRB. This requires that your developer environment has already been configured by following the steps described in the {file:AUTHENTICATION.md Authentication Guide}. An IRB console can be created with: ```sh $ cd google-cloud-core/ $ bundle exec rake console ``` ## Google Cloud Tests Tests are very important part of google-cloud. All contributions should include tests that ensure the contributed code behaves as expected. To run the unit tests, documentation tests, and code style checks together for a package: ``` sh $ cd google-cloud-core/ $ bundle exec rake ci ``` To run the command above, plus all acceptance tests, use `rake ci:acceptance` or its handy alias, `rake ci:a`. ### Google Cloud Unit Tests The project uses the [minitest](https://github.com/seattlerb/minitest) library, including [specs](https://github.com/seattlerb/minitest#specs), [mocks](https://github.com/seattlerb/minitest#mocks) and [minitest-autotest](https://github.com/seattlerb/minitest-autotest). To run the Google Cloud unit tests: ``` sh $ cd google-cloud-core/ $ bundle exec rake test ``` ### Google Cloud Documentation Tests The project tests the code examples in the gem's [YARD](https://github.com/lsegal/yard)-based documentation. The example testing functions in a way that is very similar to unit testing, and in fact the library providing it, [yard-doctest](https://github.com/p0deje/yard-doctest), is based on the project's unit test library, [minitest](https://github.com/seattlerb/minitest). To run the Google Cloud documentation tests: ``` sh $ cd google-cloud-core/ $ bundle exec rake doctest ``` If you add, remove or modify documentation examples when working on a pull request, you may need to update the setup for the tests. The stubs and mocks required to run the tests are located in `support/doctest_helper.rb`. Please note that much of the setup is matched by the title of the [`@example`](http://www.rubydoc.info/gems/yard/file/docs/Tags.md#example) tag. If you alter an example's title, you may encounter breaking tests. ## Coding Style Please follow the established coding style in the library. The style is is largely based on [The Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) with a few exceptions based on seattle-style: * Avoid parenthesis when possible, including in method definitions. * Always use double quotes strings. ([Option B](https://github.com/bbatsov/ruby-style-guide#strings)) You can check your code against these rules by running Rubocop like so: ```sh $ cd google-cloud-core/ $ bundle exec rake rubocop ``` ## Code of Conduct Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See {file:CODE_OF_CONDUCT.md Code of Conduct} for more information. ruby-google-cloud-core-1.6.1/LICENSE000066400000000000000000000261371454422617500170340ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 https://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 https://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. ruby-google-cloud-core-1.6.1/README.md000066400000000000000000000040011454422617500172700ustar00rootroot00000000000000# google-cloud-core This library contains shared types, such as error classes, for the google-cloud project. Please see the [GitHub repository](https://github.com/googleapis/google-cloud-ruby) for more information about the individual google-cloud gems. - [google-cloud-core API documentation](https://googleapis.dev/ruby/google-cloud-core/latest) ## 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. ## Versioning This library follows [Semantic Versioning](http://semver.org/). It is currently in major version zero (0.y.z), which means that anything may change at any time and the public API should not be considered stable. ## Contributing Contributions to this library are always welcome and highly encouraged. See the [Contributing Guide](https://googleapis.dev/ruby/google-cloud-core/latest/file.CONTRIBUTING.html) for more information on how to get started. Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See [Code of Conduct](https://googleapis.dev/ruby/google-cloud-core/latest/file.CODE_OF_CONDUCT.html) for more information. ## License This library is licensed under Apache 2.0. Full license text is available in [LICENSE](https://googleapis.dev/ruby/google-cloud-core/latest/file.LICENSE.html). ## Support Please [report bugs at the project on Github](https://github.com/googleapis/google-cloud-ruby/issues). Don't hesitate to [ask questions](http://stackoverflow.com/questions/tagged/google-cloud-platform+ruby) about the client or APIs on [StackOverflow](http://stackoverflow.com). ruby-google-cloud-core-1.6.1/google-cloud-core.gemspec000066400000000000000000000057731454422617500227050ustar00rootroot00000000000000######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: google-cloud-core 1.6.1 ruby lib Gem::Specification.new do |s| s.name = "google-cloud-core".freeze s.version = "1.6.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Mike Moore".freeze, "Chris Smith".freeze] s.date = "2023-12-05" s.description = "google-cloud-core is the internal shared library for google-cloud-ruby.".freeze s.email = ["mike@blowmage.com".freeze, "quartzmo@gmail.com".freeze] s.files = [".yardopts".freeze, "AUTHENTICATION.md".freeze, "CODE_OF_CONDUCT.md".freeze, "CONTRIBUTING.md".freeze, "LICENSE".freeze, "README.md".freeze, "lib/google/cloud.rb".freeze, "lib/google/cloud/config.rb".freeze, "lib/google/cloud/core/version.rb".freeze, "lib/google/cloud/credentials.rb".freeze] s.homepage = "https://github.com/googleapis/google-cloud-ruby/tree/master/google-cloud-core".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.5".freeze) s.rubygems_version = "3.3.15".freeze s.summary = "Internal shared library for google-cloud-ruby".freeze if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_runtime_dependency(%q.freeze, [">= 1.0", "< 3.a"]) s.add_runtime_dependency(%q.freeze, ["~> 1.0"]) s.add_development_dependency(%q.freeze, ["~> 1.25.1"]) s.add_development_dependency(%q.freeze, ["~> 5.14"]) s.add_development_dependency(%q.freeze, ["~> 1.0"]) s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_development_dependency(%q.freeze, ["~> 5.2"]) s.add_development_dependency(%q.freeze, ["~> 3.0"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.1.13"]) else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, [">= 1.0", "< 3.a"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 1.25.1"]) s.add_dependency(%q.freeze, ["~> 5.14"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 5.2"]) s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.1.13"]) end end ruby-google-cloud-core-1.6.1/lib/000077500000000000000000000000001454422617500165645ustar00rootroot00000000000000ruby-google-cloud-core-1.6.1/lib/google/000077500000000000000000000000001454422617500200405ustar00rootroot00000000000000ruby-google-cloud-core-1.6.1/lib/google/cloud.rb000066400000000000000000000135601454422617500215000ustar00rootroot00000000000000# Copyright 2015 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 # # https://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/cloud/config" require "google/cloud/core/version" ## # # Google Cloud # # The google-cloud library is the official library for interacting with Google # Cloud Platform. Google Cloud Platform is a set of modular cloud-based services # that allow you to create anything from simple websites to complex # applications. # # The goal of google-cloud is to provide an API that is comfortable to # Rubyists. Your authentication credentials are detected automatically in # Google Cloud Platform environments such as Google Compute Engine, Google # App Engine and Google Kubernetes Engine. In other environments you can # configure authentication easily, either directly in your code or via # environment variables. Read more about the options for connecting in the # {file:AUTHENTICATION.md Authentication Guide}. # module Google module Cloud ## # Creates a new object for connecting to Google Cloud. # # For more information on connecting to Google Cloud see the # {file:AUTHENTICATION.md Authentication Guide}. # # @param [String] project_id Project identifier for the service you are # connecting to. # @param [String, Hash, Google::Auth::Credentials] credentials The path to # the keyfile as a String, the contents of the keyfile as a Hash, or a # Google::Auth::Credentials object. # @param [Integer] retries Number of times to retry requests on server # error. The default value is `3`. Optional. # @param [Integer] timeout Default timeout to use in requests. Optional. # # @return [Google::Cloud] # # @example # require "google/cloud" # # gcloud = Google::Cloud.new # datastore = gcloud.datastore # pubsub = gcloud.pubsub # storage = gcloud.storage # def self.new project_id = nil, credentials = nil, retries: nil, timeout: nil gcloud = Object.new gcloud.instance_variable_set :@project, project_id gcloud.instance_variable_set :@keyfile, credentials gcloud.instance_variable_set :@retries, retries gcloud.instance_variable_set :@timeout, timeout gcloud.extend Google::Cloud gcloud end ## # Configure the default parameter for Google::Cloud. The values defined on # this top level will be shared across all Google::Cloud libraries, which # may also add fields to this object or add sub configuration options under # this object. # # Possible configuration parameters: # # * `project_id`: The Google Cloud Project ID. Automatically discovered # when running from GCP environments. # * `credentials`: The service account JSON file path. Automatically # discovered when running from GCP environments. # * `on_error`: A Proc to be run when an error is encountered during on a # background thread. The Proc must take the error object as # the single argument. # # @return [Google::Cloud::Config] The top-level configuration object for # Google::Cloud libraries. # def self.configure @config ||= Config.create yield @config if block_given? @config end ## # Initialize toplevel configuration # @private # def self.init_configuration configure do |config| default_project = Google::Cloud::Config.deferred do ENV["GOOGLE_CLOUD_PROJECT"] || ENV["GCLOUD_PROJECT"] end default_creds = Google::Cloud::Config.deferred do Google::Cloud::Config.credentials_from_env \ "GOOGLE_CLOUD_CREDENTIALS", "GOOGLE_CLOUD_CREDENTIALS_JSON", "GOOGLE_CLOUD_KEYFILE", "GOOGLE_CLOUD_KEYFILE_JSON", "GCLOUD_KEYFILE", "GCLOUD_KEYFILE_JSON" end config.add_field! :project_id, default_project, match: String, allow_nil: true config.add_alias! :project, :project_id config.add_field! :credentials, default_creds, match: Object config.add_alias! :keyfile, :credentials config.add_field! :on_error, nil, match: Proc end end ## # Safely load all google-cloud-* gems. # @private # def self.auto_load_gems currently_loaded_files = loaded_files auto_load_files.each do |auto_load_file| auto_load_file = File.realpath auto_load_file next if currently_loaded_files.include? auto_load_file require auto_load_file end end ## # Find files that are currently loaded. # @private # def self.loaded_files files = Array(caller).map do |backtrace_line| until backtrace_line.split(":").size < 2 || File.file?(backtrace_line) backtrace_line = backtrace_line.split(":")[0..-2].join ":" end backtrace_line end files.uniq! files.select! { |file| File.file? file } files.map { |file| File.realpath file } end ## # Find all google-cloud-* files for available gems. # @private # def self.auto_load_files return Gem.find_latest_files "google-cloud-*.rb" if Gem.respond_to? :find_latest_files # Ruby 2.0 does not have Gem.find_latest_files Gem.find_files "google-cloud-*.rb" end end end # Set the default top-level configuration Google::Cloud.init_configuration # Auto-load all Google Cloud service gems. Google::Cloud.auto_load_gems ruby-google-cloud-core-1.6.1/lib/google/cloud/000077500000000000000000000000001454422617500211465ustar00rootroot00000000000000ruby-google-cloud-core-1.6.1/lib/google/cloud/config.rb000066400000000000000000000473341454422617500227530ustar00rootroot00000000000000# Copyright 2018 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 # # https://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 Cloud ## # Configuration mechanism for Google Cloud libraries. A Config object # contains a list of predefined keys, some of which are values and others # of which are subconfigurations, i.e. categories. Field access is # generally validated to ensure that the field is defined, and when a # a value is set, it is validated for the correct type. Warnings are # printed when a validation fails. # # You generally access fields and subconfigs by calling accessor methods. # Methods meant for "administration" such as adding options, are named # with a trailing "!" or "?" so they don't pollute the method namespace. # It is also possible to access a field using the `[]` operator. # # Note that config objects inherit from `BasicObject`. This means it does # not define many methods you might expect to find in most Ruby objects. # For example, `to_s`, `inspect`, `is_a?`, `instance_variable_get`, and so # forth. # # @example # require "google/cloud/config" # # config = Google::Cloud::Config.create do |c| # c.add_field! :opt1, 10 # c.add_field! :opt2, :one, enum: [:one, :two, :three] # c.add_field! :opt3, "hi", match: [String, Symbol] # c.add_field! :opt4, "hi", match: /^[a-z]+$/, allow_nil: true # c.add_config! :sub do |c2| # c2.add_field! :opt5, false # end # end # # config.opt1 #=> 10 # config.opt1 = 20 #=> 20 # config.opt1 #=> 20 # config.opt1 = "hi" #=> "hi" (but prints a warning) # config.opt1 = nil #=> nil (but prints a warning) # # config.opt2 #=> :one # config.opt2 = :two #=> :two # config.opt2 #=> :two # config.opt2 = :four #=> :four (but prints a warning) # # config.opt3 #=> "hi" # config.opt3 = "hiho" #=> "hiho" # config.opt3 #=> "hiho" # config.opt3 = "HI" #=> "HI" (but prints a warning) # # config.opt4 #=> "yo" # config.opt4 = :yo #=> :yo (Strings and Symbols allowed) # config.opt4 #=> :yo # config.opt4 = 3.14 #=> 3.14 (but prints a warning) # config.opt4 = nil #=> nil (no warning: nil allowed) # # config.sub #=> # # config.sub.opt5 #=> false # config.sub.opt5 = true #=> true (true and false allowed) # config.sub.opt5 #=> true # config.sub.opt5 = nil #=> nil (but prints a warning) # # config.opt9 = "hi" #=> "hi" (warning about unknown key) # config.opt9 #=> "hi" (no warning: key now known) # config.sub.opt9 #=> nil (warning about unknown key) # class Config < BasicObject ## # Constructs a Config object. If a block is given, yields `self` to the # block, which makes it convenient to initialize the structure by making # calls to `add_field!` and `add_config!`. # # @param [boolean] show_warnings Whether to print warnings when a # validation fails. Defaults to `true`. # @return [Config] The constructed Config object. # def self.create show_warnings: true config = new [], show_warnings: show_warnings yield config if block_given? config end ## # Determines if the given object is a config. Useful because Config # does not define the `is_a?` method. # # @return [boolean] # def self.config? obj Config.send :===, obj end ## # Internal constructor. Generally you should not call `new` directly, # but instead use the `Config.create` method. The initializer is used # directly by a few older clients that expect a legacy interface. # # @private # def initialize legacy_categories = {}, opts = {} @show_warnings = opts.fetch :show_warnings, false @values = {} @defaults = {} @validators = {} add_options legacy_categories end ## # Legacy method of adding subconfigs. This is used by older versions of # the stackdriver client libraries but should not be used in new code. # # @deprecated # @private # def add_options legacy_categories [legacy_categories].flatten(1).each do |sub_key| case sub_key when ::Symbol add_config! sub_key, Config.new when ::Hash sub_key.each do |k, v| add_config! k, Config.new(v) end else raise ArgumentError "Category must be a Symbol or Hash" end end end ## # Add a value field to this configuration. # # You must provide a key, which becomes the field name in this config. # Field names may comprise only letters, numerals, and underscores, and # must begin with a letter. This will create accessor methods for the # new configuration key. # # You may pass an initial value (which defaults to nil if not provided). # # You may also specify how values are validated. Validation is defined # as follows: # # * If you provide a block or a `:validator` option, it is used as the # validator. A proposed value is passed to the proc, which should # return `true` or `false` to indicate whether the value is valid. # * If you provide a `:match` option, it is compared to the proposed # value using the `===` operator. You may, for example, provide a # class, a regular expression, or a range. If you pass an array, # the value is accepted if _any_ of the elements match. # * If you provide an `:enum` option, it should be an `Enumerable`. # A proposed value is valid if it is included. # * Otherwise if you do not provide any of the above options, then a # default validation strategy is inferred from the initial value: # * If the initial is `true` or `false`, then either boolean value # is considered valid. This is the same as `enum: [true, false]`. # * If the initial is `nil`, then any object is considered valid. # * Otherwise, any object of the same class as the initial value is # considered valid. This is effectively the same as # `match: initial.class`. # * You may also provide the `:allow_nil` option, which, if set to # true, alters any of the above validators to allow `nil` values. # # In many cases, you may find that the default validation behavior # (interpreted from the initial value) is sufficient. If you want to # accept any value, use `match: Object`. # # @param [String, Symbol] key The name of the option # @param [Object] initial Initial value (defaults to nil) # @param [Hash] opts Validation options # # @return [Config] self for chaining # def add_field! key, initial = nil, opts = {}, &block key = validate_new_key! key opts[:validator] = block if block validator = resolve_validator! initial, opts validate_value! key, validator, initial @values[key] = initial @defaults[key] = initial @validators[key] = validator self end ## # Add a subconfiguration field to this configuration. # # You must provide a key, which becomes the method name that you use to # navigate to the subconfig. Names may comprise only letters, numerals, # and underscores, and must begin with a letter. # # If you provide a block, the subconfig object is passed to the block, # so you can easily add fields to the subconfig. # # You may also pass in a config object that already exists. This will # "attach" that configuration in this location. # # @param [String, Symbol] key The name of the subconfig # @param [Config] config A config object to attach here. If not provided, # creates a new config. # # @return [Config] self for chaining # def add_config! key, config = nil, &block key = validate_new_key! key if config.nil? config = Config.create(&block) elsif block yield config end @values[key] = config @defaults[key] = config @validators[key] = SUBCONFIG self end ## # Cause a key to be an alias of another key. The two keys will refer to # the same field. # def add_alias! key, to_key key = validate_new_key! key @values.delete key @defaults.delete key @validators[key] = to_key.to_sym self end ## # Restore the original default value of the given key. # If the key is omitted, restore the original defaults for all keys, # and all keys of subconfigs, recursively. # # @param [Symbol, nil] key The key to reset. If omitted or `nil`, # recursively reset all fields and subconfigs. # def reset! key = nil if key.nil? @values.each_key { |k| reset! k } else key = key.to_sym if @defaults.key? key @values[key] = @defaults[key] @values[key].reset! if @validators[key] == SUBCONFIG elsif @values.key? key warn! "Key #{key.inspect} has not been added, but has a value." \ " Removing the value." @values.delete key else warn! "Key #{key.inspect} does not exist. Nothing to reset." end end self end ## # Remove the given key from the configuration, deleting any validation # and value. If the key is omitted, delete all keys. If the key is an # alias, deletes the alias but leaves the original. # # @param [Symbol, nil] key The key to delete. If omitted or `nil`, # delete all fields and subconfigs. # def delete! key = nil if key.nil? @values.clear @defaults.clear @validators.clear else @values.delete key @defaults.delete key @validators.delete key end self end ## # Assign an option with the given name to the given value. # # @param [Symbol, String] key The option name # @param [Object] value The new option value # def []= key, value key = resolve_key! key validate_value! key, @validators[key], value @values[key] = value end ## # Get the option or subconfig with the given name. # # @param [Symbol, String] key The option or subconfig name # @return [Object] The option value or subconfig object # def [] key key = resolve_key! key warn! "Key #{key.inspect} does not exist. Returning nil." unless @validators.key? key value = @values[key] value = value.call if Config::DeferredValue === value value end ## # Check if the given key has been set in this object. Returns true if the # key has been added as a normal field, subconfig, or alias, or if it has # not been added explicitly but still has a value. # # @param [Symbol] key The key to check for. # @return [boolean] # def value_set? key @values.key? resolve_key! key end alias option? value_set? ## # Check if the given key has been explicitly added as a field name. # # @param [Symbol] key The key to check for. # @return [boolean] # def field? key @validators[key.to_sym].is_a? ::Proc end alias respond_to? field? ## # Check if the given key has been explicitly added as a subconfig name. # # @param [Symbol] key The key to check for. # @return [boolean] # def subconfig? key @validators[key.to_sym] == SUBCONFIG end ## # Check if the given key has been explicitly added as an alias. # If so, return the target, otherwise return nil. # # @param [Symbol] key The key to check for. # @return [Symbol,nil] The alias target, or nil if not an alias. # def alias? key target = @validators[key.to_sym] target.is_a?(::Symbol) ? target : nil end ## # Return a list of explicitly added field names. # # @return [Array] a list of field names as symbols. # def fields! @validators.keys.find_all { |key| @validators[key].is_a? ::Proc } end ## # Return a list of explicitly added subconfig names. # # @return [Array] a list of subconfig names as symbols. # def subconfigs! @validators.keys.find_all { |key| @validators[key] == SUBCONFIG } end ## # Return a list of alias names. # # @return [Array] a list of alias names as symbols. # def aliases! @validators.keys.find_all { |key| @validators[key].is_a? ::Symbol } end ## # Returns a string representation of this configuration state, including # subconfigs. Only explicitly added fields and subconfigs are included. # # @return [String] # def to_s! elems = @validators.keys.map do |k| v = @values[k] vstr = Config.config?(v) ? v.to_s! : v.inspect " #{k}=#{vstr}" end "" end alias inspect to_s! ## # Returns a nested hash representation of this configuration state, # including subconfigs. Only explicitly added fields and subconfigs are # included. # # @return [Hash] # def to_h! h = {} @validators.each_key do |k| v = @values[k] h[k] = Config.config?(v) ? v.to_h! : v.inspect end h end ## # Search the given environment variable names for valid credential data # that can be passed to `Google::Auth::Credentials.new`. # If a variable contains a valid file path, returns that path as a string. # If a variable contains valid JSON, returns the parsed JSON as a hash. # If no variables contain valid data, returns nil. # @private # def self.credentials_from_env *vars vars.each do |var| data = ::ENV[var] next unless data str = data.strip return str if ::File.file? str json = begin ::JSON.parse str rescue ::StandardError nil end return json if json.is_a? ::Hash end nil end ## # @private # Create a configuration value that will be invoked when retrieved. # def self.deferred &block DeferredValue.new(&block) end ## # @private # Dynamic methods accessed as keys. # def method_missing name, *args name_str = name.to_s super unless name_str =~ /^[a-zA-Z]\w*=?$/ if name_str.end_with? "=" self[name_str[0...-1]] = args.first else self[name] end end ## # @private # Dynamic methods accessed as keys. # def respond_to_missing? name, include_private return true if value_set? name.to_s.chomp("=") super end ## # @private # Implement standard nil check # # @return [false] # def nil? false end private ## # @private A validator that allows all values # OPEN_VALIDATOR = proc { true } ## # @private a list of key names that are technically illegal because # they clash with method names. # ILLEGAL_KEYS = [:add_options, :initialize, :inspect, :instance_eval, :instance_exec, :method_missing, :send, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined].freeze ## # @private sentinel indicating a subconfig in the validators hash # SUBCONFIG = ::Object.new def resolve_key! key key = key.to_sym alias_target = @validators[key] alias_target.is_a?(::Symbol) ? alias_target : key end def validate_new_key! key key_str = key.to_s key = key.to_sym if key_str !~ /^[a-zA-Z]\w*$/ || ILLEGAL_KEYS.include?(key) warn! "Illegal key name: #{key_str.inspect}. Method dispatch will" \ " not work for this key." end warn! "Key #{key.inspect} already exists. It will be replaced." if @validators.key? key key end def resolve_validator! initial, opts allow_nil = initial.nil? || opts[:allow_nil] if opts.key? :validator build_proc_validator! opts[:validator], allow_nil elsif opts.key? :match build_match_validator! opts[:match], allow_nil elsif opts.key? :enum build_enum_validator! opts[:enum], allow_nil elsif [true, false].include? initial build_enum_validator! [true, false], allow_nil elsif initial.nil? OPEN_VALIDATOR else klass = Config.config?(initial) ? Config : initial.class build_match_validator! klass, allow_nil end end def build_match_validator! matches, allow_nil matches = ::Kernel.Array(matches) matches += [nil] if allow_nil && !matches.include?(nil) ->(val) { matches.any? { |m| m.send :===, val } } end def build_enum_validator! allowed, allow_nil allowed = ::Kernel.Array(allowed) allowed += [nil] if allow_nil && !allowed.include?(nil) ->(val) { allowed.include? val } end def build_proc_validator! proc, allow_nil ->(val) { proc.call(val) || (allow_nil && val.nil?) } end def validate_value! key, validator, value value = value.call if Config::DeferredValue === value case validator when ::Proc unless validator.call value warn! "Invalid value #{value.inspect} for key #{key.inspect}." \ " Setting anyway." end when Config if value != validator warn! "Key #{key.inspect} refers to a subconfig and shouldn't" \ " be changed. Setting anyway." end else warn! "Key #{key.inspect} has not been added. Setting anyway." end end def warn! msg return unless @show_warnings location = ::Kernel.caller_locations.find do |s| !s.to_s.include? "/google/cloud/config.rb:" end ::Kernel.warn "#{msg} at #{location}" end ## # @private # class DeferredValue def initialize &block @callback = block end def call @callback.call end end end end end ruby-google-cloud-core-1.6.1/lib/google/cloud/core/000077500000000000000000000000001454422617500220765ustar00rootroot00000000000000ruby-google-cloud-core-1.6.1/lib/google/cloud/core/version.rb000066400000000000000000000012371454422617500241130ustar00rootroot00000000000000# Copyright 2016 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 # # https://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 Cloud module Core VERSION = "1.6.1".freeze end end end ruby-google-cloud-core-1.6.1/lib/google/cloud/credentials.rb000066400000000000000000000112071454422617500237710ustar00rootroot00000000000000# Copyright 2014 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 # # https://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. # This file is now considered DEPRECATED. # Libraries that depend on google-cloud-core ~> 1.1 should not use this file. # Keep the implementation in place to remain compatible with so older gems. require "json" require "signet/oauth_2/client" require "forwardable" require "googleauth" module Google module Cloud ## # @private # Represents the OAuth 2.0 signing logic. # This class is intended to be inherited by API-specific classes # which overrides the SCOPE constant. class Credentials TOKEN_CREDENTIAL_URI = "https://oauth2.googleapis.com/token".freeze AUDIENCE = "https://oauth2.googleapis.com/token".freeze SCOPE = [].freeze PATH_ENV_VARS = ["GOOGLE_CLOUD_KEYFILE", "GCLOUD_KEYFILE"].freeze JSON_ENV_VARS = ["GOOGLE_CLOUD_KEYFILE_JSON", "GCLOUD_KEYFILE_JSON"].freeze DEFAULT_PATHS = ["~/.config/gcloud/application_default_credentials.json"].freeze attr_accessor :client ## # Delegate client methods to the client object. extend Forwardable def_delegators :@client, :token_credential_uri, :audience, :scope, :issuer, :signing_key def initialize keyfile, scope: nil verify_keyfile_provided! keyfile case keyfile when Signet::OAuth2::Client @client = keyfile when Hash hash = stringify_hash_keys keyfile hash["scope"] ||= scope @client = init_client hash else verify_keyfile_exists! keyfile json = JSON.parse ::File.read(keyfile) json["scope"] ||= scope @client = init_client json end @client.fetch_access_token! end ## # Returns the default credentials. # def self.default scope: nil env = ->(v) { ENV[v] } json = ->(v) { JSON.parse ENV[v] rescue nil unless ENV[v].nil? } path = ->(p) { ::File.file? p } # First try to find keyfile file from environment variables. self::PATH_ENV_VARS.map(&env).compact.select(&path).each do |file| return new file, scope: scope end # Second try to find keyfile json from environment variables. self::JSON_ENV_VARS.map(&json).compact.each do |hash| return new hash, scope: scope end # Third try to find keyfile file from known file paths. self::DEFAULT_PATHS.select(&path).each do |file| return new file, scope: scope end # Finally get instantiated client from Google::Auth. scope ||= self::SCOPE client = Google::Auth.get_application_default scope new client end protected ## # Verify that the keyfile argument is provided. def verify_keyfile_provided! keyfile raise "You must provide a keyfile to connect with." if keyfile.nil? end ## # Verify that the keyfile argument is a file. def verify_keyfile_exists! keyfile exists = ::File.file? keyfile raise "The keyfile '#{keyfile}' is not a valid file." unless exists end ## # Initializes the Signet client. def init_client keyfile client_opts = client_options keyfile Signet::OAuth2::Client.new client_opts end ## # returns a new Hash with string keys instead of symbol keys. def stringify_hash_keys hash hash.transform_keys(&:to_s) end def client_options options # Keyfile options have higher priority over constructor defaults options["token_credential_uri"] ||= self.class::TOKEN_CREDENTIAL_URI options["audience"] ||= self.class::AUDIENCE options["scope"] ||= self.class::SCOPE # client options for initializing signet client { token_credential_uri: options["token_credential_uri"], audience: options["audience"], scope: Array(options["scope"]), issuer: options["client_email"], signing_key: OpenSSL::PKey::RSA.new(options["private_key"]) } end end end end