Add vendor folder to git

This commit is contained in:
Lucas Käldström 2017-06-26 19:23:05 +03:00
parent 66cf5eaafb
commit 183585f56f
No known key found for this signature in database
GPG key ID: 600FEFBBD0D40D21
6916 changed files with 2629581 additions and 1 deletions

13
vendor/github.com/googleapis/gnostic/.gitignore generated vendored Normal file
View file

@ -0,0 +1,13 @@
# Eclipse
.checkstyle
.project
.settings
# Swift
.build
Packages
# vi
*.swp
# vscode
.vscode
.DS_Store
*~

View file

@ -0,0 +1,36 @@
#!/bin/sh
#
# Install dependencies that aren't available as Ubuntu packages.
#
# Everything goes into $HOME/local.
#
# Scripts should add
# - $HOME/local/bin to PATH
# - $HOME/local/lib to LD_LIBRARY_PATH
#
cd
mkdir -p local
# Install swift
SWIFT_BRANCH=swift-3.0.2-release
SWIFT_VERSION=swift-3.0.2-RELEASE
SWIFT_PLATFORM=ubuntu14.04
SWIFT_URL=https://swift.org/builds/$SWIFT_BRANCH/$(echo "$SWIFT_PLATFORM" | tr -d .)/$SWIFT_VERSION/$SWIFT_VERSION-$SWIFT_PLATFORM.tar.gz
echo $SWIFT_URL
curl -fSsL $SWIFT_URL -o swift.tar.gz
tar -xzf swift.tar.gz --strip-components=2 --directory=local
# Install protoc
PROTOC_URL=https://github.com/google/protobuf/releases/download/v3.2.0rc2/protoc-3.2.0rc2-linux-x86_64.zip
echo $PROTOC_URL
curl -fSsL $PROTOC_URL -o protoc.zip
unzip protoc.zip -d local
# Verify installation
find local

45
vendor/github.com/googleapis/gnostic/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,45 @@
# Travis CI build file for OpenAPI Compiler, including Go and Swift plugins
# Use Ubuntu 14.04
dist: trusty
sudo: false
language: go
addons:
apt:
packages:
- clang-3.8
- lldb-3.8
- libicu-dev
- libtool
- libcurl4-openssl-dev
- libbsd-dev
- build-essential
- libssl-dev
- uuid-dev
- curl
- unzip
install:
- go get github.com/googleapis/gnostic
- go get github.com/googleapis/gnostic/plugins/go/gnostic_go_sample
- go get github.com/googleapis/gnostic/extensions/sample/generated/openapi_extensions_samplecompanyone
- go get github.com/googleapis/gnostic/extensions/sample/generated/openapi_extensions_samplecompanytwo
- ./.travis-install.sh
script:
- go test . -v
- pushd plugins/go/gnostic_go_generator/examples/v2.0/bookstore
- make test
- popd
- export PATH=.:$HOME/local/bin:$PATH
- export LD_LIBRARY_PATH=$HOME/local/lib
- pushd plugins/swift/gnostic_swift_generator
- make
- cd examples/bookstore
- make
- .build/debug/Server &
- make test

31
vendor/github.com/googleapis/gnostic/COMPILE-PROTOS.sh generated vendored Normal file
View file

@ -0,0 +1,31 @@
#!/bin/sh
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
#
go get github.com/golang/protobuf/protoc-gen-go
protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. \
OpenAPIv2/OpenAPIv2.proto
protoc \
--go_out=:. \
plugins/plugin.proto
protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. \
OpenAPIv3/OpenAPIv3.proto

35
vendor/github.com/googleapis/gnostic/CONTRIBUTING.md generated vendored Normal file
View file

@ -0,0 +1,35 @@
# How to become a contributor and submit your own code
## Contributor License Agreements
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
(CLA).
* If you are an individual writing original source code and you're sure you
own the intellectual property, then you'll need to sign an [individual CLA]
(https://developers.google.com/open-source/cla/individual).
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a [corporate CLA]
(https://developers.google.com/open-source/cla/corporate).
Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
## Contributing A Patch
1. Submit an issue describing your proposed change to the repo in question.
1. The repo owner will respond to your issue promptly.
1. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement (see details above).
1. Fork the desired repo, develop and test your code changes.
1. Ensure that your code adheres to the existing style in the sample to which
you are contributing. Refer to the
[Google Cloud Platform Samples Style Guide]
(https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the
recommended coding standards for this organization.
1. Ensure that your code has an appropriate set of unit tests which all pass.
1. Submit a pull request.

203
vendor/github.com/googleapis/gnostic/LICENSE generated vendored Normal file
View file

@ -0,0 +1,203 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

12
vendor/github.com/googleapis/gnostic/Makefile generated vendored Normal file
View file

@ -0,0 +1,12 @@
build:
go install github.com/googleapis/gnostic
go install github.com/googleapis/gnostic/apps/report
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_sample
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_generator/encode_templates
go generate github.com/googleapis/gnostic/plugins/go/gnostic_go_generator
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_generator
rm -f $(GOPATH)/bin/gnostic_go_client $(GOPATH)/bin/gnostic_go_server
ln -s $(GOPATH)/bin/gnostic_go_generator $(GOPATH)/bin/gnostic_go_client
ln -s $(GOPATH)/bin/gnostic_go_generator $(GOPATH)/bin/gnostic_go_server

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,663 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
syntax = "proto3";
package openapi.v2;
import "google/protobuf/any.proto";
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "OpenAPIProto";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapi_v2";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
option objc_class_prefix = "OAS";
message AdditionalPropertiesItem {
oneof oneof {
Schema schema = 1;
bool boolean = 2;
}
}
message Any {
google.protobuf.Any value = 1;
string yaml = 2;
}
message ApiKeySecurity {
string type = 1;
string name = 2;
string in = 3;
string description = 4;
repeated NamedAny vendor_extension = 5;
}
message BasicAuthenticationSecurity {
string type = 1;
string description = 2;
repeated NamedAny vendor_extension = 3;
}
message BodyParameter {
// A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
string description = 1;
// The name of the parameter.
string name = 2;
// Determines the location of the parameter.
string in = 3;
// Determines whether or not this parameter is required or optional.
bool required = 4;
Schema schema = 5;
repeated NamedAny vendor_extension = 6;
}
// Contact information for the owners of the API.
message Contact {
// The identifying name of the contact person/organization.
string name = 1;
// The URL pointing to the contact information.
string url = 2;
// The email address of the contact person/organization.
string email = 3;
repeated NamedAny vendor_extension = 4;
}
message Default {
repeated NamedAny additional_properties = 1;
}
// One or more JSON objects describing the schemas being consumed and produced by the API.
message Definitions {
repeated NamedSchema additional_properties = 1;
}
message Document {
// The Swagger version of this document.
string swagger = 1;
Info info = 2;
// The host (name or ip) of the API. Example: 'swagger.io'
string host = 3;
// The base path to the API. Example: '/api'.
string base_path = 4;
// The transfer protocol of the API.
repeated string schemes = 5;
// A list of MIME types accepted by the API.
repeated string consumes = 6;
// A list of MIME types the API can produce.
repeated string produces = 7;
Paths paths = 8;
Definitions definitions = 9;
ParameterDefinitions parameters = 10;
ResponseDefinitions responses = 11;
repeated SecurityRequirement security = 12;
SecurityDefinitions security_definitions = 13;
repeated Tag tags = 14;
ExternalDocs external_docs = 15;
repeated NamedAny vendor_extension = 16;
}
message Examples {
repeated NamedAny additional_properties = 1;
}
// information about external documentation
message ExternalDocs {
string description = 1;
string url = 2;
repeated NamedAny vendor_extension = 3;
}
// A deterministic version of a JSON Schema object.
message FileSchema {
string format = 1;
string title = 2;
string description = 3;
Any default = 4;
repeated string required = 5;
string type = 6;
bool read_only = 7;
ExternalDocs external_docs = 8;
Any example = 9;
repeated NamedAny vendor_extension = 10;
}
message FormDataParameterSubSchema {
// Determines whether or not this parameter is required or optional.
bool required = 1;
// Determines the location of the parameter.
string in = 2;
// A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
string description = 3;
// The name of the parameter.
string name = 4;
// allows sending a parameter by name only or with an empty value.
bool allow_empty_value = 5;
string type = 6;
string format = 7;
PrimitivesItems items = 8;
string collection_format = 9;
Any default = 10;
double maximum = 11;
bool exclusive_maximum = 12;
double minimum = 13;
bool exclusive_minimum = 14;
int64 max_length = 15;
int64 min_length = 16;
string pattern = 17;
int64 max_items = 18;
int64 min_items = 19;
bool unique_items = 20;
repeated Any enum = 21;
double multiple_of = 22;
repeated NamedAny vendor_extension = 23;
}
message Header {
string type = 1;
string format = 2;
PrimitivesItems items = 3;
string collection_format = 4;
Any default = 5;
double maximum = 6;
bool exclusive_maximum = 7;
double minimum = 8;
bool exclusive_minimum = 9;
int64 max_length = 10;
int64 min_length = 11;
string pattern = 12;
int64 max_items = 13;
int64 min_items = 14;
bool unique_items = 15;
repeated Any enum = 16;
double multiple_of = 17;
string description = 18;
repeated NamedAny vendor_extension = 19;
}
message HeaderParameterSubSchema {
// Determines whether or not this parameter is required or optional.
bool required = 1;
// Determines the location of the parameter.
string in = 2;
// A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
string description = 3;
// The name of the parameter.
string name = 4;
string type = 5;
string format = 6;
PrimitivesItems items = 7;
string collection_format = 8;
Any default = 9;
double maximum = 10;
bool exclusive_maximum = 11;
double minimum = 12;
bool exclusive_minimum = 13;
int64 max_length = 14;
int64 min_length = 15;
string pattern = 16;
int64 max_items = 17;
int64 min_items = 18;
bool unique_items = 19;
repeated Any enum = 20;
double multiple_of = 21;
repeated NamedAny vendor_extension = 22;
}
message Headers {
repeated NamedHeader additional_properties = 1;
}
// General information about the API.
message Info {
// A unique and precise title of the API.
string title = 1;
// A semantic version number of the API.
string version = 2;
// A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed.
string description = 3;
// The terms of service for the API.
string terms_of_service = 4;
Contact contact = 5;
License license = 6;
repeated NamedAny vendor_extension = 7;
}
message ItemsItem {
repeated Schema schema = 1;
}
message JsonReference {
string _ref = 1;
string description = 2;
}
message License {
// The name of the license type. It's encouraged to use an OSI compatible license.
string name = 1;
// The URL pointing to the license.
string url = 2;
repeated NamedAny vendor_extension = 3;
}
// Automatically-generated message used to represent maps of Any as ordered (name,value) pairs.
message NamedAny {
// Map key
string name = 1;
// Mapped value
Any value = 2;
}
// Automatically-generated message used to represent maps of Header as ordered (name,value) pairs.
message NamedHeader {
// Map key
string name = 1;
// Mapped value
Header value = 2;
}
// Automatically-generated message used to represent maps of Parameter as ordered (name,value) pairs.
message NamedParameter {
// Map key
string name = 1;
// Mapped value
Parameter value = 2;
}
// Automatically-generated message used to represent maps of PathItem as ordered (name,value) pairs.
message NamedPathItem {
// Map key
string name = 1;
// Mapped value
PathItem value = 2;
}
// Automatically-generated message used to represent maps of Response as ordered (name,value) pairs.
message NamedResponse {
// Map key
string name = 1;
// Mapped value
Response value = 2;
}
// Automatically-generated message used to represent maps of ResponseValue as ordered (name,value) pairs.
message NamedResponseValue {
// Map key
string name = 1;
// Mapped value
ResponseValue value = 2;
}
// Automatically-generated message used to represent maps of Schema as ordered (name,value) pairs.
message NamedSchema {
// Map key
string name = 1;
// Mapped value
Schema value = 2;
}
// Automatically-generated message used to represent maps of SecurityDefinitionsItem as ordered (name,value) pairs.
message NamedSecurityDefinitionsItem {
// Map key
string name = 1;
// Mapped value
SecurityDefinitionsItem value = 2;
}
// Automatically-generated message used to represent maps of string as ordered (name,value) pairs.
message NamedString {
// Map key
string name = 1;
// Mapped value
string value = 2;
}
// Automatically-generated message used to represent maps of StringArray as ordered (name,value) pairs.
message NamedStringArray {
// Map key
string name = 1;
// Mapped value
StringArray value = 2;
}
message NonBodyParameter {
oneof oneof {
HeaderParameterSubSchema header_parameter_sub_schema = 1;
FormDataParameterSubSchema form_data_parameter_sub_schema = 2;
QueryParameterSubSchema query_parameter_sub_schema = 3;
PathParameterSubSchema path_parameter_sub_schema = 4;
}
}
message Oauth2AccessCodeSecurity {
string type = 1;
string flow = 2;
Oauth2Scopes scopes = 3;
string authorization_url = 4;
string token_url = 5;
string description = 6;
repeated NamedAny vendor_extension = 7;
}
message Oauth2ApplicationSecurity {
string type = 1;
string flow = 2;
Oauth2Scopes scopes = 3;
string token_url = 4;
string description = 5;
repeated NamedAny vendor_extension = 6;
}
message Oauth2ImplicitSecurity {
string type = 1;
string flow = 2;
Oauth2Scopes scopes = 3;
string authorization_url = 4;
string description = 5;
repeated NamedAny vendor_extension = 6;
}
message Oauth2PasswordSecurity {
string type = 1;
string flow = 2;
Oauth2Scopes scopes = 3;
string token_url = 4;
string description = 5;
repeated NamedAny vendor_extension = 6;
}
message Oauth2Scopes {
repeated NamedString additional_properties = 1;
}
message Operation {
repeated string tags = 1;
// A brief summary of the operation.
string summary = 2;
// A longer description of the operation, GitHub Flavored Markdown is allowed.
string description = 3;
ExternalDocs external_docs = 4;
// A unique identifier of the operation.
string operation_id = 5;
// A list of MIME types the API can produce.
repeated string produces = 6;
// A list of MIME types the API can consume.
repeated string consumes = 7;
// The parameters needed to send a valid API call.
repeated ParametersItem parameters = 8;
Responses responses = 9;
// The transfer protocol of the API.
repeated string schemes = 10;
bool deprecated = 11;
repeated SecurityRequirement security = 12;
repeated NamedAny vendor_extension = 13;
}
message Parameter {
oneof oneof {
BodyParameter body_parameter = 1;
NonBodyParameter non_body_parameter = 2;
}
}
// One or more JSON representations for parameters
message ParameterDefinitions {
repeated NamedParameter additional_properties = 1;
}
message ParametersItem {
oneof oneof {
Parameter parameter = 1;
JsonReference json_reference = 2;
}
}
message PathItem {
string _ref = 1;
Operation get = 2;
Operation put = 3;
Operation post = 4;
Operation delete = 5;
Operation options = 6;
Operation head = 7;
Operation patch = 8;
// The parameters needed to send a valid API call.
repeated ParametersItem parameters = 9;
repeated NamedAny vendor_extension = 10;
}
message PathParameterSubSchema {
// Determines whether or not this parameter is required or optional.
bool required = 1;
// Determines the location of the parameter.
string in = 2;
// A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
string description = 3;
// The name of the parameter.
string name = 4;
string type = 5;
string format = 6;
PrimitivesItems items = 7;
string collection_format = 8;
Any default = 9;
double maximum = 10;
bool exclusive_maximum = 11;
double minimum = 12;
bool exclusive_minimum = 13;
int64 max_length = 14;
int64 min_length = 15;
string pattern = 16;
int64 max_items = 17;
int64 min_items = 18;
bool unique_items = 19;
repeated Any enum = 20;
double multiple_of = 21;
repeated NamedAny vendor_extension = 22;
}
// Relative paths to the individual endpoints. They must be relative to the 'basePath'.
message Paths {
repeated NamedAny vendor_extension = 1;
repeated NamedPathItem path = 2;
}
message PrimitivesItems {
string type = 1;
string format = 2;
PrimitivesItems items = 3;
string collection_format = 4;
Any default = 5;
double maximum = 6;
bool exclusive_maximum = 7;
double minimum = 8;
bool exclusive_minimum = 9;
int64 max_length = 10;
int64 min_length = 11;
string pattern = 12;
int64 max_items = 13;
int64 min_items = 14;
bool unique_items = 15;
repeated Any enum = 16;
double multiple_of = 17;
repeated NamedAny vendor_extension = 18;
}
message Properties {
repeated NamedSchema additional_properties = 1;
}
message QueryParameterSubSchema {
// Determines whether or not this parameter is required or optional.
bool required = 1;
// Determines the location of the parameter.
string in = 2;
// A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
string description = 3;
// The name of the parameter.
string name = 4;
// allows sending a parameter by name only or with an empty value.
bool allow_empty_value = 5;
string type = 6;
string format = 7;
PrimitivesItems items = 8;
string collection_format = 9;
Any default = 10;
double maximum = 11;
bool exclusive_maximum = 12;
double minimum = 13;
bool exclusive_minimum = 14;
int64 max_length = 15;
int64 min_length = 16;
string pattern = 17;
int64 max_items = 18;
int64 min_items = 19;
bool unique_items = 20;
repeated Any enum = 21;
double multiple_of = 22;
repeated NamedAny vendor_extension = 23;
}
message Response {
string description = 1;
SchemaItem schema = 2;
Headers headers = 3;
Examples examples = 4;
repeated NamedAny vendor_extension = 5;
}
// One or more JSON representations for parameters
message ResponseDefinitions {
repeated NamedResponse additional_properties = 1;
}
message ResponseValue {
oneof oneof {
Response response = 1;
JsonReference json_reference = 2;
}
}
// Response objects names can either be any valid HTTP status code or 'default'.
message Responses {
repeated NamedResponseValue response_code = 1;
repeated NamedAny vendor_extension = 2;
}
// A deterministic version of a JSON Schema object.
message Schema {
string _ref = 1;
string format = 2;
string title = 3;
string description = 4;
Any default = 5;
double multiple_of = 6;
double maximum = 7;
bool exclusive_maximum = 8;
double minimum = 9;
bool exclusive_minimum = 10;
int64 max_length = 11;
int64 min_length = 12;
string pattern = 13;
int64 max_items = 14;
int64 min_items = 15;
bool unique_items = 16;
int64 max_properties = 17;
int64 min_properties = 18;
repeated string required = 19;
repeated Any enum = 20;
AdditionalPropertiesItem additional_properties = 21;
TypeItem type = 22;
ItemsItem items = 23;
repeated Schema all_of = 24;
Properties properties = 25;
string discriminator = 26;
bool read_only = 27;
Xml xml = 28;
ExternalDocs external_docs = 29;
Any example = 30;
repeated NamedAny vendor_extension = 31;
}
message SchemaItem {
oneof oneof {
Schema schema = 1;
FileSchema file_schema = 2;
}
}
message SecurityDefinitions {
repeated NamedSecurityDefinitionsItem additional_properties = 1;
}
message SecurityDefinitionsItem {
oneof oneof {
BasicAuthenticationSecurity basic_authentication_security = 1;
ApiKeySecurity api_key_security = 2;
Oauth2ImplicitSecurity oauth2_implicit_security = 3;
Oauth2PasswordSecurity oauth2_password_security = 4;
Oauth2ApplicationSecurity oauth2_application_security = 5;
Oauth2AccessCodeSecurity oauth2_access_code_security = 6;
}
}
message SecurityRequirement {
repeated NamedStringArray additional_properties = 1;
}
message StringArray {
repeated string value = 1;
}
message Tag {
string name = 1;
string description = 2;
ExternalDocs external_docs = 3;
repeated NamedAny vendor_extension = 4;
}
message TypeItem {
repeated string value = 1;
}
// Any property starting with x- is valid.
message VendorExtension {
repeated NamedAny additional_properties = 1;
}
message Xml {
string name = 1;
string namespace = 2;
string prefix = 3;
bool attribute = 4;
bool wrapped = 5;
repeated NamedAny vendor_extension = 6;
}

View file

@ -0,0 +1,16 @@
# OpenAPI v2 Protocol Buffer Models
This directory contains a Protocol Buffer-language model
and related code for supporting OpenAPI v2.
Gnostic applications and plugins can use OpenAPIv2.proto
to generate Protocol Buffer support code for their preferred languages.
OpenAPIv2.go is used by Gnostic to read JSON and YAML OpenAPI
descriptions into the Protocol Buffer-based datastructures
generated from OpenAPIv2.proto.
OpenAPIv2.proto and OpenAPIv2.go are generated by the Gnostic
compiler generator, and OpenAPIv2.pb.go is generated by
protoc, the Protocol Buffer compiler, and protoc-gen-go, the
Protocol Buffer Go code generation plugin.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,640 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
syntax = "proto3";
package openapi.v3;
import "google/protobuf/any.proto";
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "OpenAPIProto";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapi_v3";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
option objc_class_prefix = "OAS";
message Any {
google.protobuf.Any value = 1;
string yaml = 2;
}
message AnyOrExpression {
oneof oneof {
Any any = 1;
Expression expression = 2;
}
}
// A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
message Callback {
repeated NamedPathItem expression = 1;
repeated NamedSpecificationExtension specification_extension = 2;
}
message CallbackOrReference {
oneof oneof {
Callback callback = 1;
Reference reference = 2;
}
}
// A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
message Callbacks {
repeated NamedCallbackOrReference name = 1;
repeated NamedSpecificationExtension specification_extension = 2;
}
// Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.
message Components {
Schemas schemas = 1;
Responses responses = 2;
Parameters parameters = 3;
Examples examples = 4;
RequestBodies request_bodies = 5;
Headers headers = 6;
SecuritySchemes security_schemes = 7;
Links links = 8;
Callbacks callbacks = 9;
repeated NamedSpecificationExtension specification_extension = 10;
}
// Contact information for the exposed API.
message Contact {
string name = 1;
string url = 2;
string email = 3;
repeated NamedSpecificationExtension specification_extension = 4;
}
// Describes a set of supported media types. A Content Object can be used in Request Body Object, Parameter Objects, Header Objects, and Response Objects. Each key in the Content Object is the media type of the Media Type Object.
message Content {
repeated NamedMediaType media_type = 1;
}
message Document {
string openapi = 1;
Info info = 2;
repeated Server servers = 3;
Paths paths = 4;
Components components = 5;
repeated SecurityRequirement security = 6;
repeated Tag tags = 7;
ExternalDocs external_docs = 8;
repeated NamedSpecificationExtension specification_extension = 9;
}
// An object representing multipart region encoding for `requestBody` objects.
message Encoding {
repeated NamedEncodingProperty property = 1;
}
// A single encoding definition applied to a single schema property.
message EncodingProperty {
string content_type = 1;
Object headers = 2;
string style = 3;
bool explode = 4;
repeated NamedSpecificationExtension specification_extension = 5;
}
// Allows sharing examples for operation requests and responses. This object can either be a freeform object, array or primitive value. To represent examples of media types that cannot naturally represented in the OpenAPI definition, a string value can be used to contain the example with escaping where necessary.
message Example {
}
message ExampleOrReference {
oneof oneof {
Example example = 1;
Reference reference = 2;
}
}
message Examples {
}
message Expression {
repeated NamedAny additional_properties = 1;
}
// Allows referencing an external resource for extended documentation.
message ExternalDocs {
string description = 1;
string url = 2;
repeated NamedSpecificationExtension specification_extension = 3;
}
// The Header Object follows the structure of the Parameter Object, with the following changes: 1. `name` MUST NOT be specified, it is given in the Headers Object. 1. `in` MUST NOT be specified, it is implicitly in `header`. 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`).
message Header {
string name = 1;
string in = 2;
string description = 3;
bool required = 4;
bool deprecated = 5;
bool allow_empty_value = 6;
string style = 7;
bool explode = 8;
bool allow_reserved = 9;
SchemaOrReference schema = 10;
repeated ExampleOrReference examples = 11;
ExampleOrReference example = 12;
Content content = 13;
}
message HeaderOrReference {
oneof oneof {
Header header = 1;
Reference reference = 2;
}
}
// Lists the headers that can be sent in a response or forwarded via a link. Note that RFC 7230 states header names are case insensitive.
message Headers {
repeated NamedHeaderOrReference name = 1;
}
// The object provides metadata about the API. The metadata can be used by the clients if needed, and can be presented in editing or documentation generation tools for convenience.
message Info {
string title = 1;
string description = 2;
string terms_of_service = 3;
Contact contact = 4;
License license = 5;
string version = 6;
repeated NamedSpecificationExtension specification_extension = 7;
}
message ItemsItem {
repeated SchemaOrReference schema_or_reference = 1;
}
// License information for the exposed API.
message License {
string name = 1;
string url = 2;
repeated NamedSpecificationExtension specification_extension = 3;
}
// The `Link Object` is responsible for defining a possible operation based on a single response.
message Link {
string href = 1;
string operation_id = 2;
LinkParameters parameters = 3;
Headers headers = 4;
string description = 5;
repeated NamedSpecificationExtension specification_extension = 6;
}
message LinkOrReference {
oneof oneof {
Link link = 1;
Reference reference = 2;
}
}
// Using the `operationId` to reference an operation in the definition has many benefits, including the ability to define media type options, security requirements, response and error payloads. Many operations require parameters to be passed, and these MAY be dynamic depending on the response itself. To specify parameters required by the operation, we can use a **Link Parameters Object**. This object contains parameter names along with static or dynamic values:
message LinkParameters {
repeated NamedAnyOrExpression name = 1;
}
// The links object represents a set of possible design-time links for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. As opposed to _dynamic_ links (links provided **in** the response payload), the OAS linking mechanism does not require that link information be provided in a specific response format at runtime. For computing links, and providing instructions to execute them, variable substitution is used for accessing values in a response and using them as values while invoking the linked operation.
message Links {
repeated NamedLinkOrReference name = 1;
}
// Each Media Type Object provides schema and examples for a the media type identified by its key. Media Type Objects can be used in a Content Object.
message MediaType {
SchemaOrReference schema = 1;
repeated ExampleOrReference examples = 2;
ExampleOrReference example = 3;
Encoding encoding = 4;
repeated NamedSpecificationExtension specification_extension = 5;
}
// Automatically-generated message used to represent maps of Any as ordered (name,value) pairs.
message NamedAny {
// Map key
string name = 1;
// Mapped value
Any value = 2;
}
// Automatically-generated message used to represent maps of AnyOrExpression as ordered (name,value) pairs.
message NamedAnyOrExpression {
// Map key
string name = 1;
// Mapped value
AnyOrExpression value = 2;
}
// Automatically-generated message used to represent maps of CallbackOrReference as ordered (name,value) pairs.
message NamedCallbackOrReference {
// Map key
string name = 1;
// Mapped value
CallbackOrReference value = 2;
}
// Automatically-generated message used to represent maps of EncodingProperty as ordered (name,value) pairs.
message NamedEncodingProperty {
// Map key
string name = 1;
// Mapped value
EncodingProperty value = 2;
}
// Automatically-generated message used to represent maps of HeaderOrReference as ordered (name,value) pairs.
message NamedHeaderOrReference {
// Map key
string name = 1;
// Mapped value
HeaderOrReference value = 2;
}
// Automatically-generated message used to represent maps of LinkOrReference as ordered (name,value) pairs.
message NamedLinkOrReference {
// Map key
string name = 1;
// Mapped value
LinkOrReference value = 2;
}
// Automatically-generated message used to represent maps of MediaType as ordered (name,value) pairs.
message NamedMediaType {
// Map key
string name = 1;
// Mapped value
MediaType value = 2;
}
// Automatically-generated message used to represent maps of Parameter as ordered (name,value) pairs.
message NamedParameter {
// Map key
string name = 1;
// Mapped value
Parameter value = 2;
}
// Automatically-generated message used to represent maps of PathItem as ordered (name,value) pairs.
message NamedPathItem {
// Map key
string name = 1;
// Mapped value
PathItem value = 2;
}
// Automatically-generated message used to represent maps of RequestBody as ordered (name,value) pairs.
message NamedRequestBody {
// Map key
string name = 1;
// Mapped value
RequestBody value = 2;
}
// Automatically-generated message used to represent maps of ResponseOrReference as ordered (name,value) pairs.
message NamedResponseOrReference {
// Map key
string name = 1;
// Mapped value
ResponseOrReference value = 2;
}
// Automatically-generated message used to represent maps of Schema as ordered (name,value) pairs.
message NamedSchema {
// Map key
string name = 1;
// Mapped value
Schema value = 2;
}
// Automatically-generated message used to represent maps of SecurityScheme as ordered (name,value) pairs.
message NamedSecurityScheme {
// Map key
string name = 1;
// Mapped value
SecurityScheme value = 2;
}
// Automatically-generated message used to represent maps of ServerVariable as ordered (name,value) pairs.
message NamedServerVariable {
// Map key
string name = 1;
// Mapped value
ServerVariable value = 2;
}
// Automatically-generated message used to represent maps of SpecificationExtension as ordered (name,value) pairs.
message NamedSpecificationExtension {
// Map key
string name = 1;
// Mapped value
SpecificationExtension value = 2;
}
// Configuration details for a supported OAuth Flow
message OauthFlow {
string authorization_url = 1;
string token_url = 2;
string refresh_url = 3;
Scopes scopes = 4;
repeated NamedSpecificationExtension specification_extension = 5;
}
// Allows configuration of the supported OAuth Flows.
message OauthFlows {
OauthFlow implicit = 1;
OauthFlow password = 2;
OauthFlow client_credentials = 3;
OauthFlow authorization_code = 4;
repeated NamedSpecificationExtension specification_extension = 5;
}
message Object {
repeated NamedAny additional_properties = 1;
}
// Describes a single API operation on a path.
message Operation {
repeated string tags = 1;
string summary = 2;
string description = 3;
ExternalDocs external_docs = 4;
string operation_id = 5;
repeated ParameterOrReference parameters = 6;
RequestBodyOrReference request_body = 7;
Responses responses = 8;
Callbacks callbacks = 9;
bool deprecated = 10;
repeated SecurityRequirement security = 11;
Server servers = 12;
repeated NamedSpecificationExtension specification_extension = 13;
}
// Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.
message Parameter {
string name = 1;
string in = 2;
string description = 3;
bool required = 4;
bool deprecated = 5;
bool allow_empty_value = 6;
string style = 7;
bool explode = 8;
bool allow_reserved = 9;
SchemaOrReference schema = 10;
repeated ExampleOrReference examples = 11;
ExampleOrReference example = 12;
Content content = 13;
repeated NamedSpecificationExtension specification_extension = 14;
}
message ParameterOrReference {
oneof oneof {
Parameter parameter = 1;
Reference reference = 2;
}
}
message Parameters {
repeated NamedParameter additional_properties = 1;
}
// Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.
message PathItem {
string _ref = 1;
string summary = 2;
string description = 3;
Operation get = 4;
Operation put = 5;
Operation post = 6;
Operation delete = 7;
Operation options = 8;
Operation head = 9;
Operation patch = 10;
Operation trace = 11;
Server servers = 12;
repeated ParameterOrReference parameters = 13;
repeated NamedSpecificationExtension specification_extension = 14;
}
// Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the `Server Object` in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.
message Paths {
repeated NamedPathItem path = 1;
repeated NamedSpecificationExtension specification_extension = 2;
}
message Primitive {
oneof oneof {
int64 integer = 1;
double number = 2;
bool boolean = 3;
string string = 4;
}
}
message Properties {
repeated NamedSchema additional_properties = 1;
}
// A simple object to allow referencing other components in the specification, internally and externally. The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules. For this specification, reference resolution is done as defined by the JSON Reference specification and not by the JSON Schema specification.
message Reference {
string _ref = 1;
}
message RequestBodies {
repeated NamedRequestBody additional_properties = 1;
}
// Describes a single request body.
message RequestBody {
string description = 1;
Content content = 2;
bool required = 3;
repeated NamedSpecificationExtension specification_extension = 4;
}
message RequestBodyOrReference {
oneof oneof {
RequestBody request_body = 1;
Reference reference = 2;
}
}
// Describes a single response from an API Operation, including design-time, static `links` to operations based on the response.
message Response {
string description = 1;
Headers headers = 2;
Content content = 3;
Links links = 4;
repeated NamedSpecificationExtension specification_extension = 5;
}
message ResponseOrReference {
oneof oneof {
Response response = 1;
Reference reference = 2;
}
}
// A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. It is not expected from the documentation to necessarily cover all possible HTTP response codes, since they may not be known in advance. However, it is expected from the documentation to cover a successful operation response and any known errors. The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call.
message Responses {
ResponseOrReference default = 1;
repeated NamedResponseOrReference response_code = 2;
repeated NamedSpecificationExtension specification_extension = 3;
}
// The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. Further information about the properties can be found in JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema specification as referenced here.
message Schema {
bool nullable = 1;
string discriminator = 2;
bool read_only = 3;
bool write_only = 4;
Xml xml = 5;
ExternalDocs external_docs = 6;
bool deprecated = 7;
string title = 8;
double multiple_of = 9;
double maximum = 10;
bool exclusive_maximum = 11;
double minimum = 12;
bool exclusive_minimum = 13;
int64 max_length = 14;
int64 min_length = 15;
string pattern = 16;
int64 max_items = 17;
int64 min_items = 18;
bool unique_items = 19;
int64 max_properties = 20;
int64 min_properties = 21;
repeated string required = 22;
repeated Any enum = 23;
string type = 24;
repeated SchemaOrReference all_of = 25;
repeated SchemaOrReference one_of = 26;
repeated SchemaOrReference any_of = 27;
Schema not = 28;
ItemsItem items = 29;
Properties properties = 30;
string description = 31;
string format = 32;
repeated NamedSpecificationExtension specification_extension = 33;
}
message SchemaOrReference {
oneof oneof {
Schema schema = 1;
Reference reference = 2;
}
}
message Schemas {
repeated NamedSchema additional_properties = 1;
}
// Lists the available scopes for an OAuth2 security scheme.
message Scopes {
repeated NamedAny name = 1;
repeated NamedSpecificationExtension specification_extension = 2;
}
// Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object. Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where there multiple query parameters or HTTP headers are required to convey security information. When a list of Security Requirement Objects is defined on the Open API object or Operation Object, only one of Security Requirement Objects in the list needs to be satisfied to authorize.
message SecurityRequirement {
repeated NamedAny name = 1;
}
// Allows the definition of a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header or as a query parameter) and OAuth2's common flows (implicit, password, application and access code).
message SecurityScheme {
string type = 1;
string description = 2;
string name = 3;
string in = 4;
string scheme = 5;
string bearer_format = 6;
OauthFlows flow = 7;
string open_id_connect_url = 8;
repeated NamedSpecificationExtension specification_extension = 9;
}
message SecuritySchemes {
repeated NamedSecurityScheme additional_properties = 1;
}
// An object representing a Server.
message Server {
string url = 1;
string description = 2;
ServerVariables variables = 3;
repeated NamedSpecificationExtension specification_extension = 4;
}
// An object representing a Server Variable for server URL template substitution.
message ServerVariable {
repeated Primitive enum = 1;
Primitive default = 2;
string description = 3;
repeated NamedSpecificationExtension specification_extension = 4;
}
message ServerVariables {
repeated NamedServerVariable name = 1;
repeated NamedSpecificationExtension specification_extension = 2;
}
// Any property starting with x- is valid.
message SpecificationExtension {
oneof oneof {
int64 integer = 1;
double number = 2;
bool boolean = 3;
string string = 4;
}
}
message StringArray {
repeated string value = 1;
}
// Allows adding meta data to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag used there.
message Tag {
string name = 1;
string description = 2;
ExternalDocs external_docs = 3;
repeated NamedSpecificationExtension specification_extension = 4;
}
// A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior.
message Xml {
string name = 1;
string namespace = 2;
string prefix = 3;
bool attribute = 4;
bool wrapped = 5;
repeated NamedSpecificationExtension specification_extension = 6;
}

View file

@ -0,0 +1,25 @@
# OpenAPI v3 Protocol Buffer Models
This directory contains a Protocol Buffer-language model
and related code for supporting OpenAPI v3.
Gnostic applications and plugins can use OpenAPIv3.proto
to generate Protocol Buffer support code for their preferred
languages.
OpenAPIv3.go is used by Gnostic to read JSON and YAML OpenAPI
descriptions into the Protocol Buffer-based datastructures
generated from OpenAPIv3.proto.
OpenAPIv3.proto and OpenAPIv3.go are generated by the Gnostic
compiler generator, and OpenAPIv3.pb.go is generated by
protoc, the Protocol Buffer compiler, and protoc-gen-go, the
Protocol Buffer Go code generation plugin.
openapi-3.0.json is a preliminary draft JSON schema for OpenAPI 3.0.
It is not the official OpenAPI 3.0 JSON Schema, which at the time
of this commit, does not exist.
The schema-generator directory contains support code which
generates openapi-3.0.json from a draft of the OpenAPI 3.0
specification document (Markdown).

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,15 @@
# OpenAPI 3.0 Schema Generator
This directory contains a support tool that reads (scrapes) the
Markdown text specification for OpenAPI 3.0 and builds a
corresponding JSON schema.
It also contains "3.0.md", a local copy of the OpenAPI specification
with modifications that fix minor inconsistencies and make it easier
to read. We hope to have these changes merged into the official
document.
## Disclaimer
This does not generate the official OpenAPI 3.0 JSON Schema, which
at the time of this commit, does not exist.

View file

@ -0,0 +1,751 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// schema-generator is a support tool that generates the OpenAPI v3 JSON schema.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"regexp"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/googleapis/gnostic/jsonschema"
)
// convert the first character of a string to lower case
func lowerFirst(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
}
// model a section of the OpenAPI specification text document
type Section struct {
Level int
Text string
Title string
Children []*Section
}
// read a section of the OpenAPI Specification, recursively dividing it into subsections
func ReadSection(text string, level int) (section *Section) {
titlePattern := regexp.MustCompile("^" + strings.Repeat("#", level) + " .*$")
subtitlePattern := regexp.MustCompile("^" + strings.Repeat("#", level+1) + " .*$")
section = &Section{Level: level, Text: text}
lines := strings.Split(string(text), "\n")
subsection := ""
for i, line := range lines {
if i == 0 && titlePattern.Match([]byte(line)) {
section.Title = line
} else if subtitlePattern.Match([]byte(line)) {
// we've found a subsection title.
// if there's a subsection that we've already been reading, save it
if len(subsection) != 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
// start a new subsection
subsection = line + "\n"
} else {
// add to the subsection we've been reading
subsection += line + "\n"
}
}
// if this section has subsections, save the last one
if len(section.Children) > 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
return
}
// recursively display a section of the specification
func (s *Section) Display(section string) {
if len(s.Children) == 0 {
//fmt.Printf("%s\n", s.Text)
} else {
for i, child := range s.Children {
var subsection string
if section == "" {
subsection = fmt.Sprintf("%d", i)
} else {
subsection = fmt.Sprintf("%s.%d", section, i)
}
fmt.Printf("%-12s %s\n", subsection, child.NiceTitle())
child.Display(subsection)
}
}
}
// remove a link from a string, leaving only the text that follows it
// if there is no link, just return the string
func stripLink(input string) (output string) {
stringPattern := regexp.MustCompile("^(.*)$")
stringWithLinkPattern := regexp.MustCompile("^<a .*</a>(.*)$")
if matches := stringWithLinkPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else if matches := stringPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else {
return input
}
}
// return a nice-to-display title for a section by removing the opening "###" and any links
func (s *Section) NiceTitle() string {
titlePattern := regexp.MustCompile("^#+ (.*)$")
titleWithLinkPattern := regexp.MustCompile("^#+ <a .*</a>(.*)$")
if matches := titleWithLinkPattern.FindSubmatch([]byte(s.Title)); matches != nil {
return string(matches[1])
} else if matches := titlePattern.FindSubmatch([]byte(s.Title)); matches != nil {
return string(matches[1])
} else {
return ""
}
}
// replace markdown links with their link text (removing the URL part)
func removeMarkdownLinks(input string) (output string) {
markdownLink := regexp.MustCompile("\\[([^\\]]*)\\]\\(([^\\)]*)\\)") // matches [link title](link url)
output = string(markdownLink.ReplaceAll([]byte(input), []byte("$1")))
return
}
// extract the fixed fields from a table in a section
func parseFixedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
line = strings.Replace(line, " \\| ", " OR ", -1)
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
if fieldName != "Field Name" && fieldName != "---" {
if len(parts) == 3 || len(parts) == 4 {
// this is what we expect
} else {
log.Printf("ERROR: %+v", parts)
}
typeName := parts[1]
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
requiredLabel := "**Required.** "
if strings.Contains(description, requiredLabel) {
// only include required values if their "Validity" is "Any" or if no validity is specified
valid := true
if len(parts) == 4 {
validity := parts[2]
if strings.Contains(validity, "Any") {
valid = true
} else {
valid = false
}
}
if valid {
schemaObject.RequiredFields = append(schemaObject.RequiredFields, fieldName)
}
description = strings.Replace(description, requiredLabel, "", -1)
}
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.FixedFields = append(schemaObject.FixedFields, schemaField)
}
}
}
}
// extract the patterned fields from a table in a section
func parsePatternedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
line = strings.Replace(line, " \\| ", " OR ", -1)
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
fieldName = removeMarkdownLinks(fieldName)
if fieldName == "HTTP Status Code" {
fieldName = "^([0-9]{3})$"
}
if fieldName != "Field Pattern" && fieldName != "---" {
typeName := parts[1]
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.PatternedFields = append(schemaObject.PatternedFields, schemaField)
}
}
}
}
type SchemaObjectField struct {
Name string `json:"name"`
Type string `json:"type"`
IsArray bool `json:"is_array"`
IsMap bool `json:"is_map"`
Description string `json:"description"`
}
type SchemaObject struct {
Name string `json:"name"`
Id string `json:"id"`
Description string `json:"description"`
Extendable bool `json:"extendable"`
RequiredFields []string `json:"required"`
FixedFields []SchemaObjectField `json:"fixed"`
PatternedFields []SchemaObjectField `json:"patterned"`
}
type SchemaModel struct {
Objects []SchemaObject
}
func (m *SchemaModel) objectWithId(id string) *SchemaObject {
for _, object := range m.Objects {
if object.Id == id {
return &object
}
}
return nil
}
func NewSchemaModel(filename string) (schemaModel *SchemaModel, err error) {
b, err := ioutil.ReadFile("3.0.md")
if err != nil {
return nil, err
}
// divide the specification into sections
document := ReadSection(string(b), 1)
//document.Display("")
// read object names and their details
specification := document.Children[4] // fragile!
schema := specification.Children[5] // fragile!
anchor := regexp.MustCompile("^#### <a name=\"(.*)Object\"")
schemaObjects := make([]SchemaObject, 0)
for _, section := range schema.Children {
if matches := anchor.FindSubmatch([]byte(section.Title)); matches != nil {
id := string(matches[1])
schemaObject := SchemaObject{
Name: section.NiceTitle(),
Id: id,
RequiredFields: nil,
}
if len(section.Children) > 0 {
description := section.Children[0].Text
description = removeMarkdownLinks(description)
description = strings.Trim(description, " \t\n")
description = strings.Replace(description, "\n", " ", -1)
schemaObject.Description = description
}
// is the object extendable?
if strings.Contains(section.Text, "Specification Extensions") {
schemaObject.Extendable = true
}
// look for fixed fields
for _, child := range section.Children {
if child.NiceTitle() == "Fixed Fields" {
parseFixedFields(child.Text, &schemaObject)
}
}
// look for patterned fields
for _, child := range section.Children {
if child.NiceTitle() == "Patterned Fields" {
parsePatternedFields(child.Text, &schemaObject)
}
}
schemaObjects = append(schemaObjects, schemaObject)
}
}
return &SchemaModel{Objects: schemaObjects}, nil
}
type UnionType struct {
Name string
ObjectType1 string
ObjectType2 string
}
var unionTypes map[string]*UnionType
func noteUnionType(typeName, objectType1, objectType2 string) {
if unionTypes == nil {
unionTypes = make(map[string]*UnionType, 0)
}
unionTypes[typeName] = &UnionType{
Name: typeName,
ObjectType1: objectType1,
ObjectType2: objectType2,
}
}
type MapType struct {
Name string
ObjectType string
}
var mapTypes map[string]*MapType
func noteMapType(typeName, objectType string) {
if mapTypes == nil {
mapTypes = make(map[string]*MapType, 0)
}
mapTypes[typeName] = &MapType{
Name: typeName,
ObjectType: objectType,
}
}
func definitionNameForType(typeName string) string {
name := typeName
switch typeName {
case "OAuthFlows":
name = "oauthFlows"
case "OAuthFlow":
name = "oauthFlow"
case "XML":
name = "xml"
case "ExternalDocumentation":
name = "externalDocs"
default:
// does the name contain an "OR"
if parts := strings.Split(typeName, "OR"); len(parts) > 1 {
name = lowerFirst(parts[0]) + "Or" + parts[1]
noteUnionType(name, parts[0], parts[1])
} else {
name = lowerFirst(typeName)
}
}
return "#/definitions/" + name
}
func definitionNameForMapOfType(typeName string) string {
// pluralize the type name to get the name of an object representing a map of them
name := lowerFirst(typeName)
if name[len(name)-1] == 'y' {
name = name[0:len(name)-1] + "ies"
} else {
name = name + "s"
}
noteMapType(name, typeName)
return "#/definitions/" + name
}
func updateSchemaFieldWithModelField(schemaField *jsonschema.Schema, modelField *SchemaObjectField) {
// fmt.Printf("IN %s:%+v\n", name, schemaField)
// update the attributes of the schema field
if modelField.IsArray {
// is array
itemSchema := &jsonschema.Schema{}
switch modelField.Type {
case "string":
itemSchema.Type = jsonschema.NewStringOrStringArrayWithString("string")
case "boolean":
itemSchema.Type = jsonschema.NewStringOrStringArrayWithString("boolean")
case "primitive":
itemSchema.Ref = stringptr(definitionNameForType("Primitive"))
default:
itemSchema.Ref = stringptr(definitionNameForType(modelField.Type))
}
schemaField.Items = jsonschema.NewSchemaOrSchemaArrayWithSchema(itemSchema)
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("array")
boolValue := true // not sure about this
schemaField.UniqueItems = &boolValue
} else if modelField.IsMap {
schemaField.Ref = stringptr(definitionNameForMapOfType(modelField.Type))
} else {
// is scalar
switch modelField.Type {
case "string":
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("string")
case "boolean":
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("boolean")
case "primitive":
schemaField.Ref = stringptr(definitionNameForType("Primitive"))
default:
schemaField.Ref = stringptr(definitionNameForType(modelField.Type))
}
}
}
func buildSchemaWithModel(modelObject *SchemaObject) (schema *jsonschema.Schema) {
schema = &jsonschema.Schema{}
schema.Type = jsonschema.NewStringOrStringArrayWithString("object")
if modelObject.RequiredFields != nil && len(modelObject.RequiredFields) > 0 {
// copy array
arrayCopy := modelObject.RequiredFields
schema.Required = &arrayCopy
}
schema.Description = stringptr(modelObject.Description)
// handle fixed fields
if modelObject.FixedFields != nil {
newNamedSchemas := make([]*jsonschema.NamedSchema, 0)
for _, modelField := range modelObject.FixedFields {
schemaField := schema.PropertyWithName(modelField.Name)
if schemaField == nil {
// create and add the schema field
schemaField = &jsonschema.Schema{}
namedSchema := &jsonschema.NamedSchema{Name: modelField.Name, Value: schemaField}
newNamedSchemas = append(newNamedSchemas, namedSchema)
}
updateSchemaFieldWithModelField(schemaField, &modelField)
}
for _, pair := range newNamedSchemas {
if schema.Properties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.Properties = &properties
}
*(schema.Properties) = append(*(schema.Properties), pair)
}
} else {
if schema.Properties != nil {
fmt.Printf("SCHEMA SHOULD NOT HAVE PROPERTIES %s\n", modelObject.Id)
}
}
// handle patterned fields
if modelObject.PatternedFields != nil {
newNamedSchemas := make([]*jsonschema.NamedSchema, 0)
for _, modelField := range modelObject.PatternedFields {
schemaField := schema.PatternPropertyWithName(modelField.Name)
if schemaField == nil {
// create and add the schema field
schemaField = &jsonschema.Schema{}
namedSchema := &jsonschema.NamedSchema{Name: modelField.Name, Value: schemaField}
newNamedSchemas = append(newNamedSchemas, namedSchema)
}
updateSchemaFieldWithModelField(schemaField, &modelField)
}
for _, pair := range newNamedSchemas {
if schema.PatternProperties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.PatternProperties = &properties
}
*(schema.PatternProperties) = append(*(schema.PatternProperties), pair)
}
} else {
if schema.PatternProperties != nil && !modelObject.Extendable {
fmt.Printf("SCHEMA SHOULD NOT HAVE PATTERN PROPERTIES %s\n", modelObject.Id)
}
}
if modelObject.Extendable {
schemaField := schema.PatternPropertyWithName("^x-")
if schemaField != nil {
schemaField.Ref = stringptr("#/definitions/specificationExtension")
} else {
schemaField = &jsonschema.Schema{}
schemaField.Ref = stringptr("#/definitions/specificationExtension")
namedSchema := &jsonschema.NamedSchema{Name: "^x-", Value: schemaField}
if schema.PatternProperties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.PatternProperties = &properties
}
*(schema.PatternProperties) = append(*(schema.PatternProperties), namedSchema)
}
} else {
schemaField := schema.PatternPropertyWithName("^x-")
if schemaField != nil {
fmt.Printf("INVALID EXTENSION SUPPORT %s:%s\n", modelObject.Id, "^x-")
}
}
return schema
}
// return a pointer to a copy of a passed-in string
func stringptr(input string) (output *string) {
return &input
}
func int64ptr(input int64) (output *int64) {
return &input
}
func arrayOfSchema() *jsonschema.Schema {
return &jsonschema.Schema{
Type: jsonschema.NewStringOrStringArrayWithString("array"),
MinItems: int64ptr(1),
Items: jsonschema.NewSchemaOrSchemaArrayWithSchema(&jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")}),
}
}
func main() {
// read and parse the text specification into a model structure
model, err := NewSchemaModel("3.0.md")
if err != nil {
panic(err)
}
// write the model as JSON (for debugging)
modelJSON, _ := json.MarshalIndent(model, "", " ")
err = ioutil.WriteFile("model.json", modelJSON, 0644)
if err != nil {
panic(err)
}
// build the top-level schema using the "OAS" model
schema := buildSchemaWithModel(model.objectWithId("oas"))
// manually set a few fields
schema.Title = stringptr("A JSON Schema for OpenAPI 3.0.")
schema.Id = stringptr("http://openapis.org/v3/schema.json#")
schema.Schema = stringptr("http://json-schema.org/draft-04/schema#")
// loop over all models and create the corresponding schema objects
definitions := make([]*jsonschema.NamedSchema, 0)
schema.Definitions = &definitions
for _, modelObject := range model.Objects {
if modelObject.Id == "oas" {
continue
}
definitionSchema := buildSchemaWithModel(&modelObject)
name := modelObject.Id
if name == "externalDocumentation" {
name = "externalDocs"
}
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(name, definitionSchema))
}
// copy the properties of headerObject from parameterObject
headerObject := schema.DefinitionWithName("header")
parameterObject := schema.DefinitionWithName("parameter")
if parameterObject != nil {
// "So a shorthand for copying array arr would be tmp := append([]int{}, arr...)"
newArray := make([]*jsonschema.NamedSchema, 0)
newArray = append(newArray, *(parameterObject.Properties)...)
headerObject.Properties = &newArray
// we need to remove a few properties...
}
// generate implied union types
unionTypeKeys := make([]string, 0, len(unionTypes))
for key := range unionTypes {
unionTypeKeys = append(unionTypeKeys, key)
}
sort.Strings(unionTypeKeys)
for _, unionTypeKey := range unionTypeKeys {
unionType := unionTypes[unionTypeKey]
objectSchema := schema.DefinitionWithName(unionType.Name)
if objectSchema == nil {
objectSchema = &jsonschema.Schema{}
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Ref: stringptr("#/definitions/" + lowerFirst(unionType.ObjectType1))})
oneOf = append(oneOf, &jsonschema.Schema{Ref: stringptr("#/definitions/" + lowerFirst(unionType.ObjectType2))})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(unionType.Name, objectSchema))
}
}
// generate implied map types
mapTypeKeys := make([]string, 0, len(mapTypes))
for key := range mapTypes {
mapTypeKeys = append(mapTypeKeys, key)
}
sort.Strings(mapTypeKeys)
for _, mapTypeKey := range mapTypeKeys {
mapType := mapTypes[mapTypeKey]
objectSchema := schema.DefinitionWithName(mapType.Name)
if objectSchema == nil {
objectSchema = &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
additionalPropertiesSchema := &jsonschema.Schema{}
additionalPropertiesSchema.Ref = stringptr("#/definitions/" + lowerFirst(mapType.ObjectType))
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithSchema(additionalPropertiesSchema)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(mapType.Name, objectSchema))
}
}
// add schema objects for "object", "any", and "expression"
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
objectSchema.AdditionalItems = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("object", objectSchema))
}
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
objectSchema.AdditionalItems = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("any", objectSchema))
}
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
objectSchema.AdditionalItems = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("expression", objectSchema))
}
// add schema objects for "specificationExtension"
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Description = stringptr("Any property starting with x- is valid.")
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("integer")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("number")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("object")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("array")})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("specificationExtension", objectSchema))
}
// add schema objects for "primitive"
if true {
objectSchema := &jsonschema.Schema{}
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("integer")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("number")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("primitive", objectSchema))
}
// force a few more things into the "schema" schema
schemaObject := schema.DefinitionWithName("schema")
schemaObject.CopyOfficialSchemaProperties(
[]string{
"title",
"multipleOf",
"maximum",
"exclusiveMaximum",
"minimum",
"exclusiveMinimum",
"maxLength",
"minLength",
"pattern",
"maxItems",
"minItems",
"uniqueItems",
"maxProperties",
"minProperties",
"required",
"enum",
})
schemaObject.AddProperty("type", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
schemaObject.AddProperty("allOf", arrayOfSchema())
schemaObject.AddProperty("oneOf", arrayOfSchema())
schemaObject.AddProperty("anyOf", arrayOfSchema())
schemaObject.AddProperty("not", &jsonschema.Schema{Ref: stringptr("#/definitions/schema")})
anyOf := make([]*jsonschema.Schema, 0)
anyOf = append(anyOf, &jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")})
anyOf = append(anyOf, arrayOfSchema())
schemaObject.AddProperty("items",
&jsonschema.Schema{AnyOf: &anyOf})
schemaObject.AddProperty("properties", &jsonschema.Schema{
Type: jsonschema.NewStringOrStringArrayWithString("object"),
AdditionalProperties: jsonschema.NewSchemaOrBooleanWithSchema(
&jsonschema.Schema{Ref: stringptr("#/definitions/schema")})})
schemaObject.AddProperty("description", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
schemaObject.AddProperty("format", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
// fix the content object
contentObject := schema.DefinitionWithName("content")
pairs := make([]*jsonschema.NamedSchema, 0)
contentObject.PatternProperties = &pairs
namedSchema := &jsonschema.NamedSchema{Name: "{media-type}", Value: &jsonschema.Schema{Ref: stringptr("#/definitions/mediaType")}}
*(contentObject.PatternProperties) = append(*(contentObject.PatternProperties), namedSchema)
// write the updated schema
output := schema.JSONString()
err = ioutil.WriteFile("schema.json", []byte(output), 0644)
if err != nil {
panic(err)
}
}

100
vendor/github.com/googleapis/gnostic/README.md generated vendored Normal file
View file

@ -0,0 +1,100 @@
[![Build Status](https://travis-ci.org/googleapis/gnostic.svg?branch=master)](https://travis-ci.org/googleapis/gnostic)
# gnostic
This repository contains a Go command line tool which reads
[OpenAPI](https://github.com/OAI/OpenAPI-Specification)
descriptions in JSON or YAML formats and writes
equivalent Protocol Buffer representations.
[Protocol Buffers](https://developers.google.com/protocol-buffers/)
are a language-neutral, platform-neutral extensible mechanism
for serializing structured data.
**gnostic** reads OpenAPI descriptions into
Protocol Buffer representations, reports errors,
resolves internal dependencies, and writes the results
in a binary form that can be used in any language that is
supported by the Protocol Buffer tools.
Code generated by the Protocol Buffer tools includes data
structures with explicit fields for the elements of an OpenAPI
description. This makes it possible for developers to work
with OpenAPI descriptions in type-safe ways. This is
particularly useful in strongly-typed languages like
Go and Swift.
**gnostic** compilation code and the OpenAPI Protocol Buffer
representation are automatically generated from the
[OpenAPI JSON Schema](https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v2.0/schema.json).
Source code for the generator is in the [generator](generator) directory.
## Disclaimer
This is prerelease software and work in progress. Feedback and
contributions are welcome, but we currently make no guarantees of
function or stability.
## Requirements
**gnostic** can be run in any environment that supports [Go](http://golang.org)
and the [Google Protocol Buffer Compiler](https://github.com/google/protobuf).
## Installation
1. Get this package by downloading it with `go get`.
go get github.com/googleapis/gnostic
2. [Optional] Build and run the compiler generator.
This uses the OpenAPI JSON schema to generate a Protocol Buffer language file
that describes the OpenAPI specification and a Go-language file of code that
will read a JSON or YAML OpenAPI representation into the generated protocol
buffers. Pre-generated versions of these files are in the OpenAPIv2 directory.
cd $GOPATH/src/github.com/googleapis/gnostic/generator
go build
cd ..
./generator/generator
3. [Optional] Generate protocol buffer support code.
A pre-generated version of this file is checked into the OpenAPIv2 directory.
This step requires a local installation of protoc, the Protocol Buffer Compiler.
You can get protoc [here](https://github.com/google/protobuf).
./COMPILE-PROTOS.sh
4. [Optional] Rebuild **gnostic**. This is only necessary if you've performed steps
2 or 3 above.
go install github.com/googleapis/gnostic
5. Run **gnostic**. This will create a file in the current directory named "petstore.pb" that contains a binary
Protocol Buffer description of a sample API.
gnostic --pb_out=. examples/petstore.json
6. You can also compile files that you specify with a URL. Here's another way to compile the previous
example. This time we're creating "petstore.text", which contains a textual representation of the
Protocol Buffer description. This is mainly for use in testing and debugging.
gnostic --text_out=petstore.text https://raw.githubusercontent.com/googleapis/gnostic/master/examples/petstore.json
7. For a sample application, see apps/report.
go install github.com/googleapis/gnostic/apps/report
report petstore.pb
8. **gnostic** supports plugins. This builds and runs a sample plugin
that reports some basic information about an API. The "-" causes the plugin to
write its output to stdout.
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_sample
gnostic examples/petstore.json --go_sample_out=-
## Copyright
Copyright 2017, Google Inc.
## License
Released under the Apache 2.0 license.

View file

@ -0,0 +1,6 @@
# OpenAPI Report Sample
This directory contains a simple sample application that reads a binary
protocol buffer representation of an OpenAPI 2.0 specification that
was generated by gnostic.

View file

@ -0,0 +1,239 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// report is a demo application that displays information about an
// OpenAPI description.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/printer"
pb "github.com/googleapis/gnostic/OpenAPIv2"
)
func readDocumentFromFileWithName(filename string) *pb.Document {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf("File error: %v\n", err)
os.Exit(1)
}
document := &pb.Document{}
err = proto.Unmarshal(data, document)
if err != nil {
panic(err)
}
return document
}
func printDocument(code *printer.Code, document *pb.Document) {
code.Print("BasePath: %+v", document.BasePath)
code.Print("Consumes: %+v", document.Consumes)
code.Print("Definitions:")
code.Indent()
if document.Definitions != nil && document.Definitions.AdditionalProperties != nil {
for _, pair := range document.Definitions.AdditionalProperties {
code.Print("%s", pair.Name)
code.Indent()
printSchema(code, pair.Value)
code.Outdent()
}
}
code.Outdent()
code.Print("ExternalDocs: %+v", document.ExternalDocs)
code.Print("Host: %+v", document.Host)
if document.Info != nil {
code.Print("Info:")
code.Indent()
code.Print("Title: %s", document.Info.Title)
code.Print("Description: %s", document.Info.Description)
code.Print("Version: %s", document.Info.Version)
code.Print("TermsOfService: %s", document.Info.TermsOfService)
if document.Info.Contact != nil {
code.Print("Contact Email: %s", document.Info.Contact.Email)
}
if document.Info.License != nil {
code.Print("License Name: %s", document.Info.License.Name)
code.Print("License URL: %s", document.Info.License.Url)
}
code.Outdent()
}
code.Print("Parameters: %+v", document.Parameters)
code.Print("Paths:")
code.Indent()
for _, pair := range document.Paths.Path {
code.Print("%+v", pair.Name)
code.Indent()
v := pair.Value
if v.Get != nil {
code.Print("GET")
code.Indent()
printOperation(code, v.Get)
code.Outdent()
}
if v.Post != nil {
code.Print("POST")
code.Indent()
printOperation(code, v.Post)
code.Outdent()
}
code.Outdent()
}
code.Outdent()
code.Print("Produces: %+v", document.Produces)
code.Print("Responses: %+v", document.Responses)
code.Print("Schemes: %+v", document.Schemes)
code.Print("Security: %+v", document.Security)
if document.SecurityDefinitions != nil {
code.Print("SecurityDefinitions:")
code.Indent()
for _, pair := range document.SecurityDefinitions.AdditionalProperties {
code.Print("%s", pair.Name)
code.Indent()
v := pair.Value
switch t := v.Oneof.(type) {
default:
code.Print("unexpected type %T", t) // %T prints whatever type t has
case *pb.SecurityDefinitionsItem_ApiKeySecurity:
code.Print("ApiKeySecurity: %+v", t)
case *pb.SecurityDefinitionsItem_BasicAuthenticationSecurity:
code.Print("BasicAuthenticationSecurity: %+v", t)
case *pb.SecurityDefinitionsItem_Oauth2AccessCodeSecurity:
code.Print("Oauth2AccessCodeSecurity: %+v", t)
case *pb.SecurityDefinitionsItem_Oauth2ApplicationSecurity:
code.Print("Oauth2ApplicationSecurity: %+v", t)
case *pb.SecurityDefinitionsItem_Oauth2ImplicitSecurity:
code.Print("Oauth2ImplicitSecurity")
code.Indent()
code.Print("AuthorizationUrl: %+v", t.Oauth2ImplicitSecurity.AuthorizationUrl)
code.Print("Flow: %+v", t.Oauth2ImplicitSecurity.Flow)
code.Print("Scopes:")
code.Indent()
for _, pair := range t.Oauth2ImplicitSecurity.Scopes.AdditionalProperties {
code.Print("%s -> %s", pair.Name, pair.Value)
}
code.Outdent()
code.Outdent()
case *pb.SecurityDefinitionsItem_Oauth2PasswordSecurity:
code.Print("Oauth2PasswordSecurity: %+v", t)
}
code.Outdent()
}
code.Outdent()
}
code.Print("Swagger: %+v", document.Swagger)
code.Print("Tags:")
code.Indent()
for _, tag := range document.Tags {
code.Print("Tag:")
code.Indent()
code.Print("Name: %s", tag.Name)
code.Print("Description: %s", tag.Description)
code.Print("ExternalDocs: %s", tag.ExternalDocs)
printVendorExtension(code, tag.VendorExtension)
code.Outdent()
}
code.Outdent()
}
func printOperation(code *printer.Code, operation *pb.Operation) {
code.Print("Consumes: %+v", operation.Consumes)
code.Print("Deprecated: %+v", operation.Deprecated)
code.Print("Description: %+v", operation.Description)
code.Print("ExternalDocs: %+v", operation.ExternalDocs)
code.Print("OperationId: %+v", operation.OperationId)
code.Print("Parameters:")
code.Indent()
for _, item := range operation.Parameters {
switch t := item.Oneof.(type) {
default:
code.Print("unexpected type %T", t) // %T prints whatever type t has
case *pb.ParametersItem_JsonReference:
code.Print("JsonReference: %+v", t)
case *pb.ParametersItem_Parameter:
code.Print("Parameter: %+v", t)
}
}
code.Outdent()
code.Print("Produces: %+v", operation.Produces)
code.Print("Responses:")
code.Indent()
code.Print("ResponseCode:")
code.Indent()
for _, pair := range operation.Responses.ResponseCode {
code.Print("%s %s", pair.Name, pair.Value)
}
code.Outdent()
printVendorExtension(code, operation.Responses.VendorExtension)
code.Outdent()
code.Print("Schemes: %+v", operation.Schemes)
code.Print("Security: %+v", operation.Security)
code.Print("Summary: %+v", operation.Summary)
code.Print("Tags: %+v", operation.Tags)
printVendorExtension(code, operation.VendorExtension)
}
func printSchema(code *printer.Code, schema *pb.Schema) {
//code.Print("%+v", schema)
if schema.Format != "" {
code.Print("Format: %+v", schema.Format)
}
if schema.Properties != nil {
code.Print("Properties")
code.Indent()
for _, pair := range schema.Properties.AdditionalProperties {
code.Print("%s", pair.Name)
code.Indent()
printSchema(code, pair.Value)
code.Outdent()
}
code.Outdent()
}
if schema.Type != nil {
code.Print("Type: %+v", schema.Type)
}
if schema.Xml != nil {
code.Print("Xml: %+v", schema.Xml)
}
printVendorExtension(code, schema.VendorExtension)
}
func printVendorExtension(code *printer.Code, vendorExtension []*pb.NamedAny) {
if len(vendorExtension) > 0 {
code.Print("VendorExtension: %+v", vendorExtension)
}
}
func main() {
flag.Parse()
args := flag.Args()
if len(args) != 1 {
fmt.Printf("Usage: report <file.pb>\n")
return
}
document := readDocumentFromFileWithName(args[0])
code := &printer.Code{}
code.Print("API REPORT")
code.Print("----------")
printDocument(code, document)
fmt.Printf("%s", code)
}

View file

@ -0,0 +1,3 @@
# Compiler support code
This directory contains compiler support code used by Gnostic and Gnostic extensions.

View file

@ -0,0 +1,41 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package compiler
type Context struct {
Parent *Context
Name string
ExtensionHandlers *[]ExtensionHandler
}
func NewContextWithExtensions(name string, parent *Context, extensionHandlers *[]ExtensionHandler) *Context {
return &Context{Name: name, Parent: parent, ExtensionHandlers: extensionHandlers}
}
func NewContext(name string, parent *Context) *Context {
if parent != nil {
return &Context{Name: name, Parent: parent, ExtensionHandlers: parent.ExtensionHandlers}
} else {
return &Context{Name: name, Parent: parent, ExtensionHandlers: nil}
}
}
func (context *Context) Description() string {
if context.Parent != nil {
return context.Parent.Description() + "." + context.Name
} else {
return context.Name
}
}

59
vendor/github.com/googleapis/gnostic/compiler/error.go generated vendored Normal file
View file

@ -0,0 +1,59 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package compiler
// basic error type
type Error struct {
Context *Context
Message string
}
func NewError(context *Context, message string) *Error {
return &Error{Context: context, Message: message}
}
func (err *Error) Error() string {
if err.Context != nil {
return "ERROR " + err.Context.Description() + " " + err.Message
} else {
return "ERROR " + err.Message
}
}
// container for groups of errors
type ErrorGroup struct {
Errors []error
}
func NewErrorGroupOrNil(errors []error) error {
if len(errors) == 0 {
return nil
} else if len(errors) == 1 {
return errors[0]
} else {
return &ErrorGroup{Errors: errors}
}
}
func (group *ErrorGroup) Error() string {
result := ""
for i, err := range group.Errors {
if i > 0 {
result += "\n"
}
result += err.Error()
}
return result
}

View file

@ -0,0 +1,99 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package compiler
import (
"bytes"
"fmt"
"os/exec"
"strings"
"errors"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
ext_plugin "github.com/googleapis/gnostic/extensions"
yaml "gopkg.in/yaml.v2"
)
type ExtensionHandler struct {
Name string
}
func HandleExtension(context *Context, in interface{}, extensionName string) (bool, *any.Any, error) {
handled := false
var errFromPlugin error
var outFromPlugin *any.Any
if context.ExtensionHandlers != nil && len(*(context.ExtensionHandlers)) != 0 {
for _, customAnyProtoGenerator := range *(context.ExtensionHandlers) {
outFromPlugin, errFromPlugin = customAnyProtoGenerator.handle(in, extensionName)
if outFromPlugin == nil {
continue
} else {
handled = true
break
}
}
}
return handled, outFromPlugin, errFromPlugin
}
func (extensionHandlers *ExtensionHandler) handle(in interface{}, extensionName string) (*any.Any, error) {
if extensionHandlers.Name != "" {
binary, _ := yaml.Marshal(in)
request := &ext_plugin.ExtensionHandlerRequest{}
version := &ext_plugin.Version{}
version.Major = 0
version.Minor = 1
version.Patch = 0
request.CompilerVersion = version
request.Wrapper = &ext_plugin.Wrapper{}
request.Wrapper.Version = "v2"
request.Wrapper.Yaml = string(binary)
request.Wrapper.ExtensionName = extensionName
requestBytes, _ := proto.Marshal(request)
cmd := exec.Command(extensionHandlers.Name)
cmd.Stdin = bytes.NewReader(requestBytes)
output, err := cmd.Output()
if err != nil {
fmt.Printf("Error: %+v\n", err)
return nil, err
}
response := &ext_plugin.ExtensionHandlerResponse{}
err = proto.Unmarshal(output, response)
if err != nil {
fmt.Printf("Error: %+v\n", err)
fmt.Printf("%s\n", string(output))
return nil, err
}
if !response.Handled {
return nil, nil
}
if len(response.Error) != 0 {
message := fmt.Sprintf("Errors when parsing: %+v for field %s by vendor extension handler %s. Details %+v", in, extensionName, extensionHandlers.Name, strings.Join(response.Error, ","))
return nil, errors.New(message)
}
return response.Value, nil
}
return nil, nil
}

View file

@ -0,0 +1,193 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package compiler
import (
"fmt"
"gopkg.in/yaml.v2"
"regexp"
"sort"
"strings"
)
// compiler helper functions, usually called from generated code
func UnpackMap(in interface{}) (yaml.MapSlice, bool) {
m, ok := in.(yaml.MapSlice)
if ok {
return m, ok
} else {
// do we have an empty array?
a, ok := in.([]interface{})
if ok && len(a) == 0 {
// if so, return an empty map
return yaml.MapSlice{}, ok
} else {
return nil, ok
}
}
}
func SortedKeysForMap(m yaml.MapSlice) []string {
keys := make([]string, 0)
for _, item := range m {
keys = append(keys, item.Key.(string))
}
sort.Strings(keys)
return keys
}
func MapHasKey(m yaml.MapSlice, key string) bool {
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok && key == itemKey {
return true
}
}
return false
}
func MapValueForKey(m yaml.MapSlice, key string) interface{} {
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok && key == itemKey {
return item.Value
}
}
return nil
}
func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string {
stringArray := make([]string, 0)
for _, item := range interfaceArray {
v, ok := item.(string)
if ok {
stringArray = append(stringArray, v)
}
}
return stringArray
}
func PatternMatches(pattern string, value string) bool {
// if pattern contains a subpattern like "{path}", replace it with ".*"
if pattern[0] != '^' {
subpatternPattern := regexp.MustCompile("^.*(\\{.*\\}).*$")
if matches := subpatternPattern.FindSubmatch([]byte(pattern)); matches != nil {
match := string(matches[1])
pattern = strings.Replace(pattern, match, ".*", -1)
}
}
matched, err := regexp.Match(pattern, []byte(value))
if err != nil {
panic(err)
}
return matched
}
func MissingKeysInMap(m yaml.MapSlice, requiredKeys []string) []string {
missingKeys := make([]string, 0)
for _, k := range requiredKeys {
if !MapHasKey(m, k) {
missingKeys = append(missingKeys, k)
}
}
return missingKeys
}
func InvalidKeysInMap(m yaml.MapSlice, allowedKeys []string, allowedPatterns []string) []string {
invalidKeys := make([]string, 0)
for _, item := range m {
itemKey, ok := item.Key.(string)
if ok {
key := itemKey
found := false
// does the key match an allowed key?
for _, allowedKey := range allowedKeys {
if key == allowedKey {
found = true
break
}
}
if !found {
// does the key match an allowed pattern?
for _, allowedPattern := range allowedPatterns {
if PatternMatches(allowedPattern, key) {
found = true
break
}
}
if !found {
invalidKeys = append(invalidKeys, key)
}
}
}
}
return invalidKeys
}
// describe a map (for debugging purposes)
func DescribeMap(in interface{}, indent string) string {
description := ""
m, ok := in.(map[string]interface{})
if ok {
keys := make([]string, 0)
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := m[k]
description += fmt.Sprintf("%s%s:\n", indent, k)
description += DescribeMap(v, indent+" ")
}
return description
}
a, ok := in.([]interface{})
if ok {
for i, v := range a {
description += fmt.Sprintf("%s%d:\n", indent, i)
description += DescribeMap(v, indent+" ")
}
return description
}
description += fmt.Sprintf("%s%+v\n", indent, in)
return description
}
func PluralProperties(count int) string {
if count == 1 {
return "property"
} else {
return "properties"
}
}
func StringArrayContainsValue(array []string, value string) bool {
for _, item := range array {
if item == value {
return true
}
}
return false
}
func StringArrayContainsValues(array []string, values []string) bool {
for _, value := range values {
if !StringArrayContainsValue(array, value) {
return false
}
}
return true
}

16
vendor/github.com/googleapis/gnostic/compiler/main.go generated vendored Normal file
View file

@ -0,0 +1,16 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// Package compiler provides support functions to generated compiler code.
package compiler

167
vendor/github.com/googleapis/gnostic/compiler/reader.go generated vendored Normal file
View file

@ -0,0 +1,167 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package compiler
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"net/http"
"net/url"
"path/filepath"
"strings"
)
var file_cache map[string][]byte
var info_cache map[string]interface{}
var count int64
var VERBOSE_READER = false
func initializeFileCache() {
if file_cache == nil {
file_cache = make(map[string][]byte, 0)
}
}
func initializeInfoCache() {
if info_cache == nil {
info_cache = make(map[string]interface{}, 0)
}
}
func FetchFile(fileurl string) ([]byte, error) {
initializeFileCache()
bytes, ok := file_cache[fileurl]
if ok {
if VERBOSE_READER {
log.Printf("Cache hit %s", fileurl)
}
return bytes, nil
}
log.Printf("Fetching %s", fileurl)
response, err := http.Get(fileurl)
if err != nil {
return nil, err
} else {
defer response.Body.Close()
bytes, err := ioutil.ReadAll(response.Body)
if err == nil {
file_cache[fileurl] = bytes
}
return bytes, err
}
}
// read a file and unmarshal it as a yaml.MapSlice
func ReadInfoForFile(filename string) (interface{}, error) {
initializeInfoCache()
info, ok := info_cache[filename]
if ok {
if VERBOSE_READER {
log.Printf("Cache hit info for file %s", filename)
}
return info, nil
}
if VERBOSE_READER {
log.Printf("Reading info for file %s", filename)
}
// is the filename a url?
fileurl, _ := url.Parse(filename)
if fileurl.Scheme != "" {
// yes, fetch it
bytes, err := FetchFile(filename)
if err != nil {
return nil, err
}
var info yaml.MapSlice
err = yaml.Unmarshal(bytes, &info)
if err != nil {
return nil, err
}
info_cache[filename] = info
return info, nil
} else {
// no, it's a local filename
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("File error: %v\n", err)
return nil, err
}
var info yaml.MapSlice
err = yaml.Unmarshal(bytes, &info)
if err != nil {
return nil, err
}
info_cache[filename] = info
return info, nil
}
}
// read a file and return the fragment needed to resolve a $ref
func ReadInfoForRef(basefile string, ref string) (interface{}, error) {
initializeInfoCache()
{
info, ok := info_cache[ref]
if ok {
if VERBOSE_READER {
log.Printf("Cache hit for ref %s#%s", basefile, ref)
}
return info, nil
}
}
if VERBOSE_READER {
log.Printf("Reading info for ref %s#%s", basefile, ref)
}
count = count + 1
basedir, _ := filepath.Split(basefile)
parts := strings.Split(ref, "#")
var filename string
if parts[0] != "" {
filename = basedir + parts[0]
} else {
filename = basefile
}
info, err := ReadInfoForFile(filename)
if err != nil {
log.Printf("File error: %v\n", err)
} else {
if len(parts) > 1 {
path := strings.Split(parts[1], "/")
for i, key := range path {
if i > 0 {
m, ok := info.(yaml.MapSlice)
if ok {
found := false
for _, section := range m {
if section.Key == key {
info = section.Value
found = true
}
}
if !found {
info_cache[ref] = nil
return nil, NewError(nil, fmt.Sprintf("could not resolve %s", ref))
}
}
}
}
}
}
info_cache[ref] = info
return info, nil
}

View file

@ -0,0 +1,3 @@
# examples
This directory contains example descriptions of APIs.

View file

@ -0,0 +1,101 @@
swagger: "2.0"
info:
title: Swagger Petstore
myproperty: 123
license:
name: MIT
host: petstore.swagger.io
basePath: /v1
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
type: integer
format: int32
myproperty: 123
responses:
"200":
description: An paged array of pets
headers:
x-next:
type: string
description: A link to the next page of responses
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
post:
summary: Create a pet
operationId: createPets
tags: pets
responses:
"201":
description: Null response
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
type: string
responses:
"200":
description: Expected response to a valid request
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: '#/definitions/Pet'
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,101 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
host: petstore.swagger.io
basePath: /v1
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
type: integer
format: int32
responses:
"200":
description: An paged array of pets
headers:
x-next:
type: string
description: A link to the next page of responses
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
"201":
description: Null response
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
type: string
responses:
"200":
description: Expected response to a valid request
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
NotAPet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: '#/definitions/Pet'
NotAnError:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,58 @@
{
"swagger": "2.0",
"info": {
"title": "Simple API overview",
"version": "v2"
},
"paths": {
"/": {
"get": {
"operationId": "listVersionsv2",
"summary": "List API versions",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 300 response",
"examples": {
"application/json": "{\n \"versions\": [\n {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n }\n ]\n },\n {\n \"status\": \"EXPERIMENTAL\",\n \"updated\": \"2013-07-23T11:33:21Z\",\n \"id\": \"v3.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v3/\",\n \"rel\": \"self\"\n }\n ]\n }\n ]\n}"
}
},
"300": {
"description": "200 300 response",
"examples": {
"application/json": "{\n \"versions\": [\n {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n }\n ]\n },\n {\n \"status\": \"EXPERIMENTAL\",\n \"updated\": \"2013-07-23T11:33:21Z\",\n \"id\": \"v3.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v3/\",\n \"rel\": \"self\"\n }\n ]\n }\n ]\n}"
}
}
}
}
},
"/v2": {
"get": {
"operationId": "getVersionDetailsv2",
"summary": "Show API version details",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 203 response",
"examples": {
"application/json": "{\n \"version\": {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute+xml;version=2\"\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute+json;version=2\"\n }\n ],\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf\",\n \"type\": \"application/pdf\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n }\n ]\n }\n}"
}
},
"203": {
"description": "200 203 response",
"examples": {
"application/json": "{\n \"version\": {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute+xml;version=2\"\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute+json;version=2\"\n }\n ],\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://23.253.228.211:8774/v2/\",\n \"rel\": \"self\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf\",\n \"type\": \"application/pdf\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n }\n ]\n }\n}"
}
}
}
}
}
},
"consumes": [
"application/json"
]
}

View file

@ -0,0 +1,210 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team",
"email": "foo@example.com",
"url": "http://madskristensen.net"
},
"license": {
"name": "MIT",
"url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to\nNam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.\n\nSed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.\n",
"operationId": "findPets",
"parameters": [
{
"name": "tags",
"in": "query",
"description": "tags to filter by",
"required": false,
"type": "array",
"collectionFormat": "csv",
"items": {
"type": "string"
}
},
{
"name": "limit",
"in": "query",
"description": "maximum number of results to return",
"required": false,
"type": "integer",
"format": "int32"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"post": {
"description": "Creates a new pet in the store. Duplicates are allowed",
"operationId": "addPet",
"parameters": [
{
"name": "pet",
"in": "body",
"description": "Pet to add to the store",
"required": true,
"schema": {
"$ref": "#/definitions/NewPet"
}
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/pets/{id}": {
"get": {
"description": "Returns a user based on a single ID, if the user does not have access to the pet",
"operationId": "find pet by id",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/NewPet"
},
{
"required": [
"id"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"NewPet": {
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"Error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,68 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A list of pets.",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,16 @@
{
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}

View file

@ -0,0 +1,19 @@
{
"type": "object",
"allOf": [
{
"$ref": "Pet.json"
},
{
"required": [
"name"
],
"properties": {
"description": {
"type": "integer",
"format": "int64"
}
}
}
]
}

View file

@ -0,0 +1,19 @@
{
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
}

View file

@ -0,0 +1,21 @@
{
"tagsParam": {
"name": "tags",
"in": "query",
"description": "tags to filter by",
"required": false,
"type": "array",
"collectionFormat": "csv",
"items": {
"type": "string"
}
},
"limitsParam": {
"name": "limit",
"in": "query",
"description": "maximum number of results to return",
"required": false,
"type": "integer",
"format": "int32"
}
}

View file

@ -0,0 +1,146 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://helloreverb.com/terms/",
"contact": {
"name": "Wordnik API Team",
"email": "foo@example.com",
"url": "http://madskristensen.net"
},
"license": {
"name": "MIT",
"url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
}
},
"host": "petstore.swagger.wordnik.com",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to\nNam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.\n\nSed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.\n",
"operationId": "findPets",
"parameters": [
{
"$ref": "parameters.json#/tagsParam"
},
{
"$ref": "parameters.json#/limitsParam"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "Pet.json"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "../common/Error.json"
}
}
}
},
"post": {
"description": "Creates a new pet in the store. Duplicates are allowed",
"operationId": "addPet",
"parameters": [
{
"name": "pet",
"in": "body",
"description": "Pet to add to the store",
"required": true,
"schema": {
"$ref": "NewPet.json"
}
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "Pet.json"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "../common/Error.json"
}
}
}
}
},
"/pets/{id}": {
"get": {
"description": "Returns a user based on a single ID, if the user does not have access to the pet",
"operationId": "find pet by id",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "Pet.json"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "../common/Error.json"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "../common/Error.json"
}
}
}
}
}
}
}

View file

@ -0,0 +1,222 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to",
"operationId": "findPets",
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "tags",
"in": "query",
"description": "tags to filter by",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "csv"
},
{
"name": "limit",
"in": "query",
"description": "maximum number of results to return",
"required": false,
"type": "integer",
"format": "int32"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
},
"post": {
"description": "Creates a new pet in the store. Duplicates are allowed",
"operationId": "addPet",
"produces": [
"application/json"
],
"parameters": [
{
"name": "pet",
"in": "body",
"description": "Pet to add to the store",
"required": true,
"schema": {
"$ref": "#/definitions/NewPet"
}
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
}
},
"/pets/{id}": {
"get": {
"description": "Returns a user based on a single ID, if the user does not have access to the pet",
"operationId": "findPetById",
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/NewPet"
},
{
"required": [
"id"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"NewPet": {
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"ErrorModel": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,233 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team",
"email": "apiteam@swagger.io",
"url": "http://swagger.io"
},
"license": {
"name": "MIT",
"url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
}
},
"externalDocs": {
"description": "find more info here",
"url": "https://swagger.io/about"
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to",
"operationId": "findPets",
"externalDocs": {
"description": "find more info here",
"url": "https://swagger.io/about"
},
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "tags",
"in": "query",
"description": "tags to filter by",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "csv"
},
{
"name": "limit",
"in": "query",
"description": "maximum number of results to return",
"required": false,
"type": "integer",
"format": "int32"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
},
"post": {
"description": "Creates a new pet in the store. Duplicates are allowed",
"operationId": "addPet",
"produces": [
"application/json"
],
"parameters": [
{
"name": "pet",
"in": "body",
"description": "Pet to add to the store",
"required": true,
"schema": {
"$ref": "#/definitions/NewPet"
}
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
}
},
"/pets/{id}": {
"get": {
"description": "Returns a user based on a single ID, if the user does not have access to the pet",
"operationId": "findPetById",
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ID of pet to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/ErrorModel"
}
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/NewPet"
},
{
"required": [
"id"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"NewPet": {
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"ErrorModel": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,153 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/v1",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"summary": "List all pets",
"operationId": "listPets",
"tags": [
"pets"
],
"parameters": [
{
"name": "limit",
"in": "query",
"description": "How many items to return at one time (max 100)",
"required": false,
"type": "integer",
"format": "int32"
}
],
"responses": {
"200": {
"description": "An paged array of pets",
"headers": {
"x-next": {
"type": "string",
"description": "A link to the next page of responses"
}
},
"schema": {
"$ref": "#/definitions/Pets"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"post": {
"summary": "Create a pet",
"operationId": "createPets",
"tags": [
"pets"
],
"responses": {
"201": {
"description": "Null response"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/pets/{petId}": {
"get": {
"summary": "Info for a specific pet",
"operationId": "showPetById",
"tags": [
"pets"
],
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"description": "The id of the pet to retrieve",
"type": "string"
}
],
"responses": {
"200": {
"description": "Expected response to a valid request",
"schema": {
"$ref": "#/definitions/Pets"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
}
},
"definitions": {
"Pet": {
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"Pets": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
},
"Error": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,370 @@
{
"swagger": "2.0",
"info": {
"title": "Uber API",
"description": "Move your app forward with the Uber API",
"version": "1.0.0"
},
"host": "api.uber.com",
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
"paths": {
"/products": {
"get": {
"summary": "Product Types",
"description": "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.",
"parameters": [
{
"name": "latitude",
"in": "query",
"description": "Latitude component of location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "longitude",
"in": "query",
"description": "Longitude component of location.",
"required": true,
"type": "number",
"format": "double"
}
],
"tags": [
"Products"
],
"responses": {
"200": {
"description": "An array of products",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Product"
}
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/estimates/price": {
"get": {
"summary": "Price Estimates",
"description": "The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.<br><br>The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.",
"parameters": [
{
"name": "start_latitude",
"in": "query",
"description": "Latitude component of start location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "start_longitude",
"in": "query",
"description": "Longitude component of start location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "end_latitude",
"in": "query",
"description": "Latitude component of end location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "end_longitude",
"in": "query",
"description": "Longitude component of end location.",
"required": true,
"type": "number",
"format": "double"
}
],
"tags": [
"Estimates"
],
"responses": {
"200": {
"description": "An array of price estimates by product",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/PriceEstimate"
}
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/estimates/time": {
"get": {
"summary": "Time Estimates",
"description": "The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.",
"parameters": [
{
"name": "start_latitude",
"in": "query",
"description": "Latitude component of start location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "start_longitude",
"in": "query",
"description": "Longitude component of start location.",
"required": true,
"type": "number",
"format": "double"
},
{
"name": "customer_uuid",
"in": "query",
"type": "string",
"format": "uuid",
"description": "Unique customer identifier to be used for experience customization."
},
{
"name": "product_id",
"in": "query",
"type": "string",
"description": "Unique identifier representing a specific product for a given latitude & longitude."
}
],
"tags": [
"Estimates"
],
"responses": {
"200": {
"description": "An array of products",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Product"
}
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/me": {
"get": {
"summary": "User Profile",
"description": "The User Profile endpoint returns information about the Uber user that has authorized with the application.",
"tags": [
"User"
],
"responses": {
"200": {
"description": "Profile information for a user",
"schema": {
"$ref": "#/definitions/Profile"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/history": {
"get": {
"summary": "User Activity",
"description": "The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.<br><br>The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.",
"parameters": [
{
"name": "offset",
"in": "query",
"type": "integer",
"format": "int32",
"description": "Offset the list of returned results by this amount. Default is zero."
},
{
"name": "limit",
"in": "query",
"type": "integer",
"format": "int32",
"description": "Number of items to retrieve. Default is 5, maximum is 100."
}
],
"tags": [
"User"
],
"responses": {
"200": {
"description": "History information for the given user",
"schema": {
"$ref": "#/definitions/Activities"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
}
},
"definitions": {
"Product": {
"properties": {
"product_id": {
"type": "string",
"description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles."
},
"description": {
"type": "string",
"description": "Description of product."
},
"display_name": {
"type": "string",
"description": "Display name of product."
},
"capacity": {
"type": "string",
"description": "Capacity of product. For example, 4 people."
},
"image": {
"type": "string",
"description": "Image URL representing the product."
}
}
},
"PriceEstimate": {
"properties": {
"product_id": {
"type": "string",
"description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles"
},
"currency_code": {
"type": "string",
"description": "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code."
},
"display_name": {
"type": "string",
"description": "Display name of product."
},
"estimate": {
"type": "string",
"description": "Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or \"Metered\" for TAXI."
},
"low_estimate": {
"type": "number",
"description": "Lower bound of the estimated price."
},
"high_estimate": {
"type": "number",
"description": "Upper bound of the estimated price."
},
"surge_multiplier": {
"type": "number",
"description": "Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier."
}
}
},
"Profile": {
"properties": {
"first_name": {
"type": "string",
"description": "First name of the Uber user."
},
"last_name": {
"type": "string",
"description": "Last name of the Uber user."
},
"email": {
"type": "string",
"description": "Email address of the Uber user"
},
"picture": {
"type": "string",
"description": "Image URL of the Uber user."
},
"promo_code": {
"type": "string",
"description": "Promo code of the Uber user."
}
}
},
"Activity": {
"properties": {
"uuid": {
"type": "string",
"description": "Unique identifier for the activity"
}
}
},
"Activities": {
"properties": {
"offset": {
"type": "integer",
"format": "int32",
"description": "Position in pagination."
},
"limit": {
"type": "integer",
"format": "int32",
"description": "Number of items to retrieve (100 max)."
},
"count": {
"type": "integer",
"format": "int32",
"description": "Total number of items available."
},
"history": {
"type": "array",
"items": {
"$ref": "#/definitions/Activity"
}
}
}
},
"Error": {
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"fields": {
"type": "string"
}
}
}
}
}

View file

@ -0,0 +1,164 @@
swagger: "2.0"
info:
title: Simple API overview
version: v2
paths:
/:
get:
operationId: listVersionsv2
summary: List API versions
produces:
- application/json
responses:
"200":
description: |-
200 300 response
examples:
application/json: |-
{
"versions": [
{
"status": "CURRENT",
"updated": "2011-01-21T11:33:21Z",
"id": "v2.0",
"links": [
{
"href": "http://127.0.0.1:8774/v2/",
"rel": "self"
}
]
},
{
"status": "EXPERIMENTAL",
"updated": "2013-07-23T11:33:21Z",
"id": "v3.0",
"links": [
{
"href": "http://127.0.0.1:8774/v3/",
"rel": "self"
}
]
}
]
}
"300":
description: |-
200 300 response
examples:
application/json: |-
{
"versions": [
{
"status": "CURRENT",
"updated": "2011-01-21T11:33:21Z",
"id": "v2.0",
"links": [
{
"href": "http://127.0.0.1:8774/v2/",
"rel": "self"
}
]
},
{
"status": "EXPERIMENTAL",
"updated": "2013-07-23T11:33:21Z",
"id": "v3.0",
"links": [
{
"href": "http://127.0.0.1:8774/v3/",
"rel": "self"
}
]
}
]
}
/v2:
get:
operationId: getVersionDetailsv2
summary: Show API version details
produces:
- application/json
responses:
"200":
description: |-
200 203 response
examples:
application/json: |-
{
"version": {
"status": "CURRENT",
"updated": "2011-01-21T11:33:21Z",
"media-types": [
{
"base": "application/xml",
"type": "application/vnd.openstack.compute+xml;version=2"
},
{
"base": "application/json",
"type": "application/vnd.openstack.compute+json;version=2"
}
],
"id": "v2.0",
"links": [
{
"href": "http://127.0.0.1:8774/v2/",
"rel": "self"
},
{
"href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf",
"type": "application/pdf",
"rel": "describedby"
},
{
"href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
"type": "application/vnd.sun.wadl+xml",
"rel": "describedby"
},
{
"href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
"type": "application/vnd.sun.wadl+xml",
"rel": "describedby"
}
]
}
}
"203":
description: |-
200 203 response
examples:
application/json: |-
{
"version": {
"status": "CURRENT",
"updated": "2011-01-21T11:33:21Z",
"media-types": [
{
"base": "application/xml",
"type": "application/vnd.openstack.compute+xml;version=2"
},
{
"base": "application/json",
"type": "application/vnd.openstack.compute+json;version=2"
}
],
"id": "v2.0",
"links": [
{
"href": "http://23.253.228.211:8774/v2/",
"rel": "self"
},
{
"href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf",
"type": "application/pdf",
"rel": "describedby"
},
{
"href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
"type": "application/vnd.sun.wadl+xml",
"rel": "describedby"
}
]
}
}
consumes:
- application/json

View file

@ -0,0 +1,142 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
termsOfService: http://swagger.io/terms/
contact:
name: Swagger API Team
email: foo@example.com
url: http://madskristensen.net
license:
name: MIT
url: http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
host: petstore.swagger.io
basePath: /api
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
description: |
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
operationId: findPets
parameters:
- name: tags
in: query
description: tags to filter by
required: false
type: array
collectionFormat: csv
items:
type: string
- name: limit
in: query
description: maximum number of results to return
required: false
type: integer
format: int32
responses:
"200":
description: pet response
schema:
type: array
items:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
post:
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
parameters:
- name: pet
in: body
description: Pet to add to the store
required: true
schema:
$ref: '#/definitions/NewPet'
responses:
"200":
description: pet response
schema:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
/pets/{id}:
get:
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: id
in: path
description: ID of pet to fetch
required: true
type: integer
format: int64
responses:
"200":
description: pet response
schema:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
type: integer
format: int64
responses:
"204":
description: pet deleted
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
Pet:
allOf:
- $ref: '#/definitions/NewPet'
- required:
- id
properties:
id:
type: integer
format: int64
NewPet:
required:
- name
properties:
name:
type: string
tag:
type: string
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,47 @@
---
swagger: "2.0"
info:
version: "1.0.0"
title: "Swagger Petstore"
description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"
termsOfService: "http://swagger.io/terms/"
contact:
name: "Swagger API Team"
license:
name: "MIT"
host: "petstore.swagger.io"
basePath: "/api"
schemes:
- "http"
consumes:
- "application/json"
produces:
- "application/json"
paths:
/pets:
get:
description: "Returns all pets from the system that the user has access to"
produces:
- "application/json"
responses:
"200":
description: "A list of pets."
schema:
type: "array"
items:
$ref: "#/definitions/Pet"
definitions:
Pet:
type: "object"
required:
- "id"
- "name"
properties:
id:
type: "integer"
format: "int64"
name:
type: "string"
tag:
type: "string"

View file

@ -0,0 +1,10 @@
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,9 @@
type: object
allOf:
- $ref: 'Pet.yaml'
- required:
- name
properties:
description:
type: integer
format: int64

View file

@ -0,0 +1,12 @@
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string

View file

@ -0,0 +1,16 @@
tagsParam:
name: tags
in: query
description: tags to filter by
required: false
type: array
collectionFormat: csv
items:
type: string
limitsParam:
name: limit
in: query
description: maximum number of results to return
required: false
type: integer
format: int32

View file

@ -0,0 +1,214 @@
swagger: "2.0"
info: <
title: "Swagger Petstore"
version: "1.0.0"
description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"
terms_of_service: "http://helloreverb.com/terms/"
contact: <
name: "Wordnik API Team"
url: "http://madskristensen.net"
email: "foo@example.com"
>
license: <
name: "MIT"
url: "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
>
>
host: "petstore.swagger.wordnik.com"
base_path: "/api"
schemes: "http"
consumes: "application/json"
produces: "application/json"
paths: <
path: <
name: "/pets"
value: <
get: <
description: "Returns all pets from the system that the user has access to\nNam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.\n\nSed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.\n"
operation_id: "findPets"
parameters: <
json_reference: <
_ref: "parameters.yaml#/tagsParam"
>
>
parameters: <
json_reference: <
_ref: "parameters.yaml#/limitsParam"
>
>
responses: <
response_code: <
name: "200"
value: <
response: <
description: "pet response"
schema: <
schema: <
type: <
value: "array"
>
items: <
schema: <
_ref: "Pet.yaml"
>
>
>
>
>
>
>
response_code: <
name: "default"
value: <
response: <
description: "unexpected error"
schema: <
schema: <
_ref: "../common/Error.yaml"
>
>
>
>
>
>
>
post: <
description: "Creates a new pet in the store. Duplicates are allowed"
operation_id: "addPet"
parameters: <
parameter: <
body_parameter: <
description: "Pet to add to the store"
name: "pet"
in: "body"
required: true
schema: <
_ref: "NewPet.yaml"
>
>
>
>
responses: <
response_code: <
name: "200"
value: <
response: <
description: "pet response"
schema: <
schema: <
_ref: "Pet.yaml"
>
>
>
>
>
response_code: <
name: "default"
value: <
response: <
description: "unexpected error"
schema: <
schema: <
_ref: "../common/Error.yaml"
>
>
>
>
>
>
>
>
>
path: <
name: "/pets/{id}"
value: <
get: <
description: "Returns a user based on a single ID, if the user does not have access to the pet"
operation_id: "find pet by id"
parameters: <
parameter: <
non_body_parameter: <
path_parameter_sub_schema: <
required: true
in: "path"
description: "ID of pet to fetch"
name: "id"
type: "integer"
format: "int64"
>
>
>
>
responses: <
response_code: <
name: "200"
value: <
response: <
description: "pet response"
schema: <
schema: <
_ref: "Pet.yaml"
>
>
>
>
>
response_code: <
name: "default"
value: <
response: <
description: "unexpected error"
schema: <
schema: <
_ref: "../common/Error.yaml"
>
>
>
>
>
>
>
delete: <
description: "deletes a single pet based on the ID supplied"
operation_id: "deletePet"
parameters: <
parameter: <
non_body_parameter: <
path_parameter_sub_schema: <
required: true
in: "path"
description: "ID of pet to delete"
name: "id"
type: "integer"
format: "int64"
>
>
>
>
responses: <
response_code: <
name: "204"
value: <
response: <
description: "pet deleted"
>
>
>
response_code: <
name: "default"
value: <
response: <
description: "unexpected error"
schema: <
schema: <
_ref: "../common/Error.yaml"
>
>
>
>
>
>
>
>
>
>

View file

@ -0,0 +1,100 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
termsOfService: http://helloreverb.com/terms/
contact:
name: Wordnik API Team
email: foo@example.com
url: http://madskristensen.net
license:
name: MIT
url: http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
host: petstore.swagger.wordnik.com
basePath: /api
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
description: |
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
operationId: findPets
parameters:
- $ref: 'parameters.yaml#/tagsParam'
- $ref: 'parameters.yaml#/limitsParam'
responses:
"200":
description: pet response
schema:
type: array
items:
$ref: 'Pet.yaml'
default:
description: unexpected error
schema:
$ref: '../common/Error.yaml'
post:
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
parameters:
- name: pet
in: body
description: Pet to add to the store
required: true
schema:
$ref: 'NewPet.yaml'
responses:
"200":
description: pet response
schema:
$ref: 'Pet.yaml'
default:
description: unexpected error
schema:
$ref: '../common/Error.yaml'
/pets/{id}:
get:
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: id
in: path
description: ID of pet to fetch
required: true
type: integer
format: int64
responses:
"200":
description: pet response
schema:
$ref: 'Pet.yaml'
default:
description: unexpected error
schema:
$ref: '../common/Error.yaml'
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
type: integer
format: int64
responses:
"204":
description: pet deleted
default:
description: unexpected error
schema:
$ref: '../common/Error.yaml'

View file

@ -0,0 +1,157 @@
---
swagger: "2.0"
info:
version: "1.0.0"
title: "Swagger Petstore"
description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"
termsOfService: "http://swagger.io/terms/"
contact:
name: "Swagger API Team"
license:
name: "MIT"
host: "petstore.swagger.io"
basePath: "/api"
schemes:
- "http"
consumes:
- "application/json"
produces:
- "application/json"
paths:
/pets:
get:
description: "Returns all pets from the system that the user has access to"
operationId: "findPets"
produces:
- "application/json"
- "application/xml"
- "text/xml"
- "text/html"
parameters:
-
name: "tags"
in: "query"
description: "tags to filter by"
required: false
type: "array"
items:
type: "string"
collectionFormat: "csv"
-
name: "limit"
in: "query"
description: "maximum number of results to return"
required: false
type: "integer"
format: "int32"
responses:
"200":
description: "pet response"
schema:
type: "array"
items:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
post:
description: "Creates a new pet in the store. Duplicates are allowed"
operationId: "addPet"
produces:
- "application/json"
parameters:
-
name: "pet"
in: "body"
description: "Pet to add to the store"
required: true
schema:
$ref: "#/definitions/NewPet"
responses:
"200":
description: "pet response"
schema:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
/pets/{id}:
get:
description: "Returns a user based on a single ID, if the user does not have access to the pet"
operationId: "findPetById"
produces:
- "application/json"
- "application/xml"
- "text/xml"
- "text/html"
parameters:
-
name: "id"
in: "path"
description: "ID of pet to fetch"
required: true
type: "integer"
format: "int64"
responses:
"200":
description: "pet response"
schema:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
delete:
description: "deletes a single pet based on the ID supplied"
operationId: "deletePet"
parameters:
-
name: "id"
in: "path"
description: "ID of pet to delete"
required: true
type: "integer"
format: "int64"
responses:
"204":
description: "pet deleted"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
definitions:
Pet:
type: "object"
allOf:
-
$ref: "#/definitions/NewPet"
-
required:
- "id"
properties:
id:
type: "integer"
format: "int64"
NewPet:
type: "object"
required:
- "name"
properties:
name:
type: "string"
tag:
type: "string"
ErrorModel:
type: "object"
required:
- "code"
- "message"
properties:
code:
type: "integer"
format: "int32"
message:
type: "string"

View file

@ -0,0 +1,166 @@
---
swagger: "2.0"
info:
version: "1.0.0"
title: "Swagger Petstore"
description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"
termsOfService: "http://swagger.io/terms/"
contact:
name: "Swagger API Team"
email: "apiteam@swagger.io"
url: "http://swagger.io"
license:
name: "MIT"
url: "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
externalDocs:
description: "find more info here"
url: "https://swagger.io/about"
host: "petstore.swagger.io"
basePath: "/api"
schemes:
- "http"
consumes:
- "application/json"
produces:
- "application/json"
paths:
/pets:
get:
description: "Returns all pets from the system that the user has access to"
operationId: "findPets"
externalDocs:
description: "find more info here"
url: "https://swagger.io/about"
produces:
- "application/json"
- "application/xml"
- "text/xml"
- "text/html"
parameters:
-
name: "tags"
in: "query"
description: "tags to filter by"
required: false
type: "array"
items:
type: "string"
collectionFormat: "csv"
-
name: "limit"
in: "query"
description: "maximum number of results to return"
required: false
type: "integer"
format: "int32"
responses:
"200":
description: "pet response"
schema:
type: "array"
items:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
post:
description: "Creates a new pet in the store. Duplicates are allowed"
operationId: "addPet"
produces:
- "application/json"
parameters:
-
name: "pet"
in: "body"
description: "Pet to add to the store"
required: true
schema:
$ref: "#/definitions/NewPet"
responses:
"200":
description: "pet response"
schema:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
/pets/{id}:
get:
description: "Returns a user based on a single ID, if the user does not have access to the pet"
operationId: "findPetById"
produces:
- "application/json"
- "application/xml"
- "text/xml"
- "text/html"
parameters:
-
name: "id"
in: "path"
description: "ID of pet to fetch"
required: true
type: "integer"
format: "int64"
responses:
"200":
description: "pet response"
schema:
$ref: "#/definitions/Pet"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
delete:
description: "deletes a single pet based on the ID supplied"
operationId: "deletePet"
parameters:
-
name: "id"
in: "path"
description: "ID of pet to delete"
required: true
type: "integer"
format: "int64"
responses:
"204":
description: "pet deleted"
default:
description: "unexpected error"
schema:
$ref: "#/definitions/ErrorModel"
definitions:
Pet:
type: "object"
allOf:
-
$ref: "#/definitions/NewPet"
-
required:
- "id"
properties:
id:
type: "integer"
format: "int64"
NewPet:
type: "object"
required:
- "name"
properties:
name:
type: "string"
tag:
type: "string"
ErrorModel:
type: "object"
required:
- "code"
- "message"
properties:
code:
type: "integer"
format: "int32"
message:
type: "string"

View file

@ -0,0 +1,101 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
host: petstore.swagger.io
basePath: /v1
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
type: integer
format: int32
responses:
"200":
description: An paged array of pets
headers:
x-next:
type: string
description: A link to the next page of responses
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
"201":
description: Null response
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
type: string
responses:
"200":
description: Expected response to a valid request
schema:
$ref: '#/definitions/Pets'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: '#/definitions/Pet'
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,273 @@
# this is an example of the Uber API
# as a demonstration of an API spec in YAML
swagger: "2.0"
info:
title: Uber API
description: Move your app forward with the Uber API
version: "1.0.0"
# the domain of the service
host: api.uber.com
# array of all schemes that your API supports
schemes:
- https
# will be prefixed to all paths
basePath: /v1
securityDefinitions:
apikey:
type: apiKey
name: server_token
in: query
produces:
- application/json
paths:
/products:
get:
summary: Product Types
description: The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.
parameters:
- name: latitude
in: query
description: Latitude component of location.
required: true
type: number
format: double
- name: longitude
in: query
description: Longitude component of location.
required: true
type: number
format: double
security:
- apikey: []
tags:
- Products
responses:
"200":
description: An array of products
schema:
type: array
items:
$ref: '#/definitions/Product'
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
/estimates/price:
get:
summary: Price Estimates
description: The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.<br><br>The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.
parameters:
- name: start_latitude
in: query
description: Latitude component of start location.
required: true
type: number
format: double
- name: start_longitude
in: query
description: Longitude component of start location.
required: true
type: number
format: double
- name: end_latitude
in: query
description: Latitude component of end location.
required: true
type: number
format: double
- name: end_longitude
in: query
description: Longitude component of end location.
required: true
type: number
format: double
tags:
- Estimates
responses:
"200":
description: An array of price estimates by product
schema:
type: array
items:
$ref: '#/definitions/PriceEstimate'
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
/estimates/time:
get:
summary: Time Estimates
description: The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.
parameters:
- name: start_latitude
in: query
description: Latitude component of start location.
required: true
type: number
format: double
- name: start_longitude
in: query
description: Longitude component of start location.
required: true
type: number
format: double
- name: customer_uuid
in: query
type: string
format: uuid
description: Unique customer identifier to be used for experience customization.
- name: product_id
in: query
type: string
description: Unique identifier representing a specific product for a given latitude & longitude.
tags:
- Estimates
responses:
"200":
description: An array of products
schema:
type: array
items:
$ref: '#/definitions/Product'
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
/me:
get:
summary: User Profile
description: The User Profile endpoint returns information about the Uber user that has authorized with the application.
tags:
- User
responses:
"200":
description: Profile information for a user
schema:
$ref: '#/definitions/Profile'
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
/history:
get:
summary: User Activity
description: The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.<br><br>The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.
parameters:
- name: offset
in: query
type: integer
format: int32
description: Offset the list of returned results by this amount. Default is zero.
- name: limit
in: query
type: integer
format: int32
description: Number of items to retrieve. Default is 5, maximum is 100.
tags:
- User
responses:
"200":
description: History information for the given user
schema:
$ref: '#/definitions/Activities'
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
Product:
properties:
product_id:
type: string
description: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles.
description:
type: string
description: Description of product.
display_name:
type: string
description: Display name of product.
capacity:
type: integer
description: Capacity of product. For example, 4 people.
image:
type: string
description: Image URL representing the product.
ProductList:
properties:
products:
description: Contains the list of products
type: array
items:
$ref: "#/definitions/Product"
PriceEstimate:
properties:
product_id:
type: string
description: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles
currency_code:
type: string
description: "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code."
display_name:
type: string
description: Display name of product.
estimate:
type: string
description: Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or "Metered" for TAXI.
low_estimate:
type: number
description: Lower bound of the estimated price.
high_estimate:
type: number
description: Upper bound of the estimated price.
surge_multiplier:
type: number
description: Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier.
Profile:
properties:
first_name:
type: string
description: First name of the Uber user.
last_name:
type: string
description: Last name of the Uber user.
email:
type: string
description: Email address of the Uber user
picture:
type: string
description: Image URL of the Uber user.
promo_code:
type: string
description: Promo code of the Uber user.
Activity:
properties:
uuid:
type: string
description: Unique identifier for the activity
Activities:
properties:
offset:
type: integer
format: int32
description: Position in pagination.
limit:
type: integer
format: int32
description: Number of items to retrieve (100 max).
count:
type: integer
format: int32
description: Total number of items available.
history:
type: array
items:
$ref: '#/definitions/Activity'
Error:
properties:
code:
type: integer
format: int32
message:
type: string
fields:
type: string

View file

@ -0,0 +1,176 @@
{
"openapi": "3.0",
"info": {
"version": "1.0.0",
"title": "OpenAPI Petstore",
"license": {
"name": "MIT"
}
},
"servers": [
{
"url": "https://petstore.openapis.org/v1",
"description": "Development server"
}
],
"paths": {
"/pets": {
"get": {
"summary": "List all pets",
"operationId": "listPets",
"tags": [
"pets"
],
"parameters": [
{
"name": "limit",
"in": "query",
"description": "How many items to return at one time (max 100)",
"required": false,
"schema": {
"type": "integer",
"format": "int32"
}
}
],
"responses": {
"200": {
"description": "An paged array of pets",
"headers": {
"x-next": {
"schema": {
"type": "string"
},
"description": "A link to the next page of responses"
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pets"
}
}
}
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
},
"post": {
"summary": "Create a pet",
"operationId": "createPets",
"tags": [
"pets"
],
"responses": {
"201": {
"description": "Null response"
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/pets/{petId}": {
"get": {
"summary": "Info for a specific pet",
"operationId": "showPetById",
"tags": [
"pets"
],
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"description": "The id of the pet to retrieve",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Expected response to a valid request",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pets"
}
}
}
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Pet": {
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"Pets": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Pet"
}
},
"Error": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}
}

View file

@ -0,0 +1,110 @@
openapi: "3.0"
info:
version: 1.0.0
title: OpenAPI Petstore
license:
name: MIT
servers:
- url: https://petstore.openapis.org/v1
description: Development server
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
"200":
description: An paged array of pets
headers:
x-next:
schema:
type: string
description: A link to the next page of responses
content:
application/json:
schema:
$ref: '#/components/schemas/Pets'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
"201":
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
"200":
description: Expected response to a valid request
content:
application/json:
schema:
$ref: '#/components/schemas/Pets'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: '#/components/schemas/Pet'
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string

View file

@ -0,0 +1,7 @@
go get github.com/golang/protobuf/protoc-gen-go
protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto
go build
go install

View file

@ -0,0 +1,5 @@
# Extensions
This directory contains support code for building Gnostic extensions and associated examples.
Extensions are used to compile vendor or specification extensions into protocol buffer structures.

View file

@ -0,0 +1,219 @@
// Code generated by protoc-gen-go.
// source: extension.proto
// DO NOT EDIT!
/*
Package openapiextension_v1 is a generated protocol buffer package.
It is generated from these files:
extension.proto
It has these top-level messages:
Version
ExtensionHandlerRequest
ExtensionHandlerResponse
Wrapper
*/
package openapiextension_v1
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/ptypes/any"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// The version number of OpenAPI compiler.
type Version struct {
Major int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
Minor int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
Patch int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
Suffix string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"`
}
func (m *Version) Reset() { *m = Version{} }
func (m *Version) String() string { return proto.CompactTextString(m) }
func (*Version) ProtoMessage() {}
func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *Version) GetMajor() int32 {
if m != nil {
return m.Major
}
return 0
}
func (m *Version) GetMinor() int32 {
if m != nil {
return m.Minor
}
return 0
}
func (m *Version) GetPatch() int32 {
if m != nil {
return m.Patch
}
return 0
}
func (m *Version) GetSuffix() string {
if m != nil {
return m.Suffix
}
return ""
}
// An encoded Request is written to the ExtensionHandler's stdin.
type ExtensionHandlerRequest struct {
// The OpenAPI descriptions that were explicitly listed on the command line.
// The specifications will appear in the order they are specified to openapic.
Wrapper *Wrapper `protobuf:"bytes,1,opt,name=wrapper" json:"wrapper,omitempty"`
// The version number of openapi compiler.
CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"`
}
func (m *ExtensionHandlerRequest) Reset() { *m = ExtensionHandlerRequest{} }
func (m *ExtensionHandlerRequest) String() string { return proto.CompactTextString(m) }
func (*ExtensionHandlerRequest) ProtoMessage() {}
func (*ExtensionHandlerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *ExtensionHandlerRequest) GetWrapper() *Wrapper {
if m != nil {
return m.Wrapper
}
return nil
}
func (m *ExtensionHandlerRequest) GetCompilerVersion() *Version {
if m != nil {
return m.CompilerVersion
}
return nil
}
// The extensions writes an encoded ExtensionHandlerResponse to stdout.
type ExtensionHandlerResponse struct {
// true if the extension is handled by the extension handler; false otherwise
Handled bool `protobuf:"varint,1,opt,name=handled" json:"handled,omitempty"`
// Error message. If non-empty, the extension handling failed.
// The extension handler process should exit with status code zero
// even if it reports an error in this way.
//
// This should be used to indicate errors which prevent the extension from
// operating as intended. Errors which indicate a problem in gnostic
// itself -- such as the input Document being unparseable -- should be
// reported by writing a message to stderr and exiting with a non-zero
// status code.
Error []string `protobuf:"bytes,2,rep,name=error" json:"error,omitempty"`
// text output
Value *google_protobuf.Any `protobuf:"bytes,3,opt,name=value" json:"value,omitempty"`
}
func (m *ExtensionHandlerResponse) Reset() { *m = ExtensionHandlerResponse{} }
func (m *ExtensionHandlerResponse) String() string { return proto.CompactTextString(m) }
func (*ExtensionHandlerResponse) ProtoMessage() {}
func (*ExtensionHandlerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *ExtensionHandlerResponse) GetHandled() bool {
if m != nil {
return m.Handled
}
return false
}
func (m *ExtensionHandlerResponse) GetError() []string {
if m != nil {
return m.Error
}
return nil
}
func (m *ExtensionHandlerResponse) GetValue() *google_protobuf.Any {
if m != nil {
return m.Value
}
return nil
}
type Wrapper struct {
// version of the OpenAPI specification in which this extension was written.
Version string `protobuf:"bytes,1,opt,name=version" json:"version,omitempty"`
// Name of the extension
ExtensionName string `protobuf:"bytes,2,opt,name=extension_name,json=extensionName" json:"extension_name,omitempty"`
// Must be a valid yaml for the proto
Yaml string `protobuf:"bytes,3,opt,name=yaml" json:"yaml,omitempty"`
}
func (m *Wrapper) Reset() { *m = Wrapper{} }
func (m *Wrapper) String() string { return proto.CompactTextString(m) }
func (*Wrapper) ProtoMessage() {}
func (*Wrapper) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
func (m *Wrapper) GetVersion() string {
if m != nil {
return m.Version
}
return ""
}
func (m *Wrapper) GetExtensionName() string {
if m != nil {
return m.ExtensionName
}
return ""
}
func (m *Wrapper) GetYaml() string {
if m != nil {
return m.Yaml
}
return ""
}
func init() {
proto.RegisterType((*Version)(nil), "openapiextension.v1.Version")
proto.RegisterType((*ExtensionHandlerRequest)(nil), "openapiextension.v1.ExtensionHandlerRequest")
proto.RegisterType((*ExtensionHandlerResponse)(nil), "openapiextension.v1.ExtensionHandlerResponse")
proto.RegisterType((*Wrapper)(nil), "openapiextension.v1.Wrapper")
}
func init() { proto.RegisterFile("extension.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 355 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x74, 0x91, 0x4d, 0x4b, 0xf3, 0x40,
0x1c, 0xc4, 0x49, 0xdf, 0xf2, 0x64, 0x1f, 0xb4, 0xb2, 0x16, 0x8d, 0xe2, 0xa1, 0x04, 0x84, 0x22,
0xb8, 0xa5, 0x0a, 0xde, 0x5b, 0x28, 0xea, 0xc5, 0x96, 0x3d, 0xd4, 0x9b, 0x65, 0x9b, 0xfe, 0xdb,
0x46, 0x92, 0xdd, 0x75, 0xf3, 0x62, 0xfb, 0x55, 0x3c, 0xfa, 0x49, 0x25, 0xbb, 0xd9, 0x7a, 0x50,
0x6f, 0x99, 0x1f, 0x93, 0xfc, 0x67, 0x26, 0xa8, 0x0d, 0xdb, 0x0c, 0x78, 0x1a, 0x09, 0x4e, 0xa4,
0x12, 0x99, 0xc0, 0xc7, 0x42, 0x02, 0x67, 0x32, 0xfa, 0xe6, 0xc5, 0xe0, 0xfc, 0x6c, 0x2d, 0xc4,
0x3a, 0x86, 0xbe, 0xb6, 0x2c, 0xf2, 0x55, 0x9f, 0xf1, 0x9d, 0xf1, 0x07, 0x21, 0x72, 0x67, 0xa0,
0x4a, 0x23, 0xee, 0xa0, 0x66, 0xc2, 0x5e, 0x85, 0xf2, 0x9d, 0xae, 0xd3, 0x6b, 0x52, 0x23, 0x34,
0x8d, 0xb8, 0x50, 0x7e, 0xad, 0xa2, 0xa5, 0x28, 0xa9, 0x64, 0x59, 0xb8, 0xf1, 0xeb, 0x86, 0x6a,
0x81, 0x4f, 0x50, 0x2b, 0xcd, 0x57, 0xab, 0x68, 0xeb, 0x37, 0xba, 0x4e, 0xcf, 0xa3, 0x95, 0x0a,
0x3e, 0x1c, 0x74, 0x3a, 0xb6, 0x81, 0x1e, 0x18, 0x5f, 0xc6, 0xa0, 0x28, 0xbc, 0xe5, 0x90, 0x66,
0xf8, 0x0e, 0xb9, 0xef, 0x8a, 0x49, 0x09, 0xe6, 0xee, 0xff, 0x9b, 0x0b, 0xf2, 0x4b, 0x05, 0xf2,
0x6c, 0x3c, 0xd4, 0x9a, 0xf1, 0x3d, 0x3a, 0x0a, 0x45, 0x22, 0xa3, 0x18, 0xd4, 0xbc, 0x30, 0x0d,
0x74, 0x98, 0xbf, 0x3e, 0x50, 0xb5, 0xa4, 0x6d, 0xfb, 0x56, 0x05, 0x82, 0x02, 0xf9, 0x3f, 0xb3,
0xa5, 0x52, 0xf0, 0x14, 0xb0, 0x8f, 0xdc, 0x8d, 0x46, 0x4b, 0x1d, 0xee, 0x1f, 0xb5, 0xb2, 0x1c,
0x00, 0x94, 0xd2, 0xb3, 0xd4, 0x7b, 0x1e, 0x35, 0x02, 0x5f, 0xa1, 0x66, 0xc1, 0xe2, 0x1c, 0xaa,
0x24, 0x1d, 0x62, 0x86, 0x27, 0x76, 0x78, 0x32, 0xe4, 0x3b, 0x6a, 0x2c, 0xc1, 0x0b, 0x72, 0xab,
0x52, 0xe5, 0x19, 0x5b, 0xc1, 0xd1, 0xc3, 0x59, 0x89, 0x2f, 0xd1, 0xe1, 0xbe, 0xc5, 0x9c, 0xb3,
0x04, 0xf4, 0x6f, 0xf0, 0xe8, 0xc1, 0x9e, 0x3e, 0xb1, 0x04, 0x30, 0x46, 0x8d, 0x1d, 0x4b, 0x62,
0x7d, 0xd6, 0xa3, 0xfa, 0x79, 0x74, 0x8d, 0xda, 0x42, 0xad, 0xed, 0x16, 0x21, 0x29, 0x06, 0x23,
0x3c, 0x91, 0xc0, 0x87, 0xd3, 0xc7, 0x7d, 0xdf, 0xd9, 0x60, 0xea, 0x7c, 0xd6, 0xea, 0x93, 0xe1,
0x78, 0xd1, 0xd2, 0x19, 0x6f, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x56, 0x40, 0x4d, 0x52,
0x02, 0x00, 0x00,
}

View file

@ -0,0 +1,93 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
syntax = "proto3";
import "google/protobuf/any.proto";
package openapiextension.v1;
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "OpenAPIExtensionV1";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapic.v1";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
//
option objc_class_prefix = "OAE"; // "OpenAPI Extension"
// The version number of OpenAPI compiler.
message Version {
int32 major = 1;
int32 minor = 2;
int32 patch = 3;
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
string suffix = 4;
}
// An encoded Request is written to the ExtensionHandler's stdin.
message ExtensionHandlerRequest {
// The OpenAPI descriptions that were explicitly listed on the command line.
// The specifications will appear in the order they are specified to openapic.
Wrapper wrapper = 1;
// The version number of openapi compiler.
Version compiler_version = 3;
}
// The extensions writes an encoded ExtensionHandlerResponse to stdout.
message ExtensionHandlerResponse {
// true if the extension is handled by the extension handler; false otherwise
bool handled = 1;
// Error message. If non-empty, the extension handling failed.
// The extension handler process should exit with status code zero
// even if it reports an error in this way.
//
// This should be used to indicate errors which prevent the extension from
// operating as intended. Errors which indicate a problem in gnostic
// itself -- such as the input Document being unparseable -- should be
// reported by writing a message to stderr and exiting with a non-zero
// status code.
repeated string error = 2;
// text output
google.protobuf.Any value = 3;
}
message Wrapper {
// version of the OpenAPI specification in which this extension was written.
string version = 1;
// Name of the extension
string extension_name = 2;
// Must be a valid yaml for the proto
string yaml = 3;
}

View file

@ -0,0 +1,83 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package openapiextension_v1
import (
"fmt"
"io/ioutil"
"os"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"gopkg.in/yaml.v2"
)
type documentHandler func(version string, extensionName string, document string)
type extensionHandler func(name string, info yaml.MapSlice) (bool, proto.Message, error)
func forInputYamlFromOpenapic(handler documentHandler) {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Println("File error:", err.Error())
os.Exit(1)
}
request := &ExtensionHandlerRequest{}
err = proto.Unmarshal(data, request)
handler(request.Wrapper.Version, request.Wrapper.ExtensionName, request.Wrapper.Yaml)
}
func ProcessExtension(handleExtension extensionHandler) {
response := &ExtensionHandlerResponse{}
forInputYamlFromOpenapic(
func(version string, extensionName string, yamlInput string) {
var info yaml.MapSlice
var newObject proto.Message
var err error
err = yaml.Unmarshal([]byte(yamlInput), &info)
if err != nil {
response.Error = append(response.Error, err.Error())
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
handled, newObject, err := handleExtension(extensionName, info)
if !handled {
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
// If we reach here, then the extension is handled
response.Handled = true
if err != nil {
response.Error = append(response.Error, err.Error())
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
response.Value, err = ptypes.MarshalAny(newObject)
if err != nil {
response.Error = append(response.Error, err.Error())
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
})
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
}

View file

@ -0,0 +1,62 @@
go get github.com/golang/protobuf/protoc-gen-go
# ONE TIME
#
#
############################# FOR E2E TESTING ########################################
# ensure vendorextension proto contract is compiled.
pushd $GOPATH/src/github.com/googleapis/gnostic/extensions
./COMPILE-EXTENSION.sh
popd
pushd $GOPATH/src/github.com/googleapis/gnostic/generator
./INSTALL.sh
pushd $GOPATH/src/github.com/googleapis/gnostic
go install
######################################################################################
# Now generate sample extension plugins and install them.
#
#
pushd $GOPATH/src/github.com/googleapis/gnostic/extensions
EXTENSION_OUT_DIR=$GOPATH/src/"github.com/googleapis/gnostic/extensions/sample/generated"
# For SAMPLE_ONE Extension Example
#
#
SAMPLE_ONE_EXTENSION_SCHEMA="sample/x-samplecompanyone.json"
generator --extension $SAMPLE_ONE_EXTENSION_SCHEMA --out_dir=$EXTENSION_OUT_DIR
pushd $EXTENSION_OUT_DIR/openapi_extensions_samplecompanyone/proto
protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto
go install
popd
pushd $EXTENSION_OUT_DIR/openapi_extensions_samplecompanyone
go install
popd
# For SAMPLE_TWO Extension Example
#
#
SAMPLE_TWO_EXTENSION_SCHEMA="sample/x-samplecompanytwo.json"
generator --extension $SAMPLE_TWO_EXTENSION_SCHEMA --out_dir=$EXTENSION_OUT_DIR
pushd $EXTENSION_OUT_DIR/openapi_extensions_samplecompanytwo/proto
protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto
go install
popd
pushd $EXTENSION_OUT_DIR/openapi_extensions_samplecompanytwo
go install
popd
popd

View file

@ -0,0 +1,44 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
package main
import (
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/compiler"
"github.com/googleapis/gnostic/extensions"
"github.com/googleapis/gnostic/extensions/sample/generated/openapi_extensions_samplecompanyone/proto"
"gopkg.in/yaml.v2"
)
func handleExtension(extensionName string, info yaml.MapSlice) (bool, proto.Message, error) {
switch extensionName {
// All supported extensions
case "x-samplecompanyone-book":
newObject, err := samplecompanyone.NewSampleCompanyOneBook(info, compiler.NewContext("$root", nil))
return true, newObject, err
case "x-samplecompanyone-shelve":
newObject, err := samplecompanyone.NewSampleCompanyOneShelve(info, compiler.NewContext("$root", nil))
return true, newObject, err
default:
return false, nil, nil
}
}
func main() {
openapiextension_v1.ProcessExtension(handleExtension)
}

View file

@ -0,0 +1,131 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
package samplecompanyone
import (
"fmt"
"github.com/googleapis/gnostic/compiler"
"strings"
)
func Version() string {
return "samplecompanyone"
}
func NewSampleCompanyOneBook(in interface{}, context *compiler.Context) (*SampleCompanyOneBook, error) {
errors := make([]error, 0)
x := &SampleCompanyOneBook{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
requiredKeys := []string{"code", "message"}
missingKeys := compiler.MissingKeysInMap(m, requiredKeys)
if len(missingKeys) > 0 {
message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
allowedKeys := []string{"code", "message"}
allowedPatterns := []string{}
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// int64 code = 1;
v1 := compiler.MapValueForKey(m, "code")
if v1 != nil {
t, ok := v1.(int)
if ok {
x.Code = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for code: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// int64 message = 2;
v2 := compiler.MapValueForKey(m, "message")
if v2 != nil {
t, ok := v2.(int)
if ok {
x.Message = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for message: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
}
func NewSampleCompanyOneShelve(in interface{}, context *compiler.Context) (*SampleCompanyOneShelve, error) {
errors := make([]error, 0)
x := &SampleCompanyOneShelve{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
requiredKeys := []string{"bar", "foo1"}
missingKeys := compiler.MissingKeysInMap(m, requiredKeys)
if len(missingKeys) > 0 {
message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
allowedKeys := []string{"bar", "foo1"}
allowedPatterns := []string{}
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// int64 foo1 = 1;
v1 := compiler.MapValueForKey(m, "foo1")
if v1 != nil {
t, ok := v1.(int)
if ok {
x.Foo1 = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for foo1: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// int64 bar = 2;
v2 := compiler.MapValueForKey(m, "bar")
if v2 != nil {
t, ok := v2.(int)
if ok {
x.Bar = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for bar: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
}
func (m *SampleCompanyOneBook) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
return nil, compiler.NewErrorGroupOrNil(errors)
}
func (m *SampleCompanyOneShelve) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
return nil, compiler.NewErrorGroupOrNil(errors)
}

View file

@ -0,0 +1,101 @@
// Code generated by protoc-gen-go.
// source: x-samplecompanyone.proto
// DO NOT EDIT!
/*
Package samplecompanyone is a generated protocol buffer package.
It is generated from these files:
x-samplecompanyone.proto
It has these top-level messages:
SampleCompanyOneBook
SampleCompanyOneShelve
*/
package samplecompanyone
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type SampleCompanyOneBook struct {
Code int64 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
Message int64 `protobuf:"varint,2,opt,name=message" json:"message,omitempty"`
}
func (m *SampleCompanyOneBook) Reset() { *m = SampleCompanyOneBook{} }
func (m *SampleCompanyOneBook) String() string { return proto.CompactTextString(m) }
func (*SampleCompanyOneBook) ProtoMessage() {}
func (*SampleCompanyOneBook) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *SampleCompanyOneBook) GetCode() int64 {
if m != nil {
return m.Code
}
return 0
}
func (m *SampleCompanyOneBook) GetMessage() int64 {
if m != nil {
return m.Message
}
return 0
}
type SampleCompanyOneShelve struct {
Foo1 int64 `protobuf:"varint,1,opt,name=foo1" json:"foo1,omitempty"`
Bar int64 `protobuf:"varint,2,opt,name=bar" json:"bar,omitempty"`
}
func (m *SampleCompanyOneShelve) Reset() { *m = SampleCompanyOneShelve{} }
func (m *SampleCompanyOneShelve) String() string { return proto.CompactTextString(m) }
func (*SampleCompanyOneShelve) ProtoMessage() {}
func (*SampleCompanyOneShelve) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *SampleCompanyOneShelve) GetFoo1() int64 {
if m != nil {
return m.Foo1
}
return 0
}
func (m *SampleCompanyOneShelve) GetBar() int64 {
if m != nil {
return m.Bar
}
return 0
}
func init() {
proto.RegisterType((*SampleCompanyOneBook)(nil), "samplecompanyone.SampleCompanyOneBook")
proto.RegisterType((*SampleCompanyOneShelve)(nil), "samplecompanyone.SampleCompanyOneShelve")
}
func init() { proto.RegisterFile("x-samplecompanyone.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 192 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x92, 0xa8, 0xd0, 0x2d, 0x4e,
0xcc, 0x2d, 0xc8, 0x49, 0x4d, 0xce, 0xcf, 0x2d, 0x48, 0xcc, 0xab, 0xcc, 0xcf, 0x4b, 0xd5, 0x2b,
0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x40, 0x17, 0x57, 0x72, 0xe1, 0x12, 0x09, 0x06, 0x8b, 0x39,
0x43, 0xc4, 0xfc, 0xf3, 0x52, 0x9d, 0xf2, 0xf3, 0xb3, 0x85, 0x84, 0xb8, 0x58, 0x92, 0xf3, 0x53,
0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83, 0xc0, 0x6c, 0x21, 0x09, 0x2e, 0xf6, 0xdc, 0xd4,
0xe2, 0xe2, 0xc4, 0xf4, 0x54, 0x09, 0x26, 0xb0, 0x30, 0x8c, 0xab, 0x64, 0xc7, 0x25, 0x86, 0x6e,
0x4a, 0x70, 0x46, 0x6a, 0x4e, 0x59, 0x2a, 0xc8, 0x9c, 0xb4, 0xfc, 0x7c, 0x43, 0x98, 0x39, 0x20,
0xb6, 0x90, 0x00, 0x17, 0x73, 0x52, 0x62, 0x11, 0xd4, 0x0c, 0x10, 0xd3, 0x29, 0x98, 0x4b, 0x2d,
0xbf, 0x28, 0x5d, 0x2f, 0xbf, 0x20, 0x35, 0x2f, 0xb1, 0x20, 0x53, 0x2f, 0xb5, 0xa2, 0x24, 0x35,
0xaf, 0x38, 0x33, 0x3f, 0x4f, 0x0f, 0xdd, 0xbd, 0x4e, 0x22, 0x61, 0xa9, 0x79, 0x29, 0xf9, 0x45,
0xae, 0x30, 0x15, 0x01, 0x20, 0x7f, 0x05, 0x30, 0x2e, 0x62, 0xc2, 0xf0, 0x5a, 0x12, 0x1b, 0xd8,
0xcf, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x66, 0x17, 0xf7, 0x22, 0x0f, 0x01, 0x00, 0x00,
}

View file

@ -0,0 +1,51 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
syntax = "proto3";
package samplecompanyone;
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "VendorExtensionProto";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapi.extension.samplecompanyone";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
option objc_class_prefix = "samplecompanyone";
message SampleCompanyOneBook {
int64 code = 1;
int64 message = 2;
}
message SampleCompanyOneShelve {
int64 foo1 = 1;
int64 bar = 2;
}

View file

@ -0,0 +1,44 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
package main
import (
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/compiler"
"github.com/googleapis/gnostic/extensions"
"github.com/googleapis/gnostic/extensions/sample/generated/openapi_extensions_samplecompanytwo/proto"
"gopkg.in/yaml.v2"
)
func handleExtension(extensionName string, info yaml.MapSlice) (bool, proto.Message, error) {
switch extensionName {
// All supported extensions
case "x-samplecompanytwo-book":
newObject, err := samplecompanytwo.NewSampleCompanyTwoBook(info, compiler.NewContext("$root", nil))
return true, newObject, err
case "x-samplecompanytwo-shelve":
newObject, err := samplecompanytwo.NewSampleCompanyTwoShelve(info, compiler.NewContext("$root", nil))
return true, newObject, err
default:
return false, nil, nil
}
}
func main() {
openapiextension_v1.ProcessExtension(handleExtension)
}

View file

@ -0,0 +1,131 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
package samplecompanytwo
import (
"fmt"
"github.com/googleapis/gnostic/compiler"
"strings"
)
func Version() string {
return "samplecompanytwo"
}
func NewSampleCompanyTwoBook(in interface{}, context *compiler.Context) (*SampleCompanyTwoBook, error) {
errors := make([]error, 0)
x := &SampleCompanyTwoBook{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
requiredKeys := []string{"code", "message"}
missingKeys := compiler.MissingKeysInMap(m, requiredKeys)
if len(missingKeys) > 0 {
message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
allowedKeys := []string{"code", "message"}
allowedPatterns := []string{}
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// int64 code = 1;
v1 := compiler.MapValueForKey(m, "code")
if v1 != nil {
t, ok := v1.(int)
if ok {
x.Code = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for code: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// int64 message = 2;
v2 := compiler.MapValueForKey(m, "message")
if v2 != nil {
t, ok := v2.(int)
if ok {
x.Message = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for message: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
}
func NewSampleCompanyTwoShelve(in interface{}, context *compiler.Context) (*SampleCompanyTwoShelve, error) {
errors := make([]error, 0)
x := &SampleCompanyTwoShelve{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else {
requiredKeys := []string{"bar", "foo1"}
missingKeys := compiler.MissingKeysInMap(m, requiredKeys)
if len(missingKeys) > 0 {
message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
allowedKeys := []string{"bar", "foo1"}
allowedPatterns := []string{}
invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
if len(invalidKeys) > 0 {
message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
errors = append(errors, compiler.NewError(context, message))
}
// int64 foo1 = 1;
v1 := compiler.MapValueForKey(m, "foo1")
if v1 != nil {
t, ok := v1.(int)
if ok {
x.Foo1 = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for foo1: %+v (%T)", v1, v1)
errors = append(errors, compiler.NewError(context, message))
}
}
// int64 bar = 2;
v2 := compiler.MapValueForKey(m, "bar")
if v2 != nil {
t, ok := v2.(int)
if ok {
x.Bar = int64(t)
} else {
message := fmt.Sprintf("has unexpected value for bar: %+v (%T)", v2, v2)
errors = append(errors, compiler.NewError(context, message))
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
}
func (m *SampleCompanyTwoBook) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
return nil, compiler.NewErrorGroupOrNil(errors)
}
func (m *SampleCompanyTwoShelve) ResolveReferences(root string) (interface{}, error) {
errors := make([]error, 0)
return nil, compiler.NewErrorGroupOrNil(errors)
}

View file

@ -0,0 +1,101 @@
// Code generated by protoc-gen-go.
// source: x-samplecompanytwo.proto
// DO NOT EDIT!
/*
Package samplecompanytwo is a generated protocol buffer package.
It is generated from these files:
x-samplecompanytwo.proto
It has these top-level messages:
SampleCompanyTwoBook
SampleCompanyTwoShelve
*/
package samplecompanytwo
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type SampleCompanyTwoBook struct {
Code int64 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
Message int64 `protobuf:"varint,2,opt,name=message" json:"message,omitempty"`
}
func (m *SampleCompanyTwoBook) Reset() { *m = SampleCompanyTwoBook{} }
func (m *SampleCompanyTwoBook) String() string { return proto.CompactTextString(m) }
func (*SampleCompanyTwoBook) ProtoMessage() {}
func (*SampleCompanyTwoBook) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *SampleCompanyTwoBook) GetCode() int64 {
if m != nil {
return m.Code
}
return 0
}
func (m *SampleCompanyTwoBook) GetMessage() int64 {
if m != nil {
return m.Message
}
return 0
}
type SampleCompanyTwoShelve struct {
Foo1 int64 `protobuf:"varint,1,opt,name=foo1" json:"foo1,omitempty"`
Bar int64 `protobuf:"varint,2,opt,name=bar" json:"bar,omitempty"`
}
func (m *SampleCompanyTwoShelve) Reset() { *m = SampleCompanyTwoShelve{} }
func (m *SampleCompanyTwoShelve) String() string { return proto.CompactTextString(m) }
func (*SampleCompanyTwoShelve) ProtoMessage() {}
func (*SampleCompanyTwoShelve) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *SampleCompanyTwoShelve) GetFoo1() int64 {
if m != nil {
return m.Foo1
}
return 0
}
func (m *SampleCompanyTwoShelve) GetBar() int64 {
if m != nil {
return m.Bar
}
return 0
}
func init() {
proto.RegisterType((*SampleCompanyTwoBook)(nil), "samplecompanytwo.SampleCompanyTwoBook")
proto.RegisterType((*SampleCompanyTwoShelve)(nil), "samplecompanytwo.SampleCompanyTwoShelve")
}
func init() { proto.RegisterFile("x-samplecompanytwo.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 191 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x64, 0x8f, 0x41, 0xeb, 0x82, 0x30,
0x18, 0x87, 0x51, 0xff, 0xfc, 0x83, 0x9d, 0x64, 0x48, 0xec, 0x18, 0x1e, 0xa2, 0x4b, 0x83, 0xe8,
0xde, 0xc1, 0xea, 0x2e, 0x19, 0xdd, 0xa7, 0xbe, 0x99, 0xa4, 0x7b, 0xc7, 0x26, 0x69, 0x5f, 0xa7,
0x4f, 0x1a, 0x5b, 0x79, 0xb1, 0xdb, 0x6f, 0x0f, 0xe3, 0xe1, 0x7d, 0x08, 0x1b, 0xd6, 0x46, 0xb4,
0xaa, 0x81, 0x02, 0x5b, 0x25, 0xe4, 0xb3, 0xeb, 0x91, 0x2b, 0x8d, 0x1d, 0xd2, 0x70, 0xca, 0xe3,
0x03, 0x89, 0x32, 0xc7, 0xf6, 0x1f, 0x76, 0xee, 0x31, 0x41, 0xbc, 0x53, 0x4a, 0xfe, 0x0a, 0x2c,
0x81, 0x79, 0x0b, 0x6f, 0x15, 0x9c, 0xdc, 0xa6, 0x8c, 0xcc, 0x5a, 0x30, 0x46, 0x54, 0xc0, 0x7c,
0x87, 0xc7, 0x67, 0xbc, 0x23, 0xf3, 0xa9, 0x25, 0xbb, 0x41, 0xf3, 0x00, 0xeb, 0xb9, 0x22, 0x6e,
0x46, 0x8f, 0xdd, 0x34, 0x24, 0x41, 0x2e, 0xf4, 0xd7, 0x61, 0x67, 0x92, 0x91, 0x25, 0xea, 0x8a,
0xa3, 0x02, 0x29, 0x54, 0xcd, 0x61, 0xe8, 0x40, 0x9a, 0x1a, 0x25, 0x9f, 0xde, 0x9b, 0x44, 0x17,
0x90, 0x25, 0xea, 0xe3, 0xf8, 0x23, 0xb5, 0x5d, 0xa9, 0xf7, 0xf2, 0x7f, 0xd2, 0xf2, 0x7f, 0xd7,
0xbc, 0x7d, 0x07, 0x00, 0x00, 0xff, 0xff, 0xe0, 0x45, 0x2d, 0x48, 0x0f, 0x01, 0x00, 0x00,
}

View file

@ -0,0 +1,51 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// THIS FILE IS AUTOMATICALLY GENERATED.
syntax = "proto3";
package samplecompanytwo;
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "VendorExtensionProto";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapi.extension.samplecompanytwo";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
option objc_class_prefix = "samplecompanytwo";
message SampleCompanyTwoBook {
int64 code = 1;
int64 message = 2;
}
message SampleCompanyTwoShelve {
int64 foo1 = 1;
int64 bar = 2;
}

View file

@ -0,0 +1,38 @@
{
"definitions": {
"SampleCompanyOneBook": {
"type": "object",
"id": "x-samplecompanyone-book",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "integer"
}
}
},
"SampleCompanyOneShelve": {
"type": "object",
"id": "x-samplecompanyone-shelve",
"required": [
"foo1",
"bar"
],
"properties": {
"foo1": {
"type": "integer",
"format": "int32"
},
"bar": {
"type": "integer"
}
}
}
}
}

View file

@ -0,0 +1,38 @@
{
"definitions": {
"SampleCompanyTwoBook": {
"type": "object",
"id": "x-samplecompanytwo-book",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "integer"
}
}
},
"SampleCompanyTwoShelve": {
"type": "object",
"id": "x-samplecompanytwo-shelve",
"required": [
"foo1",
"bar"
],
"properties": {
"foo1": {
"type": "integer",
"format": "int32"
},
"bar": {
"type": "integer"
}
}
}
}
}

View file

@ -0,0 +1,18 @@
go get github.com/golang/protobuf/protoc-gen-go
pushd $GOPATH/src/github.com/googleapis/gnostic/generator
go build
cd ..
./generator/generator
popd
pushd $GOPATH/src/github.com/googleapis/gnostic/generator
go install
popd
pushd $GOPATH/src/github.com/googleapis/gnostic/OpenAPIv2
protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. OpenAPIv2.proto
go build
go install
popd

View file

@ -0,0 +1,11 @@
# The gnostic compiler generator
This directory contains code that generates a protocol buffer
representation and supporting code for a JSON schema.
It is currently used to build models of OpenAPI specifications
and extensions which are described as "vendor extensions" in
OpenAPI 2.0 and "specification extensions" in OpenAPI 3.0.
For usage information, run the "generator" binary with no
options.

View file

@ -0,0 +1,620 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
import (
"errors"
"fmt"
"log"
"sort"
"strings"
"github.com/googleapis/gnostic/jsonschema"
)
// models a collection of types that is defined by a schema
type Domain struct {
TypeModels map[string]*TypeModel // models of the types in the domain
Prefix string // type prefix to use
Schema *jsonschema.Schema // top-level schema
PatternNames map[string]string // a configured mapping from patterns to property names
ObjectTypeRequests map[string]*TypeRequest // anonymous types implied by type instantiation
MapTypeRequests map[string]string // "NamedObject" types that will be used to implement ordered maps
Version string // OpenAPI Version ("v2" or "v3")
}
func NewDomain(schema *jsonschema.Schema, version string) *Domain {
cc := &Domain{}
cc.TypeModels = make(map[string]*TypeModel, 0)
cc.PatternNames = make(map[string]string, 0)
cc.ObjectTypeRequests = make(map[string]*TypeRequest, 0)
cc.MapTypeRequests = make(map[string]string, 0)
cc.Schema = schema
cc.Version = version
return cc
}
// Returns a capitalized name to use for a generated type
func (domain *Domain) TypeNameForStub(stub string) string {
return domain.Prefix + strings.ToUpper(stub[0:1]) + stub[1:len(stub)]
}
// Returns a capitalized name to use for a generated type based on a JSON reference
func (domain *Domain) typeNameForReference(reference string) string {
parts := strings.Split(reference, "/")
first := parts[0]
last := parts[len(parts)-1]
if first == "#" {
return domain.TypeNameForStub(last)
} else {
return "Schema"
}
}
// Returns a property name to use for a JSON reference
func (domain *Domain) propertyNameForReference(reference string) *string {
parts := strings.Split(reference, "/")
first := parts[0]
last := parts[len(parts)-1]
if first == "#" {
return &last
} else {
return nil
}
return nil
}
// Determines the item type for arrays defined by a schema
func (domain *Domain) arrayItemTypeForSchema(propertyName string, schema *jsonschema.Schema) string {
// default
itemTypeName := "Any"
if schema.Items != nil {
if schema.Items.SchemaArray != nil {
if len(*(schema.Items.SchemaArray)) > 0 {
ref := (*schema.Items.SchemaArray)[0].Ref
if ref != nil {
itemTypeName = domain.typeNameForReference(*ref)
} else {
types := (*schema.Items.SchemaArray)[0].Type
if types == nil {
// do nothing
} else if (types.StringArray != nil) && len(*(types.StringArray)) == 1 {
itemTypeName = (*types.StringArray)[0]
} else if (types.StringArray != nil) && len(*(types.StringArray)) > 1 {
itemTypeName = fmt.Sprintf("%+v", types.StringArray)
} else if types.String != nil {
itemTypeName = *(types.String)
} else {
itemTypeName = "UNKNOWN"
}
}
}
} else if schema.Items.Schema != nil {
types := schema.Items.Schema.Type
if schema.Items.Schema.Ref != nil {
itemTypeName = domain.typeNameForReference(*schema.Items.Schema.Ref)
} else if schema.Items.Schema.OneOf != nil {
// this type is implied by the "oneOf"
itemTypeName = domain.TypeNameForStub(propertyName + "Item")
domain.ObjectTypeRequests[itemTypeName] =
NewTypeRequest(itemTypeName, propertyName, schema.Items.Schema)
} else if types == nil {
// do nothing
} else if (types.StringArray != nil) && len(*(types.StringArray)) == 1 {
itemTypeName = (*types.StringArray)[0]
} else if (types.StringArray != nil) && len(*(types.StringArray)) > 1 {
itemTypeName = fmt.Sprintf("%+v", types.StringArray)
} else if types.String != nil {
itemTypeName = *(types.String)
} else {
itemTypeName = "UNKNOWN"
}
}
}
return itemTypeName
}
func (domain *Domain) buildTypeProperties(typeModel *TypeModel, schema *jsonschema.Schema) {
if schema.Properties != nil {
for _, pair := range *(schema.Properties) {
propertyName := pair.Name
propertySchema := pair.Value
if propertySchema.Ref != nil {
// the property schema is a reference, so we will add a property with the type of the referenced schema
propertyTypeName := domain.typeNameForReference(*(propertySchema.Ref))
typeProperty := NewTypeProperty()
typeProperty.Name = propertyName
typeProperty.Type = propertyTypeName
typeModel.addProperty(typeProperty)
} else if propertySchema.Type != nil {
// the property schema specifies a type, so add a property with the specified type
if propertySchema.TypeIs("string") {
typeProperty := NewTypePropertyWithNameAndType(propertyName, "string")
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
if propertySchema.Enumeration != nil {
allowedValues := make([]string, 0)
for _, enumValue := range *propertySchema.Enumeration {
if enumValue.String != nil {
allowedValues = append(allowedValues, *enumValue.String)
}
}
typeProperty.StringEnumValues = allowedValues
}
typeModel.addProperty(typeProperty)
} else if propertySchema.TypeIs("boolean") {
typeProperty := NewTypePropertyWithNameAndType(propertyName, "bool")
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
typeModel.addProperty(typeProperty)
} else if propertySchema.TypeIs("number") {
typeProperty := NewTypePropertyWithNameAndType(propertyName, "float")
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
typeModel.addProperty(typeProperty)
} else if propertySchema.TypeIs("integer") {
typeProperty := NewTypePropertyWithNameAndType(propertyName, "int")
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
typeModel.addProperty(typeProperty)
} else if propertySchema.TypeIs("object") {
// the property has an "anonymous" object schema, so define a new type for it and request its creation
anonymousObjectTypeName := domain.TypeNameForStub(propertyName)
domain.ObjectTypeRequests[anonymousObjectTypeName] =
NewTypeRequest(anonymousObjectTypeName, propertyName, propertySchema)
// add a property with the type of the requested type
typeProperty := NewTypePropertyWithNameAndType(propertyName, anonymousObjectTypeName)
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
typeModel.addProperty(typeProperty)
} else if propertySchema.TypeIs("array") {
// the property has an array type, so define it as a repeated property of the specified type
propertyTypeName := domain.arrayItemTypeForSchema(propertyName, propertySchema)
typeProperty := NewTypePropertyWithNameAndType(propertyName, propertyTypeName)
typeProperty.Repeated = true
if propertySchema.Description != nil {
typeProperty.Description = *propertySchema.Description
}
if typeProperty.Type == "string" {
itemSchema := propertySchema.Items.Schema
if itemSchema != nil {
if itemSchema.Enumeration != nil {
allowedValues := make([]string, 0)
for _, enumValue := range *itemSchema.Enumeration {
if enumValue.String != nil {
allowedValues = append(allowedValues, *enumValue.String)
}
}
typeProperty.StringEnumValues = allowedValues
}
}
}
typeModel.addProperty(typeProperty)
} else {
log.Printf("ignoring %+v, which has an unsupported property type '%s'", propertyName, propertySchema.Type.Description())
}
} else if propertySchema.IsEmpty() {
// an empty schema can contain anything, so add an accessor for a generic object
typeName := "Any"
typeProperty := NewTypePropertyWithNameAndType(propertyName, typeName)
typeModel.addProperty(typeProperty)
} else if propertySchema.OneOf != nil {
anonymousObjectTypeName := domain.TypeNameForStub(propertyName + "Item")
domain.ObjectTypeRequests[anonymousObjectTypeName] =
NewTypeRequest(anonymousObjectTypeName, propertyName, propertySchema)
typeProperty := NewTypePropertyWithNameAndType(propertyName, anonymousObjectTypeName)
typeModel.addProperty(typeProperty)
} else if propertySchema.AnyOf != nil {
anonymousObjectTypeName := domain.TypeNameForStub(propertyName + "Item")
domain.ObjectTypeRequests[anonymousObjectTypeName] =
NewTypeRequest(anonymousObjectTypeName, propertyName, propertySchema)
typeProperty := NewTypePropertyWithNameAndType(propertyName, anonymousObjectTypeName)
typeModel.addProperty(typeProperty)
} else {
log.Printf("ignoring %s.%s, which has an unrecognized schema:\n%+v", typeModel.Name, propertyName, propertySchema.String())
}
}
}
}
func (domain *Domain) buildTypeRequirements(typeModel *TypeModel, schema *jsonschema.Schema) {
if schema.Required != nil {
typeModel.Required = (*schema.Required)
}
}
func (domain *Domain) buildPatternPropertyAccessors(typeModel *TypeModel, schema *jsonschema.Schema) {
if schema.PatternProperties != nil {
typeModel.OpenPatterns = make([]string, 0)
for _, pair := range *(schema.PatternProperties) {
propertyPattern := pair.Name
propertySchema := pair.Value
typeModel.OpenPatterns = append(typeModel.OpenPatterns, propertyPattern)
typeName := "Any"
propertyName := domain.PatternNames[propertyPattern]
if propertySchema.Ref != nil {
typeName = domain.typeNameForReference(*propertySchema.Ref)
}
propertyTypeName := fmt.Sprintf("Named%s", typeName)
property := NewTypePropertyWithNameTypeAndPattern(propertyName, propertyTypeName, propertyPattern)
property.Implicit = true
property.MapType = typeName
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
}
}
}
func (domain *Domain) buildAdditionalPropertyAccessors(typeModel *TypeModel, schema *jsonschema.Schema) {
if schema.AdditionalProperties != nil {
if schema.AdditionalProperties.Boolean != nil {
if *schema.AdditionalProperties.Boolean == true {
typeModel.Open = true
propertyName := "additionalProperties"
typeName := "NamedAny"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Implicit = true
property.MapType = "Any"
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
return
}
} else if schema.AdditionalProperties.Schema != nil {
typeModel.Open = true
schema := schema.AdditionalProperties.Schema
if schema.Ref != nil {
propertyName := "additionalProperties"
mapType := domain.typeNameForReference(*schema.Ref)
typeName := fmt.Sprintf("Named%s", mapType)
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Implicit = true
property.MapType = mapType
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
return
} else if schema.Type != nil {
typeName := *schema.Type.String
if typeName == "string" {
propertyName := "additionalProperties"
typeName := "NamedString"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Implicit = true
property.MapType = "string"
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
return
} else if typeName == "array" {
if schema.Items != nil {
itemType := *schema.Items.Schema.Type.String
if itemType == "string" {
propertyName := "additionalProperties"
typeName := "NamedStringArray"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Implicit = true
property.MapType = "StringArray"
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
return
}
}
}
} else if schema.OneOf != nil {
propertyTypeName := domain.TypeNameForStub(typeModel.Name + "Item")
propertyName := "additionalProperties"
typeName := fmt.Sprintf("Named%s", propertyTypeName)
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Implicit = true
property.MapType = propertyTypeName
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
domain.ObjectTypeRequests[propertyTypeName] =
NewTypeRequest(propertyTypeName, propertyName, schema)
}
}
}
}
func (domain *Domain) buildOneOfAccessors(typeModel *TypeModel, schema *jsonschema.Schema) {
oneOfs := schema.OneOf
if oneOfs == nil {
return
}
typeModel.Open = true
typeModel.OneOfWrapper = true
for _, oneOf := range *oneOfs {
if oneOf.Ref != nil {
ref := *oneOf.Ref
typeName := domain.typeNameForReference(ref)
propertyName := domain.propertyNameForReference(ref)
if propertyName != nil {
typeProperty := NewTypePropertyWithNameAndType(*propertyName, typeName)
typeModel.addProperty(typeProperty)
}
} else if oneOf.Type != nil && oneOf.Type.String != nil {
switch *oneOf.Type.String {
case "boolean":
typeProperty := NewTypePropertyWithNameAndType("boolean", "bool")
typeModel.addProperty(typeProperty)
case "integer":
typeProperty := NewTypePropertyWithNameAndType("integer", "int")
typeModel.addProperty(typeProperty)
case "number":
typeProperty := NewTypePropertyWithNameAndType("number", "float")
typeModel.addProperty(typeProperty)
case "string":
typeProperty := NewTypePropertyWithNameAndType("string", "string")
typeModel.addProperty(typeProperty)
default:
log.Printf("Unsupported oneOf:\n%+v", oneOf.String())
}
} else {
log.Printf("Unsupported oneOf:\n%+v", oneOf.String())
}
}
}
func schemaIsContainedInArray(s1 *jsonschema.Schema, s2 *jsonschema.Schema) bool {
if s2.TypeIs("array") {
if s2.Items.Schema != nil {
if s1.IsEqual(s2.Items.Schema) {
return true
} else {
return false
}
} else {
return false
}
} else {
return false
}
}
func (domain *Domain) addAnonymousAccessorForSchema(
typeModel *TypeModel,
schema *jsonschema.Schema,
repeated bool) {
ref := schema.Ref
if ref != nil {
typeName := domain.typeNameForReference(*ref)
propertyName := domain.propertyNameForReference(*ref)
if propertyName != nil {
property := NewTypePropertyWithNameAndType(*propertyName, typeName)
property.Repeated = true
typeModel.addProperty(property)
typeModel.IsItemArray = true
}
} else {
typeName := "string"
propertyName := "value"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.Repeated = true
typeModel.addProperty(property)
typeModel.IsStringArray = true
}
}
func (domain *Domain) buildAnyOfAccessors(typeModel *TypeModel, schema *jsonschema.Schema) {
anyOfs := schema.AnyOf
if anyOfs == nil {
return
}
if len(*anyOfs) == 2 {
if schemaIsContainedInArray((*anyOfs)[0], (*anyOfs)[1]) {
//log.Printf("ARRAY OF %+v", (*anyOfs)[0].String())
schema := (*anyOfs)[0]
domain.addAnonymousAccessorForSchema(typeModel, schema, true)
} else if schemaIsContainedInArray((*anyOfs)[1], (*anyOfs)[0]) {
//log.Printf("ARRAY OF %+v", (*anyOfs)[1].String())
schema := (*anyOfs)[1]
domain.addAnonymousAccessorForSchema(typeModel, schema, true)
} else {
for _, anyOf := range *anyOfs {
ref := anyOf.Ref
if ref != nil {
typeName := domain.typeNameForReference(*ref)
propertyName := domain.propertyNameForReference(*ref)
if propertyName != nil {
property := NewTypePropertyWithNameAndType(*propertyName, typeName)
typeModel.addProperty(property)
}
} else {
typeName := "bool"
propertyName := "boolean"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
typeModel.addProperty(property)
}
}
}
} else {
log.Printf("Unhandled anyOfs:\n%s", schema.String())
}
}
func (domain *Domain) buildDefaultAccessors(typeModel *TypeModel, schema *jsonschema.Schema) {
typeModel.Open = true
propertyName := "additionalProperties"
typeName := "NamedAny"
property := NewTypePropertyWithNameAndType(propertyName, typeName)
property.MapType = "Any"
property.Repeated = true
domain.MapTypeRequests[property.MapType] = property.MapType
typeModel.addProperty(property)
}
func (domain *Domain) BuildTypeForDefinition(
typeName string,
propertyName string,
schema *jsonschema.Schema) *TypeModel {
if (schema.Type == nil) || (*schema.Type.String == "object") {
return domain.buildTypeForDefinitionObject(typeName, propertyName, schema)
} else {
return nil
}
}
func (domain *Domain) buildTypeForDefinitionObject(
typeName string,
propertyName string,
schema *jsonschema.Schema) *TypeModel {
typeModel := NewTypeModel()
typeModel.Name = typeName
if schema.IsEmpty() {
domain.buildDefaultAccessors(typeModel, schema)
} else {
if schema.Description != nil {
typeModel.Description = *schema.Description
}
domain.buildTypeProperties(typeModel, schema)
domain.buildTypeRequirements(typeModel, schema)
domain.buildPatternPropertyAccessors(typeModel, schema)
domain.buildAdditionalPropertyAccessors(typeModel, schema)
domain.buildOneOfAccessors(typeModel, schema)
domain.buildAnyOfAccessors(typeModel, schema)
}
return typeModel
}
func (domain *Domain) Build() (err error) {
if (domain.Schema == nil) || (domain.Schema.Definitions == nil) {
return errors.New("missing definitions section")
}
// create a type for the top-level schema
typeName := domain.Prefix + "Document"
typeModel := NewTypeModel()
typeModel.Name = typeName
domain.buildTypeProperties(typeModel, domain.Schema)
domain.buildTypeRequirements(typeModel, domain.Schema)
domain.buildPatternPropertyAccessors(typeModel, domain.Schema)
domain.buildAdditionalPropertyAccessors(typeModel, domain.Schema)
domain.buildOneOfAccessors(typeModel, domain.Schema)
domain.buildAnyOfAccessors(typeModel, domain.Schema)
if len(typeModel.Properties) > 0 {
domain.TypeModels[typeName] = typeModel
}
// create a type for each object defined in the schema
if domain.Schema.Definitions != nil {
for _, pair := range *(domain.Schema.Definitions) {
definitionName := pair.Name
definitionSchema := pair.Value
typeName := domain.TypeNameForStub(definitionName)
typeModel := domain.BuildTypeForDefinition(typeName, definitionName, definitionSchema)
if typeModel != nil {
domain.TypeModels[typeName] = typeModel
}
}
}
// iterate over anonymous object types to be instantiated and generate a type for each
for typeName, typeRequest := range domain.ObjectTypeRequests {
domain.TypeModels[typeRequest.Name] =
domain.buildTypeForDefinitionObject(typeName, typeRequest.PropertyName, typeRequest.Schema)
}
// iterate over map item types to be instantiated and generate a type for each
mapTypeNames := make([]string, 0)
for mapTypeName, _ := range domain.MapTypeRequests {
mapTypeNames = append(mapTypeNames, mapTypeName)
}
sort.Strings(mapTypeNames)
for _, mapTypeName := range mapTypeNames {
typeName := "Named" + strings.Title(mapTypeName)
typeModel := NewTypeModel()
typeModel.Name = typeName
typeModel.Description = fmt.Sprintf(
"Automatically-generated message used to represent maps of %s as ordered (name,value) pairs.",
mapTypeName)
typeModel.IsPair = true
typeModel.PairValueType = mapTypeName
nameProperty := NewTypeProperty()
nameProperty.Name = "name"
nameProperty.Type = "string"
nameProperty.Description = "Map key"
typeModel.addProperty(nameProperty)
valueProperty := NewTypeProperty()
valueProperty.Name = "value"
valueProperty.Type = mapTypeName
valueProperty.Description = "Mapped value"
typeModel.addProperty(valueProperty)
domain.TypeModels[typeName] = typeModel
}
// add a type for string arrays
stringArrayType := NewTypeModel()
stringArrayType.Name = "StringArray"
stringProperty := NewTypeProperty()
stringProperty.Name = "value"
stringProperty.Type = "string"
stringProperty.Repeated = true
stringArrayType.addProperty(stringProperty)
domain.TypeModels[stringArrayType.Name] = stringArrayType
// add a type for "Any"
anyType := NewTypeModel()
anyType.Name = "Any"
anyType.Open = true
anyType.IsBlob = true
valueProperty := NewTypeProperty()
valueProperty.Name = "value"
valueProperty.Type = "google.protobuf.Any"
anyType.addProperty(valueProperty)
yamlProperty := NewTypeProperty()
yamlProperty.Name = "yaml"
yamlProperty.Type = "string"
anyType.addProperty(yamlProperty)
domain.TypeModels[anyType.Name] = anyType
return err
}
func (domain *Domain) sortedTypeNames() []string {
typeNames := make([]string, 0)
for typeName, _ := range domain.TypeModels {
typeNames = append(typeNames, typeName)
}
sort.Strings(typeNames)
return typeNames
}
func (domain *Domain) Description() string {
typeNames := domain.sortedTypeNames()
result := ""
for _, typeName := range typeNames {
result += domain.TypeModels[typeName].description()
}
return result
}

View file

@ -0,0 +1,638 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
import (
"fmt"
"sort"
"strings"
"github.com/googleapis/gnostic/printer"
)
func (domain *Domain) GenerateCompiler(packageName string, license string, imports []string) string {
code := &printer.Code{}
code.Print(license)
code.Print("// THIS FILE IS AUTOMATICALLY GENERATED.\n")
// generate package declaration
code.Print("package %s\n", packageName)
code.Print("import (")
for _, filename := range imports {
code.Print("\"" + filename + "\"")
}
code.Print(")\n")
// generate a simple Version() function
code.Print("func Version() string {")
code.Print(" return \"%s\"", packageName)
code.Print("}\n")
typeNames := domain.sortedTypeNames()
// generate NewX() constructor functions for each type
for _, typeName := range typeNames {
domain.generateConstructorForType(code, typeName)
}
// generate ResolveReferences() methods for each type
for _, typeName := range typeNames {
domain.generateResolveReferencesMethodsForType(code, typeName)
}
return code.String()
}
func (domain *Domain) generateConstructorForType(code *printer.Code, typeName string) {
code.Print("func New%s(in interface{}, context *compiler.Context) (*%s, error) {", typeName, typeName)
code.Print("errors := make([]error, 0)")
typeModel := domain.TypeModels[typeName]
parentTypeName := typeName
if typeModel.IsStringArray {
code.Print("x := &TypeItem{}")
code.Print("switch in := in.(type) {")
code.Print("case string:")
code.Print(" x.Value = make([]string, 0)")
code.Print(" x.Value = append(x.Value, in)")
code.Print("case []interface{}:")
code.Print(" x.Value = make([]string, 0)")
code.Print(" for _, v := range in {")
code.Print(" value, ok := v.(string)")
code.Print(" if ok {")
code.Print(" x.Value = append(x.Value, value)")
code.Print(" } else {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for string array element: %%+v (%%T)\", value, value)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print(" }")
code.Print(" }")
code.Print("default:")
code.Print(" message := fmt.Sprintf(\"has unexpected value for string array: %%+v (%%T)\", in, in)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
} else if typeModel.IsItemArray {
if domain.Version == "v2" {
code.Print("x := &ItemsItem{}")
code.Print("m, ok := compiler.UnpackMap(in)")
code.Print("if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for item array: %%+v (%%T)\", in, in)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("} else {")
code.Print(" x.Schema = make([]*Schema, 0)")
code.Print(" y, err := NewSchema(m, compiler.NewContext(\"<array>\", context))")
code.Print(" if err != nil {")
code.Print(" return nil, err")
code.Print(" }")
code.Print(" x.Schema = append(x.Schema, y)")
code.Print("}")
} else if domain.Version == "v3" {
code.Print("x := &ItemsItem{}")
code.Print("m, ok := compiler.UnpackMap(in)")
code.Print("if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for item array: %%+v (%%T)\", in, in)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("} else {")
code.Print(" x.SchemaOrReference = make([]*SchemaOrReference, 0)")
code.Print(" y, err := NewSchemaOrReference(m, compiler.NewContext(\"<array>\", context))")
code.Print(" if err != nil {")
code.Print(" return nil, err")
code.Print(" }")
code.Print(" x.SchemaOrReference = append(x.SchemaOrReference, y)")
code.Print("}")
}
} else if typeModel.IsBlob {
code.Print("x := &Any{}")
code.Print("bytes, _ := yaml.Marshal(in)")
code.Print("x.Yaml = string(bytes)")
} else if typeModel.Name == "StringArray" {
code.Print("x := &StringArray{}")
code.Print("a, ok := in.([]interface{})")
code.Print("if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for StringArray: %%+v (%%T)\", in, in)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("} else {")
code.Print(" x.Value = make([]string, 0)")
code.Print(" for _, s := range a {")
code.Print(" x.Value = append(x.Value, s.(string))")
code.Print(" }")
code.Print("}")
} else if typeModel.Name == "Primitive" {
code.Print(" x := &Primitive{}")
code.Print(" matched := false")
code.Print(" switch in := in.(type) {")
code.Print(" case bool:")
code.Print(" x.Oneof = &Primitive_Boolean{Boolean: in}")
code.Print(" matched = true")
code.Print(" case string:")
code.Print(" x.Oneof = &Primitive_String_{String_: in}")
code.Print(" matched = true")
code.Print(" case int64:")
code.Print(" x.Oneof = &Primitive_Integer{Integer: in}")
code.Print(" matched = true")
code.Print(" case int32:")
code.Print(" x.Oneof = &Primitive_Integer{Integer: int64(in)}")
code.Print(" matched = true")
code.Print(" case int:")
code.Print(" x.Oneof = &Primitive_Integer{Integer: int64(in)}")
code.Print(" matched = true")
code.Print(" case float64:")
code.Print(" x.Oneof = &Primitive_Number{Number: in}")
code.Print(" matched = true")
code.Print(" case float32:")
code.Print(" x.Oneof = &Primitive_Number{Number: float64(in)}")
code.Print(" matched = true")
code.Print(" }")
code.Print(" if matched {")
code.Print(" // since the oneof matched one of its possibilities, discard any matching errors")
code.Print(" errors = make([]error, 0)")
code.Print(" }")
} else if typeModel.Name == "SpecificationExtension" {
code.Print(" x := &SpecificationExtension{}")
code.Print(" matched := false")
code.Print(" switch in := in.(type) {")
code.Print(" case bool:")
code.Print(" x.Oneof = &SpecificationExtension_Boolean{Boolean: in}")
code.Print(" matched = true")
code.Print(" case string:")
code.Print(" x.Oneof = &SpecificationExtension_String_{String_: in}")
code.Print(" matched = true")
code.Print(" case int64:")
code.Print(" x.Oneof = &SpecificationExtension_Integer{Integer: in}")
code.Print(" matched = true")
code.Print(" case int32:")
code.Print(" x.Oneof = &SpecificationExtension_Integer{Integer: int64(in)}")
code.Print(" matched = true")
code.Print(" case int:")
code.Print(" x.Oneof = &SpecificationExtension_Integer{Integer: int64(in)}")
code.Print(" matched = true")
code.Print(" case float64:")
code.Print(" x.Oneof = &SpecificationExtension_Number{Number: in}")
code.Print(" matched = true")
code.Print(" case float32:")
code.Print(" x.Oneof = &SpecificationExtension_Number{Number: float64(in)}")
code.Print(" matched = true")
code.Print(" }")
code.Print(" if matched {")
code.Print(" // since the oneof matched one of its possibilities, discard any matching errors")
code.Print(" errors = make([]error, 0)")
code.Print(" }")
} else {
oneOfWrapper := typeModel.OneOfWrapper
code.Print("x := &%s{}", typeName)
if oneOfWrapper {
code.Print("matched := false")
}
unpackAtTop := !oneOfWrapper || len(typeModel.Required) > 0
if unpackAtTop {
code.Print("m, ok := compiler.UnpackMap(in)")
code.Print("if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value: %%+v (%%T)\", in, in)")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("} else {")
}
if len(typeModel.Required) > 0 {
// verify that map includes all required keys
keyString := ""
sort.Strings(typeModel.Required)
for _, k := range typeModel.Required {
if keyString != "" {
keyString += ","
}
keyString += "\""
keyString += k
keyString += "\""
}
code.Print("requiredKeys := []string{%s}", keyString)
code.Print("missingKeys := compiler.MissingKeysInMap(m, requiredKeys)")
code.Print("if len(missingKeys) > 0 {")
code.Print(" message := fmt.Sprintf(\"is missing required %%s: %%+v\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \", \"))")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
}
if !typeModel.Open {
// verify that map has no unspecified keys
allowedKeys := make([]string, 0)
for _, property := range typeModel.Properties {
if !property.Implicit {
allowedKeys = append(allowedKeys, property.Name)
}
}
sort.Strings(allowedKeys)
allowedKeyString := ""
for _, allowedKey := range allowedKeys {
if allowedKeyString != "" {
allowedKeyString += ","
}
allowedKeyString += "\""
allowedKeyString += allowedKey
allowedKeyString += "\""
}
allowedPatternString := ""
if typeModel.OpenPatterns != nil {
for _, pattern := range typeModel.OpenPatterns {
if allowedPatternString != "" {
allowedPatternString += ","
}
allowedPatternString += "\""
allowedPatternString += pattern
allowedPatternString += "\""
}
}
// verify that map includes only allowed keys and patterns
code.Print("allowedKeys := []string{%s}", allowedKeyString)
code.Print("allowedPatterns := []string{%s}", allowedPatternString)
code.Print("invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)")
code.Print("if len(invalidKeys) > 0 {")
code.Print(" message := fmt.Sprintf(\"has invalid %%s: %%+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))")
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
}
var fieldNumber = 0
for _, propertyModel := range typeModel.Properties {
propertyName := propertyModel.Name
fieldNumber += 1
propertyType := propertyModel.Type
if propertyType == "int" {
propertyType = "int64"
}
var displayName = propertyName
if displayName == "$ref" {
displayName = "_ref"
}
if displayName == "$schema" {
displayName = "_schema"
}
displayName = camelCaseToSnakeCase(displayName)
var line = fmt.Sprintf("%s %s = %d;", propertyType, displayName, fieldNumber)
if propertyModel.Repeated {
line = "repeated " + line
}
code.Print("// " + line)
fieldName := strings.Title(propertyName)
if propertyName == "$ref" {
fieldName = "XRef"
}
typeModel, typeFound := domain.TypeModels[propertyType]
if typeFound && !typeModel.IsPair {
if propertyModel.Repeated {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" // repeated %s", typeModel.Name)
code.Print(" x.%s = make([]*%s, 0)", fieldName, typeModel.Name)
code.Print(" a, ok := v%d.([]interface{})", fieldNumber)
code.Print(" if ok {")
code.Print(" for _, item := range a {")
code.Print(" y, err := New%s(item, compiler.NewContext(\"%s\", context))", typeModel.Name, propertyName)
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" }")
code.Print(" x.%s = append(x.%s, y)", fieldName, fieldName)
code.Print(" }")
code.Print(" }")
code.Print("}")
} else {
if oneOfWrapper {
code.Print("{")
if !unpackAtTop {
code.Print(" m, ok := compiler.UnpackMap(in)")
code.Print(" if ok {")
}
code.Print(" // errors might be ok here, they mean we just don't have the right subtype")
code.Print(" t, matching_error := New%s(m, compiler.NewContext(\"%s\", context))", typeModel.Name, propertyName)
code.Print(" if matching_error == nil {")
code.Print(" x.Oneof = &%s_%s{%s: t}", parentTypeName, typeModel.Name, typeModel.Name)
code.Print(" matched = true")
code.Print(" } else {")
code.Print(" errors = append(errors, matching_error)")
code.Print(" }")
if !unpackAtTop {
code.Print(" }")
}
code.Print("}")
} else {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" var err error")
code.Print(" x.%s, err = New%s(v%d, compiler.NewContext(\"%s\", context))",
fieldName, typeModel.Name, fieldNumber, propertyName)
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" }")
code.Print("}")
}
}
} else if propertyType == "string" {
if propertyModel.Repeated {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" v, ok := v%d.([]interface{})", fieldNumber)
code.Print(" if ok {")
code.Print(" x.%s = compiler.ConvertInterfaceArrayToStringArray(v)", fieldName)
code.Print(" } else {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
if propertyModel.StringEnumValues != nil {
code.Print("// check for valid enum values")
code.Print("// %+v", propertyModel.StringEnumValues)
stringArrayLiteral := "[]string{"
for i, item := range propertyModel.StringEnumValues {
if i > 0 {
stringArrayLiteral += ","
}
stringArrayLiteral += "\"" + item + "\""
}
stringArrayLiteral += "}"
code.Print("if ok && !compiler.StringArrayContainsValues(%s, x.%s) {", stringArrayLiteral, fieldName)
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v\", v%d)", propertyName, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
}
code.Print("}")
} else {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" x.%s, ok = v%d.(string)", fieldName, fieldNumber)
code.Print(" if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print(" }")
if propertyModel.StringEnumValues != nil {
code.Print("// check for valid enum values")
code.Print("// %+v", propertyModel.StringEnumValues)
stringArrayLiteral := "[]string{"
for i, item := range propertyModel.StringEnumValues {
if i > 0 {
stringArrayLiteral += ","
}
stringArrayLiteral += "\"" + item + "\""
}
stringArrayLiteral += "}"
code.Print("if ok && !compiler.StringArrayContainsValue(%s, x.%s) {", stringArrayLiteral, fieldName)
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print("}")
}
code.Print("}")
}
} else if propertyType == "float" {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" switch v%d := v%d.(type) {", fieldNumber, fieldNumber)
code.Print(" case float64:")
code.Print(" x.%s = v%d", fieldName, fieldNumber)
code.Print(" case float32:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" case uint64:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" case uint32:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" case int64:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" case int32:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" case int:")
code.Print(" x.%s = float64(v%d)", fieldName, fieldNumber)
code.Print(" default:")
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print(" }")
code.Print("}")
} else if propertyType == "int64" {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" t, ok := v%d.(int)", fieldNumber)
code.Print(" if ok {")
code.Print(" x.%s = int64(t)", fieldName)
code.Print(" } else {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print(" }")
code.Print("}")
} else if propertyType == "bool" {
if oneOfWrapper {
propertyName := "Boolean"
code.Print("boolValue, ok := in.(bool)")
code.Print("if ok {")
code.Print(" x.Oneof = &%s_%s{%s: boolValue}", parentTypeName, propertyName, propertyName)
code.Print("}")
} else {
code.Print("v%d := compiler.MapValueForKey(m, \"%s\")", fieldNumber, propertyName)
code.Print("if (v%d != nil) {", fieldNumber)
code.Print(" x.%s, ok = v%d.(bool)", fieldName, fieldNumber)
code.Print(" if !ok {")
code.Print(" message := fmt.Sprintf(\"has unexpected value for %s: %%+v (%%T)\", v%d, v%d)", propertyName, fieldNumber, fieldNumber)
code.Print(" errors = append(errors, compiler.NewError(context, message))")
code.Print(" }")
code.Print("}")
}
} else {
mapTypeName := propertyModel.MapType
if mapTypeName != "" {
code.Print("// MAP: %s %s", mapTypeName, propertyModel.Pattern)
if mapTypeName == "string" {
code.Print("x.%s = make([]*NamedString, 0)", fieldName)
} else {
code.Print("x.%s = make([]*Named%s, 0)", fieldName, mapTypeName)
}
code.Print("for _, item := range m {")
code.Print("k, ok := item.Key.(string)")
code.Print("if ok {")
code.Print("v := item.Value")
if propertyModel.Pattern != "" {
code.Print("if compiler.PatternMatches(\"%s\", k) {", propertyModel.Pattern)
}
code.Print("pair := &Named" + strings.Title(mapTypeName) + "{}")
code.Print("pair.Name = k")
if mapTypeName == "string" {
code.Print("pair.Value = v.(string)")
} else if mapTypeName == "Any" {
code.Print("result := &Any{}")
code.Print("handled, resultFromExt, err := compiler.HandleExtension(context, v, k)")
code.Print("if handled {")
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" } else {")
code.Print(" bytes, _ := yaml.Marshal(v)")
code.Print(" result.Yaml = string(bytes)")
code.Print(" result.Value = resultFromExt")
code.Print(" pair.Value = result")
code.Print(" }")
code.Print("} else {")
code.Print(" pair.Value, err = NewAny(v, compiler.NewContext(k, context))")
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" }")
code.Print("}")
} else {
code.Print("var err error")
code.Print("pair.Value, err = New%s(v, compiler.NewContext(k, context))", mapTypeName)
code.Print("if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print("}")
}
code.Print("x.%s = append(x.%s, pair)", fieldName, fieldName)
if propertyModel.Pattern != "" {
code.Print("}")
}
code.Print("}")
code.Print("}")
} else {
code.Print("// TODO: %s", propertyType)
}
}
}
if unpackAtTop {
code.Print("}")
}
if oneOfWrapper {
code.Print("if matched {")
code.Print(" // since the oneof matched one of its possibilities, discard any matching errors")
code.Print(" errors = make([]error, 0)")
code.Print("}")
}
}
// assumes that the return value is in a variable named "x"
code.Print(" return x, compiler.NewErrorGroupOrNil(errors)")
code.Print("}\n")
}
// ResolveReferences() methods
func (domain *Domain) generateResolveReferencesMethodsForType(code *printer.Code, typeName string) {
code.Print("func (m *%s) ResolveReferences(root string) (interface{}, error) {", typeName)
code.Print("errors := make([]error, 0)")
typeModel := domain.TypeModels[typeName]
if typeModel.OneOfWrapper {
// call ResolveReferences on whatever is in the Oneof.
for _, propertyModel := range typeModel.Properties {
propertyType := propertyModel.Type
_, typeFound := domain.TypeModels[propertyType]
if typeFound {
code.Print("{")
code.Print("p, ok := m.Oneof.(*%s_%s)", typeName, propertyType)
code.Print("if ok {")
if propertyType == "JsonReference" { // Special case for OpenAPI
code.Print("info, err := p.%s.ResolveReferences(root)", propertyType)
code.Print("if err != nil {")
code.Print(" return nil, err")
code.Print("} else if info != nil {")
code.Print(" n, err := New%s(info, nil)", typeName)
code.Print(" if err != nil {")
code.Print(" return nil, err")
code.Print(" } else if n != nil {")
code.Print(" *m = *n")
code.Print(" return nil, nil")
code.Print(" }")
code.Print("}")
} else {
code.Print("_, err := p.%s.ResolveReferences(root)", propertyType)
code.Print("if err != nil {")
code.Print(" return nil, err")
code.Print("}")
}
code.Print("}")
code.Print("}")
}
}
} else {
for _, propertyModel := range typeModel.Properties {
propertyName := propertyModel.Name
var displayName = propertyName
if displayName == "$ref" {
displayName = "_ref"
}
if displayName == "$schema" {
displayName = "_schema"
}
displayName = camelCaseToSnakeCase(displayName)
fieldName := strings.Title(propertyName)
if propertyName == "$ref" {
fieldName = "XRef"
code.Print("if m.XRef != \"\" {")
//code.Print("log.Printf(\"%s reference to resolve %%+v\", m.XRef)", typeName)
code.Print("info, err := compiler.ReadInfoForRef(root, m.XRef)")
code.Print("if err != nil {")
code.Print(" return nil, err")
code.Print("}")
//code.Print("log.Printf(\"%%+v\", info)")
if len(typeModel.Properties) > 1 {
code.Print("if info != nil {")
code.Print(" replacement, err := New%s(info, nil)", typeName)
code.Print(" if err == nil {")
code.Print(" *m = *replacement")
code.Print(" return m.ResolveReferences(root)")
code.Print(" }")
code.Print("}")
}
code.Print("return info, nil")
code.Print("}")
}
if !propertyModel.Repeated {
propertyType := propertyModel.Type
typeModel, typeFound := domain.TypeModels[propertyType]
if typeFound && !typeModel.IsPair {
code.Print("if m.%s != nil {", fieldName)
code.Print(" _, err := m.%s.ResolveReferences(root)", fieldName)
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" }")
code.Print("}")
}
} else {
propertyType := propertyModel.Type
_, typeFound := domain.TypeModels[propertyType]
if typeFound {
code.Print("for _, item := range m.%s {", fieldName)
code.Print("if item != nil {")
code.Print(" _, err := item.ResolveReferences(root)")
code.Print(" if err != nil {")
code.Print(" errors = append(errors, err)")
code.Print(" }")
code.Print("}")
code.Print("}")
}
}
}
}
code.Print(" return nil, compiler.NewErrorGroupOrNil(errors)")
code.Print("}\n")
}

View file

@ -0,0 +1,297 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"github.com/googleapis/gnostic/compiler"
"github.com/googleapis/gnostic/jsonschema"
"github.com/googleapis/gnostic/printer"
)
var PROTO_OPTIONS_FOR_EXTENSION = []ProtoOption{
ProtoOption{
Name: "java_multiple_files",
Value: "true",
Comment: "// This option lets the proto compiler generate Java code inside the package\n" +
"// name (see below) instead of inside an outer class. It creates a simpler\n" +
"// developer experience by reducing one-level of name nesting and be\n" +
"// consistent with most programming languages that don't support outer classes.",
},
ProtoOption{
Name: "java_outer_classname",
Value: "VendorExtensionProto",
Comment: "// The Java outer classname should be the filename in UpperCamelCase. This\n" +
"// class is only used to hold proto descriptor, so developers don't need to\n" +
"// work with it directly.",
},
}
const additionalCompilerCodeWithMain = "" +
"func handleExtension(extensionName string, info yaml.MapSlice) (bool, proto.Message, error) {\n" +
" switch extensionName {\n" +
" // All supported extensions\n" +
" %s\n" +
" default:\n" +
" return false, nil, nil\n" +
" }\n" +
"}\n" +
"\n" +
"func main() {\n" +
" openapiextension_v1.ProcessExtension(handleExtension)\n" +
"}\n"
const caseString = "\n" +
"case \"%s\":\n" +
"newObject, err := %s.New%s(info, compiler.NewContext(\"$root\", nil))\n" +
"return true, newObject, err"
func GenerateMainFile(packageName string, license string, codeBody string, imports []string) string {
code := &printer.Code{}
code.Print(license)
code.Print("// THIS FILE IS AUTOMATICALLY GENERATED.\n")
// generate package declaration
code.Print("package %s\n", packageName)
code.Print("import (")
for _, filename := range imports {
code.Print("\"" + filename + "\"")
}
code.Print(")\n")
code.Print(codeBody)
return code.String()
}
func getBaseFileNameWithoutExt(filePath string) string {
tmp := filepath.Base(filePath)
return tmp[0 : len(tmp)-len(filepath.Ext(tmp))]
}
func toProtoPackageName(input string) string {
var out = ""
nonAlphaNumeric := regexp.MustCompile("[^0-9A-Za-z_]+")
input = nonAlphaNumeric.ReplaceAllString(input, "")
for index, character := range input {
if character >= 'A' && character <= 'Z' {
if index > 0 && input[index-1] != '_' {
out += "_"
}
out += string(character - 'A' + 'a')
} else {
out += string(character)
}
}
return out
}
func GenerateExtension(schemaFile string, outDir string) error {
outFileBaseName := getBaseFileNameWithoutExt(schemaFile)
extensionNameWithoutXDashPrefix := outFileBaseName[len("x-"):]
outDir = path.Join(outDir, "openapi_extensions_"+extensionNameWithoutXDashPrefix)
protoPackage := toProtoPackageName(extensionNameWithoutXDashPrefix)
protoPackageName := strings.ToLower(protoPackage)
goPackageName := protoPackageName
protoOutDirectory := outDir + "/" + "proto"
var err error
project_root := os.Getenv("GOPATH") + "/src/github.com/googleapis/gnostic/"
baseSchema, err := jsonschema.NewSchemaFromFile(project_root + "jsonschema/schema.json")
if err != nil {
return err
}
baseSchema.ResolveRefs()
baseSchema.ResolveAllOfs()
openapiSchema, err := jsonschema.NewSchemaFromFile(schemaFile)
if err != nil {
return err
}
openapiSchema.ResolveRefs()
openapiSchema.ResolveAllOfs()
// build a simplified model of the types described by the schema
cc := NewDomain(openapiSchema, "v2") // TODO fix for OpenAPI v3
// create a type for each object defined in the schema
extensionToMessage := make(map[string]string)
schemaErrors := make([]error, 0)
if cc.Schema.Definitions != nil {
for _, pair := range *(cc.Schema.Definitions) {
definitionName := pair.Name
definitionSchema := pair.Value
// ensure the id field is set
if definitionSchema.Id == nil || len(*(definitionSchema.Id)) == 0 {
schemaErrors = append(schemaErrors,
errors.New(
fmt.Sprintf("Schema %s has no 'id' field, which must match the name of the OpenAPI extension that the schema represents.\n", definitionName)))
} else {
if _, ok := extensionToMessage[*(definitionSchema.Id)]; ok {
schemaErrors = append(schemaErrors,
errors.New(
fmt.Sprintf("Schema %s and %s have the same 'id' field value.\n",
definitionName, extensionToMessage[*(definitionSchema.Id)])))
}
extensionToMessage[*(definitionSchema.Id)] = definitionName
}
typeName := cc.TypeNameForStub(definitionName)
typeModel := cc.BuildTypeForDefinition(typeName, definitionName, definitionSchema)
if typeModel != nil {
cc.TypeModels[typeName] = typeModel
}
}
}
if len(schemaErrors) > 0 {
// error has been reported.
return compiler.NewErrorGroupOrNil(schemaErrors)
}
err = os.MkdirAll(outDir, os.ModePerm)
if err != nil {
return err
}
err = os.MkdirAll(protoOutDirectory, os.ModePerm)
if err != nil {
return err
}
// generate the protocol buffer description
PROTO_OPTIONS := append(PROTO_OPTIONS_FOR_EXTENSION,
ProtoOption{Name: "java_package", Value: "org.openapi.extension." + strings.ToLower(protoPackage), Comment: "// The Java package name must be proto package name with proper prefix."},
ProtoOption{Name: "objc_class_prefix", Value: strings.ToLower(protoPackage),
Comment: "// A reasonable prefix for the Objective-C symbols generated from the package.\n" +
"// It should at a minimum be 3 characters long, all uppercase, and convention\n" +
"// is to use an abbreviation of the package name. Something short, but\n" +
"// hopefully unique enough to not conflict with things that may come along in\n" +
"// the future. 'GPB' is reserved for the protocol buffer implementation itself.",
})
proto := cc.GenerateProto(protoPackageName, LICENSE, PROTO_OPTIONS, nil)
protoFilename := path.Join(protoOutDirectory, outFileBaseName+".proto")
err = ioutil.WriteFile(protoFilename, []byte(proto), 0644)
if err != nil {
return err
}
// generate the compiler
compiler := cc.GenerateCompiler(goPackageName, LICENSE, []string{
"fmt",
"strings",
"github.com/googleapis/gnostic/compiler",
})
goFilename := path.Join(protoOutDirectory, outFileBaseName+".go")
err = ioutil.WriteFile(goFilename, []byte(compiler), 0644)
if err != nil {
return err
}
err = exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", goFilename).Run()
// generate the main file.
outDirRelativeToGoPathSrc := strings.Replace(outDir, path.Join(os.Getenv("GOPATH"), "src")+"/", "", 1)
imports := []string{
"gopkg.in/yaml.v2",
"github.com/golang/protobuf/proto",
"github.com/googleapis/gnostic/extensions",
"github.com/googleapis/gnostic/compiler",
outDirRelativeToGoPathSrc + "/" + "proto",
}
var extensionNameKeys []string
for k := range extensionToMessage {
extensionNameKeys = append(extensionNameKeys, k)
}
sort.Strings(extensionNameKeys)
var cases string
for _, extensionName := range extensionNameKeys {
cases += fmt.Sprintf(caseString, extensionName, goPackageName, extensionToMessage[extensionName])
}
extMainCode := fmt.Sprintf(additionalCompilerCodeWithMain, cases)
main := GenerateMainFile("main", LICENSE, extMainCode, imports)
mainFileName := path.Join(outDir, "main.go")
err = ioutil.WriteFile(mainFileName, []byte(main), 0644)
if err != nil {
return err
}
// format the compiler
return exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", mainFileName).Run()
}
func ProcessExtensionGenCommandline(usage string) error {
outDir := ""
schameFile := ""
extParamRegex, _ := regexp.Compile("--(.+)=(.+)")
for i, arg := range os.Args {
if i == 0 {
continue // skip the tool name
}
var m [][]byte
if m = extParamRegex.FindSubmatch([]byte(arg)); m != nil {
flagName := string(m[1])
flagValue := string(m[2])
switch flagName {
case "out_dir":
outDir = flagValue
default:
fmt.Printf("Unknown option: %s.\n%s\n", arg, usage)
os.Exit(-1)
}
} else if arg == "--extension" {
continue
} else if arg[0] == '-' {
fmt.Printf("Unknown option: %s.\n%s\n", arg, usage)
os.Exit(-1)
} else {
schameFile = arg
}
}
if schameFile == "" {
fmt.Printf("No input json schema specified.\n%s\n", usage)
os.Exit(-1)
}
if outDir == "" {
fmt.Printf("Missing output directive.\n%s\n", usage)
os.Exit(-1)
}
if !strings.HasPrefix(getBaseFileNameWithoutExt(schameFile), "x-") {
fmt.Printf("Schema file name has to start with 'x-'.\n%s\n", usage)
os.Exit(-1)
}
return GenerateExtension(schameFile, outDir)
}

View file

@ -0,0 +1,118 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
import (
"fmt"
"strings"
"github.com/googleapis/gnostic/printer"
)
type ProtoOption struct {
Name string
Value string
Comment string
}
func (domain *Domain) GenerateProto(packageName string, license string, options []ProtoOption, imports []string) string {
code := &printer.Code{}
code.Print(license)
code.Print("// THIS FILE IS AUTOMATICALLY GENERATED.")
code.Print()
code.Print("syntax = \"proto3\";")
code.Print()
code.Print("package " + packageName + ";")
for _, importString := range imports {
code.Print()
code.Print("import \"" + importString + "\";")
}
code.Print()
// generate option declarations
for _, option := range options {
commentLines := strings.Split(option.Comment, "\n")
for _, commentLine := range commentLines {
code.Print(commentLine)
}
line := "option " + option.Name + " = "
if option.Value == "true" || option.Value == "false" {
line += option.Value
} else {
line += "\"" + option.Value + "\""
}
line += ";\n"
code.Print(line)
}
// generate message definitions
typeNames := domain.sortedTypeNames()
for _, typeName := range typeNames {
typeModel := domain.TypeModels[typeName]
if typeModel.Description != "" {
code.Print("// %s", typeModel.Description)
}
code.Print("message %s {", typeName)
code.Indent()
if typeModel.OneOfWrapper {
code.Print("oneof oneof {")
code.Indent()
}
var fieldNumber = 0
for _, propertyModel := range typeModel.Properties {
if propertyModel.Description != "" {
code.Print("// %s", propertyModel.Description)
}
propertyName := propertyModel.Name
fieldNumber += 1
propertyType := propertyModel.Type
if propertyType == "int" {
propertyType = "int64"
}
if propertyType == "float" {
propertyType = "double"
}
// TODO may be remove this.
if propertyType == "blob" {
propertyType = "string"
}
var displayName = propertyName
if displayName == "$ref" {
displayName = "_ref"
}
if displayName == "$schema" {
displayName = "_schema"
}
displayName = camelCaseToSnakeCase(displayName)
var line = fmt.Sprintf("%s %s = %d;", propertyType, displayName, fieldNumber)
if propertyModel.Repeated {
line = "repeated " + line
}
code.Print(line)
}
if typeModel.OneOfWrapper {
code.Outdent()
code.Print("}")
}
code.Outdent()
code.Print("}")
code.Print()
}
return code.String()
}

View file

@ -0,0 +1,34 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
// Returns a "snake case" form of a camel-cased string.
func camelCaseToSnakeCase(input string) string {
var out = ""
for index, runeValue := range input {
//fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
if runeValue >= 'A' && runeValue <= 'Z' {
if index > 0 {
out += "_"
}
out += string(runeValue - 'A' + 'a')
} else {
out += string(runeValue)
}
}
return out
}

235
vendor/github.com/googleapis/gnostic/generator/main.go generated vendored Normal file
View file

@ -0,0 +1,235 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// generator generates Protocol Buffer models and support code from
// JSON Schemas. It is used to generate representations of the
// OpenAPI Specification and vendor and specification extensions
// that are added by third-party OpenAPI authors.
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"runtime"
"strings"
"github.com/googleapis/gnostic/jsonschema"
)
const LICENSE = "" +
"// Copyright 2017 Google Inc. All Rights Reserved.\n" +
"//\n" +
"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
"// you may not use this file except in compliance with the License.\n" +
"// You may obtain a copy of the License at\n" +
"//\n" +
"// http://www.apache.org/licenses/LICENSE-2.0\n" +
"//\n" +
"// Unless required by applicable law or agreed to in writing, software\n" +
"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +
"// See the License for the specific language governing permissions and\n" +
"// limitations under the License.\n"
func proto_options(packageName string) []ProtoOption {
return []ProtoOption{
ProtoOption{
Name: "java_multiple_files",
Value: "true",
Comment: "// This option lets the proto compiler generate Java code inside the package\n" +
"// name (see below) instead of inside an outer class. It creates a simpler\n" +
"// developer experience by reducing one-level of name nesting and be\n" +
"// consistent with most programming languages that don't support outer classes.",
},
ProtoOption{
Name: "java_outer_classname",
Value: "OpenAPIProto",
Comment: "// The Java outer classname should be the filename in UpperCamelCase. This\n" +
"// class is only used to hold proto descriptor, so developers don't need to\n" +
"// work with it directly.",
},
ProtoOption{
Name: "java_package",
Value: "org." + packageName,
Comment: "// The Java package name must be proto package name with proper prefix.",
},
ProtoOption{
Name: "objc_class_prefix",
Value: "OAS",
Comment: "// A reasonable prefix for the Objective-C symbols generated from the package.\n" +
"// It should at a minimum be 3 characters long, all uppercase, and convention\n" +
"// is to use an abbreviation of the package name. Something short, but\n" +
"// hopefully unique enough to not conflict with things that may come along in\n" +
"// the future. 'GPB' is reserved for the protocol buffer implementation itself.",
},
}
}
func GenerateOpenAPIModel(version string) error {
var input string
var filename string
var proto_packagename string
var extension_name string
switch version {
case "v2":
input = "openapi-2.0.json"
filename = "OpenAPIv2"
proto_packagename = "openapi.v2"
extension_name = "vendorExtension"
case "v3":
input = "openapi-3.0.json"
filename = "OpenAPIv3"
proto_packagename = "openapi.v3"
extension_name = "specificationExtension"
default:
return errors.New(fmt.Sprintf("Unknown OpenAPI version %s", version))
}
go_packagename := strings.Replace(proto_packagename, ".", "_", -1)
project_root := os.Getenv("GOPATH") + "/src/github.com/googleapis/gnostic/"
base_schema, err := jsonschema.NewSchemaFromFile(project_root + "jsonschema/schema.json")
if err != nil {
return err
}
base_schema.ResolveRefs()
base_schema.ResolveAllOfs()
openapi_schema, err := jsonschema.NewSchemaFromFile(project_root + filename + "/" + input)
if err != nil {
return err
}
openapi_schema.ResolveRefs()
openapi_schema.ResolveAllOfs()
// build a simplified model of the types described by the schema
cc := NewDomain(openapi_schema, version)
// generators will map these patterns to the associated property names
// these pattern names are a bit of a hack until we find a more automated way to obtain them
cc.PatternNames = map[string]string{
"^x-": extension_name,
// v2
"^/": "path",
"^([0-9]{3})$|^(default)$": "responseCode",
// v3
"^([0-9]{3})$": "responseCode",
"{property}": "property",
"{name}": "name",
"{expression}": "expression",
"/{path}": "path",
"{media-type}": "mediaType",
}
err = cc.Build()
if err != nil {
return err
}
if true {
log.Printf("Type Model:\n%s", cc.Description())
}
// ensure that the target directory exists
err = os.MkdirAll(filename, 0755)
if err != nil {
return err
}
// generate the protocol buffer description
proto := cc.GenerateProto(proto_packagename, LICENSE,
proto_options(go_packagename), []string{"google/protobuf/any.proto"})
proto_filename := project_root + filename + "/" + filename + ".proto"
err = ioutil.WriteFile(proto_filename, []byte(proto), 0644)
if err != nil {
return err
}
// generate the compiler
compiler := cc.GenerateCompiler(go_packagename, LICENSE, []string{
"fmt",
"gopkg.in/yaml.v2",
"strings",
"github.com/googleapis/gnostic/compiler",
})
go_filename := project_root + filename + "/" + filename + ".go"
err = ioutil.WriteFile(go_filename, []byte(compiler), 0644)
if err != nil {
return err
}
// format the compiler
return exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", go_filename).Run()
}
func usage() string {
return fmt.Sprintf(`
Usage: %s [OPTIONS]
Options:
--v2
Generate Protocol Buffer representation and support code for OpenAPI v2.
Files are read from and written to appropriate locations in the gnostic project directory.
--v3
Generate Protocol Buffer representation and support code for OpenAPI v3
Files are read from and written to appropriate locations in the gnostic project directory.
--extension EXTENSION_SCHEMA [EXTENSIONOPTIONS]
Generate a gnostic extension that reads a set of OpenAPI extensions.
EXTENSION_SCHEMA is the json schema for the OpenAPI extensions to be supported.
EXTENSION_OPTIONS
--out_dir=PATH: Location for writing extension models and support code.
`, path.Base(os.Args[0]))
}
func main() {
var openapi_version = ""
var generate_extensions = false
for i, arg := range os.Args {
if i == 0 {
continue // skip the tool name
}
if arg == "--v2" {
openapi_version = "v2"
} else if arg == "--v3" {
openapi_version = "v3"
} else if arg == "--extension" {
generate_extensions = true
break
} else {
fmt.Printf("Unknown option: %s.\n%s\n", arg, usage())
os.Exit(-1)
}
}
if openapi_version != "" {
err := GenerateOpenAPIModel(openapi_version)
if err != nil {
fmt.Printf("%+v\n", err)
}
} else if generate_extensions {
err := ProcessExtensionGenCommandline(usage())
if err != nil {
fmt.Printf("%+v\n", err)
}
} else {
fmt.Printf("%s\n", usage())
}
}

117
vendor/github.com/googleapis/gnostic/generator/types.go generated vendored Normal file
View file

@ -0,0 +1,117 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package main
import (
"fmt"
"github.com/googleapis/gnostic/jsonschema"
)
/// Type Modeling
// models types that we encounter during model-building that have no named schema
type TypeRequest struct {
Name string // name of type to be created
PropertyName string // name of a property that refers to this type
Schema *jsonschema.Schema // schema for type
OneOfWrapper bool // true if the type wraps "oneOfs"
}
func NewTypeRequest(name string, propertyName string, schema *jsonschema.Schema) *TypeRequest {
return &TypeRequest{Name: name, PropertyName: propertyName, Schema: schema}
}
// models type properties, eg. fields
type TypeProperty struct {
Name string // name of property
Type string // type for property (scalar or message type)
StringEnumValues []string // possible values if this is an enumerated string type
MapType string // if this property is for a map, the name of the mapped type
Repeated bool // true if this property is repeated (an array)
Pattern string // if the property is a pattern property, names must match this pattern.
Implicit bool // true if this property is implied by a pattern or "additional properties" property
Description string // if present, the "description" field in the schema
}
func (typeProperty *TypeProperty) description() string {
result := ""
if typeProperty.Description != "" {
result += fmt.Sprintf("\t// %+s\n", typeProperty.Description)
}
if typeProperty.Repeated {
result += fmt.Sprintf("\t%s %s repeated %s\n", typeProperty.Name, typeProperty.Type, typeProperty.Pattern)
} else {
result += fmt.Sprintf("\t%s %s %s \n", typeProperty.Name, typeProperty.Type, typeProperty.Pattern)
}
return result
}
func NewTypeProperty() *TypeProperty {
return &TypeProperty{}
}
func NewTypePropertyWithNameAndType(name string, typeName string) *TypeProperty {
return &TypeProperty{Name: name, Type: typeName}
}
func NewTypePropertyWithNameTypeAndPattern(name string, typeName string, pattern string) *TypeProperty {
return &TypeProperty{Name: name, Type: typeName, Pattern: pattern}
}
// models types
type TypeModel struct {
Name string // type name
Properties []*TypeProperty // slice of properties
Required []string // required property names
OneOfWrapper bool // true if this type wraps "oneof" properties
Open bool // open types can have keys outside the specified set
OpenPatterns []string // patterns for properties that we allow
IsStringArray bool // ugly override
IsItemArray bool // ugly override
IsBlob bool // ugly override
IsPair bool // type is a name-value pair used to support ordered maps
PairValueType string // type for pair values (valid if IsPair == true)
Description string // if present, the "description" field in the schema
}
func (typeModel *TypeModel) addProperty(property *TypeProperty) {
if typeModel.Properties == nil {
typeModel.Properties = make([]*TypeProperty, 0)
}
typeModel.Properties = append(typeModel.Properties, property)
}
func (typeModel *TypeModel) description() string {
result := ""
if typeModel.Description != "" {
result += fmt.Sprintf("// %+s\n", typeModel.Description)
}
var wrapperinfo string
if typeModel.OneOfWrapper {
wrapperinfo = " oneof wrapper"
}
result += fmt.Sprintf("%+s%s\n", typeModel.Name, wrapperinfo)
for _, property := range typeModel.Properties {
result += property.description()
}
return result
}
func NewTypeModel() *TypeModel {
typeModel := &TypeModel{}
typeModel.Properties = make([]*TypeProperty, 0)
return typeModel
}

393
vendor/github.com/googleapis/gnostic/gnostic.go generated vendored Normal file
View file

@ -0,0 +1,393 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
//go:generate ./COMPILE-PROTOS.sh
// Gnostic is a tool for building better REST APIs through knowledge.
//
// Gnostic reads declarative descriptions of REST APIs that conform
// to the OpenAPI Specification, reports errors, resolves internal
// dependencies, and puts the results in a binary form that can
// be used in any language that is supported by the Protocol Buffer
// tools.
//
// Gnostic models are validated and typed. This allows API tool
// developers to focus on their product and not worry about input
// validation and type checking.
//
// Gnostic calls plugins that implement a variety of API implementation
// and support features including generation of client and server
// support code.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/OpenAPIv2"
"github.com/googleapis/gnostic/OpenAPIv3"
"github.com/googleapis/gnostic/compiler"
plugins "github.com/googleapis/gnostic/plugins"
)
const ( // OpenAPI Version
OpenAPIvUnknown = 0
OpenAPIv2 = 2
OpenAPIv3 = 3
)
func openapi_version(info interface{}) int {
m, ok := compiler.UnpackMap(info)
if !ok {
return OpenAPIvUnknown
}
swagger, ok := compiler.MapValueForKey(m, "swagger").(string)
if ok && swagger == "2.0" {
return OpenAPIv2
}
openapi, ok := compiler.MapValueForKey(m, "openapi").(string)
if ok && openapi == "3.0" {
return OpenAPIv3
}
return OpenAPIvUnknown
}
type PluginCall struct {
Name string
Invocation string
}
func (pluginCall *PluginCall) perform(document proto.Message, openapi_version int, sourceName string) error {
if pluginCall.Name != "" {
request := &plugins.Request{}
// Infer the name of the executable by adding the prefix.
executableName := "gnostic_" + pluginCall.Name
// validate invocation string with regular expression
invocation := pluginCall.Invocation
//
// Plugin invocations must consist of
// zero or more comma-separated key=value pairs followed by a path.
// If pairs are present, a colon separates them from the path.
// Keys and values must be alphanumeric strings and may contain
// dashes, underscores, periods, or forward slashes.
// A path can contain any characters other than the separators ',', ':', and '='.
//
invocation_regex := regexp.MustCompile(`^([\w-_\/\.]+=[\w-_\/\.]+(,[\w-_\/\.]+=[\w-_\/\.]+)*:)?[^,:=]+$`)
if !invocation_regex.Match([]byte(pluginCall.Invocation)) {
return errors.New(fmt.Sprintf("Invalid invocation of %s: %s", executableName, invocation))
}
invocationParts := strings.Split(pluginCall.Invocation, ":")
var outputLocation string
switch len(invocationParts) {
case 1:
outputLocation = invocationParts[0]
case 2:
parameters := strings.Split(invocationParts[0], ",")
for _, keyvalue := range parameters {
pair := strings.Split(keyvalue, "=")
if len(pair) == 2 {
request.Parameters = append(request.Parameters, &plugins.Parameter{Name: pair[0], Value: pair[1]})
}
}
outputLocation = invocationParts[1]
default:
// badly-formed request
outputLocation = invocationParts[len(invocationParts)-1]
}
version := &plugins.Version{}
version.Major = 0
version.Minor = 1
version.Patch = 0
request.CompilerVersion = version
request.OutputPath = outputLocation
wrapper := &plugins.Wrapper{}
wrapper.Name = sourceName
switch openapi_version {
case OpenAPIv2:
wrapper.Version = "v2"
case OpenAPIv3:
wrapper.Version = "v3"
default:
wrapper.Version = "unknown"
}
protoBytes, _ := proto.Marshal(document)
wrapper.Value = protoBytes
request.Wrapper = wrapper
requestBytes, _ := proto.Marshal(request)
cmd := exec.Command(executableName)
cmd.Stdin = bytes.NewReader(requestBytes)
cmd.Stderr = os.Stderr
output, err := cmd.Output()
if err != nil {
return err
}
response := &plugins.Response{}
err = proto.Unmarshal(output, response)
if err != nil {
return err
}
if response.Errors != nil {
return errors.New(fmt.Sprintf("Plugin error: %+v", response.Errors))
}
// write files to the specified directory
var writer io.Writer
if outputLocation == "!" {
// write nothing
} else if outputLocation == "-" {
writer = os.Stdout
for _, file := range response.Files {
writer.Write([]byte("\n\n" + file.Name + " -------------------- \n"))
writer.Write(file.Data)
}
} else if isFile(outputLocation) {
return errors.New(fmt.Sprintf("Error, unable to overwrite %s\n", outputLocation))
} else {
if !isDirectory(outputLocation) {
os.Mkdir(outputLocation, 0755)
}
for _, file := range response.Files {
p := outputLocation + "/" + file.Name
dir := path.Dir(p)
os.MkdirAll(dir, 0755)
f, _ := os.Create(p)
defer f.Close()
f.Write(file.Data)
}
}
}
return nil
}
func isFile(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
}
return !fileInfo.IsDir()
}
func isDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
}
return fileInfo.IsDir()
}
func writeFile(name string, bytes []byte, source string, extension string) {
var writer io.Writer
if name == "!" {
return
} else if name == "-" {
writer = os.Stdout
} else if name == "=" {
writer = os.Stderr
} else if isDirectory(name) {
base := filepath.Base(source)
// remove the original source extension
base = base[0 : len(base)-len(filepath.Ext(base))]
// build the path that puts the result in the passed-in directory
filename := name + "/" + base + "." + extension
file, _ := os.Create(filename)
defer file.Close()
writer = file
} else {
file, _ := os.Create(name)
defer file.Close()
writer = file
}
writer.Write(bytes)
if name == "-" || name == "=" {
writer.Write([]byte("\n"))
}
}
func main() {
usage := `
Usage: gnostic OPENAPI_SOURCE [OPTIONS]
OPENAPI_SOURCE is the filename or URL of an OpenAPI description to read.
Options:
--pb_out=PATH Write a binary proto to the specified location.
--json_out=PATH Write a json proto to the specified location.
--text_out=PATH Write a text proto to the specified location.
--errors_out=PATH Write compilation errors to the specified location.
--PLUGIN_out=PATH Run the plugin named gnostic_PLUGIN and write results
to the specified location.
--resolve_refs Explicitly resolve $ref references.
This could have problems with recursive definitions.
--extension=NAME Run the specified gnostic extension to process
extensions found in OpenAPI descriptions.
`
// default values for all options
sourceName := ""
binaryProtoPath := ""
jsonProtoPath := ""
textProtoPath := ""
errorPath := ""
pluginCalls := make([]*PluginCall, 0)
resolveReferences := false
extensionHandlers := make([]compiler.ExtensionHandler, 0)
// arg processing matches patterns of the form "--PLUGIN_out=PATH"
plugin_regex := regexp.MustCompile("--(.+)_out=(.+)")
// arg processing matches patterns of the form "--extension=GENERATOR_NAME"
extensionHandler_regex, err := regexp.Compile("--extension=(.+)")
defaultPrefixForExtensions := "openapi_extensions_"
for i, arg := range os.Args {
if i == 0 {
continue // skip the tool name
}
var m [][]byte
if m = plugin_regex.FindSubmatch([]byte(arg)); m != nil {
pluginName := string(m[1])
invocation := string(m[2])
switch pluginName {
case "pb":
binaryProtoPath = invocation
case "json":
jsonProtoPath = invocation
case "text":
textProtoPath = invocation
case "errors":
errorPath = invocation
default:
pluginCall := &PluginCall{Name: pluginName, Invocation: invocation}
pluginCalls = append(pluginCalls, pluginCall)
}
} else if m = extensionHandler_regex.FindSubmatch([]byte(arg)); m != nil {
extensionHandlers = append(extensionHandlers, compiler.ExtensionHandler{Name: defaultPrefixForExtensions + string(m[1])})
} else if arg == "--resolve_refs" {
resolveReferences = true
} else if arg[0] == '-' {
fmt.Fprintf(os.Stderr, "Unknown option: %s.\n%s\n", arg, usage)
os.Exit(-1)
} else {
sourceName = arg
}
}
if binaryProtoPath == "" &&
jsonProtoPath == "" &&
textProtoPath == "" &&
errorPath == "" &&
len(pluginCalls) == 0 {
fmt.Fprintf(os.Stderr, "Missing output directives.\n%s\n", usage)
os.Exit(-1)
}
if sourceName == "" {
fmt.Fprintf(os.Stderr, "No input specified.\n%s\n", usage)
os.Exit(-1)
}
errorPrefix := "Errors reading " + sourceName + "\n"
// If we get here and the error output is unspecified, write errors to stderr.
if errorPath == "" {
errorPath = "="
}
// Read the OpenAPI source.
info, err := compiler.ReadInfoForFile(sourceName)
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
os.Exit(-1)
}
// Determine the OpenAPI version.
openapi_version := openapi_version(info)
if openapi_version == OpenAPIvUnknown {
fmt.Fprintf(os.Stderr, "Unknown OpenAPI Version\n")
os.Exit(-1)
}
var message proto.Message
if openapi_version == OpenAPIv2 {
document, err := openapi_v2.NewDocument(info, compiler.NewContextWithExtensions("$root", nil, &extensionHandlers))
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
os.Exit(-1)
}
// optionally resolve internal references
if resolveReferences {
_, err = document.ResolveReferences(sourceName)
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
os.Exit(-1)
}
}
message = document
} else if openapi_version == OpenAPIv3 {
document, err := openapi_v3.NewDocument(info, compiler.NewContextWithExtensions("$root", nil, &extensionHandlers))
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
os.Exit(-1)
}
// optionally resolve internal references
if resolveReferences {
_, err = document.ResolveReferences(sourceName)
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
os.Exit(-1)
}
}
message = document
}
// perform all specified actions
if binaryProtoPath != "" {
// write proto in binary format
protoBytes, _ := proto.Marshal(message)
writeFile(binaryProtoPath, protoBytes, sourceName, "pb")
}
if jsonProtoPath != "" {
// write proto in json format
jsonBytes, _ := json.Marshal(message)
writeFile(jsonProtoPath, jsonBytes, sourceName, "json")
}
if textProtoPath != "" {
// write proto in text format
bytes := []byte(proto.MarshalTextString(message))
writeFile(textProtoPath, bytes, sourceName, "text")
}
for _, pluginCall := range pluginCalls {
err = pluginCall.perform(message, openapi_version, sourceName)
if err != nil {
writeFile(errorPath, []byte(errorPrefix+err.Error()), sourceName, "errors")
defer os.Exit(-1)
}
}
}

252
vendor/github.com/googleapis/gnostic/gnostic_test.go generated vendored Normal file
View file

@ -0,0 +1,252 @@
package main
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func test_compiler(t *testing.T, input_file string, reference_file string, expect_errors bool) {
text_file := strings.Replace(filepath.Base(input_file), filepath.Ext(input_file), ".text", 1)
errors_file := strings.Replace(filepath.Base(input_file), filepath.Ext(input_file), ".errors", 1)
// remove any preexisting output files
os.Remove(text_file)
os.Remove(errors_file)
// run the compiler
var err error
var cmd = exec.Command(
"gnostic",
input_file,
"--text_out=.",
"--errors_out=.",
"--resolve_refs")
t.Log(cmd.Args)
err = cmd.Run()
if err != nil && !expect_errors {
t.Logf("Compile failed: %+v", err)
t.FailNow()
}
// verify the output against a reference
var output_file string
if expect_errors {
output_file = errors_file
} else {
output_file = text_file
}
err = exec.Command("diff", output_file, reference_file).Run()
if err != nil {
t.Logf("Diff failed: %+v", err)
t.FailNow()
} else {
// if the test succeeded, clean up
os.Remove(text_file)
os.Remove(errors_file)
}
}
func test_normal(t *testing.T, input_file string, reference_file string) {
test_compiler(t, input_file, reference_file, false)
}
func test_errors(t *testing.T, input_file string, reference_file string) {
test_compiler(t, input_file, reference_file, true)
}
func TestPetstoreJSON(t *testing.T) {
test_normal(t,
"examples/v2.0/json/petstore.json",
"test/v2.0/petstore.text")
}
func TestPetstoreYAML(t *testing.T) {
test_normal(t,
"examples/v2.0/yaml/petstore.yaml",
"test/v2.0/petstore.text")
}
func TestSeparateYAML(t *testing.T) {
test_normal(t,
"examples/v2.0/yaml/petstore-separate/spec/swagger.yaml",
"test/v2.0/yaml/petstore-separate/spec/swagger.text")
}
func TestSeparateJSON(t *testing.T) {
test_normal(t,
"examples/v2.0/json/petstore-separate/spec/swagger.json",
"test/v2.0/yaml/petstore-separate/spec/swagger.text") // yaml and json results should be identical
}
func TestRemotePetstoreJSON(t *testing.T) {
test_normal(t,
"https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/json/petstore.json",
"test/v2.0/petstore.text")
}
func TestRemotePetstoreYAML(t *testing.T) {
test_normal(t,
"https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/yaml/petstore.yaml",
"test/v2.0/petstore.text")
}
func TestRemoteSeparateYAML(t *testing.T) {
test_normal(t,
"https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/yaml/petstore-separate/spec/swagger.yaml",
"test/v2.0/yaml/petstore-separate/spec/swagger.text")
}
func TestRemoteSeparateJSON(t *testing.T) {
test_normal(t,
"https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/json/petstore-separate/spec/swagger.json",
"test/v2.0/yaml/petstore-separate/spec/swagger.text")
}
func TestErrorBadProperties(t *testing.T) {
test_errors(t,
"examples/errors/petstore-badproperties.yaml",
"test/errors/petstore-badproperties.errors")
}
func TestErrorUnresolvedRefs(t *testing.T) {
test_errors(t,
"examples/errors/petstore-unresolvedrefs.yaml",
"test/errors/petstore-unresolvedrefs.errors")
}
func test_plugin(t *testing.T, plugin string, input_file string, output_file string, reference_file string) {
// remove any preexisting output files
os.Remove(output_file)
// run the compiler
var err error
output, err := exec.Command(
"gnostic",
"--"+plugin+"_out=-",
input_file).Output()
if err != nil {
t.Logf("Compile failed: %+v", err)
t.FailNow()
}
_ = ioutil.WriteFile(output_file, output, 0644)
err = exec.Command("diff", output_file, reference_file).Run()
if err != nil {
t.Logf("Diff failed: %+v", err)
t.FailNow()
} else {
// if the test succeeded, clean up
os.Remove(output_file)
}
}
func TestSamplePluginWithPetstore(t *testing.T) {
test_plugin(t,
"go_sample",
"examples/v2.0/yaml/petstore.yaml",
"sample-petstore.out",
"test/v2.0/yaml/sample-petstore.out")
}
func TestErrorInvalidPluginInvocations(t *testing.T) {
var err error
output, err := exec.Command(
"gnostic",
"examples/v2.0/yaml/petstore.yaml",
"--errors_out=-",
"--plugin_out=foo=bar,:abc",
"--plugin_out=,foo=bar:abc",
"--plugin_out=foo=:abc",
"--plugin_out==bar:abc",
"--plugin_out=,,:abc",
"--plugin_out=foo=bar=baz:abc",
).Output()
if err == nil {
t.Logf("Invalid invocations were accepted")
t.FailNow()
}
output_file := "invalid-plugin-invocation.errors"
_ = ioutil.WriteFile(output_file, output, 0644)
err = exec.Command("diff", output_file, "test/errors/invalid-plugin-invocation.errors").Run()
if err != nil {
t.Logf("Diff failed: %+v", err)
t.FailNow()
} else {
// if the test succeeded, clean up
os.Remove(output_file)
}
}
func TestValidPluginInvocations(t *testing.T) {
var err error
output, err := exec.Command(
"gnostic",
"examples/v2.0/yaml/petstore.yaml",
"--errors_out=-",
// verify an invocation with no parameters
"--go_sample_out=!", // "!" indicates that no output should be generated
// verify single pair of parameters
"--go_sample_out=a=b:!",
// verify multiple parameters
"--go_sample_out=a=b,c=123,xyz=alphabetagammadelta:!",
// verify that special characters / . - _ can be included in parameter keys and values
"--go_sample_out=a/b/c=x/y/z:!",
"--go_sample_out=a.b.c=x.y.z:!",
"--go_sample_out=a-b-c=x-y-z:!",
"--go_sample_out=a_b_c=x_y_z:!",
).Output()
if len(output) != 0 {
t.Logf("Valid invocations generated invalid errors\n%s", string(output))
t.FailNow()
}
if err != nil {
t.Logf("Valid invocations were not accepted")
t.FailNow()
}
}
func TestExtensionHandlerWithLibraryExample(t *testing.T) {
output_file := "library-example-with-ext.text.out"
input_file := "test/library-example-with-ext.json"
reference_file := "test/library-example-with-ext.text.out"
os.Remove(output_file)
// run the compiler
var err error
command := exec.Command(
"gnostic",
"--extension=samplecompanyone",
"--extension=samplecompanytwo",
"--text_out="+output_file,
"--resolve_refs",
input_file)
_, err = command.Output()
if err != nil {
t.Logf("Compile failed for command %v: %+v", command, err)
t.FailNow()
}
//_ = ioutil.WriteFile(output_file, output, 0644)
err = exec.Command("diff", output_file, reference_file).Run()
if err != nil {
t.Logf("Diff failed: %+v", err)
t.FailNow()
} else {
// if the test succeeded, clean up
os.Remove(output_file)
}
}
// OpenAPI 3.0 tests
func TestPetstoreYAML_30(t *testing.T) {
test_normal(t,
"examples/v3.0/yaml/petstore.yaml",
"test/v3.0/petstore.text")
}
func TestPetstoreJSON_30(t *testing.T) {
test_normal(t,
"examples/v3.0/json/petstore.json",
"test/v3.0/petstore.text")
}

View file

@ -0,0 +1,3 @@
# jsonschema
This directory contains code for reading, writing, and manipulating JSON schemas.

View file

@ -0,0 +1,228 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package jsonschema
import (
"fmt"
"strings"
)
//
// DISPLAY
// The following methods display Schemas.
//
func (s *StringOrStringArray) Description() string {
if s.String != nil {
return *s.String
}
if s.StringArray != nil {
return strings.Join(*s.StringArray, ", ")
}
return ""
}
// Returns a string representation of a Schema.
func (schema *Schema) String() string {
return schema.describeSchema("")
}
// Helper: Returns a string representation of a Schema indented by a specified string.
func (schema *Schema) describeSchema(indent string) string {
result := ""
if schema.Schema != nil {
result += indent + "$schema: " + *(schema.Schema) + "\n"
}
if schema.Id != nil {
result += indent + "id: " + *(schema.Id) + "\n"
}
if schema.MultipleOf != nil {
result += indent + fmt.Sprintf("multipleOf: %+v\n", *(schema.MultipleOf))
}
if schema.Maximum != nil {
result += indent + fmt.Sprintf("maximum: %+v\n", *(schema.Maximum))
}
if schema.ExclusiveMaximum != nil {
result += indent + fmt.Sprintf("exclusiveMaximum: %+v\n", *(schema.ExclusiveMaximum))
}
if schema.Minimum != nil {
result += indent + fmt.Sprintf("minimum: %+v\n", *(schema.Minimum))
}
if schema.ExclusiveMinimum != nil {
result += indent + fmt.Sprintf("exclusiveMinimum: %+v\n", *(schema.ExclusiveMinimum))
}
if schema.MaxLength != nil {
result += indent + fmt.Sprintf("maxLength: %+v\n", *(schema.MaxLength))
}
if schema.MinLength != nil {
result += indent + fmt.Sprintf("minLength: %+v\n", *(schema.MinLength))
}
if schema.Pattern != nil {
result += indent + fmt.Sprintf("pattern: %+v\n", *(schema.Pattern))
}
if schema.AdditionalItems != nil {
s := schema.AdditionalItems.Schema
if s != nil {
result += indent + "additionalItems:\n"
result += s.describeSchema(indent + " ")
} else {
b := *(schema.AdditionalItems.Boolean)
result += indent + fmt.Sprintf("additionalItems: %+v\n", b)
}
}
if schema.Items != nil {
result += indent + "items:\n"
items := schema.Items
if items.SchemaArray != nil {
for i, s := range *(items.SchemaArray) {
result += indent + " " + fmt.Sprintf("%d", i) + ":\n"
result += s.describeSchema(indent + " " + " ")
}
} else if items.Schema != nil {
result += items.Schema.describeSchema(indent + " " + " ")
}
}
if schema.MaxItems != nil {
result += indent + fmt.Sprintf("maxItems: %+v\n", *(schema.MaxItems))
}
if schema.MinItems != nil {
result += indent + fmt.Sprintf("minItems: %+v\n", *(schema.MinItems))
}
if schema.UniqueItems != nil {
result += indent + fmt.Sprintf("uniqueItems: %+v\n", *(schema.UniqueItems))
}
if schema.MaxProperties != nil {
result += indent + fmt.Sprintf("maxProperties: %+v\n", *(schema.MaxProperties))
}
if schema.MinProperties != nil {
result += indent + fmt.Sprintf("minProperties: %+v\n", *(schema.MinProperties))
}
if schema.Required != nil {
result += indent + fmt.Sprintf("required: %+v\n", *(schema.Required))
}
if schema.AdditionalProperties != nil {
s := schema.AdditionalProperties.Schema
if s != nil {
result += indent + "additionalProperties:\n"
result += s.describeSchema(indent + " ")
} else {
b := *(schema.AdditionalProperties.Boolean)
result += indent + fmt.Sprintf("additionalProperties: %+v\n", b)
}
}
if schema.Properties != nil {
result += indent + "properties:\n"
for _, pair := range *(schema.Properties) {
name := pair.Name
s := pair.Value
result += indent + " " + name + ":\n"
result += s.describeSchema(indent + " " + " ")
}
}
if schema.PatternProperties != nil {
result += indent + "patternProperties:\n"
for _, pair := range *(schema.PatternProperties) {
name := pair.Name
s := pair.Value
result += indent + " " + name + ":\n"
result += s.describeSchema(indent + " " + " ")
}
}
if schema.Dependencies != nil {
result += indent + "dependencies:\n"
for _, pair := range *(schema.Dependencies) {
name := pair.Name
schemaOrStringArray := pair.Value
s := schemaOrStringArray.Schema
if s != nil {
result += indent + " " + name + ":\n"
result += s.describeSchema(indent + " " + " ")
} else {
a := schemaOrStringArray.StringArray
if a != nil {
result += indent + " " + name + ":\n"
for _, s2 := range *a {
result += indent + " " + " " + s2 + "\n"
}
}
}
}
}
if schema.Enumeration != nil {
result += indent + "enumeration:\n"
for _, value := range *(schema.Enumeration) {
if value.String != nil {
result += indent + " " + fmt.Sprintf("%+v\n", *value.String)
} else {
result += indent + " " + fmt.Sprintf("%+v\n", *value.Bool)
}
}
}
if schema.Type != nil {
result += indent + fmt.Sprintf("type: %+v\n", schema.Type.Description())
}
if schema.AllOf != nil {
result += indent + "allOf:\n"
for _, s := range *(schema.AllOf) {
result += s.describeSchema(indent + " ")
result += indent + "-\n"
}
}
if schema.AnyOf != nil {
result += indent + "anyOf:\n"
for _, s := range *(schema.AnyOf) {
result += s.describeSchema(indent + " ")
result += indent + "-\n"
}
}
if schema.OneOf != nil {
result += indent + "oneOf:\n"
for _, s := range *(schema.OneOf) {
result += s.describeSchema(indent + " ")
result += indent + "-\n"
}
}
if schema.Not != nil {
result += indent + "not:\n"
result += schema.Not.describeSchema(indent + " ")
}
if schema.Definitions != nil {
result += indent + "definitions:\n"
for _, pair := range *(schema.Definitions) {
name := pair.Name
s := pair.Value
result += indent + " " + name + ":\n"
result += s.describeSchema(indent + " " + " ")
}
}
if schema.Title != nil {
result += indent + "title: " + *(schema.Title) + "\n"
}
if schema.Description != nil {
result += indent + "description: " + *(schema.Description) + "\n"
}
if schema.Default != nil {
result += indent + "default:\n"
result += indent + fmt.Sprintf(" %+v\n", *(schema.Default))
}
if schema.Format != nil {
result += indent + "format: " + *(schema.Format) + "\n"
}
if schema.Ref != nil {
result += indent + "$ref: " + *(schema.Ref) + "\n"
}
return result
}

View file

@ -0,0 +1,212 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// Package jsonschema supports the reading, writing, and manipulation
// of JSON Schemas.
package jsonschema
// The Schema struct models a JSON Schema and, because schemas are
// defined hierarchically, contains many references to itself.
// All fields are pointers and are nil if the associated values
// are not specified.
type Schema struct {
Schema *string // $schema
Id *string // id keyword used for $ref resolution scope
Ref *string // $ref, i.e. JSON Pointers
// http://json-schema.org/latest/json-schema-validation.html
// 5.1. Validation keywords for numeric instances (number and integer)
MultipleOf *SchemaNumber
Maximum *SchemaNumber
ExclusiveMaximum *bool
Minimum *SchemaNumber
ExclusiveMinimum *bool
// 5.2. Validation keywords for strings
MaxLength *int64
MinLength *int64
Pattern *string
// 5.3. Validation keywords for arrays
AdditionalItems *SchemaOrBoolean
Items *SchemaOrSchemaArray
MaxItems *int64
MinItems *int64
UniqueItems *bool
// 5.4. Validation keywords for objects
MaxProperties *int64
MinProperties *int64
Required *[]string
AdditionalProperties *SchemaOrBoolean
Properties *[]*NamedSchema
PatternProperties *[]*NamedSchema
Dependencies *[]*NamedSchemaOrStringArray
// 5.5. Validation keywords for any instance type
Enumeration *[]SchemaEnumValue
Type *StringOrStringArray
AllOf *[]*Schema
AnyOf *[]*Schema
OneOf *[]*Schema
Not *Schema
Definitions *[]*NamedSchema
// 6. Metadata keywords
Title *string
Description *string
Default *interface{}
// 7. Semantic validation with "format"
Format *string
}
// These helper structs represent "combination" types that generally can
// have values of one type or another. All are used to represent parts
// of Schemas.
// SchemaNumber represents a value that can be either an Integer or a Float.
type SchemaNumber struct {
Integer *int64
Float *float64
}
func NewSchemaNumberWithInteger(i int64) *SchemaNumber {
result := &SchemaNumber{}
result.Integer = &i
return result
}
func NewSchemaNumberWithFloat(f float64) *SchemaNumber {
result := &SchemaNumber{}
result.Float = &f
return result
}
// SchemaOrBoolean represents a value that can be either a Schema or a Boolean.
type SchemaOrBoolean struct {
Schema *Schema
Boolean *bool
}
func NewSchemaOrBooleanWithSchema(s *Schema) *SchemaOrBoolean {
result := &SchemaOrBoolean{}
result.Schema = s
return result
}
func NewSchemaOrBooleanWithBoolean(b bool) *SchemaOrBoolean {
result := &SchemaOrBoolean{}
result.Boolean = &b
return result
}
// StringOrStringArray represents a value that can be either
// a String or an Array of Strings.
type StringOrStringArray struct {
String *string
StringArray *[]string
}
func NewStringOrStringArrayWithString(s string) *StringOrStringArray {
result := &StringOrStringArray{}
result.String = &s
return result
}
func NewStringOrStringArrayWithStringArray(a []string) *StringOrStringArray {
result := &StringOrStringArray{}
result.StringArray = &a
return result
}
// SchemaOrStringArray represents a value that can be either
// a Schema or an Array of Strings.
type SchemaOrStringArray struct {
Schema *Schema
StringArray *[]string
}
// SchemaOrSchemaArray represents a value that can be either
// a Schema or an Array of Schemas.
type SchemaOrSchemaArray struct {
Schema *Schema
SchemaArray *[]*Schema
}
func NewSchemaOrSchemaArrayWithSchema(s *Schema) *SchemaOrSchemaArray {
result := &SchemaOrSchemaArray{}
result.Schema = s
return result
}
func NewSchemaOrSchemaArrayWithSchemaArray(a []*Schema) *SchemaOrSchemaArray {
result := &SchemaOrSchemaArray{}
result.SchemaArray = &a
return result
}
// SchemaEnumValue represents a value that can be part of an
// enumeration in a Schema.
type SchemaEnumValue struct {
String *string
Bool *bool
}
// NamedSchema is a name-value pair that is used to emulate maps
// with ordered keys.
type NamedSchema struct {
Name string
Value *Schema
}
func NewNamedSchema(name string, value *Schema) *NamedSchema {
return &NamedSchema{Name: name, Value: value}
}
// NamedSchemaOrSringArray is a name-value pair that is used
// to emulate maps with ordered keys.
type NamedSchemaOrStringArray struct {
Name string
Value *SchemaOrStringArray
}
// Access named subschemas by name
func namedSchemaArrayElementWithName(array *[]*NamedSchema, name string) *Schema {
if array == nil {
return nil
}
for _, pair := range *array {
if pair.Name == name {
return pair.Value
}
}
return nil
}
func (s *Schema) PropertyWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.Properties, name)
}
func (s *Schema) PatternPropertyWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.PatternProperties, name)
}
func (s *Schema) DefinitionWithName(name string) *Schema {
return namedSchemaArrayElementWithName(s.Definitions, name)
}
func (s *Schema) AddProperty(name string, property *Schema) {
*s.Properties = append(*s.Properties, NewNamedSchema(name, property))
}

View file

@ -0,0 +1,394 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package jsonschema
import (
"errors"
"fmt"
"log"
"strings"
)
//
// OPERATIONS
// The following methods perform operations on Schemas.
//
// Returns true if no members of the Schema are specified.
func (schema *Schema) IsEmpty() bool {
return (schema.Schema == nil) &&
(schema.Id == nil) &&
(schema.MultipleOf == nil) &&
(schema.Maximum == nil) &&
(schema.ExclusiveMaximum == nil) &&
(schema.Minimum == nil) &&
(schema.ExclusiveMinimum == nil) &&
(schema.MaxLength == nil) &&
(schema.MinLength == nil) &&
(schema.Pattern == nil) &&
(schema.AdditionalItems == nil) &&
(schema.Items == nil) &&
(schema.MaxItems == nil) &&
(schema.MinItems == nil) &&
(schema.UniqueItems == nil) &&
(schema.MaxProperties == nil) &&
(schema.MinProperties == nil) &&
(schema.Required == nil) &&
(schema.AdditionalProperties == nil) &&
(schema.Properties == nil) &&
(schema.PatternProperties == nil) &&
(schema.Dependencies == nil) &&
(schema.Enumeration == nil) &&
(schema.Type == nil) &&
(schema.AllOf == nil) &&
(schema.AnyOf == nil) &&
(schema.OneOf == nil) &&
(schema.Not == nil) &&
(schema.Definitions == nil) &&
(schema.Title == nil) &&
(schema.Description == nil) &&
(schema.Default == nil) &&
(schema.Format == nil) &&
(schema.Ref == nil)
}
func (schema *Schema) IsEqual(schema2 *Schema) bool {
return schema.String() == schema2.String()
}
// A type that represents a function that can be applied to a Schema.
type SchemaOperation func(schema *Schema, context string)
// Applies a specified function to a Schema and all of the Schemas that it contains.
func (schema *Schema) applyToSchemas(operation SchemaOperation, context string) {
if schema.AdditionalItems != nil {
s := schema.AdditionalItems.Schema
if s != nil {
s.applyToSchemas(operation, "AdditionalItems")
}
}
if schema.Items != nil {
if schema.Items.SchemaArray != nil {
for _, s := range *(schema.Items.SchemaArray) {
s.applyToSchemas(operation, "Items.SchemaArray")
}
} else if schema.Items.Schema != nil {
schema.Items.Schema.applyToSchemas(operation, "Items.Schema")
}
}
if schema.AdditionalProperties != nil {
s := schema.AdditionalProperties.Schema
if s != nil {
s.applyToSchemas(operation, "AdditionalProperties")
}
}
if schema.Properties != nil {
for _, pair := range *(schema.Properties) {
s := pair.Value
s.applyToSchemas(operation, "Properties")
}
}
if schema.PatternProperties != nil {
for _, pair := range *(schema.PatternProperties) {
s := pair.Value
s.applyToSchemas(operation, "PatternProperties")
}
}
if schema.Dependencies != nil {
for _, pair := range *(schema.Dependencies) {
schemaOrStringArray := pair.Value
s := schemaOrStringArray.Schema
if s != nil {
s.applyToSchemas(operation, "Dependencies")
}
}
}
if schema.AllOf != nil {
for _, s := range *(schema.AllOf) {
s.applyToSchemas(operation, "AllOf")
}
}
if schema.AnyOf != nil {
for _, s := range *(schema.AnyOf) {
s.applyToSchemas(operation, "AnyOf")
}
}
if schema.OneOf != nil {
for _, s := range *(schema.OneOf) {
s.applyToSchemas(operation, "OneOf")
}
}
if schema.Not != nil {
schema.Not.applyToSchemas(operation, "Not")
}
if schema.Definitions != nil {
for _, pair := range *(schema.Definitions) {
s := pair.Value
s.applyToSchemas(operation, "Definitions")
}
}
operation(schema, context)
}
// Copies all non-nil properties from the source Schema to the destination Schema.
func (destination *Schema) CopyProperties(source *Schema) {
if source.Schema != nil {
destination.Schema = source.Schema
}
if source.Id != nil {
destination.Id = source.Id
}
if source.MultipleOf != nil {
destination.MultipleOf = source.MultipleOf
}
if source.Maximum != nil {
destination.Maximum = source.Maximum
}
if source.ExclusiveMaximum != nil {
destination.ExclusiveMaximum = source.ExclusiveMaximum
}
if source.Minimum != nil {
destination.Minimum = source.Minimum
}
if source.ExclusiveMinimum != nil {
destination.ExclusiveMinimum = source.ExclusiveMinimum
}
if source.MaxLength != nil {
destination.MaxLength = source.MaxLength
}
if source.MinLength != nil {
destination.MinLength = source.MinLength
}
if source.Pattern != nil {
destination.Pattern = source.Pattern
}
if source.AdditionalItems != nil {
destination.AdditionalItems = source.AdditionalItems
}
if source.Items != nil {
destination.Items = source.Items
}
if source.MaxItems != nil {
destination.MaxItems = source.MaxItems
}
if source.MinItems != nil {
destination.MinItems = source.MinItems
}
if source.UniqueItems != nil {
destination.UniqueItems = source.UniqueItems
}
if source.MaxProperties != nil {
destination.MaxProperties = source.MaxProperties
}
if source.MinProperties != nil {
destination.MinProperties = source.MinProperties
}
if source.Required != nil {
destination.Required = source.Required
}
if source.AdditionalProperties != nil {
destination.AdditionalProperties = source.AdditionalProperties
}
if source.Properties != nil {
destination.Properties = source.Properties
}
if source.PatternProperties != nil {
destination.PatternProperties = source.PatternProperties
}
if source.Dependencies != nil {
destination.Dependencies = source.Dependencies
}
if source.Enumeration != nil {
destination.Enumeration = source.Enumeration
}
if source.Type != nil {
destination.Type = source.Type
}
if source.AllOf != nil {
destination.AllOf = source.AllOf
}
if source.AnyOf != nil {
destination.AnyOf = source.AnyOf
}
if source.OneOf != nil {
destination.OneOf = source.OneOf
}
if source.Not != nil {
destination.Not = source.Not
}
if source.Definitions != nil {
destination.Definitions = source.Definitions
}
if source.Title != nil {
destination.Title = source.Title
}
if source.Description != nil {
destination.Description = source.Description
}
if source.Default != nil {
destination.Default = source.Default
}
if source.Format != nil {
destination.Format = source.Format
}
if source.Ref != nil {
destination.Ref = source.Ref
}
}
// Returns true if the Type of a Schema includes the specified type
func (schema *Schema) TypeIs(typeName string) bool {
if schema.Type != nil {
// the schema Type is either a string or an array of strings
if schema.Type.String != nil {
return (*(schema.Type.String) == typeName)
} else if schema.Type.StringArray != nil {
for _, n := range *(schema.Type.StringArray) {
if n == typeName {
return true
}
}
}
}
return false
}
// Resolves "$ref" elements in a Schema and its children.
// But if a reference refers to an object type, is inside a oneOf, or contains a oneOf,
// the reference is kept and we expect downstream tools to separately model these
// referenced schemas.
func (schema *Schema) ResolveRefs() {
rootSchema := schema
count := 1
for count > 0 {
count = 0
schema.applyToSchemas(
func(schema *Schema, context string) {
if schema.Ref != nil {
resolvedRef, err := rootSchema.resolveJSONPointer(*(schema.Ref))
if err != nil {
log.Printf("%+v", err)
} else if resolvedRef.TypeIs("object") {
// don't substitute for objects, we'll model the referenced schema with a class
} else if context == "OneOf" {
// don't substitute for references inside oneOf declarations
} else if resolvedRef.OneOf != nil {
// don't substitute for references that contain oneOf declarations
} else {
schema.Ref = nil
schema.CopyProperties(resolvedRef)
count += 1
}
}
}, "")
}
}
// Resolves JSON pointers.
// This current implementation is very crude and custom for OpenAPI 2.0 schemas.
// It panics for any pointer that it is unable to resolve.
func (root *Schema) resolveJSONPointer(ref string) (schema *Schema, err error) {
var result *Schema
parts := strings.Split(ref, "#")
if len(parts) == 2 {
documentName := parts[0] + "#"
if documentName == "#" && root.Id != nil {
documentName = *(root.Id)
}
path := parts[1]
document := schemas[documentName]
pathParts := strings.Split(path, "/")
// we currently do a very limited (hard-coded) resolution of certain paths and log errors for missed cases
if len(pathParts) == 1 {
return document, nil
} else if len(pathParts) == 3 {
switch pathParts[1] {
case "definitions":
dictionary := document.Definitions
for _, pair := range *dictionary {
if pair.Name == pathParts[2] {
result = pair.Value
}
}
case "properties":
dictionary := document.Properties
for _, pair := range *dictionary {
if pair.Name == pathParts[2] {
result = pair.Value
}
}
default:
break
}
}
}
if result == nil {
return nil, errors.New(fmt.Sprintf("UNRESOLVED POINTER: %+v", ref))
}
return result, nil
}
// Replaces "allOf" elements by merging their properties into the parent Schema.
func (schema *Schema) ResolveAllOfs() {
schema.applyToSchemas(
func(schema *Schema, context string) {
if schema.AllOf != nil {
for _, allOf := range *(schema.AllOf) {
schema.CopyProperties(allOf)
}
schema.AllOf = nil
}
}, "resolveAllOfs")
}
// Replaces all "anyOf" elements with "oneOf".
func (schema *Schema) ResolveAnyOfs() {
schema.applyToSchemas(
func(schema *Schema, context string) {
if schema.AnyOf != nil {
schema.OneOf = schema.AnyOf
schema.AnyOf = nil
}
}, "resolveAnyOfs")
}
// return a pointer to a copy of a passed-in string
func stringptr(input string) (output *string) {
return &input
}
// Copy a named property from the official JSON Schema definition
func (schema *Schema) CopyOfficialSchemaProperty(name string) {
*schema.Properties = append(*schema.Properties,
NewNamedSchema(name,
&Schema{Ref: stringptr("http://json-schema.org/draft-04/schema#/properties/" + name)}))
}
// Copy named properties from the official JSON Schema definition
func (schema *Schema) CopyOfficialSchemaProperties(names []string) {
for _, name := range names {
schema.CopyOfficialSchemaProperty(name)
}
}

View file

@ -0,0 +1,409 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package jsonschema
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// This is a global map of all known Schemas.
// It is initialized when the first Schema is created and inserted.
var schemas map[string]*Schema
// Reads a schema from a file.
// Currently this assumes that schemas are stored in the source distribution of this project.
func NewSchemaFromFile(filename string) (schema *Schema, err error) {
file, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var info yaml.MapSlice
err = yaml.Unmarshal(file, &info)
if err != nil {
return nil, err
}
return NewSchemaFromObject(info), nil
}
// Constructs a schema from a parsed JSON object.
// Due to the complexity of the schema representation, this is a
// custom reader and not the standard Go JSON reader (encoding/json).
func NewSchemaFromObject(jsonData interface{}) *Schema {
switch t := jsonData.(type) {
default:
fmt.Printf("schemaValue: unexpected type %T\n", t)
return nil
case yaml.MapSlice:
schema := &Schema{}
for _, mapItem := range t {
k := mapItem.Key.(string)
v := mapItem.Value
switch k {
case "$schema":
schema.Schema = schema.stringValue(v)
case "id":
schema.Id = schema.stringValue(v)
case "multipleOf":
schema.MultipleOf = schema.numberValue(v)
case "maximum":
schema.Maximum = schema.numberValue(v)
case "exclusiveMaximum":
schema.ExclusiveMaximum = schema.boolValue(v)
case "minimum":
schema.Minimum = schema.numberValue(v)
case "exclusiveMinimum":
schema.ExclusiveMinimum = schema.boolValue(v)
case "maxLength":
schema.MaxLength = schema.intValue(v)
case "minLength":
schema.MinLength = schema.intValue(v)
case "pattern":
schema.Pattern = schema.stringValue(v)
case "additionalItems":
schema.AdditionalItems = schema.schemaOrBooleanValue(v)
case "items":
schema.Items = schema.schemaOrSchemaArrayValue(v)
case "maxItems":
schema.MaxItems = schema.intValue(v)
case "minItems":
schema.MinItems = schema.intValue(v)
case "uniqueItems":
schema.UniqueItems = schema.boolValue(v)
case "maxProperties":
schema.MaxProperties = schema.intValue(v)
case "minProperties":
schema.MinProperties = schema.intValue(v)
case "required":
schema.Required = schema.arrayOfStringsValue(v)
case "additionalProperties":
schema.AdditionalProperties = schema.schemaOrBooleanValue(v)
case "properties":
schema.Properties = schema.mapOfSchemasValue(v)
case "patternProperties":
schema.PatternProperties = schema.mapOfSchemasValue(v)
case "dependencies":
schema.Dependencies = schema.mapOfSchemasOrStringArraysValue(v)
case "enum":
schema.Enumeration = schema.arrayOfEnumValuesValue(v)
case "type":
schema.Type = schema.stringOrStringArrayValue(v)
case "allOf":
schema.AllOf = schema.arrayOfSchemasValue(v)
case "anyOf":
schema.AnyOf = schema.arrayOfSchemasValue(v)
case "oneOf":
schema.OneOf = schema.arrayOfSchemasValue(v)
case "not":
schema.Not = NewSchemaFromObject(v)
case "definitions":
schema.Definitions = schema.mapOfSchemasValue(v)
case "title":
schema.Title = schema.stringValue(v)
case "description":
schema.Description = schema.stringValue(v)
case "default":
schema.Default = &v
case "format":
schema.Format = schema.stringValue(v)
case "$ref":
schema.Ref = schema.stringValue(v)
default:
fmt.Printf("UNSUPPORTED (%s)\n", k)
}
}
// insert schema in global map
if schema.Id != nil {
if schemas == nil {
schemas = make(map[string]*Schema, 0)
}
schemas[*(schema.Id)] = schema
}
return schema
}
return nil
}
//
// BUILDERS
// The following methods build elements of Schemas from interface{} values.
// Each returns nil if it is unable to build the desired element.
//
// Gets the string value of an interface{} value if possible.
func (schema *Schema) stringValue(v interface{}) *string {
switch v := v.(type) {
default:
fmt.Printf("stringValue: unexpected type %T\n", v)
case string:
return &v
}
return nil
}
// Gets the numeric value of an interface{} value if possible.
func (schema *Schema) numberValue(v interface{}) *SchemaNumber {
number := &SchemaNumber{}
switch v := v.(type) {
default:
fmt.Printf("numberValue: unexpected type %T\n", v)
case float64:
v2 := float64(v)
number.Float = &v2
return number
case float32:
v2 := float64(v)
number.Float = &v2
return number
case int:
v2 := int64(v)
number.Integer = &v2
}
return nil
}
// Gets the integer value of an interface{} value if possible.
func (schema *Schema) intValue(v interface{}) *int64 {
switch v := v.(type) {
default:
fmt.Printf("intValue: unexpected type %T\n", v)
case float64:
v2 := int64(v)
return &v2
case int64:
return &v
case int:
v2 := int64(v)
return &v2
}
return nil
}
// Gets the bool value of an interface{} value if possible.
func (schema *Schema) boolValue(v interface{}) *bool {
switch v := v.(type) {
default:
fmt.Printf("boolValue: unexpected type %T\n", v)
case bool:
return &v
}
return nil
}
// Gets a map of Schemas from an interface{} value if possible.
func (schema *Schema) mapOfSchemasValue(v interface{}) *[]*NamedSchema {
switch v := v.(type) {
default:
fmt.Printf("mapOfSchemasValue: unexpected type %T\n", v)
case yaml.MapSlice:
m := make([]*NamedSchema, 0)
for _, mapItem := range v {
k2 := mapItem.Key.(string)
v2 := mapItem.Value
pair := &NamedSchema{Name: k2, Value: NewSchemaFromObject(v2)}
m = append(m, pair)
}
return &m
}
return nil
}
// Gets an array of Schemas from an interface{} value if possible.
func (schema *Schema) arrayOfSchemasValue(v interface{}) *[]*Schema {
switch v := v.(type) {
default:
fmt.Printf("arrayOfSchemasValue: unexpected type %T\n", v)
case []interface{}:
m := make([]*Schema, 0)
for _, v2 := range v {
switch v2 := v2.(type) {
default:
fmt.Printf("arrayOfSchemasValue: unexpected type %T\n", v2)
case yaml.MapSlice:
s := NewSchemaFromObject(v2)
m = append(m, s)
}
}
return &m
case yaml.MapSlice:
m := make([]*Schema, 0)
s := NewSchemaFromObject(v)
m = append(m, s)
return &m
}
return nil
}
// Gets a Schema or an array of Schemas from an interface{} value if possible.
func (schema *Schema) schemaOrSchemaArrayValue(v interface{}) *SchemaOrSchemaArray {
switch v := v.(type) {
default:
fmt.Printf("schemaOrSchemaArrayValue: unexpected type %T\n", v)
case []interface{}:
m := make([]*Schema, 0)
for _, v2 := range v {
switch v2 := v2.(type) {
default:
fmt.Printf("schemaOrSchemaArrayValue: unexpected type %T\n", v2)
case map[string]interface{}:
s := NewSchemaFromObject(v2)
m = append(m, s)
}
}
return &SchemaOrSchemaArray{SchemaArray: &m}
case yaml.MapSlice:
s := NewSchemaFromObject(v)
return &SchemaOrSchemaArray{Schema: s}
}
return nil
}
// Gets an array of strings from an interface{} value if possible.
func (schema *Schema) arrayOfStringsValue(v interface{}) *[]string {
switch v := v.(type) {
default:
fmt.Printf("arrayOfStringsValue: unexpected type %T\n", v)
case []string:
return &v
case string:
a := []string{v}
return &a
case []interface{}:
a := make([]string, 0)
for _, v2 := range v {
switch v2 := v2.(type) {
default:
fmt.Printf("arrayOfStringsValue: unexpected type %T\n", v2)
case string:
a = append(a, v2)
}
}
return &a
}
return nil
}
// Gets a string or an array of strings from an interface{} value if possible.
func (schema *Schema) stringOrStringArrayValue(v interface{}) *StringOrStringArray {
switch v := v.(type) {
default:
fmt.Printf("arrayOfStringsValue: unexpected type %T\n", v)
case []string:
s := &StringOrStringArray{}
s.StringArray = &v
return s
case string:
s := &StringOrStringArray{}
s.String = &v
return s
case []interface{}:
a := make([]string, 0)
for _, v2 := range v {
switch v2 := v2.(type) {
default:
fmt.Printf("arrayOfStringsValue: unexpected type %T\n", v2)
case string:
a = append(a, v2)
}
}
s := &StringOrStringArray{}
s.StringArray = &a
return s
}
return nil
}
// Gets an array of enum values from an interface{} value if possible.
func (schema *Schema) arrayOfEnumValuesValue(v interface{}) *[]SchemaEnumValue {
a := make([]SchemaEnumValue, 0)
switch v := v.(type) {
default:
fmt.Printf("arrayOfEnumValuesValue: unexpected type %T\n", v)
case []interface{}:
for _, v2 := range v {
switch v2 := v2.(type) {
default:
fmt.Printf("arrayOfEnumValuesValue: unexpected type %T\n", v2)
case string:
a = append(a, SchemaEnumValue{String: &v2})
case bool:
a = append(a, SchemaEnumValue{Bool: &v2})
}
}
}
return &a
}
// Gets a map of schemas or string arrays from an interface{} value if possible.
func (schema *Schema) mapOfSchemasOrStringArraysValue(v interface{}) *[]*NamedSchemaOrStringArray {
m := make([]*NamedSchemaOrStringArray, 0)
switch v := v.(type) {
default:
fmt.Printf("mapOfSchemasOrStringArraysValue: unexpected type %T %+v\n", v, v)
case yaml.MapSlice:
for _, mapItem := range v {
k2 := mapItem.Key.(string)
v2 := mapItem.Value
switch v2 := v2.(type) {
default:
fmt.Printf("mapOfSchemasOrStringArraysValue: unexpected type %T %+v\n", v2, v2)
case []interface{}:
a := make([]string, 0)
for _, v3 := range v2 {
switch v3 := v3.(type) {
default:
fmt.Printf("mapOfSchemasOrStringArraysValue: unexpected type %T %+v\n", v3, v3)
case string:
a = append(a, v3)
}
}
s := &SchemaOrStringArray{}
s.StringArray = &a
pair := &NamedSchemaOrStringArray{Name: k2, Value: s}
m = append(m, pair)
}
}
}
return &m
}
// Gets a schema or a boolean value from an interface{} value if possible.
func (schema *Schema) schemaOrBooleanValue(v interface{}) *SchemaOrBoolean {
schemaOrBoolean := &SchemaOrBoolean{}
switch v := v.(type) {
case bool:
schemaOrBoolean.Boolean = &v
case yaml.MapSlice:
schemaOrBoolean.Schema = NewSchemaFromObject(v)
default:
fmt.Printf("schemaOrBooleanValue: unexpected type %T\n", v)
case []map[string]interface{}:
}
return schemaOrBoolean
}

View file

@ -0,0 +1,150 @@
{
"id": "http://json-schema.org/draft-04/schema#",
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Core schema meta-schema",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"positiveInteger": {
"type": "integer",
"minimum": 0
},
"positiveIntegerDefault0": {
"allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
},
"simpleTypes": {
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
}
},
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"$schema": {
"type": "string",
"format": "uri"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": {},
"multipleOf": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"maximum": {
"type": "number"
},
"exclusiveMaximum": {
"type": "boolean",
"default": false
},
"minimum": {
"type": "number"
},
"exclusiveMinimum": {
"type": "boolean",
"default": false
},
"maxLength": { "$ref": "#/definitions/positiveInteger" },
"minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
"pattern": {
"type": "string",
"format": "regex"
},
"additionalItems": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" }
],
"default": {}
},
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": {}
},
"maxItems": { "$ref": "#/definitions/positiveInteger" },
"minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
"uniqueItems": {
"type": "boolean",
"default": false
},
"maxProperties": { "$ref": "#/definitions/positiveInteger" },
"minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
"required": { "$ref": "#/definitions/stringArray" },
"additionalProperties": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" }
],
"default": {}
},
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"enum": {
"type": "array",
"minItems": 1,
"uniqueItems": true
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" }
},
"dependencies": {
"exclusiveMaximum": [ "maximum" ],
"exclusiveMinimum": [ "minimum" ]
},
"default": {}
}

View file

@ -0,0 +1,333 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package jsonschema
import (
"fmt"
"gopkg.in/yaml.v2"
)
const INDENT = " "
func renderMap(info interface{}, indent string) (result string) {
result = "{\n"
inner_indent := indent + INDENT
switch pairs := info.(type) {
case yaml.MapSlice:
for i, pair := range pairs {
// first print the key
result += fmt.Sprintf("%s\"%+v\": ", inner_indent, pair.Key)
// then the value
switch value := pair.Value.(type) {
case string:
result += "\"" + value + "\""
case bool:
if value {
result += "true"
} else {
result += "false"
}
case []interface{}:
result += renderArray(value, inner_indent)
case yaml.MapSlice:
result += renderMap(value, inner_indent)
case int:
result += fmt.Sprintf("%d", value)
case int64:
result += fmt.Sprintf("%d", value)
case []string:
result += renderStringArray(value, inner_indent)
default:
result += fmt.Sprintf("???MapItem(%+v, %T)", value, value)
}
if i < len(pairs)-1 {
result += ","
}
result += "\n"
}
default:
// t is some other type that we didn't name.
}
result += indent + "}"
return result
}
func renderArray(array []interface{}, indent string) (result string) {
result = "[\n"
inner_indent := indent + INDENT
for i, item := range array {
switch item := item.(type) {
case string:
result += inner_indent + "\"" + item + "\""
case bool:
if item {
result += inner_indent + "true"
} else {
result += inner_indent + "false"
}
case yaml.MapSlice:
result += inner_indent + renderMap(item, inner_indent) + ""
default:
result += inner_indent + fmt.Sprintf("???ArrayItem(%+v)", item)
}
if i < len(array)-1 {
result += ","
}
result += "\n"
}
result += indent + "]"
return result
}
func renderStringArray(array []string, indent string) (result string) {
result = "[\n"
inner_indent := indent + INDENT
for i, item := range array {
result += inner_indent + "\"" + item + "\""
if i < len(array)-1 {
result += ","
}
result += "\n"
}
result += indent + "]"
return result
}
func Render(info yaml.MapSlice) string {
return renderMap(info, "") + "\n"
}
func (object *SchemaNumber) jsonValue() interface{} {
if object.Integer != nil {
return object.Integer
} else if object.Float != nil {
return object.Float
} else {
return nil
}
}
func (object *SchemaOrBoolean) jsonValue() interface{} {
if object.Schema != nil {
return object.Schema.jsonValue()
} else if object.Boolean != nil {
return *object.Boolean
} else {
return nil
}
}
func (object *StringOrStringArray) jsonValue() interface{} {
if object.String != nil {
return *object.String
} else if object.StringArray != nil {
array := make([]interface{}, 0)
for _, item := range *(object.StringArray) {
array = append(array, item)
}
return array
} else {
return nil
}
}
func (object *SchemaOrStringArray) jsonValue() interface{} {
if object.Schema != nil {
return object.Schema.jsonValue()
} else if object.StringArray != nil {
array := make([]interface{}, 0)
for _, item := range *(object.StringArray) {
array = append(array, item)
}
return array
} else {
return nil
}
}
func (object *SchemaOrSchemaArray) jsonValue() interface{} {
if object.Schema != nil {
return object.Schema.jsonValue()
} else if object.SchemaArray != nil {
array := make([]interface{}, 0)
for _, item := range *(object.SchemaArray) {
array = append(array, item.jsonValue())
}
return array
} else {
return nil
}
}
func (object *SchemaEnumValue) jsonValue() interface{} {
if object.String != nil {
return *object.String
} else if object.Bool != nil {
return *object.Bool
} else {
return nil
}
}
func namedSchemaArrayValue(array *[]*NamedSchema) interface{} {
m2 := yaml.MapSlice{}
for _, pair := range *(array) {
var item2 yaml.MapItem
item2.Key = pair.Name
item2.Value = pair.Value.jsonValue()
m2 = append(m2, item2)
}
return m2
}
func namedSchemaOrStringArrayValue(array *[]*NamedSchemaOrStringArray) interface{} {
m2 := yaml.MapSlice{}
for _, pair := range *(array) {
var item2 yaml.MapItem
item2.Key = pair.Name
item2.Value = pair.Value.jsonValue()
m2 = append(m2, item2)
}
return m2
}
func schemaEnumArrayValue(array *[]SchemaEnumValue) []interface{} {
a := make([]interface{}, 0)
for _, item := range *array {
a = append(a, item.jsonValue())
}
return a
}
func schemaArrayValue(array *[]*Schema) []interface{} {
a := make([]interface{}, 0)
for _, item := range *array {
a = append(a, item.jsonValue())
}
return a
}
func (schema *Schema) jsonValue() yaml.MapSlice {
m := yaml.MapSlice{}
if schema.Title != nil {
m = append(m, yaml.MapItem{"title", *schema.Title})
}
if schema.Id != nil {
m = append(m, yaml.MapItem{"id", *schema.Id})
}
if schema.Schema != nil {
m = append(m, yaml.MapItem{"$schema", *schema.Schema})
}
if schema.Type != nil {
m = append(m, yaml.MapItem{"type", schema.Type.jsonValue()})
}
if schema.Items != nil {
m = append(m, yaml.MapItem{"items", schema.Items.jsonValue()})
}
if schema.Description != nil {
m = append(m, yaml.MapItem{"description", *schema.Description})
}
if schema.Required != nil {
m = append(m, yaml.MapItem{"required", *schema.Required})
}
if schema.AdditionalProperties != nil {
m = append(m, yaml.MapItem{"additionalProperties", schema.AdditionalProperties.jsonValue()})
}
if schema.PatternProperties != nil {
m = append(m, yaml.MapItem{"patternProperties", namedSchemaArrayValue(schema.PatternProperties)})
}
if schema.Properties != nil {
m = append(m, yaml.MapItem{"properties", namedSchemaArrayValue(schema.Properties)})
}
if schema.Dependencies != nil {
m = append(m, yaml.MapItem{"dependencies", namedSchemaOrStringArrayValue(schema.Dependencies)})
}
if schema.Ref != nil {
m = append(m, yaml.MapItem{"$ref", *schema.Ref})
}
if schema.MultipleOf != nil {
m = append(m, yaml.MapItem{"multipleOf", schema.MultipleOf.jsonValue()})
}
if schema.Maximum != nil {
m = append(m, yaml.MapItem{"maximum", schema.Maximum.jsonValue()})
}
if schema.ExclusiveMaximum != nil {
m = append(m, yaml.MapItem{"exclusiveMaximum", *schema.ExclusiveMaximum})
}
if schema.Minimum != nil {
m = append(m, yaml.MapItem{"minimum", schema.Minimum.jsonValue()})
}
if schema.ExclusiveMinimum != nil {
m = append(m, yaml.MapItem{"exclusiveMinimum", *schema.ExclusiveMinimum})
}
if schema.MaxLength != nil {
m = append(m, yaml.MapItem{"maxLength", *schema.MaxLength})
}
if schema.MinLength != nil {
m = append(m, yaml.MapItem{"minLength", *schema.MinLength})
}
if schema.Pattern != nil {
m = append(m, yaml.MapItem{"pattern", *schema.Pattern})
}
if schema.AdditionalItems != nil {
m = append(m, yaml.MapItem{"additionalItems", schema.AdditionalItems.jsonValue()})
}
if schema.MaxItems != nil {
m = append(m, yaml.MapItem{"maxItems", *schema.MaxItems})
}
if schema.MinItems != nil {
m = append(m, yaml.MapItem{"minItems", *schema.MinItems})
}
if schema.UniqueItems != nil {
m = append(m, yaml.MapItem{"uniqueItems", *schema.UniqueItems})
}
if schema.MaxProperties != nil {
m = append(m, yaml.MapItem{"maxProperties", *schema.MaxProperties})
}
if schema.MinProperties != nil {
m = append(m, yaml.MapItem{"minProperties", *schema.MinProperties})
}
if schema.Enumeration != nil {
m = append(m, yaml.MapItem{"enum", schemaEnumArrayValue(schema.Enumeration)})
}
if schema.AllOf != nil {
m = append(m, yaml.MapItem{"allOf", schemaArrayValue(schema.AllOf)})
}
if schema.AnyOf != nil {
m = append(m, yaml.MapItem{"anyOf", schemaArrayValue(schema.AnyOf)})
}
if schema.OneOf != nil {
m = append(m, yaml.MapItem{"oneOf", schemaArrayValue(schema.OneOf)})
}
if schema.Not != nil {
m = append(m, yaml.MapItem{"not", schema.Not.jsonValue()})
}
if schema.Definitions != nil {
m = append(m, yaml.MapItem{"definitions", namedSchemaArrayValue(schema.Definitions)})
}
if schema.Default != nil {
m = append(m, yaml.MapItem{"default", *schema.Default})
}
if schema.Format != nil {
m = append(m, yaml.MapItem{"format", *schema.Format})
}
return m
}
func (schema *Schema) JSONString() string {
info := schema.jsonValue()
return Render(info)
}

View file

@ -0,0 +1,7 @@
# Plugins
This directory contains support code for building Gnostic plugins and associated examples.
Plugins are used to process API descriptions and can perform tasks like documentation and
code generation. Plugins can be written in any language that is supported by the Protocol
Buffer tools.

View file

@ -0,0 +1,23 @@
# gnostic_analyze
This directory contains a `gnostic` plugin that analyzes an OpenAPI description for factors
that might influence code generation and other API automation.
The plugin can be invoked like this:
gnostic bookstore.json --analyze_out=.
This will write analysis results to a file in the current directory.
Results are written to a file named `summary.json`.
The plugin can be applied to a directory of descriptions using a command
like the following:
find APIs -name "swagger.yaml" -exec gnostic --analyze_out=analysis {} \;
This finds all `swagger.yaml` files in a directory named `APIs` and its subdirectories
and writes corresponding `summary.json` files into a directory named `analysis`.
Results of multiple analysis runs can be gathered together and summarized
using the `summarize` program, which is in the `summarize` subdirectory.
Just run `summarize` in the same location as the `find` command shown above.

View file

@ -0,0 +1,100 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// gnostic_analyze is a tool for analyzing OpenAPI descriptions.
//
// It scans an API description and evaluates properties
// that influence the ease and quality of code generation.
// - The number of HTTP operations of each method (GET, POST, etc).
// - The number of HTTP operations with no OperationId value.
// - The parameter types used and their frequencies.
// - The response types used and their frequencies.
// - The types used in definition objects and arrays and their frequencies.
// Results are returned in a JSON structure.
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/plugins/go/gnostic_analyze/statistics"
openapi "github.com/googleapis/gnostic/OpenAPIv2"
plugins "github.com/googleapis/gnostic/plugins"
)
// Record an error, then serialize and return a response.
func sendAndExitIfError(err error, response *plugins.Response) {
if err != nil {
response.Errors = append(response.Errors, err.Error())
sendAndExit(response)
}
}
// Serialize and return a response.
func sendAndExit(response *plugins.Response) {
responseBytes, _ := proto.Marshal(response)
os.Stdout.Write(responseBytes)
os.Exit(0)
}
func main() {
// Initialize the response.
response := &plugins.Response{}
// Read the request.
data, err := ioutil.ReadAll(os.Stdin)
sendAndExitIfError(err, response)
// Unmarshal the request.
request := &plugins.Request{}
err = proto.Unmarshal(data, request)
sendAndExitIfError(err, response)
// Verify that the passed-in description is supported.
wrapper := request.Wrapper
if wrapper.Version != "v2" {
err = errors.New(
fmt.Sprintf("%s requires an OpenAPI v2 description.",
os.Args[0]))
sendAndExitIfError(err, response)
}
// Unmarshal the description.
document := &openapi.Document{}
err = proto.Unmarshal(wrapper.Value, document)
sendAndExitIfError(err, response)
// Analyze the API document.
stats := statistics.NewDocumentStatistics(wrapper.Name, document)
// Return the analysis results with an appropriate filename.
// Results are in files named "summary.json" in the same relative
// locations as the description source files.
file := &plugins.File{}
file.Name = strings.Replace(stats.Name, path.Base(stats.Name), "summary.json", -1)
file.Data, err = json.MarshalIndent(stats, "", " ")
file.Data = append(file.Data, []byte("\n")...)
sendAndExitIfError(err, response)
response.Files = append(response.Files, file)
// Send the final results. Success!
sendAndExit(response)
}

View file

@ -0,0 +1,328 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
package statistics
import (
"fmt"
"strings"
openapi "github.com/googleapis/gnostic/OpenAPIv2"
)
// DocumentStatistics contains information collected about an API description.
type DocumentStatistics struct {
Name string `json:"name"`
Title string `json:"title"`
Operations map[string]int `json:"operations"`
DefinitionCount int `json:"definitions"`
ParameterTypes map[string]int `json:"parameterTypes"`
ResultTypes map[string]int `json:"resultTypes"`
DefinitionFieldTypes map[string]int `json:"definitionFieldTypes"`
DefinitionArrayTypes map[string]int `json:"definitionArrayTypes"`
DefinitionPrimitiveTypes map[string]int `json:"definitionPrimitiveTypes"`
AnonymousOperations []string `json:"anonymousOperations"`
AnonymousObjects []string `json:"anonymousObjects"`
}
func NewDocumentStatistics(source string, document *openapi.Document) *DocumentStatistics {
s := &DocumentStatistics{}
s.Operations = make(map[string]int, 0)
s.ParameterTypes = make(map[string]int, 0)
s.ResultTypes = make(map[string]int, 0)
s.DefinitionFieldTypes = make(map[string]int, 0)
s.DefinitionArrayTypes = make(map[string]int, 0)
s.DefinitionPrimitiveTypes = make(map[string]int, 0)
s.AnonymousOperations = make([]string, 0)
s.AnonymousObjects = make([]string, 0)
s.analyzeDocument(source, document)
return s
}
func (s *DocumentStatistics) addOperation(name string) {
s.Operations[name] = s.Operations[name] + 1
}
func (s *DocumentStatistics) addParameterType(path string, name string) {
if strings.Contains(name, "object") {
s.AnonymousObjects = append(s.AnonymousObjects, path)
}
s.ParameterTypes[name] = s.ParameterTypes[name] + 1
}
func (s *DocumentStatistics) addResultType(path string, name string) {
if strings.Contains(name, "object") {
s.AnonymousObjects = append(s.AnonymousObjects, path)
}
s.ResultTypes[name] = s.ResultTypes[name] + 1
}
func (s *DocumentStatistics) addDefinitionFieldType(path string, name string) {
if strings.Contains(name, "object") {
s.AnonymousObjects = append(s.AnonymousObjects, path)
}
s.DefinitionFieldTypes[name] = s.DefinitionFieldTypes[name] + 1
}
func (s *DocumentStatistics) addDefinitionArrayType(path string, name string) {
if strings.Contains(name, "object") {
s.AnonymousObjects = append(s.AnonymousObjects, path)
}
s.DefinitionArrayTypes[name] = s.DefinitionArrayTypes[name] + 1
}
func (s *DocumentStatistics) addDefinitionPrimitiveType(path string, name string) {
s.DefinitionPrimitiveTypes[name] = s.DefinitionPrimitiveTypes[name] + 1
}
func typeForPrimitivesItems(p *openapi.PrimitivesItems) string {
if p.Type != "" {
return p.Type
} else if p.Items != nil && p.Items.Type != "" {
return p.Items.Type
} else {
return "object"
}
}
func (s *DocumentStatistics) analyzeOperation(method string, path string, operation *openapi.Operation) {
s.addOperation(method)
s.addOperation("total")
if operation.OperationId == "" {
s.addOperation("anonymous")
s.AnonymousOperations = append(s.AnonymousOperations, path)
}
for _, parameter := range operation.Parameters {
p := parameter.GetParameter()
if p != nil {
b := p.GetBodyParameter()
if b != nil {
typeName := typeForSchema(b.Schema)
s.addParameterType(path+"/"+b.Name, typeName)
}
n := p.GetNonBodyParameter()
if n != nil {
hp := n.GetHeaderParameterSubSchema()
if hp != nil {
t := hp.Type
if t == "array" {
t += "-of-" + typeForPrimitivesItems(hp.Items)
}
s.addParameterType(path+"/"+hp.Name, t)
}
fp := n.GetFormDataParameterSubSchema()
if fp != nil {
t := fp.Type
if t == "array" {
t += "-of-" + typeForPrimitivesItems(fp.Items)
}
s.addParameterType(path+"/"+fp.Name, t)
}
qp := n.GetQueryParameterSubSchema()
if qp != nil {
t := qp.Type
if t == "array" {
if t == "array" {
t += "-of-" + typeForPrimitivesItems(qp.Items)
}
}
s.addParameterType(path+"/"+qp.Name, t)
}
pp := n.GetPathParameterSubSchema()
if pp != nil {
t := pp.Type
if t == "array" {
if t == "array" {
t += "-of-" + typeForPrimitivesItems(pp.Items)
}
}
s.addParameterType(path+"/"+pp.Name, t)
}
}
}
r := parameter.GetJsonReference()
if r != nil {
s.addParameterType(path+"/", "reference")
}
}
for _, pair := range operation.Responses.ResponseCode {
value := pair.Value
response := value.GetResponse()
if response != nil {
responseSchema := response.Schema
responseSchemaSchema := responseSchema.GetSchema()
if responseSchemaSchema != nil {
s.addResultType(path+"/responses/"+pair.Name, typeForSchema(responseSchemaSchema))
}
responseFileSchema := responseSchema.GetFileSchema()
if responseFileSchema != nil {
s.addResultType(path+"/responses/"+pair.Name, typeForFileSchema(responseFileSchema))
}
}
ref := value.GetJsonReference()
if ref != nil {
}
}
}
// Analyze a definition in an OpenAPI description.
// Collect information about the definition type and any subsidiary types,
// such as the types of object fields or array elements.
func (s *DocumentStatistics) analyzeDefinition(path string, definition *openapi.Schema) {
s.DefinitionCount++
typeName := typeNameForSchema(definition)
switch typeName {
case "object":
if definition.Properties != nil {
for _, pair := range definition.Properties.AdditionalProperties {
propertySchema := pair.Value
propertyType := typeForSchema(propertySchema)
s.addDefinitionFieldType(path+"/"+pair.Name, propertyType)
}
}
case "array":
s.addDefinitionArrayType(path+"/", typeForSchema(definition))
default: // string, boolean, integer, number, null...
s.addDefinitionPrimitiveType(path+"/", typeName)
}
}
// Analyze an OpenAPI description.
// Collect information about types used in the API.
// This should be called exactly once per DocumentStatistics object.
func (s *DocumentStatistics) analyzeDocument(source string, document *openapi.Document) {
s.Name = source
s.Title = document.Info.Title
for _, pair := range document.Paths.Path {
path := pair.Value
if path.Get != nil {
s.analyzeOperation("get", "paths"+pair.Name+"/get", path.Get)
}
if path.Post != nil {
s.analyzeOperation("post", "paths"+pair.Name+"/post", path.Post)
}
if path.Put != nil {
s.analyzeOperation("put", "paths"+pair.Name+"/put", path.Put)
}
if path.Delete != nil {
s.analyzeOperation("delete", "paths"+pair.Name+"/delete", path.Delete)
}
}
if document.Definitions != nil {
for _, pair := range document.Definitions.AdditionalProperties {
definition := pair.Value
s.analyzeDefinition("definitions/"+pair.Name, definition)
}
}
}
// helpers
func typeNameForSchema(schema *openapi.Schema) string {
typeName := "object" // default type
if schema.Type != nil && len(schema.Type.Value) > 0 {
typeName = ""
for i, name := range schema.Type.Value {
if i > 0 {
typeName += "|"
}
typeName += name
}
}
return typeName
}
// Return a type name to use for a schema.
func typeForSchema(schema *openapi.Schema) string {
if schema.XRef != "" {
return "reference"
}
if len(schema.Enum) > 0 {
enumType := typeNameForSchema(schema)
return "enum-of-" + enumType
}
typeName := typeNameForSchema(schema)
if typeName == "array" {
if schema.Items != nil {
// items contains an array of schemas
itemType := ""
for i, itemSchema := range schema.Items.Schema {
if i > 0 {
itemType += "|"
}
itemType += typeForSchema(itemSchema)
}
return "array-of-" + itemType
} else if schema.XRef != "" {
return "array-of-reference"
} else {
// we need to do more work to understand this type
return fmt.Sprintf("array-of-[%+v]", schema)
}
} else if typeName == "object" {
// this object might be representable with a map
// but not if it has properties
if (schema.Properties != nil) && (len(schema.Properties.AdditionalProperties) > 0) {
return typeName
}
if schema.AdditionalProperties != nil {
if schema.AdditionalProperties.GetSchema() != nil {
additionalPropertiesSchemaType := typeForSchema(schema.AdditionalProperties.GetSchema())
return "map-of-" + additionalPropertiesSchemaType
}
if schema.AdditionalProperties.GetBoolean() == false {
// no additional properties are allowed, so we're not sure what to do if we get here...
return typeName
}
}
if schema.Items != nil {
itemType := ""
for i, itemSchema := range schema.Items.Schema {
if i > 0 {
itemType += "|"
}
itemType += typeForSchema(itemSchema)
}
return "map-of-" + itemType
}
return "map-of-object"
} else {
return typeName
}
}
func typeForFileSchema(schema *openapi.FileSchema) string {
if schema.Type != "" {
value := schema.Type
switch value {
case "boolean":
return "fileschema-" + value
case "string":
return "fileschema-" + value
case "file":
return "fileschema-" + value
case "number":
return "fileschema-" + value
case "integer":
return "fileschema-" + value
case "object":
return "fileschema-" + value
case "null":
return "fileschema-" + value
}
}
return fmt.Sprintf("FILE SCHEMA %+v", schema)
}

View file

@ -0,0 +1,156 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// summarize is a tool for summarizing the results of gnostic_analyze runs.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"github.com/googleapis/gnostic/plugins/go/gnostic_analyze/statistics"
)
// Results are collected in this global slice.
var stats []statistics.DocumentStatistics
// walker is called for each summary file found.
func walker(p string, info os.FileInfo, err error) error {
basename := path.Base(p)
if basename != "summary.json" {
return nil
}
data, err := ioutil.ReadFile(p)
if err != nil {
return err
}
var s statistics.DocumentStatistics
err = json.Unmarshal(data, &s)
if err != nil {
return err
}
stats = append(stats, s)
return nil
}
func printFrequencies(m map[string]int) {
for _, pair := range rankByCount(m) {
fmt.Printf("%6d %s\n", pair.Value, pair.Key)
}
}
func rankByCount(frequencies map[string]int) PairList {
pl := make(PairList, len(frequencies))
i := 0
for k, v := range frequencies {
pl[i] = Pair{k, v}
i++
}
sort.Sort(sort.Reverse(pl))
return pl
}
type Pair struct {
Key string
Value int
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func main() {
// Collect all statistics in the current directory and its subdirectories.
stats = make([]statistics.DocumentStatistics, 0)
filepath.Walk(".", walker)
// Compute some interesting properties.
apis_with_anonymous_operations := 0
apis_with_anonymous_objects := 0
apis_with_anonymous_anything := 0
op_frequencies := make(map[string]int, 0)
parameter_type_frequencies := make(map[string]int, 0)
result_type_frequencies := make(map[string]int, 0)
definition_field_type_frequencies := make(map[string]int, 0)
definition_array_type_frequencies := make(map[string]int, 0)
definition_primitive_type_frequencies := make(map[string]int, 0)
for _, api := range stats {
if api.Operations["anonymous"] != 0 {
apis_with_anonymous_operations += 1
}
if len(api.AnonymousObjects) > 0 {
apis_with_anonymous_objects += 1
}
if len(api.AnonymousOperations) > 0 {
apis_with_anonymous_anything += 1
if len(api.AnonymousObjects) > 0 {
fmt.Printf("%s has anonymous operations and objects\n", api.Name)
} else {
fmt.Printf("%s has anonymous operations\n", api.Name)
}
} else {
if len(api.AnonymousObjects) > 0 {
apis_with_anonymous_anything += 1
fmt.Printf("%s has anonymous objects\n", api.Name)
} else {
fmt.Printf("%s has no anonymous operations or objects\n", api.Name)
}
}
for k, v := range api.Operations {
op_frequencies[k] += v
}
for k, v := range api.ParameterTypes {
parameter_type_frequencies[k] += v
}
for k, v := range api.ResultTypes {
result_type_frequencies[k] += v
}
for k, v := range api.DefinitionFieldTypes {
definition_field_type_frequencies[k] += v
}
for k, v := range api.DefinitionArrayTypes {
definition_array_type_frequencies[k] += v
}
for k, v := range api.DefinitionPrimitiveTypes {
definition_primitive_type_frequencies[k] += v
}
}
// Report the results.
fmt.Printf("\n")
fmt.Printf("Collected information on %d APIs.\n\n", len(stats))
fmt.Printf("APIs with anonymous operations: %d\n", apis_with_anonymous_operations)
fmt.Printf("APIs with anonymous objects: %d\n", apis_with_anonymous_objects)
fmt.Printf("APIs with anonymous anything: %d\n", apis_with_anonymous_anything)
fmt.Printf("\nOperation frequencies:\n")
printFrequencies(op_frequencies)
fmt.Printf("\nParameter type frequencies:\n")
printFrequencies(parameter_type_frequencies)
fmt.Printf("\nResult type frequencies:\n")
printFrequencies(result_type_frequencies)
fmt.Printf("\nDefinition object field type frequencies:\n")
printFrequencies(definition_field_type_frequencies)
fmt.Printf("\nDefinition array type frequencies:\n")
printFrequencies(definition_array_type_frequencies)
fmt.Printf("\nDefinition primitive type frequencies:\n")
printFrequencies(definition_primitive_type_frequencies)
}

View file

@ -0,0 +1,10 @@
build:
go install github.com/googleapis/gnostic
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_generator/encode_templates
go generate github.com/googleapis/gnostic/plugins/go/gnostic_go_generator
go install github.com/googleapis/gnostic/plugins/go/gnostic_go_generator
rm -f $(GOPATH)/bin/gnostic_go_client $(GOPATH)/bin/gnostic_go_server
ln -s $(GOPATH)/bin/gnostic_go_generator $(GOPATH)/bin/gnostic_go_client
ln -s $(GOPATH)/bin/gnostic_go_generator $(GOPATH)/bin/gnostic_go_server

Some files were not shown because too many files have changed in this diff Show more