google-cloud-core-1.2.0/0000755000175000017500000000000013505441366014363 5ustar samyaksamyakgoogle-cloud-core-1.2.0/lib/0000755000175000017500000000000013505441366015131 5ustar samyaksamyakgoogle-cloud-core-1.2.0/lib/google/0000755000175000017500000000000013505441366016405 5ustar samyaksamyakgoogle-cloud-core-1.2.0/lib/google/cloud/0000755000175000017500000000000013505441366017513 5ustar samyaksamyakgoogle-cloud-core-1.2.0/lib/google/cloud/errors.rb0000644000175000017500000002630313505441366021360 0ustar samyaksamyak# 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 "English" module Google module Cloud ## # Base google-cloud exception class. class Error < StandardError ## # Construct a new Google::Cloud::Error object, optionally passing in a # message. def initialize msg = nil super @cause = $ERROR_INFO end # Add Error#cause (introduced in 2.1) to Ruby 2.0. unless respond_to?(:cause) ## # The previous exception at the time this exception was raised. This is # useful for wrapping exceptions and retaining the original exception # information. define_method(:cause) do @cause end end ## # Returns the value of `status_code` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over HTTP/REST. # # @returns [Object, nil] def status_code return nil unless cause && cause.respond_to?(:status_code) cause.status_code end ## # Returns the value of `body` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over HTTP/REST. # # @returns [Object, nil] def body return nil unless cause && cause.respond_to?(:body) cause.body end ## # Returns the value of `header` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over HTTP/REST. # # @returns [Object, nil] def header return nil unless cause && cause.respond_to?(:header) cause.header end ## # Returns the value of `code` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over gRPC. # # @returns [Object, nil] def code return nil unless cause && cause.respond_to?(:code) cause.code end ## # Returns the value of `details` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over gRPC. # # @returns [Object, nil] def details return nil unless cause && cause.respond_to?(:details) cause.details end ## # Returns the value of `metadata` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over gRPC. # # @returns [Object, nil] def metadata return nil unless cause && cause.respond_to?(:metadata) cause.metadata end ## # Returns the value of `status_details` from the underlying cause error # object, if both are present. Otherwise returns `nil`. # # This is typically present on errors originating from calls to an API # over gRPC. # # @returns [Object, nil] def status_details return nil unless cause && cause.respond_to?(:status_details) cause.status_details end # @private Create a new error object from a client error def self.from_error error klass = if error.respond_to? :code grpc_error_class_for error.code elsif error.respond_to? :status_code gapi_error_class_for error.status_code else self end klass.new error.message end # @private Identify the subclass for a gRPC error def self.grpc_error_class_for grpc_error_code # The gRPC status code 0 is for a successful response. # So there is no error subclass for a 0 status code, use current class. [ self, CanceledError, UnknownError, InvalidArgumentError, DeadlineExceededError, NotFoundError, AlreadyExistsError, PermissionDeniedError, ResourceExhaustedError, FailedPreconditionError, AbortedError, OutOfRangeError, UnimplementedError, InternalError, UnavailableError, DataLossError, UnauthenticatedError ][grpc_error_code] || self end # @private Identify the subclass for a Google API Client error def self.gapi_error_class_for http_status_code # The http status codes mapped to their error classes. { 400 => InvalidArgumentError, # FailedPreconditionError/OutOfRangeError 401 => UnauthenticatedError, 403 => PermissionDeniedError, 404 => NotFoundError, 409 => AlreadyExistsError, # AbortedError 412 => FailedPreconditionError, 429 => ResourceExhaustedError, 499 => CanceledError, 500 => InternalError, # UnknownError/DataLossError 501 => UnimplementedError, 503 => UnavailableError, 504 => DeadlineExceededError }[http_status_code] || self end end ## # Canceled indicates the operation was cancelled (typically by the caller). class CanceledError < Error end ## # Unknown error. An example of where this error may be returned is # if a Status value received from another address space belongs to # an error-space that is not known in this address space. Also # errors raised by APIs that do not return enough error information # may be converted to this error. class UnknownError < Error end ## # InvalidArgument indicates client specified an invalid argument. # Note that this differs from FailedPrecondition. It indicates arguments # that are problematic regardless of the state of the system # (e.g., a malformed file name). class InvalidArgumentError < Error end ## # DeadlineExceeded means operation expired before completion. # For operations that change the state of the system, this error may be # returned even if the operation has completed successfully. For # example, a successful response from a server could have been delayed # long enough for the deadline to expire. class DeadlineExceededError < Error end ## # NotFound means some requested entity (e.g., file or directory) was # not found. class NotFoundError < Error end ## # AlreadyExists means an attempt to create an entity failed because one # already exists. class AlreadyExistsError < Error end ## # PermissionDenied indicates the caller does not have permission to # execute the specified operation. It must not be used for rejections # caused by exhausting some resource (use ResourceExhausted # instead for those errors). It must not be # used if the caller cannot be identified (use Unauthenticated # instead for those errors). class PermissionDeniedError < Error end ## # Unauthenticated indicates the request does not have valid # authentication credentials for the operation. class UnauthenticatedError < Error end ## # ResourceExhausted indicates some resource has been exhausted, perhaps # a per-user quota, or perhaps the entire file system is out of space. class ResourceExhaustedError < Error end ## # FailedPrecondition indicates operation was rejected because the # system is not in a state required for the operation's execution. # For example, directory to be deleted may be non-empty, an rmdir # operation is applied to a non-directory, etc. # # A litmus test that may help a service implementor in deciding # between FailedPrecondition, Aborted, and Unavailable: # (a) Use Unavailable if the client can retry just the failing call. # (b) Use Aborted if the client should retry at a higher-level # (e.g., restarting a read-modify-write sequence). # (c) Use FailedPrecondition if the client should not retry until # the system state has been explicitly fixed. E.g., if an "rmdir" # fails because the directory is non-empty, FailedPrecondition # should be returned since the client should not retry unless # they have first fixed up the directory by deleting files from it. # (d) Use FailedPrecondition if the client performs conditional # REST Get/Update/Delete on a resource and the resource on the # server does not match the condition. E.g., conflicting # read-modify-write on the same resource. class FailedPreconditionError < Error end ## # Aborted indicates the operation was aborted, typically due to a # concurrency issue like sequencer check failures, transaction aborts, # etc. # # See litmus test above for deciding between FailedPrecondition, # Aborted, and Unavailable. class AbortedError < Error end ## # OutOfRange means operation was attempted past the valid range. # E.g., seeking or reading past end of file. # # Unlike InvalidArgument, this error indicates a problem that may # be fixed if the system state changes. For example, a 32-bit file # system will generate InvalidArgument if asked to read at an # offset that is not in the range [0,2^32-1], but it will generate # OutOfRange if asked to read from an offset past the current # file size. # # There is a fair bit of overlap between FailedPrecondition and # OutOfRange. We recommend using OutOfRange (the more specific # error) when it applies so that callers who are iterating through # a space can easily look for an OutOfRange error to detect when # they are done. class OutOfRangeError < Error end ## # Unimplemented indicates operation is not implemented or not # supported/enabled in this service. class UnimplementedError < Error end ## # Internal errors. Means some invariants expected by underlying # system has been broken. If you see one of these errors, # something is very broken. class InternalError < Error end ## # Unavailable indicates the service is currently unavailable. # This is a most likely a transient condition and may be corrected # by retrying with a backoff. # # See litmus test above for deciding between FailedPrecondition, # Aborted, and Unavailable. class UnavailableError < Error end ## # DataLoss indicates unrecoverable data loss or corruption. class DataLossError < Error end end end google-cloud-core-1.2.0/lib/google/cloud/credentials.rb0000644000175000017500000001110313505441366022331 0ustar samyaksamyak# 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://accounts.google.com/o/oauth2/token" AUDIENCE = "https://accounts.google.com/o/oauth2/token" SCOPE = [] PATH_ENV_VARS = %w[GOOGLE_CLOUD_KEYFILE GCLOUD_KEYFILE] JSON_ENV_VARS = %w[GOOGLE_CLOUD_KEYFILE_JSON GCLOUD_KEYFILE_JSON] DEFAULT_PATHS = ["~/.config/gcloud/application_default_credentials.json"] 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 if keyfile.is_a? Signet::OAuth2::Client @client = keyfile elsif keyfile.is_a? 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[hash.map { |k, v| [k.to_s, v] }] 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 google-cloud-core-1.2.0/lib/google/cloud/config.rb0000644000175000017500000004706213505441366021316 0ustar samyaksamyak# 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 unless @validators.key? key warn! "Key #{key.inspect} does not exist. Returning nil." end 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 ## # 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! : value.inspect " #{k}=#{vstr}" end "" end ## # 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.chomp! "=" self[name_str] = 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.new { true } ## # @private a list of key names that are technically illegal because # they clash with method names. # ILLEGAL_KEYS = %i[ add_options initialize instance_eval instance_exec method_missing 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 if @validators.key? key warn! "Key #{key.inspect} already exists. It will be replaced." end 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 google-cloud-core-1.2.0/lib/google/cloud/core/0000755000175000017500000000000013505441366020443 5ustar samyaksamyakgoogle-cloud-core-1.2.0/lib/google/cloud/core/version.rb0000644000175000017500000000123713505441366022460 0ustar samyaksamyak# 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.2.0".freeze end end end google-cloud-core-1.2.0/lib/google/cloud.rb0000644000175000017500000001122313505441366020037 0ustar samyaksamyak# 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 # [Authentication # Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/guides/authentication). # # You can learn more about various options for connection on the [Authentication # Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/guides/authentication). # module Google module Cloud ## # Creates a new object for connecting to Google Cloud. # # For more information on connecting to Google Cloud see the [Authentication # Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/guides/authentication). # # @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. # # @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 end end # Set the default top-level configuration Google::Cloud.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 end # Auto-load all Google Cloud service gems. Gem.find_files("google-cloud-*.rb").each do |google_cloud_service| require google_cloud_service end google-cloud-core-1.2.0/google-cloud-core.gemspec0000644000175000017500000000650513505441366021244 0ustar samyaksamyak######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: google-cloud-core 1.2.0 ruby lib Gem::Specification.new do |s| s.name = "google-cloud-core".freeze s.version = "1.2.0" 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 = "2018-02-27" 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, "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, "lib/google/cloud/errors.rb".freeze] s.homepage = "https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/master/google-cloud-core".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0.0".freeze) s.rubygems_version = "2.7.6.2".freeze s.summary = "Internal shared library for google-cloud-ruby".freeze if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_runtime_dependency(%q.freeze, ["~> 1.0"]) s.add_development_dependency(%q.freeze, ["~> 5.10"]) 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, ["~> 0.50.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.8"]) else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 5.10"]) 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, ["~> 0.50.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["<= 0.1.8"]) end else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 5.10"]) 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, ["~> 0.50.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["<= 0.1.8"]) end end google-cloud-core-1.2.0/LICENSE0000644000175000017500000002613713505441366015401 0ustar samyaksamyak 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. google-cloud-core-1.2.0/.yardopts0000644000175000017500000000012413505441366016226 0ustar samyaksamyak--no-private --title=Google Cloud Core --markup markdown ./lib/**/*.rb - README.md google-cloud-core-1.2.0/README.md0000644000175000017500000000272013505441366015643 0ustar samyaksamyak# google-cloud-core This library contains shared types, such as error classes, for the google-cloud project. Please see the top-level project [README](../README.md) for general information. - [google-cloud-core API documentation](http://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-core/latest) ## Supported Ruby Versions This library is supported on Ruby 2.0+. ## 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://googlecloudplatform.github.io/google-cloud-ruby/#/docs/guides/contributing) 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](../CODE_OF_CONDUCT.md) for more information. ## License This library is licensed under Apache 2.0. Full license text is available in [LICENSE](LICENSE). ## Support Please [report bugs at the project on Github](https://github.com/GoogleCloudPlatform/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).