diff --git a/.rspec b/.rspec index 7438fbe51..16f9cdb01 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,2 @@ ---colour +--color --format documentation diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..33d647ecf --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,7 @@ +inherit_from: .rubocop_todo.yml + +Metrics/LineLength: + Max: 120 + +Style/FormatString: + EnforcedStyle: sprintf diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 000000000..5f8512603 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,63 @@ +# This configuration was generated by `rubocop --auto-gen-config` +# on 2015-03-25 23:30:36 -0700 using RuboCop version 0.29.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 19 +Metrics/AbcSize: + Max: 79 + +# Offense count: 2 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 220 + +# Offense count: 5 +Metrics/CyclomaticComplexity: + Max: 10 + +# Offense count: 99 +# Configuration parameters: AllowURI, URISchemes. +Metrics/LineLength: + Max: 127 + +# Offense count: 18 +# Configuration parameters: CountComments. +Metrics/MethodLength: + Max: 43 + +# Offense count: 1 +# Configuration parameters: CountKeywordArgs. +Metrics/ParameterLists: + Max: 6 + +# Offense count: 4 +Metrics/PerceivedComplexity: + Max: 11 + +# Offense count: 14 +Style/Documentation: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/EmptyLines: + Enabled: false + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/EmptyLinesAroundClassBody: + Enabled: false + +# Offense count: 2 +# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles. +Style/Next: + Enabled: false + +# Offense count: 3 +# Cop supports --auto-correct. +Style/RedundantSelf: + Enabled: false diff --git a/.travis.yml b/.travis.yml index 2a453720d..fb752eda9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,15 +3,13 @@ rvm: - 2.2 - 2.0.0 - 2.1 - - 1.9.3 - - rbx-2 - - jruby + - jruby-9000 env: - RAILS_VERSION="~>3.2" - RAILS_VERSION="~>4.0.0" - RAILS_VERSION="~>4.1.0" - RAILS_VERSION="~>4.2.0" -script: "bundle exec rake spec:all" +script: "rake spec:all" before_install: - sudo apt-get update - sudo apt-get install idn diff --git a/.yardopts b/.yardopts index fa8f29d03..00feaac9c 100644 --- a/.yardopts +++ b/.yardopts @@ -1,7 +1,12 @@ ---markup markdown +--hide-void-return +--no-private +--verbose +--markup-provider=redcarpet +--markup=markdown lib/**/*.rb -ext/**/*.c +generated/**/*.rb - README.md -CHANGELOG.md +MIGRATING.md +CONTRIBUTING.md LICENSE diff --git a/CHANGELOG.md b/CHANGELOG.md index 049eff05c..1c0af91b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 0.9.0 +* WARNING: Please see [MIGRATING](MIGRATING.md) for important information. +* API classes are now generated ahead of time instead of at runtime. +* Drop support for Ruby versions < 2.0 +* Switch from Faraday to Hurley for HTTP client + # 0.8.6 * Use discovered 'rootUrl' as base URI for services * Respect discovered methods with colons in path diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1e65911f8..448f78ab4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## Contributor License Agreements -We'd love to accept your sample apps and patches! Before we can take them, we +We'd love to accept your sample apps and patches! Before we can take them, we have to jump a couple of legal hurdles. Please fill out either the individual or corporate Contributor License Agreement @@ -29,4 +29,3 @@ accept your pull requests. 1. Ensure that your code is clear and comprehensible. 1. Ensure that your code has an appropriate set of unit tests which all pass. 1. Submit a pull request. - diff --git a/Gemfile b/Gemfile index 9e6d43ad8..837bdf48c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,9 +1,35 @@ source 'https://rubygems.org' +# Specify your gem's dependencies in google-apis.gemspec gemspec -gem 'jruby-openssl', :platforms => :jruby + +group :development do + gem 'bundler', '~> 1.7' + gem 'rake', '~> 10.0' + gem 'rspec', '~> 3.1' + gem 'json_spec', '~> 1.1' + gem 'webmock', '~> 1.21' + gem 'simplecov', '~> 0.9' + gem 'coveralls', '~> 0.7.11' + gem 'rubocop', '~> 0.29' + gem 'launchy', '~> 2.4' +end + +platforms :jruby do + group :development do + gem 'jruby-openssl' + end +end + +platforms :ruby do + group :development do + gem 'yard', '~> 0.8' + gem 'redcarpet', '~> 3.2' + gem 'github-markup', '~> 1.3' + end +end if ENV['RAILS_VERSION'] gem 'rails', ENV['RAILS_VERSION'] -end \ No newline at end of file +end diff --git a/MIGRATING.md b/MIGRATING.md new file mode 100644 index 000000000..f86eec363 --- /dev/null +++ b/MIGRATING.md @@ -0,0 +1,171 @@ +# Migrating from version `0.8.x` to `0.9` + +Many changes and improvements have been made to the `google-api-ruby-client` +library to bring it to `0.9`. If you are starting a new project or haven't used +this library before version `0.9`, see the [README][readme] to get started +as you won't need to migrate anything. + +Code written against the `0.8.x` version of this library will not work with the `0.9` +version without modification. + +## Discovery + +In `0.8.x` the library would "discover" APIs on the fly, introducing +additional network calls and instability. That has been fixed in `0.9`. + +To get the `drive` client in `0.8.x` required this: + +```ruby +require 'google/api_client' + +client = Google::APIClient.new +drive = client.discovered_api('drive', 'v2') +``` + +In `0.9` the same thing can be accomplished like this: + +```ruby +require 'google/apis/drive_v2' + +drive = Google::Apis::DriveV2::DriveService.new +``` + +All APIs are immediately accessible without requiring additional network calls or runtime code generation. + +## API Methods + +The calling style for API methods has changed. In `0.8.x` all calls were via a generic `execute` method. In `0.9` +the generated services have fully defined method signatures for all available methods. + +To get a file using the Google Drive API in `0.8.x` required this: + +```ruby +file = client.execute(:api_method => drive.file.get, :parameters => { 'id' => 'abc123' }) +``` + +In `0.9` the same thing can be accomplished like this: + +```ruby +file = drive.get_file('abc123') +``` + +Full API definitions including available methods, parameters, and data classes can be found in the `generated` directory. + +## Authorization + +In the 0.9 version of this library, the authentication and authorization code was moved +to the new [googleauth](https://github.com/google/google-auth-library-ruby) library. While the new library provides +significantly simpler APIs for some use cases, not all features have been migrated. Missing features +are expected to be added by end of Q2 2015. + +The underlying [Signet](https://github.com/google/signet) is still used for authorization. OAuth 2 credentials obtained +previously will continue to work with the `0.9` version. OAuth 1 is no longer supported. + +## Media uploads + +Media uploads are significantly simpler in `0.9`. + +The old `0.8.x` way of uploading media: + +```ruby +media = Google::APIClient::UploadIO.new('mymovie.m4v', 'video/mp4') +metadata = { + 'title' => 'My movie', + 'description' => 'The best home movie ever made' +} +client.execute(:api_method => drive.files.insert, + :parameters => { 'uploadType' => 'multipart' }, + :body_object => metadata, + :media => media ) +``` + +The new way in `0.9` using `upload_source` and `content_type` parameters: + +```ruby +metadata = { + title: 'My movie', + description: 'The best home movie ever made' +} +drive.insert_file(metadata, upload_source: 'mymovie.m4v', content_type: 'video/mp4') +``` + +`upload_source` can be either a path to a file, an `IO` stream, or a `StringIO` instance. + +Uploads are resumable and will be automatically retried if interrupted. + +## Media downloads + +`0.9` introduces support for media downloads (`alt=media`). To download content, use the `download_dest` parameter: + +```ruby +drive.get_file('abc123', download_dest: '/tmp/myfile.txt') +``` + +`download_dest` may be either a path to a file or an `IO` stream. + +## Batch Requests + +The old `0.8.x` way of performing batch requests: + +```ruby +client = Google::APIClient.new +urlshortener = client.discovered_api('urlshortener') + +batch = Google::APIClient::BatchRequest.new do |result| + puts result.data +end + +batch.add(:api_method => urlshortener.url.insert, + :body_object => { 'longUrl' => 'http://example.com/foo' }) +batch.add(:api_method => urlshortener.url.insert, + :body_object => { 'longUrl' => 'http://example.com/bar' }) +client.execute(batch) +``` + +In `0.9`, the equivalent code is: + +```ruby +require 'google/apis/urlshortner_v1' + +urlshortener = Google::Apis::UrlshortenerV1::UrlshortenerService.new + +urlshortener.batch do |urlshortener| + urlshortner.insert_url({long_url: 'http://example.com/foo'}) do |res, err| + puts res + end + urlshortner.insert_url({long_url: 'http://example.com/bar'}) do |res, err| + puts res + end +end +``` + +Or if sharing the same block: + +```ruby +require 'google/apis/urlshortner_v1' + +urlshortener = Google::Apis::UrlshortenerV1::UrlshortenerService.new + +callback = lambda { |res, err| puts res } +urlshortener.batch do |urlshortener| + urlshortner.insert_url({long_url: 'http://example.com/foo'}, &callback) + urlshortner.insert_url({long_url: 'http://example.com/bar'}, &callback) +end +``` + +## JRuby + +Jruby 1.7.4 in 2.0 compatibility mode is supported. To enable for a specific script: + +``` +jruby --2.0 myscript.rb +``` + +Or set as the default: + +``` +export JRUBY_OPTS=--2.0 +``` + +JRuby 9000 will be supported once released. + diff --git a/README.md b/README.md index 510ae817e..974f4ea08 100644 --- a/README.md +++ b/README.md @@ -1,218 +1,226 @@ # Google API Client -
:two_legged_oauth_1
:oauth_1
:oauth_2
:google_app_default
String
representation of the service's state.
- #
- # @return [String] The service's state, as a String
.
- def inspect
- sprintf(
- "#<%s:%#0x ID:%s>", self.class.to_s, self.object_id, self.id
- )
- end
-
- ##
- # Marshalling support - serialize the API to a string (doc base + original
- # discovery document).
- def _dump(level)
- MultiJson.dump([@document_base.to_s, @discovery_document])
- end
-
- ##
- # Marshalling support - Restore an API instance from serialized form
- def self._load(obj)
- new(*MultiJson.load(obj))
- end
-
- end
- end
-end
diff --git a/lib/google/api_client/discovery/media.rb b/lib/google/api_client/discovery/media.rb
deleted file mode 100644
index ffa7e87c3..000000000
--- a/lib/google/api_client/discovery/media.rb
+++ /dev/null
@@ -1,77 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-require 'addressable/uri'
-require 'addressable/template'
-
-require 'google/api_client/errors'
-
-
-module Google
- class APIClient
- ##
- # Media upload elements for discovered methods
- class MediaUpload
-
- ##
- # Creates a description of a particular method.
- #
- # @param [Google::APIClient::API] api
- # Base discovery document for the API
- # @param [Addressable::URI] method_base
- # The base URI for the service.
- # @param [Hash] discovery_document
- # The media upload section of the discovery document.
- #
- # @return [Google::APIClient::Method] The constructed method object.
- def initialize(api, method_base, discovery_document)
- @api = api
- @method_base = method_base
- @discovery_document = discovery_document
- end
-
- ##
- # List of acceptable mime types
- #
- # @return [Array]
- # List of acceptable mime types for uploaded content
- def accepted_types
- @discovery_document['accept']
- end
-
- ##
- # Maximum size of an uplad
- # TODO: Parse & convert to numeric value
- #
- # @return [String]
- def max_size
- @discovery_document['maxSize']
- end
-
- ##
- # Returns the URI template for the method. A parameter list can be
- # used to expand this into a URI.
- #
- # @return [Addressable::Template] The URI template.
- def uri_template
- return @uri_template ||= Addressable::Template.new(
- @api.method_base.join(Addressable::URI.parse(@discovery_document['protocols']['simple']['path']))
- )
- end
-
- end
-
- end
-end
diff --git a/lib/google/api_client/discovery/method.rb b/lib/google/api_client/discovery/method.rb
deleted file mode 100644
index 3a06857c0..000000000
--- a/lib/google/api_client/discovery/method.rb
+++ /dev/null
@@ -1,363 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-require 'addressable/uri'
-require 'addressable/template'
-
-require 'google/api_client/errors'
-
-
-module Google
- class APIClient
- ##
- # A method that has been described by a discovery document.
- class Method
-
- ##
- # Creates a description of a particular method.
- #
- # @param [Google::APIClient::API] api
- # The API this method belongs to.
- # @param [Addressable::URI] method_base
- # The base URI for the service.
- # @param [String] method_name
- # The identifier for the method.
- # @param [Hash] discovery_document
- # The section of the discovery document that applies to this method.
- #
- # @return [Google::APIClient::Method] The constructed method object.
- def initialize(api, method_base, method_name, discovery_document)
- @api = api
- @method_base = method_base
- @name = method_name
- @discovery_document = discovery_document
- end
-
- # @return [String] unparsed discovery document for the method
- attr_reader :discovery_document
-
- ##
- # Returns the API this method belongs to.
- #
- # @return [Google::APIClient::API] The API this method belongs to.
- attr_reader :api
-
- ##
- # Returns the identifier for the method.
- #
- # @return [String] The method identifier.
- attr_reader :name
-
- ##
- # Returns the base URI for the method.
- #
- # @return [Addressable::URI]
- # The base URI that this method will be joined to.
- attr_reader :method_base
-
- ##
- # Updates the method with the new base.
- #
- # @param [Addressable::URI, #to_str, String] new_method_base
- # The new base URI to use for the method.
- def method_base=(new_method_base)
- @method_base = Addressable::URI.parse(new_method_base)
- @uri_template = nil
- end
-
- ##
- # Returns a human-readable description of the method.
- #
- # @return [Hash] The API description.
- def description
- return @discovery_document['description']
- end
-
- ##
- # Returns the method ID.
- #
- # @return [String] The method identifier.
- def id
- return @discovery_document['id']
- end
-
- ##
- # Returns the HTTP method or 'GET' if none is specified.
- #
- # @return [String] The HTTP method that will be used in the request.
- def http_method
- return @discovery_document['httpMethod'] || 'GET'
- end
-
- ##
- # Returns the URI template for the method. A parameter list can be
- # used to expand this into a URI.
- #
- # @return [Addressable::Template] The URI template.
- def uri_template
- return @uri_template ||= Addressable::Template.new(
- self.method_base.join(Addressable::URI.parse("./" + @discovery_document['path']))
- )
- end
-
- ##
- # Returns media upload information for this method, if supported
- #
- # @return [Google::APIClient::MediaUpload] Description of upload endpoints
- def media_upload
- if @discovery_document['mediaUpload']
- return @media_upload ||= Google::APIClient::MediaUpload.new(self, self.method_base, @discovery_document['mediaUpload'])
- else
- return nil
- end
- end
-
- ##
- # Returns the Schema object for the method's request, if any.
- #
- # @return [Google::APIClient::Schema] The request schema.
- def request_schema
- if @discovery_document['request']
- schema_name = @discovery_document['request']['$ref']
- return @api.schemas[schema_name]
- else
- return nil
- end
- end
-
- ##
- # Returns the Schema object for the method's response, if any.
- #
- # @return [Google::APIClient::Schema] The response schema.
- def response_schema
- if @discovery_document['response']
- schema_name = @discovery_document['response']['$ref']
- return @api.schemas[schema_name]
- else
- return nil
- end
- end
-
- ##
- # Normalizes parameters, converting to the appropriate types.
- #
- # @param [Hash, Array] parameters
- # The parameters to normalize.
- #
- # @return [Hash] The normalized parameters.
- def normalize_parameters(parameters={})
- # Convert keys to Strings when appropriate
- if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
- # Returning an array since parameters can be repeated (ie, Adsense Management API)
- parameters = parameters.inject([]) do |accu, (k, v)|
- k = k.to_s if k.kind_of?(Symbol)
- k = k.to_str if k.respond_to?(:to_str)
- unless k.kind_of?(String)
- raise TypeError, "Expected String, got #{k.class}."
- end
- accu << [k, v]
- accu
- end
- else
- raise TypeError,
- "Expected Hash or Array, got #{parameters.class}."
- end
- return parameters
- end
-
- ##
- # Expands the method's URI template using a parameter list.
- #
- # @api private
- # @param [Hash, Array] parameters
- # The parameter list to use.
- #
- # @return [Addressable::URI] The URI after expansion.
- def generate_uri(parameters={})
- parameters = self.normalize_parameters(parameters)
-
- self.validate_parameters(parameters)
- template_variables = self.uri_template.variables
- upload_type = parameters.assoc('uploadType') || parameters.assoc('upload_type')
- if upload_type
- unless self.media_upload
- raise ArgumentException, "Media upload not supported for this method"
- end
- case upload_type.last
- when 'media', 'multipart', 'resumable'
- uri = self.media_upload.uri_template.expand(parameters)
- else
- raise ArgumentException, "Invalid uploadType '#{upload_type}'"
- end
- else
- uri = self.uri_template.expand(parameters)
- end
- query_parameters = parameters.reject do |k, v|
- template_variables.include?(k)
- end
- # encode all non-template parameters
- params = ""
- unless query_parameters.empty?
- params = "?" + Addressable::URI.form_encode(query_parameters.sort)
- end
- # Normalization is necessary because of undesirable percent-escaping
- # during URI template expansion
- return uri.normalize + params
- end
-
- ##
- # Generates an HTTP request for this method.
- #
- # @api private
- # @param [Hash, Array] parameters
- # The parameters to send.
- # @param [String, StringIO] body The body for the HTTP request.
- # @param [Hash, Array] headers The HTTP headers for the request.
- # @option options [Faraday::Connection] :connection
- # The HTTP connection to use.
- #
- # @return [Array] The generated HTTP request.
- def generate_request(parameters={}, body='', headers={}, options={})
- if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
- raise TypeError, "Expected Hash or Array, got #{headers.class}."
- end
- method = self.http_method.to_s.downcase.to_sym
- uri = self.generate_uri(parameters)
- headers = Faraday::Utils::Headers.new(headers)
- return [method, uri, headers, body]
- end
-
-
- ##
- # Returns a Hash
of the parameter descriptions for
- # this method.
- #
- # @return [Hash] The parameter descriptions.
- def parameter_descriptions
- @parameter_descriptions ||= (
- @discovery_document['parameters'] || {}
- ).inject({}) { |h,(k,v)| h[k]=v; h }
- end
-
- ##
- # Returns an Array
of the parameters for this method.
- #
- # @return [Array] The parameters.
- def parameters
- @parameters ||= ((
- @discovery_document['parameters'] || {}
- ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
- end
-
- ##
- # Returns an Array
of the required parameters for this
- # method.
- #
- # @return [Array] The required parameters.
- #
- # @example
- # # A list of all required parameters.
- # method.required_parameters
- def required_parameters
- @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
- v['required']
- end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
- end
-
- ##
- # Returns an Array
of the optional parameters for this
- # method.
- #
- # @return [Array] The optional parameters.
- #
- # @example
- # # A list of all optional parameters.
- # method.optional_parameters
- def optional_parameters
- @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
- v['required']
- end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
- end
-
- ##
- # Verifies that the parameters are valid for this method. Raises an
- # exception if validation fails.
- #
- # @api private
- # @param [Hash, Array] parameters
- # The parameters to verify.
- #
- # @return [NilClass] nil
if validation passes.
- def validate_parameters(parameters={})
- parameters = self.normalize_parameters(parameters)
- required_variables = ((self.parameter_descriptions.select do |k, v|
- v['required']
- end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
- missing_variables = required_variables - parameters.map { |(k, _)| k }
- if missing_variables.size > 0
- raise ArgumentError,
- "Missing required parameters: #{missing_variables.join(', ')}."
- end
- parameters.each do |k, v|
- # Handle repeated parameters.
- if self.parameter_descriptions[k] &&
- self.parameter_descriptions[k]['repeated'] &&
- v.kind_of?(Array)
- # If this is a repeated parameter and we've got an array as a
- # value, just provide the whole array to the loop below.
- items = v
- else
- # If this is not a repeated parameter, or if it is but we're
- # being given a single value, wrap the value in an array, so that
- # the loop below still works for the single element.
- items = [v]
- end
-
- items.each do |item|
- if self.parameter_descriptions[k]
- enum = self.parameter_descriptions[k]['enum']
- if enum && !enum.include?(item)
- raise ArgumentError,
- "Parameter '#{k}' has an invalid value: #{item}. " +
- "Must be one of #{enum.inspect}."
- end
- pattern = self.parameter_descriptions[k]['pattern']
- if pattern
- regexp = Regexp.new("^#{pattern}$")
- if item !~ regexp
- raise ArgumentError,
- "Parameter '#{k}' has an invalid value: #{item}. " +
- "Must match: /^#{pattern}$/."
- end
- end
- end
- end
- end
- return nil
- end
-
- ##
- # Returns a String
representation of the method's state.
- #
- # @return [String] The method's state, as a String
.
- def inspect
- sprintf(
- "#<%s:%#0x ID:%s>",
- self.class.to_s, self.object_id, self.id
- )
- end
- end
- end
-end
diff --git a/lib/google/api_client/discovery/resource.rb b/lib/google/api_client/discovery/resource.rb
deleted file mode 100644
index 9b757c684..000000000
--- a/lib/google/api_client/discovery/resource.rb
+++ /dev/null
@@ -1,156 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-require 'addressable/uri'
-
-require 'active_support/inflector'
-require 'google/api_client/discovery/method'
-
-
-module Google
- class APIClient
- ##
- # A resource that has been described by a discovery document.
- class Resource
-
- ##
- # Creates a description of a particular version of a resource.
- #
- # @param [Google::APIClient::API] api
- # The API this resource belongs to.
- # @param [Addressable::URI] method_base
- # The base URI for the service.
- # @param [String] resource_name
- # The identifier for the resource.
- # @param [Hash] discovery_document
- # The section of the discovery document that applies to this resource.
- #
- # @return [Google::APIClient::Resource] The constructed resource object.
- def initialize(api, method_base, resource_name, discovery_document)
- @api = api
- @method_base = method_base
- @name = resource_name
- @discovery_document = discovery_document
- metaclass = (class <String
.
- def inspect
- sprintf(
- "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
- )
- end
- end
- end
-end
diff --git a/lib/google/api_client/discovery/schema.rb b/lib/google/api_client/discovery/schema.rb
deleted file mode 100644
index 57666e698..000000000
--- a/lib/google/api_client/discovery/schema.rb
+++ /dev/null
@@ -1,117 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-require 'time'
-require 'multi_json'
-require 'compat/multi_json'
-require 'base64'
-require 'autoparse'
-require 'addressable/uri'
-require 'addressable/template'
-
-require 'active_support/inflector'
-require 'google/api_client/errors'
-
-
-module Google
- class APIClient
- ##
- # @api private
- module Schema
- def self.parse(api, schema_data)
- # This method is super-long, but hard to break up due to the
- # unavoidable dependence on closures and execution context.
- schema_name = schema_data['id']
-
- # Due to an oversight, schema IDs may not be URI references.
- # TODO(bobaman): Remove this code once this has been resolved.
- schema_uri = (
- api.document_base +
- (schema_name[0..0] != '#' ? '#' + schema_name : schema_name)
- )
-
- # Due to an oversight, schema IDs may not be URI references.
- # TODO(bobaman): Remove this whole lambda once this has been resolved.
- reformat_references = lambda do |data|
- # This code is not particularly efficient due to recursive traversal
- # and excess object creation, but this hopefully shouldn't be an
- # issue since it should only be called only once per schema per
- # process.
- if data.kind_of?(Hash) &&
- data['$ref'] && !data['$ref'].kind_of?(Hash)
- if data['$ref'].respond_to?(:to_str)
- reference = data['$ref'].to_str
- else
- raise TypeError, "Expected String, got #{data['$ref'].class}"
- end
- reference = '#' + reference if reference[0..0] != '#'
- data.merge({
- '$ref' => reference
- })
- elsif data.kind_of?(Hash)
- data.inject({}) do |accu, (key, value)|
- if value.kind_of?(Hash)
- accu[key] = reformat_references.call(value)
- else
- accu[key] = value
- end
- accu
- end
- else
- data
- end
- end
- schema_data = reformat_references.call(schema_data)
-
- if schema_name
- api_name_string = ActiveSupport::Inflector.camelize(api.name)
- api_version_string = ActiveSupport::Inflector.camelize(api.version).gsub('.', '_')
- # This is for compatibility with Ruby 1.8.7.
- # TODO(bobaman) Remove this when we eventually stop supporting 1.8.7.
- args = []
- args << false if Class.method(:const_defined?).arity != 1
- if Google::APIClient::Schema.const_defined?(api_name_string, *args)
- api_name = Google::APIClient::Schema.const_get(
- api_name_string, *args
- )
- else
- api_name = Google::APIClient::Schema.const_set(
- api_name_string, Module.new
- )
- end
- if api_name.const_defined?(api_version_string, *args)
- api_version = api_name.const_get(api_version_string, *args)
- else
- api_version = api_name.const_set(api_version_string, Module.new)
- end
- if api_version.const_defined?(schema_name, *args)
- schema_class = api_version.const_get(schema_name, *args)
- end
- end
-
- # It's possible the schema has already been defined. If so, don't
- # redefine it. This means that reloading a schema which has already
- # been loaded into memory is not possible.
- unless schema_class
- schema_class = AutoParse.generate(schema_data, :uri => schema_uri)
- if schema_name
- api_version.const_set(schema_name, schema_class)
- end
- end
- return schema_class
- end
- end
- end
-end
diff --git a/lib/google/api_client/environment.rb b/lib/google/api_client/environment.rb
deleted file mode 100644
index 50c84fe5c..000000000
--- a/lib/google/api_client/environment.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-module Google
- class APIClient
- module ENV
- OS_VERSION = begin
- if RUBY_PLATFORM =~ /mswin|win32|mingw|bccwin|cygwin/
- # TODO(bobaman)
- # Confirm that all of these Windows environments actually have access
- # to the `ver` command.
- `ver`.sub(/\s*\[Version\s*/, '/').sub(']', '').strip
- elsif RUBY_PLATFORM =~ /darwin/i
- "Mac OS X/#{`sw_vers -productVersion`}"
- elsif RUBY_PLATFORM == 'java'
- # Get the information from java system properties to avoid spawning a
- # sub-process, which is not friendly in some contexts (web servers).
- require 'java'
- name = java.lang.System.getProperty('os.name')
- version = java.lang.System.getProperty('os.version')
- "#{name}/#{version}"
- else
- `uname -sr`.sub(' ', '/')
- end
- rescue Exception
- RUBY_PLATFORM
- end
- end
- end
-end
diff --git a/lib/google/api_client/gzip.rb b/lib/google/api_client/gzip.rb
deleted file mode 100644
index 42fabbbdb..000000000
--- a/lib/google/api_client/gzip.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-require 'faraday'
-require 'zlib'
-
-module Google
- class APIClient
- class Gzip < Faraday::Response::Middleware
- include Google::APIClient::Logging
-
- def on_complete(env)
- encoding = env[:response_headers]['content-encoding'].to_s.downcase
- case encoding
- when 'gzip'
- logger.debug { "Decompressing gzip encoded response (#{env[:body].length} bytes)" }
- env[:body] = Zlib::GzipReader.new(StringIO.new(env[:body])).read
- env[:response_headers].delete('content-encoding')
- logger.debug { "Decompressed (#{env[:body].length} bytes)" }
- when 'deflate'
- logger.debug{ "Decompressing deflate encoded response (#{env[:body].length} bytes)" }
- env[:body] = Zlib::Inflate.inflate(env[:body])
- env[:response_headers].delete('content-encoding')
- logger.debug { "Decompressed (#{env[:body].length} bytes)" }
- end
- end
- end
- end
-end
-
-Faraday::Response.register_middleware :gzip => Google::APIClient::Gzip
\ No newline at end of file
diff --git a/lib/google/api_client/logging.rb b/lib/google/api_client/logging.rb
deleted file mode 100644
index 09a075b5c..000000000
--- a/lib/google/api_client/logging.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-require 'logger'
-
-module Google
- class APIClient
-
- class << self
- ##
- # Logger for the API client
- #
- # @return [Logger] logger instance.
- attr_accessor :logger
- end
-
- self.logger = Logger.new(STDOUT)
- self.logger.level = Logger::WARN
-
- ##
- # Module to make accessing the logger simpler
- module Logging
- ##
- # Logger for the API client
- #
- # @return [Logger] logger instance.
- def logger
- Google::APIClient.logger
- end
- end
-
- end
-
-
-end
\ No newline at end of file
diff --git a/lib/google/api_client/media.rb b/lib/google/api_client/media.rb
deleted file mode 100644
index 5066bcebd..000000000
--- a/lib/google/api_client/media.rb
+++ /dev/null
@@ -1,259 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-require 'google/api_client/reference'
-
-module Google
- class APIClient
- ##
- # Uploadable media support. Holds an IO stream & content type.
- #
- # @see Faraday::UploadIO
- # @example
- # media = Google::APIClient::UploadIO.new('mymovie.m4v', 'video/mp4')
- class UploadIO < Faraday::UploadIO
-
- # @return [Fixnum] Size of chunks to upload. Default is nil, meaning upload the entire file in a single request
- attr_accessor :chunk_size
-
- ##
- # Get the length of the stream
- #
- # @return [Fixnum]
- # Length of stream, in bytes
- def length
- io.respond_to?(:length) ? io.length : File.size(local_path)
- end
- end
-
- ##
- # Wraps an input stream and limits data to a given range
- #
- # @example
- # chunk = Google::APIClient::RangedIO.new(io, 0, 1000)
- class RangedIO
- ##
- # Bind an input stream to a specific range.
- #
- # @param [IO] io
- # Source input stream
- # @param [Fixnum] offset
- # Starting offset of the range
- # @param [Fixnum] length
- # Length of range
- def initialize(io, offset, length)
- @io = io
- @offset = offset
- @length = length
- self.rewind
- end
-
- ##
- # @see IO#read
- def read(amount = nil, buf = nil)
- buffer = buf || ''
- if amount.nil?
- size = @length - @pos
- done = ''
- elsif amount == 0
- size = 0
- done = ''
- else
- size = [@length - @pos, amount].min
- done = nil
- end
-
- if size > 0
- result = @io.read(size)
- result.force_encoding("BINARY") if result.respond_to?(:force_encoding)
- buffer << result if result
- @pos = @pos + size
- end
-
- if buffer.length > 0
- buffer
- else
- done
- end
- end
-
- ##
- # @see IO#rewind
- def rewind
- self.pos = 0
- end
-
- ##
- # @see IO#pos
- def pos
- @pos
- end
-
- ##
- # @see IO#pos=
- def pos=(pos)
- @pos = pos
- @io.pos = @offset + pos
- end
- end
-
- ##
- # Resumable uploader.
- #
- class ResumableUpload < Request
- # @return [Fixnum] Max bytes to send in a single request
- attr_accessor :chunk_size
-
- ##
- # Creates a new uploader.
- #
- # @param [Hash] options
- # Request options
- def initialize(options={})
- super options
- self.uri = options[:uri]
- self.http_method = :put
- @offset = options[:offset] || 0
- @complete = false
- @expired = false
- end
-
- ##
- # Sends all remaining chunks to the server
- #
- # @deprecated Pass the instance to {Google::APIClient#execute} instead
- #
- # @param [Google::APIClient] api_client
- # API Client instance to use for sending
- def send_all(api_client)
- result = nil
- until complete?
- result = send_chunk(api_client)
- break unless result.status == 308
- end
- return result
- end
-
-
- ##
- # Sends the next chunk to the server
- #
- # @deprecated Pass the instance to {Google::APIClient#execute} instead
- #
- # @param [Google::APIClient] api_client
- # API Client instance to use for sending
- def send_chunk(api_client)
- return api_client.execute(self)
- end
-
- ##
- # Check if upload is complete
- #
- # @return [TrueClass, FalseClass]
- # Whether or not the upload complete successfully
- def complete?
- return @complete
- end
-
- ##
- # Check if the upload URL expired (upload not completed in alotted time.)
- # Expired uploads must be restarted from the beginning
- #
- # @return [TrueClass, FalseClass]
- # Whether or not the upload has expired and can not be resumed
- def expired?
- return @expired
- end
-
- ##
- # Check if upload is resumable. That is, neither complete nor expired
- #
- # @return [TrueClass, FalseClass] True if upload can be resumed
- def resumable?
- return !(self.complete? or self.expired?)
- end
-
- ##
- # Convert to an HTTP request. Returns components in order of method, URI,
- # request headers, and body
- #
- # @api private
- #
- # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
- def to_http_request
- if @complete
- raise Google::APIClient::ClientError, "Upload already complete"
- elsif @offset.nil?
- self.headers.update({
- 'Content-Length' => "0",
- 'Content-Range' => "bytes */#{media.length}" })
- else
- start_offset = @offset
- remaining = self.media.length - start_offset
- chunk_size = self.media.chunk_size || self.chunk_size || self.media.length
- content_length = [remaining, chunk_size].min
- chunk = RangedIO.new(self.media.io, start_offset, content_length)
- end_offset = start_offset + content_length - 1
- self.headers.update({
- 'Content-Length' => "#{content_length}",
- 'Content-Type' => self.media.content_type,
- 'Content-Range' => "bytes #{start_offset}-#{end_offset}/#{media.length}" })
- self.body = chunk
- end
- super
- end
-
- ##
- # Check the result from the server, updating the offset and/or location
- # if available.
- #
- # @api private
- #
- # @param [Faraday::Response] response
- # HTTP response
- #
- # @return [Google::APIClient::Result]
- # Processed API response
- def process_http_response(response)
- case response.status
- when 200...299
- @complete = true
- when 308
- range = response.headers['range']
- if range
- @offset = range.scan(/\d+/).collect{|x| Integer(x)}.last + 1
- end
- if response.headers['location']
- self.uri = response.headers['location']
- end
- when 400...499
- @expired = true
- when 500...599
- # Invalidate the offset to mark it needs to be queried on the
- # next request
- @offset = nil
- end
- return Google::APIClient::Result.new(self, response)
- end
-
- ##
- # Hashified verison of the API request
- #
- # @return [Hash]
- def to_hash
- super.merge(:offset => @offset)
- end
-
- end
- end
-end
\ No newline at end of file
diff --git a/lib/google/api_client/railtie.rb b/lib/google/api_client/railtie.rb
deleted file mode 100644
index 86d9a6b20..000000000
--- a/lib/google/api_client/railtie.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'rails/railtie'
-require 'google/api_client/logging'
-
-module Google
- class APIClient
-
- ##
- # Optional support class for Rails. Currently replaces the built-in logger
- # with Rails' application log.
- #
- class Railtie < Rails::Railtie
- initializer 'google-api-client' do |app|
- logger = app.config.logger || Rails.logger
- Google::APIClient.logger = logger unless logger.nil?
- end
- end
- end
-end
diff --git a/lib/google/api_client/request.rb b/lib/google/api_client/request.rb
deleted file mode 100644
index d043e0016..000000000
--- a/lib/google/api_client/request.rb
+++ /dev/null
@@ -1,350 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-require 'faraday'
-require 'faraday/request/multipart'
-require 'compat/multi_json'
-require 'addressable/uri'
-require 'stringio'
-require 'google/api_client/discovery'
-require 'google/api_client/logging'
-
-module Google
- class APIClient
-
- ##
- # Represents an API request.
- class Request
- include Google::APIClient::Logging
-
- MULTIPART_BOUNDARY = "-----------RubyApiMultipartPost".freeze
-
- # @return [Hash] Request parameters
- attr_reader :parameters
- # @return [Hash] Additional HTTP headers
- attr_reader :headers
- # @return [Google::APIClient::Method] API method to invoke
- attr_reader :api_method
- # @return [Google::APIClient::UploadIO] File to upload
- attr_accessor :media
- # @return [#generated_authenticated_request] User credentials
- attr_accessor :authorization
- # @return [TrueClass,FalseClass] True if request should include credentials
- attr_accessor :authenticated
- # @return [#read, #to_str] Request body
- attr_accessor :body
-
- ##
- # Build a request
- #
- # @param [Hash] options
- # @option options [Hash, Array] :parameters
- # Request parameters for the API method.
- # @option options [Google::APIClient::Method] :api_method
- # API method to invoke. Either :api_method or :uri must be specified
- # @option options [TrueClass, FalseClass] :authenticated
- # True if request should include credentials. Implicitly true if
- # unspecified and :authorization present
- # @option options [#generate_signed_request] :authorization
- # OAuth credentials
- # @option options [Google::APIClient::UploadIO] :media
- # File to upload, if media upload request
- # @option options [#to_json, #to_hash] :body_object
- # Main body of the API request. Typically hash or object that can
- # be serialized to JSON
- # @option options [#read, #to_str] :body
- # Raw body to send in POST/PUT requests
- # @option options [String, Addressable::URI] :uri
- # URI to request. Either :api_method or :uri must be specified
- # @option options [String, Symbol] :http_method
- # HTTP method when requesting a URI
- def initialize(options={})
- @parameters = Faraday::Utils::ParamsHash.new
- @headers = Faraday::Utils::Headers.new
-
- self.parameters.merge!(options[:parameters]) unless options[:parameters].nil?
- self.headers.merge!(options[:headers]) unless options[:headers].nil?
- self.api_method = options[:api_method]
- self.authenticated = options[:authenticated]
- self.authorization = options[:authorization]
-
- # These parameters are handled differently because they're not
- # parameters to the API method, but rather to the API system.
- self.parameters['key'] ||= options[:key] if options[:key]
- self.parameters['userIp'] ||= options[:user_ip] if options[:user_ip]
-
- if options[:media]
- self.initialize_media_upload(options)
- elsif options[:body]
- self.body = options[:body]
- elsif options[:body_object]
- self.headers['Content-Type'] ||= 'application/json'
- self.body = serialize_body(options[:body_object])
- else
- self.body = ''
- end
-
- unless self.api_method
- self.http_method = options[:http_method] || 'GET'
- self.uri = options[:uri]
- end
- end
-
- # @!attribute [r] upload_type
- # @return [String] protocol used for upload
- def upload_type
- return self.parameters['uploadType'] || self.parameters['upload_type']
- end
-
- # @!attribute http_method
- # @return [Symbol] HTTP method if invoking a URI
- def http_method
- return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
- end
-
- def http_method=(new_http_method)
- if new_http_method.kind_of?(Symbol)
- @http_method = new_http_method.to_s.downcase.to_sym
- elsif new_http_method.respond_to?(:to_str)
- @http_method = new_http_method.to_s.downcase.to_sym
- else
- raise TypeError,
- "Expected String or Symbol, got #{new_http_method.class}."
- end
- end
-
- def api_method=(new_api_method)
- if new_api_method.nil? || new_api_method.kind_of?(Google::APIClient::Method)
- @api_method = new_api_method
- else
- raise TypeError,
- "Expected Google::APIClient::Method, got #{new_api_method.class}."
- end
- end
-
- # @!attribute uri
- # @return [Addressable::URI] URI to send request
- def uri
- return @uri ||= self.api_method.generate_uri(self.parameters)
- end
-
- def uri=(new_uri)
- @uri = Addressable::URI.parse(new_uri)
- @parameters.update(@uri.query_values) unless @uri.query_values.nil?
- end
-
-
- # Transmits the request with the given connection
- #
- # @api private
- #
- # @param [Faraday::Connection] connection
- # the connection to transmit with
- # @param [TrueValue,FalseValue] is_retry
- # True if request has been previous sent
- #
- # @return [Google::APIClient::Result]
- # result of API request
- def send(connection, is_retry = false)
- self.body.rewind if is_retry && self.body.respond_to?(:rewind)
- env = self.to_env(connection)
- logger.debug { "#{self.class} Sending API request #{env[:method]} #{env[:url].to_s} #{env[:request_headers]}" }
- http_response = connection.app.call(env)
- result = self.process_http_response(http_response)
-
- logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
-
- # Resumamble slightly different than other upload protocols in that it requires at least
- # 2 requests.
- if result.status == 200 && self.upload_type == 'resumable' && self.media
- upload = result.resumable_upload
- unless upload.complete?
- logger.debug { "#{self.class} Sending upload body" }
- result = upload.send(connection)
- end
- end
- return result
- end
-
- # Convert to an HTTP request. Returns components in order of method, URI,
- # request headers, and body
- #
- # @api private
- #
- # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
- def to_http_request
- request = (
- if self.api_method
- self.api_method.generate_request(self.parameters, self.body, self.headers)
- elsif self.uri
- unless self.parameters.empty?
- self.uri.query = Addressable::URI.form_encode(self.parameters)
- end
- [self.http_method, self.uri.to_s, self.headers, self.body]
- end)
- return request
- end
-
- ##
- # Hashified verison of the API request
- #
- # @return [Hash]
- def to_hash
- options = {}
- if self.api_method
- options[:api_method] = self.api_method
- options[:parameters] = self.parameters
- else
- options[:http_method] = self.http_method
- options[:uri] = self.uri
- end
- options[:headers] = self.headers
- options[:body] = self.body
- options[:media] = self.media
- unless self.authorization.nil?
- options[:authorization] = self.authorization
- end
- return options
- end
-
- ##
- # Prepares the request for execution, building a hash of parts
- # suitable for sending to Faraday::Connection.
- #
- # @api private
- #
- # @param [Faraday::Connection] connection
- # Connection for building the request
- #
- # @return [Hash]
- # Encoded request
- def to_env(connection)
- method, uri, headers, body = self.to_http_request
- http_request = connection.build_request(method) do |req|
- req.url(uri.to_s)
- req.headers.update(headers)
- req.body = body
- end
-
- if self.authorization.respond_to?(:generate_authenticated_request)
- http_request = self.authorization.generate_authenticated_request(
- :request => http_request,
- :connection => connection
- )
- end
-
- http_request.to_env(connection)
- end
-
- ##
- # Convert HTTP response to an API Result
- #
- # @api private
- #
- # @param [Faraday::Response] response
- # HTTP response
- #
- # @return [Google::APIClient::Result]
- # Processed API response
- def process_http_response(response)
- Result.new(self, response)
- end
-
- protected
-
- ##
- # Adjust headers & body for media uploads
- #
- # @api private
- #
- # @param [Hash] options
- # @option options [Hash, Array] :parameters
- # Request parameters for the API method.
- # @option options [Google::APIClient::UploadIO] :media
- # File to upload, if media upload request
- # @option options [#to_json, #to_hash] :body_object
- # Main body of the API request. Typically hash or object that can
- # be serialized to JSON
- # @option options [#read, #to_str] :body
- # Raw body to send in POST/PUT requests
- def initialize_media_upload(options)
- self.media = options[:media]
- case self.upload_type
- when "media"
- if options[:body] || options[:body_object]
- raise ArgumentError, "Can not specify body & body object for simple uploads"
- end
- self.headers['Content-Type'] ||= self.media.content_type
- self.headers['Content-Length'] ||= self.media.length.to_s
- self.body = self.media
- when "multipart"
- unless options[:body_object]
- raise ArgumentError, "Multipart requested but no body object"
- end
- metadata = StringIO.new(serialize_body(options[:body_object]))
- build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
- when "resumable"
- file_length = self.media.length
- self.headers['X-Upload-Content-Type'] = self.media.content_type
- self.headers['X-Upload-Content-Length'] = file_length.to_s
- if options[:body_object]
- self.headers['Content-Type'] ||= 'application/json'
- self.body = serialize_body(options[:body_object])
- else
- self.body = ''
- end
- end
- end
-
- ##
- # Assemble a multipart message from a set of parts
- #
- # @api private
- #
- # @param [Array<[#read,#to_str]>] parts
- # Array of parts to encode.
- # @param [String] mime_type
- # MIME type of the message
- # @param [String] boundary
- # Boundary for separating each part of the message
- def build_multipart(parts, mime_type = 'multipart/related', boundary = MULTIPART_BOUNDARY)
- env = Faraday::Env.new
- env.request = Faraday::RequestOptions.new
- env.request.boundary = boundary
- env.request_headers = {'Content-Type' => "#{mime_type};boundary=#{boundary}"}
- multipart = Faraday::Request::Multipart.new
- self.body = multipart.create_multipart(env, parts.map {|part| [nil, part]})
- self.headers.update(env[:request_headers])
- end
-
- ##
- # Serialize body object to JSON
- #
- # @api private
- #
- # @param [#to_json,#to_hash] body
- # object to serialize
- #
- # @return [String]
- # JSON
- def serialize_body(body)
- return body.to_json if body.respond_to?(:to_json)
- return MultiJson.dump(body.to_hash) if body.respond_to?(:to_hash)
- raise TypeError, 'Could not convert body object to JSON.' +
- 'Must respond to :to_json or :to_hash.'
- end
-
- end
- end
-end
diff --git a/lib/google/api_client/result.rb b/lib/google/api_client/result.rb
deleted file mode 100644
index 090f22947..000000000
--- a/lib/google/api_client/result.rb
+++ /dev/null
@@ -1,259 +0,0 @@
-# Copyright 2010 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-module Google
- class APIClient
- ##
- # This class wraps a result returned by an API call.
- class Result
- extend Forwardable
-
- ##
- # Init the result
- #
- # @param [Google::APIClient::Request] request
- # The original request
- # @param [Faraday::Response] response
- # Raw HTTP Response
- def initialize(request, response)
- @request = request
- @response = response
- @media_upload = reference if reference.kind_of?(ResumableUpload)
- end
-
- # @return [Google::APIClient::Request] Original request object
- attr_reader :request
- # @return [Faraday::Response] HTTP response
- attr_reader :response
- # @!attribute [r] reference
- # @return [Google::APIClient::Request] Original request object
- # @deprecated See {#request}
- alias_method :reference, :request # For compatibility with pre-beta clients
-
- # @!attribute [r] status
- # @return [Fixnum] HTTP status code
- # @!attribute [r] headers
- # @return [Hash] HTTP response headers
- # @!attribute [r] body
- # @return [String] HTTP response body
- def_delegators :@response, :status, :headers, :body
-
- # @!attribute [r] resumable_upload
- # @return [Google::APIClient::ResumableUpload] For resuming media uploads
- def resumable_upload
- @media_upload ||= (
- options = self.reference.to_hash.merge(
- :uri => self.headers['location'],
- :media => self.reference.media
- )
- Google::APIClient::ResumableUpload.new(options)
- )
- end
-
- ##
- # Get the content type of the response
- # @!attribute [r] media_type
- # @return [String]
- # Value of content-type header
- def media_type
- _, content_type = self.headers.detect do |h, v|
- h.downcase == 'Content-Type'.downcase
- end
- if content_type
- return content_type[/^([^;]*);?.*$/, 1].strip.downcase
- else
- return nil
- end
- end
-
- ##
- # Check if request failed - which is anything other than 200/201 OK
- #
- # @!attribute [r] error?
- # @return [TrueClass, FalseClass]
- # true if result of operation is an error
- def error?
- return !self.success?
- end
-
- ##
- # Check if request was successful
- #
- # @!attribute [r] success?
- # @return [TrueClass, FalseClass]
- # true if result of operation was successful
- def success?
- if self.response.status == 200 || self.response.status == 201
- return true
- else
- return false
- end
- end
-
- ##
- # Extracts error messages from the response body
- #
- # @!attribute [r] error_message
- # @return [String]
- # error message, if available
- def error_message
- if self.data?
- if self.data.respond_to?(:error) &&
- self.data.error.respond_to?(:message)
- # You're going to get a terrible error message if the response isn't
- # parsed successfully as an error.
- return self.data.error.message
- elsif self.data['error'] && self.data['error']['message']
- return self.data['error']['message']
- end
- end
- return self.body
- end
-
- ##
- # Check for parsable data in response
- #
- # @!attribute [r] data?
- # @return [TrueClass, FalseClass]
- # true if body can be parsed
- def data?
- !(self.body.nil? || self.body.empty? || self.media_type != 'application/json')
- end
-
- ##
- # Return parsed version of the response body.
- #
- # @!attribute [r] data
- # @return [Object, Hash, String]
- # Object if body parsable from API schema, Hash if JSON, raw body if unable to parse
- def data
- return @data ||= (begin
- if self.data?
- media_type = self.media_type
- data = self.body
- case media_type
- when 'application/json'
- data = MultiJson.load(data)
- # Strip data wrapper, if present
- data = data['data'] if data.has_key?('data')
- else
- raise ArgumentError,
- "Content-Type not supported for parsing: #{media_type}"
- end
- if @request.api_method && @request.api_method.response_schema
- # Automatically parse using the schema designated for the
- # response of this API method.
- data = @request.api_method.response_schema.new(data)
- data
- else
- # Otherwise, return the raw unparsed value.
- # This value must be indexable like a Hash.
- data
- end
- end
- end)
- end
-
- ##
- # Get the token used for requesting the next page of data
- #
- # @!attribute [r] next_page_token
- # @return [String]
- # next page token
- def next_page_token
- if self.data.respond_to?(:next_page_token)
- return self.data.next_page_token
- elsif self.data.respond_to?(:[])
- return self.data["nextPageToken"]
- else
- raise TypeError, "Data object did not respond to #next_page_token."
- end
- end
-
- ##
- # Build a request for fetching the next page of data
- #
- # @return [Google::APIClient::Request]
- # API request for retrieving next page, nil if no page token available
- def next_page
- return nil unless self.next_page_token
- merged_parameters = Hash[self.reference.parameters].merge({
- self.page_token_param => self.next_page_token
- })
- # Because Requests can be coerced to Hashes, we can merge them,
- # preserving all context except the API method parameters that we're
- # using for pagination.
- return Google::APIClient::Request.new(
- Hash[self.reference].merge(:parameters => merged_parameters)
- )
- end
-
- ##
- # Get the token used for requesting the previous page of data
- #
- # @!attribute [r] prev_page_token
- # @return [String]
- # previous page token
- def prev_page_token
- if self.data.respond_to?(:prev_page_token)
- return self.data.prev_page_token
- elsif self.data.respond_to?(:[])
- return self.data["prevPageToken"]
- else
- raise TypeError, "Data object did not respond to #next_page_token."
- end
- end
-
- ##
- # Build a request for fetching the previous page of data
- #
- # @return [Google::APIClient::Request]
- # API request for retrieving previous page, nil if no page token available
- def prev_page
- return nil unless self.prev_page_token
- merged_parameters = Hash[self.reference.parameters].merge({
- self.page_token_param => self.prev_page_token
- })
- # Because Requests can be coerced to Hashes, we can merge them,
- # preserving all context except the API method parameters that we're
- # using for pagination.
- return Google::APIClient::Request.new(
- Hash[self.reference].merge(:parameters => merged_parameters)
- )
- end
-
- ##
- # Pagination scheme used by this request/response
- #
- # @!attribute [r] pagination_type
- # @return [Symbol]
- # currently always :token
- def pagination_type
- return :token
- end
-
- ##
- # Name of the field that contains the pagination token
- #
- # @!attribute [r] page_token_param
- # @return [String]
- # currently always 'pageToken'
- def page_token_param
- return "pageToken"
- end
-
- end
- end
-end
diff --git a/lib/google/api_client/service.rb b/lib/google/api_client/service.rb
deleted file mode 100755
index d80257a89..000000000
--- a/lib/google/api_client/service.rb
+++ /dev/null
@@ -1,235 +0,0 @@
-# Copyright 2013 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-require 'google/api_client'
-require 'google/api_client/service/stub_generator'
-require 'google/api_client/service/resource'
-require 'google/api_client/service/request'
-require 'google/api_client/service/result'
-require 'google/api_client/service/batch'
-require 'google/api_client/service/simple_file_store'
-
-module Google
- class APIClient
-
- ##
- # Experimental new programming interface at the API level.
- # Hides Google::APIClient. Designed to be easier to use, with less code.
- #
- # @example
- # calendar = Google::APIClient::Service.new('calendar', 'v3')
- # result = calendar.events.list('calendarId' => 'primary').execute()
- class Service
- include Google::APIClient::Service::StubGenerator
- extend Forwardable
-
- DEFAULT_CACHE_FILE = 'discovery.cache'
-
- # Cache for discovered APIs.
- @@discovered = {}
-
- ##
- # Creates a new Service.
- #
- # @param [String, Symbol] api_name
- # The name of the API this service will access.
- # @param [String, Symbol] api_version
- # The version of the API this service will access.
- # @param [Hash] options
- # The configuration parameters for the service.
- # @option options [Symbol, #generate_authenticated_request] :authorization
- # (:oauth_1)
- # The authorization mechanism used by the client. The following
- # mechanisms are supported out-of-the-box:
- # :two_legged_oauth_1
:oauth_1
:oauth_2
blocks like blocks.
- data = data.gsub(/\(.+)\<\/code\>/, "`\\1`")
- super(object, data)
- end
-
- def serialized_path(object)
- return object if object.is_a?(String)
-
- if object.is_a?(CodeObjects::ExtraFileObject)
- fspath = ['file.' + object.name + (extension.empty? ? '' : ".#{extension}")]
- else
- # This line is the only change of significance.
- # Changed from 'top-level-namespace' to 'TopLevelNamespace' to
- # conform to wiki word page naming convention.
- objname = object != YARD::Registry.root ? object.name.to_s : "TopLevelNamespace"
- objname += '_' + object.scope.to_s[0,1] if object.is_a?(CodeObjects::MethodObject)
- fspath = [objname + (extension.empty? ? '' : ".#{extension}")]
- if object.namespace && object.namespace.path != ""
- fspath.unshift(*object.namespace.path.split(CodeObjects::NSEP))
- end
- end
-
- # Don't change the filenames, it just makes it more complicated
- # to figure out the original name.
- #fspath.map! do |p|
- # p.gsub(/([a-z])([A-Z])/, '\1_\2').downcase
- #end
-
- # Remove special chars from filenames.
- # Windows disallows \ / : * ? " < > | but we will just remove any
- # non alphanumeric (plus period, underscore and dash).
- fspath.map! do |p|
- p.gsub(/[^\w\.-]/) do |x|
- encoded = '_'
-
- x.each_byte { |b| encoded << ("%X" % b) }
- encoded
- end
- end
- fspath.join("")
- end
- end
- end
-end
diff --git a/yard/lib/yard/templates/helpers/wiki_helper.rb b/yard/lib/yard/templates/helpers/wiki_helper.rb
deleted file mode 100644
index e03dfb668..000000000
--- a/yard/lib/yard/templates/helpers/wiki_helper.rb
+++ /dev/null
@@ -1,502 +0,0 @@
-require 'cgi'
-require 'rdiscount'
-
-module YARD
- module Templates::Helpers
- # The helper module for HTML templates.
- module WikiHelper
- include MarkupHelper
-
- # @return [String] escapes text
- def h(text)
- out = ""
- text = text.split(/\n/)
- text.each_with_index do |line, i|
- out <<
- case line
- when /^\s*$/; "\n\n"
- when /^\s+\S/, /^=/; line + "\n"
- else; line + (text[i + 1] =~ /^\s+\S/ ? "\n" : " ")
- end
- end
- out.strip
- end
-
- # @return [String] wraps text at +col+ columns.
- def wrap(text, col = 72)
- text.strip.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/, "\\1\\3\n")
- end
-
- # Escapes a URL
- #
- # @param [String] text the URL
- # @return [String] the escaped URL
- def urlencode(text)
- CGI.escape(text.to_s)
- end
-
- def indent(text, len = 2)
- text.gsub(/^/, ' ' * len)
- end
-
- def unindent(text)
- lines = text.split("\n", -1)
- min_indent_size = text.size
- for line in lines
- indent_size = (line.gsub("\t", " ") =~ /[^\s]/) || text.size
- min_indent_size = indent_size if indent_size < min_indent_size
- end
- text.gsub("\t", " ").gsub(Regexp.new("^" + " " * min_indent_size), '')
- end
-
- # @group Converting Markup to HTML
-
- # Turns text into HTML using +markup+ style formatting.
- #
- # @param [String] text the text to format
- # @param [Symbol] markup examples are +:markdown+, +:textile+, +:rdoc+.
- # To add a custom markup type, see {MarkupHelper}
- # @return [String] the HTML
- def htmlify(text, markup = options[:markup])
- markup_meth = "html_markup_#{markup}"
- return text unless respond_to?(markup_meth)
- return "" unless text
- return text unless markup
- load_markup_provider(markup)
- html = send(markup_meth, text)
- if html.respond_to?(:encode)
- html = html.force_encoding(text.encoding) # for libs that mess with encoding
- html = html.encode(:invalid => :replace, :replace => '?')
- end
- html = resolve_links(html)
- html = html.gsub(/(?:\s*)?(.+?)(?:<\/code>\s*)?<\/pre>/m) do
- str = unindent($1).strip
- str = html_syntax_highlight(CGI.unescapeHTML(str)) unless options[:no_highlight]
- str
- end unless markup == :text
- html
- end
-
- # Converts Markdown to HTML
- # @param [String] text input Markdown text
- # @return [String] output HTML
- # @since 0.6.0
- def html_markup_markdown(text)
- Markdown.new(text).to_html
- end
-
- # Converts Textile to HTML
- # @param [String] text the input Textile text
- # @return [String] output HTML
- # @since 0.6.0
- def html_markup_textile(text)
- doc = markup_class(:textile).new(text)
- doc.hard_breaks = false if doc.respond_to?(:hard_breaks=)
- doc.to_html
- end
-
- # Converts plaintext to HTML
- # @param [String] text the input text
- # @return [String] the output HTML
- # @since 0.6.0
- def html_markup_text(text)
- "" + text + "
"
- end
-
- # Converts HTML to HTML
- # @param [String] text input html
- # @return [String] output HTML
- # @since 0.6.0
- def html_markup_html(text)
- text
- end
-
- # @return [String] HTMLified text as a single line (paragraphs removed)
- def htmlify_line(*args)
- htmlify(*args)
- end
-
- # Fixes RDoc behaviour with ++ only supporting alphanumeric text.
- #
- # @todo Refactor into own SimpleMarkup subclass
- def fix_typewriter(text)
- text.gsub(/\+(?! )([^\n\+]{1,900})(?! )\+/) do
- type_text, pre_text, no_match = $1, $`, $&
- pre_match = pre_text.scan(%r(?(?:pre|tt|code).*?>))
- if pre_match.last.nil? || pre_match.last.include?('/')
- '`' + h(type_text) + '`'
- else
- no_match
- end
- end
- end
-
- # Don't allow -- to turn into — element. The chances of this being
- # some --option is far more likely than the typographical meaning.
- #
- # @todo Refactor into own SimpleMarkup subclass
- def fix_dash_dash(text)
- text.gsub(/—(?=\S)/, '--')
- end
-
- # @group Syntax Highlighting Source Code
-
- # Syntax highlights +source+ in language +type+.
- #
- # @note To support a specific language +type+, implement the method
- # +html_syntax_highlight_TYPE+ in this class.
- #
- # @param [String] source the source code to highlight
- # @param [Symbol] type the language type (:ruby, :plain, etc). Use
- # :plain for no syntax highlighting.
- # @return [String] the highlighted source
- def html_syntax_highlight(source, type = nil)
- return "" unless source
- return "{{{\n#{source}\n}}}"
- end
-
- # @return [String] unhighlighted source
- def html_syntax_highlight_plain(source)
- return "" unless source
- return "{{{\n#{source}\n}}}"
- end
-
- # @group Linking Objects and URLs
-
- # Resolves any text in the form of +{Name}+ to the object specified by
- # Name. Also supports link titles in the form +{Name title}+.
- #
- # @example Linking to an instance method
- # resolve_links("{MyClass#method}") # => "MyClass#method"
- # @example Linking to a class with a title
- # resolve_links("{A::B::C the C class}") # => "the c class"
- # @param [String] text the text to resolve links in
- # @return [String] HTML with linkified references
- def resolve_links(text)
- code_tags = 0
- text.gsub(/<(\/)?(pre|code|tt)|\{(\S+?)(?:\s(.*?\S))?\}(?=[\W<]|.+<\/|$)/) do |str|
- closed, tag, name, title, match = $1, $2, $3, $4, $&
- if tag
- code_tags += (closed ? -1 : 1)
- next str
- end
- next str unless code_tags == 0
-
- next(match) if name[0,1] == '|'
- if object.is_a?(String)
- object
- else
- link = linkify(name, title)
- if link == name || link == title
- match = /(.+)?(\{#{Regexp.quote name}(?:\s.*?)?\})(.+)?/.match(text)
- file = (@file ? @file : object.file) || '(unknown)'
- line = (@file ? 1 : (object.docstring.line_range ? object.docstring.line_range.first : 1)) + (match ? $`.count("\n") : 0)
- log.warn "In file `#{file}':#{line}: Cannot resolve link to #{name} from text" + (match ? ":" : ".")
- log.warn((match[1] ? '...' : '') + match[2].gsub("\n","") + (match[3] ? '...' : '')) if match
- end
-
- link
- end
- end
- end
-
- def unlink(value)
- value.gsub(/\b(([A-Z][a-z]+){2,99})\b/, "!\\1")
- end
-
- # (see BaseHelper#link_file)
- def link_file(filename, title = nil, anchor = nil)
- link_url(url_for_file(filename, anchor), title)
- end
-
- # (see BaseHelper#link_include_object)
- def link_include_object(obj)
- htmlify(obj.docstring)
- end
-
- # (see BaseHelper#link_object)
- def link_object(obj, otitle = nil, anchor = nil, relative = true)
- return otitle if obj.nil?
- obj = Registry.resolve(object, obj, true, true) if obj.is_a?(String)
- if !otitle && obj.root?
- title = "Top Level Namespace"
- elsif otitle
- # title = "`" + otitle.to_s + "`"
- title = otitle.to_s
- elsif object.is_a?(CodeObjects::Base)
- # title = "`" + h(object.relative_path(obj)) + "`"
- title = h(object.relative_path(obj))
- else
- # title = "`" + h(obj.to_s) + "`"
- title = h(obj.to_s)
- end
- unless serializer
- return unlink(title)
- end
- return unlink(title) if obj.is_a?(CodeObjects::Proxy)
-
- link = url_for(obj, anchor, relative)
- if link
- link_url(link, title, :formatted => false)
- else
- unlink(title)
- end
- end
-
- # (see BaseHelper#link_url)
- def link_url(url, title = nil, params = {})
- title ||= url
- if url.to_s == ""
- title
- else
- if params[:formatted]
- "#{title}"
- else
- "[#{url} #{title}]"
- end
- end
- end
-
- # @group URL Helpers
-
- # @param [CodeObjects::Base] object the object to get an anchor for
- # @return [String] the anchor for a specific object
- def anchor_for(object)
- # Method:_Google::APIClient#execute!
- case object
- when CodeObjects::MethodObject
- if object.scope == :instance
- "Method:_#{object.path}"
- elsif object.scope == :class
- "Method:_#{object.path}"
- end
- when CodeObjects::ClassVariableObject
- "#{object.name.to_s.gsub('@@', '')}-#{object.type}"
- when CodeObjects::Base
- "#{object.name}-#{object.type}"
- when CodeObjects::Proxy
- object.path
- else
- object.to_s
- end
- end
-
- # Returns the URL for an object.
- #
- # @param [String, CodeObjects::Base] obj the object (or object path) to link to
- # @param [String] anchor the anchor to link to
- # @param [Boolean] relative use a relative or absolute link
- # @return [String] the URL location of the object
- def url_for(obj, anchor = nil, relative = true)
- link = nil
- return link unless serializer
- if obj.kind_of?(CodeObjects::Base) && obj.root?
- return 'TopLevelNamespace'
- end
-
- if obj.is_a?(CodeObjects::Base) && !obj.is_a?(CodeObjects::NamespaceObject)
- # If the obj is not a namespace obj make it the anchor.
- anchor, obj = obj, obj.namespace
- end
-
- objpath = serializer.serialized_path(obj)
- return link unless objpath
-
- if relative
- fromobj = object
- if object.is_a?(CodeObjects::Base) &&
- !object.is_a?(CodeObjects::NamespaceObject)
- fromobj = fromobj.namespace
- end
-
- from = serializer.serialized_path(fromobj)
- link = File.relative_path(from, objpath)
- else
- link = objpath
- end
-
- return (
- link.gsub(/\.html$/, '').gsub(/\.wiki$/, '') +
- (anchor ? '#' + urlencode(anchor_for(anchor)) : '')
- )
- end
-
- # Returns the URL for a specific file
- #
- # @param [String] filename the filename to link to
- # @param [String] anchor optional anchor
- # @return [String] the URL pointing to the file
- def url_for_file(filename, anchor = nil)
- fromobj = object
- if CodeObjects::Base === fromobj && !fromobj.is_a?(CodeObjects::NamespaceObject)
- fromobj = fromobj.namespace
- end
- from = serializer.serialized_path(fromobj)
- if filename == options[:readme]
- filename = 'Documentation'
- else
- filename = File.basename(filename).gsub(/\.[^.]+$/, '').capitalize
- end
- link = File.relative_path(from, filename)
- return (
- link.gsub(/\.html$/, '').gsub(/\.wiki$/, '') +
- (anchor ? '#' + urlencode(anchor) : '')
- )
- end
-
- # @group Formatting Objects and Attributes
-
- # Formats a list of objects and links them
- # @return [String] a formatted list of objects
- def format_object_name_list(objects)
- objects.sort_by {|o| o.name.to_s.downcase }.map do |o|
- "" + linkify(o, o.name) + ""
- end.join(", ")
- end
-
- # Formats a list of types from a tag.
- #
- # @param [Array, FalseClass] typelist
- # the list of types to be formatted.
- #
- # @param [Boolean] brackets omits the surrounding
- # brackets if +brackets+ is set to +false+.
- #
- # @return [String] the list of types formatted
- # as [Type1, Type2, ...] with the types linked
- # to their respective descriptions.
- #
- def format_types(typelist, brackets = true)
- return unless typelist.is_a?(Array)
- list = typelist.map do |type|
- type = type.gsub(/([<>])/) { h($1) }
- type = type.gsub(/([\w:]+)/) do
- $1 == "lt" || $1 == "gt" ? "`#{$1}`" : linkify($1, $1)
- end
- end
- list.empty? ? "" : (brackets ? "(#{list.join(", ")})" : list.join(", "))
- end
-
- # Get the return types for a method signature.
- #
- # @param [CodeObjects::MethodObject] meth the method object
- # @param [Boolean] link whether to link the types
- # @return [String] the signature types
- # @since 0.5.3
- def signature_types(meth, link = true)
- meth = convert_method_to_overload(meth)
-
- type = options[:default_return] || ""
- if meth.tag(:return) && meth.tag(:return).types
- types = meth.tags(:return).map {|t| t.types ? t.types : [] }.flatten.uniq
- first = link ? h(types.first) : format_types([types.first], false)
- if types.size == 2 && types.last == 'nil'
- type = first + '?'
- elsif types.size == 2 && types.last =~ /^(Array)?<#{Regexp.quote types.first}>$/
- type = first + '+'
- elsif types.size > 2
- type = [first, '...'].join(', ')
- elsif types == ['void'] && options[:hide_void_return]
- type = ""
- else
- type = link ? h(types.join(", ")) : format_types(types, false)
- end
- elsif !type.empty?
- type = link ? h(type) : format_types([type], false)
- end
- type = "(#{type.to_s.strip}) " unless type.empty?
- type
- end
-
- # Formats the signature of method +meth+.
- #
- # @param [CodeObjects::MethodObject] meth the method object to list
- # the signature of
- # @param [Boolean] link whether to link the method signature to the details view
- # @param [Boolean] show_extras whether to show extra meta-data (visibility, attribute info)
- # @param [Boolean] full_attr_name whether to show the full attribute name
- # ("name=" instead of "name")
- # @return [String] the formatted method signature
- def signature(meth, link = true, show_extras = true, full_attr_name = true)
- meth = convert_method_to_overload(meth)
-
- type = signature_types(meth, link)
- name = full_attr_name ? meth.name : meth.name.to_s.gsub(/^(\w+)=$/, '\1')
- blk = format_block(meth)
- args = !full_attr_name && meth.writer? ? "" : format_args(meth)
- extras = []
- extras_text = ''
- if show_extras
- if rw = meth.attr_info
- attname = [rw[:read] ? 'read' : nil, rw[:write] ? 'write' : nil].compact
- attname = attname.size == 1 ? attname.join('') + 'only' : nil
- extras << attname if attname
- end
- extras << meth.visibility if meth.visibility != :public
- extras_text = ' (' + extras.join(", ") + ')' unless extras.empty?
- end
- title = "%s *`%s`* `%s` `%s`" % [type, h(name.to_s).strip, args, blk]
- title.gsub!(//, "")
- title.gsub!(/<\/tt>/, "")
- title.gsub!(/`\s*`/, "")
- title.strip!
- if link
- if meth.is_a?(YARD::CodeObjects::MethodObject)
- link_title =
- "#{h meth.name(true)} (#{meth.scope} #{meth.type})"
- else
- link_title = "#{h name} (#{meth.type})"
- end
- # This has to be raw HTML, can't wiki-format a link title otherwise.
- "#{title}#{extras_text}"
- else
- title + extras_text
- end
- end
-
- # @group Getting the Character Encoding
-
- # Returns the current character set. The default value can be overridden
- # by setting the +LANG+ environment variable or by overriding this
- # method. In Ruby 1.9 you can also modify this value by setting
- # +Encoding.default_external+.
- #
- # @return [String] the current character set
- # @since 0.5.4
- def charset
- return 'utf-8' unless RUBY19 || lang = ENV['LANG']
- if RUBY19
- lang = Encoding.default_external.name.downcase
- else
- lang = lang.downcase.split('.').last
- end
- case lang
- when "ascii-8bit", "us-ascii", "ascii-7bit"; 'iso-8859-1'
- else; lang
- end
- end
-
- # @endgroup
-
- private
-
- # Converts a set of hash options into HTML attributes for a tag
- #
- # @param [Hash{String => String}] opts the tag options
- # @return [String] the tag attributes of an HTML tag
- def tag_attrs(opts = {})
- opts.sort_by {|k, v| k.to_s }.map {|k,v| "#{k}=#{v.to_s.inspect}" if v }.join(" ")
- end
-
- # Converts a {CodeObjects::MethodObject} into an overload object
- # @since 0.5.3
- def convert_method_to_overload(meth)
- # use first overload tag if it has a return type and method itself does not
- if !meth.tag(:return) && meth.tags(:overload).size == 1 && meth.tag(:overload).tag(:return)
- return meth.tag(:overload)
- end
- meth
- end
- end
- end
-end
diff --git a/yard/templates/default/class/setup.rb b/yard/templates/default/class/setup.rb
deleted file mode 100644
index 0b4dc12f8..000000000
--- a/yard/templates/default/class/setup.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-include T('default/module')
-
-def init
- super
- sections.place(:subclasses).before(:children)
- sections.place(:constructor_details, [T('method_details')]).before(:methodmissing)
- # Weird bug w/ doubled sections
- sections.uniq!
-end
-
-def constructor_details
- ctors = object.meths(:inherited => true, :included => true)
- return unless @ctor = ctors.find {|o| o.name == :initialize }
- return if prune_method_listing([@ctor]).empty?
- erb(:constructor_details)
-end
-
-def subclasses
- return if object.path == "Object" # don't show subclasses for Object
- unless globals.subclasses
- globals.subclasses = {}
- list = run_verifier Registry.all(:class)
- list.each do |o|
- (globals.subclasses[o.superclass.path] ||= []) << o if o.superclass
- end
- end
-
- @subclasses = globals.subclasses[object.path]
- return if @subclasses.nil? || @subclasses.empty?
- @subclasses = @subclasses.sort_by {|o| o.path }.map do |child|
- name = child.path
- if object.namespace
- name = object.relative_path(child)
- end
- [name, child]
- end
- erb(:subclasses)
-end
\ No newline at end of file
diff --git a/yard/templates/default/docstring/setup.rb b/yard/templates/default/docstring/setup.rb
deleted file mode 100644
index 63a5877fb..000000000
--- a/yard/templates/default/docstring/setup.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-def init
- return if object.docstring.blank? && !object.has_tag?(:api)
- sections :index, [:private, :deprecated, :abstract, :todo, :note, :returns_void, :text], T('tags')
-end
-
-def private
- return unless object.has_tag?(:api) && object.tag(:api).text == 'private'
- erb(:private)
-end
-
-def abstract
- return unless object.has_tag?(:abstract)
- erb(:abstract)
-end
-
-def deprecated
- return unless object.has_tag?(:deprecated)
- erb(:deprecated)
-end
-
-def todo
- return unless object.has_tag?(:todo)
- erb(:todo)
-end
-
-def note
- return unless object.has_tag?(:note)
- erb(:note)
-end
-
-def returns_void
- return unless object.type == :method
- return if object.name == :initialize && object.scope == :instance
- return unless object.tags(:return).size == 1 && object.tag(:return).types == ['void']
- erb(:returns_void)
-end
-
-def docstring_text
- text = ""
- unless object.tags(:overload).size == 1 && object.docstring.empty?
- text = object.docstring
- end
-
- if text.strip.empty? && object.tags(:return).size == 1 && object.tag(:return).text
- text = object.tag(:return).text.gsub(/\A([a-z])/) {|x| x.upcase }
- end
-
- text.strip
-end
\ No newline at end of file
diff --git a/yard/templates/default/method/setup.rb b/yard/templates/default/method/setup.rb
deleted file mode 100644
index a6ed29924..000000000
--- a/yard/templates/default/method/setup.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-def init
- sections :header, [T('method_details')]
-end
\ No newline at end of file
diff --git a/yard/templates/default/method_details/setup.rb b/yard/templates/default/method_details/setup.rb
deleted file mode 100644
index e3bfea003..000000000
--- a/yard/templates/default/method_details/setup.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-def init
- sections :header, [:method_signature, T('docstring')]
-end
diff --git a/yard/templates/default/module/setup.rb b/yard/templates/default/module/setup.rb
deleted file mode 100644
index d2559eaa4..000000000
--- a/yard/templates/default/module/setup.rb
+++ /dev/null
@@ -1,133 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-include Helpers::ModuleHelper
-
-def init
- sections :header, :box_info, :pre_docstring, T('docstring'), :children,
- :constant_summary, [T('docstring')], :inherited_constants,
- :inherited_methods,
- :methodmissing, [T('method_details')],
- :attribute_details, [T('method_details')],
- :method_details_list, [T('method_details')]
-end
-
-def pre_docstring
- return if object.docstring.blank?
- erb(:pre_docstring)
-end
-
-def children
- @inner = [[:modules, []], [:classes, []]]
- object.children.each do |child|
- @inner[0][1] << child if child.type == :module
- @inner[1][1] << child if child.type == :class
- end
- @inner.map! {|v| [v[0], run_verifier(v[1].sort_by {|o| o.name.to_s })] }
- return if (@inner[0][1].size + @inner[1][1].size) == 0
- erb(:children)
-end
-
-def methodmissing
- mms = object.meths(:inherited => true, :included => true)
- return unless @mm = mms.find {|o| o.name == :method_missing && o.scope == :instance }
- erb(:methodmissing)
-end
-
-def method_listing(include_specials = true)
- return @smeths ||= method_listing.reject {|o| special_method?(o) } unless include_specials
- return @meths if @meths
- @meths = object.meths(:inherited => false, :included => false)
- @meths = sort_listing(prune_method_listing(@meths))
- @meths
-end
-
-def special_method?(meth)
- return true if meth.name(true) == '#method_missing'
- return true if meth.constructor?
- false
-end
-
-def attr_listing
- return @attrs if @attrs
- @attrs = []
- [:class, :instance].each do |scope|
- object.attributes[scope].each do |name, rw|
- @attrs << (rw[:read] || rw[:write])
- end
- end
- @attrs = sort_listing(prune_method_listing(@attrs, false))
-end
-
-def constant_listing
- return @constants if @constants
- @constants = object.constants(:included => false, :inherited => false)
- @constants += object.cvars
- @constants = run_verifier(@constants)
- @constants
-end
-
-def sort_listing(list)
- list.sort_by {|o| [o.scope.to_s, o.name.to_s.downcase] }
-end
-
-def docstring_full(obj)
- docstring = ""
- if obj.tags(:overload).size == 1 && obj.docstring.empty?
- docstring = obj.tag(:overload).docstring
- else
- docstring = obj.docstring
- end
-
- if docstring.summary.empty? && obj.tags(:return).size == 1 && obj.tag(:return).text
- docstring = Docstring.new(obj.tag(:return).text.gsub(/\A([a-z])/) {|x| x.upcase }.strip)
- end
-
- docstring
-end
-
-def docstring_summary(obj)
- docstring_full(obj).summary
-end
-
-def groups(list, type = "Method")
- if groups_data = object.groups
- others = list.select {|m| !m.group }
- groups_data.each do |name|
- items = list.select {|m| m.group == name }
- yield(items, name) unless items.empty?
- end
- else
- others = []
- group_data = {}
- list.each do |meth|
- if meth.group
- (group_data[meth.group] ||= []) << meth
- else
- others << meth
- end
- end
- group_data.each {|group, items| yield(items, group) unless items.empty? }
- end
-
- scopes(others) {|items, scope| yield(items, "#{scope.to_s.capitalize} #{type} Summary") }
-end
-
-def scopes(list)
- [:class, :instance].each do |scope|
- items = list.select {|m| m.scope == scope }
- yield(items, scope) unless items.empty?
- end
-end
-
-def mixed_into(object)
- unless globals.mixed_into
- globals.mixed_into = {}
- list = run_verifier Registry.all(:class, :module)
- list.each {|o| o.mixins.each {|m| (globals.mixed_into[m.path] ||= []) << o } }
- end
-
- globals.mixed_into[object.path] || []
-end
diff --git a/yard/templates/default/tags/setup.rb b/yard/templates/default/tags/setup.rb
deleted file mode 100644
index 33dc42cac..000000000
--- a/yard/templates/default/tags/setup.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../../lib'))
-$LOAD_PATH.unshift(lib_dir)
-$LOAD_PATH.uniq!
-require 'yard-google-code'
-
-def init
- tags = Tags::Library.visible_tags - [:abstract, :deprecated, :note, :todo]
- create_tag_methods(tags - [:example, :option, :overload, :see])
- sections :index, tags
- sections.any(:overload).push(T('docstring'))
-end
-
-def return
- if object.type == :method
- return if object.name == :initialize && object.scope == :instance
- return if object.tags(:return).size == 1 && object.tag(:return).types == ['void']
- end
- tag(:return)
-end
-
-private
-
-def tag(name, opts = nil)
- return unless object.has_tag?(name)
- opts ||= options_for_tag(name)
- @no_names = true if opts[:no_names]
- @no_types = true if opts[:no_types]
- @name = name
- out = erb('tag')
- @no_names, @no_types = nil, nil
- out
-end
-
-def create_tag_methods(tags)
- tags.each do |tag|
- next if respond_to?(tag)
- instance_eval(<<-eof, __FILE__, __LINE__ + 1)
- def #{tag}; tag(#{tag.inspect}) end
- eof
- end
-end
-
-def options_for_tag(tag)
- opts = {:no_types => true, :no_names => true}
- case Tags::Library.factory_method_for(tag)
- when :with_types
- opts[:no_types] = false
- when :with_types_and_name
- opts[:no_types] = false
- opts[:no_names] = false
- when :with_name
- opts[:no_names] = false
- end
- opts
-end