Bumping k8s version to 1.13.0-beta.1

This commit is contained in:
Cheng Xing
2018-11-19 14:10:50 -08:00
parent 01bd7f356e
commit e2f1bdc372
633 changed files with 11189 additions and 126194 deletions

View File

@@ -1,26 +0,0 @@
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
# Set default charset
[*.{js,py,go,scala,rb,java,html,css,less,sass,md}]
charset = utf-8
# Tab indentation (no size specified)
[*.go]
indent_style = tab
[*.md]
trim_trailing_whitespace = false
# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

View File

@@ -1,117 +0,0 @@
## Contribution Guidelines
### Pull requests are always welcome
We are always thrilled to receive pull requests, and do our best to
process them as fast as possible. Not sure if that typo is worth a pull
request? Do it! We will appreciate it.
If your pull request is not accepted on the first try, don't be
discouraged! If there's a problem with the implementation, hopefully you
received feedback on what to improve.
We're trying very hard to keep go-swagger lean and focused. We don't want it
to do everything for everybody. This means that we might decide against
incorporating a new feature. However, there might be a way to implement
that feature *on top of* go-swagger.
### Conventions
Fork the repo and make changes on your fork in a feature branch:
- If it's a bugfix branch, name it XXX-something where XXX is the number of the
issue
- If it's a feature branch, create an enhancement issue to announce your
intentions, and name it XXX-something where XXX is the number of the issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test suite on
your branch before submitting a pull request.
Update the documentation when creating or modifying features. Test
your documentation changes for clarity, concision, and correctness, as
well as a clean documentation build. See ``docs/README.md`` for more
information on building the docs and how docs get released.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plugins that do this automatically.
Pull requests descriptions should be as clear as possible and include a
reference to all the issues that they address.
Pull requests must not contain commits from other users or branches.
Commit messages must start with a capitalized and short summary (max. 50
chars) written in the imperative, followed by an optional, more detailed
explanatory text which is separated from the summary by an empty line.
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Be
sure to post a comment after pushing. The new commits will show up in the pull
request automatically, but the reviewers will not be notified unless you
comment.
Before the pull request is merged, make sure that you squash your commits into
logical units of work using `git rebase -i` and `git push -f`. After every
commit the test suite should be passing. Include documentation changes in the
same commit so that a revert would remove all traces of the feature or fix.
Commits that fix or close an issue should include a reference like `Closes #XXX`
or `Fixes #XXX`, which will automatically close the issue when merged.
### Sign your work
The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below (from
[developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
then you just add a line to every git commit message:
Signed-off-by: Joe Smith <joe@gmail.com>
using your real name (sorry, no pseudonyms or anonymous contributions.)
You can add the sign off when creating the git commit via `git commit -s`.

View File

@@ -1 +0,0 @@
secrets.yml

View File

@@ -1,15 +0,0 @@
after_success:
- bash <(curl -s https://codecov.io/bash)
go:
- '1.9'
- 1.10.x
- 1.11.x
install:
- go get -u github.com/stretchr/testify/assert
- go get -u github.com/go-openapi/swag
language: go
notifications:
slack:
secure: a5VgoiwB1G/AZqzmephPZIhEB9avMlsWSlVnM1dSAtYAwdrQHGTQxAmpOxYIoSPDhWNN5bfZmjd29++UlTwLcHSR+e0kJhH6IfDlsHj/HplNCJ9tyI0zYc7XchtdKgeMxMzBKCzgwFXGSbQGydXTliDNBo0HOzmY3cou/daMFTP60K+offcjS+3LRAYb1EroSRXZqrk1nuF/xDL3792DZUdPMiFR/L/Df6y74D6/QP4sTkTDFQitz4Wy/7jbsfj8dG6qK2zivgV6/l+w4OVjFkxVpPXogDWY10vVXNVynqxfJ7to2d1I9lNCHE2ilBCkWMIPdyJF7hjF8pKW+82yP4EzRh0vu8Xn0HT5MZpQxdRY/YMxNrWaG7SxsoEaO4q5uhgdzAqLYY3TRa7MjIK+7Ur+aqOeTXn6OKwVi0CjvZ6mIU3WUKSwiwkFZMbjRAkSb5CYwMEfGFO/z964xz83qGt6WAtBXNotqCQpTIiKtDHQeLOMfksHImCg6JLhQcWBVxamVgu0G3Pdh8Y6DyPnxraXY95+QDavbjqv7TeYT9T/FNnrkXaTTK0s4iWE5H4ACU0Qvz0wUYgfQrZv0/Hp7V17+rabUwnzYySHCy9SWX/7OV9Cfh31iMp9ZIffr76xmmThtOEqs8TrTtU6BWI3rWwvA9cXQipZTVtL0oswrGw=
script:
- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...

View File

@@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ivan+abuse@flanders.co.nz. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,202 +0,0 @@
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.

View File

@@ -1,15 +0,0 @@
# gojsonpointer [![Build Status](https://travis-ci.org/go-openapi/jsonpointer.svg?branch=master)](https://travis-ci.org/go-openapi/jsonpointer) [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io)
[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonpointer?status.svg)](http://godoc.org/github.com/go-openapi/jsonpointer)
An implementation of JSON Pointer - Go language
## Status
Completed YES
Tested YES
## References
http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
### Note
The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented.

View File

@@ -1,10 +0,0 @@
module github.com/go-openapi/jsonpointer
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-openapi/swag v0.17.0
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
gopkg.in/yaml.v2 v2.2.1 // indirect
)

View File

@@ -1,11 +0,0 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/swag v0.17.0 h1:7wu+dZ5k83kvUWeAb+WUkFiUhDzwGqzTR/NhWzeo1JU=
github.com/go-openapi/swag v0.17.0/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -1,390 +0,0 @@
// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
//
// 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.
// author sigu-399
// author-github https://github.com/sigu-399
// author-mail sigu.399@gmail.com
//
// repository-name jsonpointer
// repository-desc An implementation of JSON Pointer - Go language
//
// description Main and unique file.
//
// created 25-02-2013
package jsonpointer
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/go-openapi/swag"
)
const (
emptyPointer = ``
pointerSeparator = `/`
invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator
)
var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem()
var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem()
// JSONPointable is an interface for structs to implement when they need to customize the
// json pointer process
type JSONPointable interface {
JSONLookup(string) (interface{}, error)
}
// JSONSetable is an interface for structs to implement when they need to customize the
// json pointer process
type JSONSetable interface {
JSONSet(string, interface{}) error
}
// New creates a new json pointer for the given string
func New(jsonPointerString string) (Pointer, error) {
var p Pointer
err := p.parse(jsonPointerString)
return p, err
}
// Pointer the json pointer reprsentation
type Pointer struct {
referenceTokens []string
}
// "Constructor", parses the given string JSON pointer
func (p *Pointer) parse(jsonPointerString string) error {
var err error
if jsonPointerString != emptyPointer {
if !strings.HasPrefix(jsonPointerString, pointerSeparator) {
err = errors.New(invalidStart)
} else {
referenceTokens := strings.Split(jsonPointerString, pointerSeparator)
for _, referenceToken := range referenceTokens[1:] {
p.referenceTokens = append(p.referenceTokens, referenceToken)
}
}
}
return err
}
// Get uses the pointer to retrieve a value from a JSON document
func (p *Pointer) Get(document interface{}) (interface{}, reflect.Kind, error) {
return p.get(document, swag.DefaultJSONNameProvider)
}
// Set uses the pointer to set a value from a JSON document
func (p *Pointer) Set(document interface{}, value interface{}) (interface{}, error) {
return document, p.set(document, value, swag.DefaultJSONNameProvider)
}
// GetForToken gets a value for a json pointer token 1 level deep
func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) {
return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider)
}
// SetForToken gets a value for a json pointer token 1 level deep
func SetForToken(document interface{}, decodedToken string, value interface{}) (interface{}, error) {
return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider)
}
func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) {
rValue := reflect.Indirect(reflect.ValueOf(node))
kind := rValue.Kind()
switch kind {
case reflect.Struct:
if rValue.Type().Implements(jsonPointableType) {
r, err := node.(JSONPointable).JSONLookup(decodedToken)
if err != nil {
return nil, kind, err
}
return r, kind, nil
}
nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
if !ok {
return nil, kind, fmt.Errorf("object has no field %q", decodedToken)
}
fld := rValue.FieldByName(nm)
return fld.Interface(), kind, nil
case reflect.Map:
kv := reflect.ValueOf(decodedToken)
mv := rValue.MapIndex(kv)
if mv.IsValid() && !swag.IsZero(mv) {
return mv.Interface(), kind, nil
}
return nil, kind, fmt.Errorf("object has no key %q", decodedToken)
case reflect.Slice:
tokenIndex, err := strconv.Atoi(decodedToken)
if err != nil {
return nil, kind, err
}
sLength := rValue.Len()
if tokenIndex < 0 || tokenIndex >= sLength {
return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex)
}
elem := rValue.Index(tokenIndex)
return elem.Interface(), kind, nil
default:
return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken)
}
}
func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *swag.NameProvider) error {
rValue := reflect.Indirect(reflect.ValueOf(node))
switch rValue.Kind() {
case reflect.Struct:
if ns, ok := node.(JSONSetable); ok { // pointer impl
return ns.JSONSet(decodedToken, data)
}
if rValue.Type().Implements(jsonSetableType) {
return node.(JSONSetable).JSONSet(decodedToken, data)
}
nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
if !ok {
return fmt.Errorf("object has no field %q", decodedToken)
}
fld := rValue.FieldByName(nm)
if fld.IsValid() {
fld.Set(reflect.ValueOf(data))
}
return nil
case reflect.Map:
kv := reflect.ValueOf(decodedToken)
rValue.SetMapIndex(kv, reflect.ValueOf(data))
return nil
case reflect.Slice:
tokenIndex, err := strconv.Atoi(decodedToken)
if err != nil {
return err
}
sLength := rValue.Len()
if tokenIndex < 0 || tokenIndex >= sLength {
return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex)
}
elem := rValue.Index(tokenIndex)
if !elem.CanSet() {
return fmt.Errorf("can't set slice index %s to %v", decodedToken, data)
}
elem.Set(reflect.ValueOf(data))
return nil
default:
return fmt.Errorf("invalid token reference %q", decodedToken)
}
}
func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) {
if nameProvider == nil {
nameProvider = swag.DefaultJSONNameProvider
}
kind := reflect.Invalid
// Full document when empty
if len(p.referenceTokens) == 0 {
return node, kind, nil
}
for _, token := range p.referenceTokens {
decodedToken := Unescape(token)
r, knd, err := getSingleImpl(node, decodedToken, nameProvider)
if err != nil {
return nil, knd, err
}
node, kind = r, knd
}
rValue := reflect.ValueOf(node)
kind = rValue.Kind()
return node, kind, nil
}
func (p *Pointer) set(node, data interface{}, nameProvider *swag.NameProvider) error {
knd := reflect.ValueOf(node).Kind()
if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array {
return fmt.Errorf("only structs, pointers, maps and slices are supported for setting values")
}
if nameProvider == nil {
nameProvider = swag.DefaultJSONNameProvider
}
// Full document when empty
if len(p.referenceTokens) == 0 {
return nil
}
lastI := len(p.referenceTokens) - 1
for i, token := range p.referenceTokens {
isLastToken := i == lastI
decodedToken := Unescape(token)
if isLastToken {
return setSingleImpl(node, data, decodedToken, nameProvider)
}
rValue := reflect.Indirect(reflect.ValueOf(node))
kind := rValue.Kind()
switch kind {
case reflect.Struct:
if rValue.Type().Implements(jsonPointableType) {
r, err := node.(JSONPointable).JSONLookup(decodedToken)
if err != nil {
return err
}
fld := reflect.ValueOf(r)
if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr {
node = fld.Addr().Interface()
continue
}
node = r
continue
}
nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
if !ok {
return fmt.Errorf("object has no field %q", decodedToken)
}
fld := rValue.FieldByName(nm)
if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr {
node = fld.Addr().Interface()
continue
}
node = fld.Interface()
case reflect.Map:
kv := reflect.ValueOf(decodedToken)
mv := rValue.MapIndex(kv)
if !mv.IsValid() {
return fmt.Errorf("object has no key %q", decodedToken)
}
if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr {
node = mv.Addr().Interface()
continue
}
node = mv.Interface()
case reflect.Slice:
tokenIndex, err := strconv.Atoi(decodedToken)
if err != nil {
return err
}
sLength := rValue.Len()
if tokenIndex < 0 || tokenIndex >= sLength {
return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex)
}
elem := rValue.Index(tokenIndex)
if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr {
node = elem.Addr().Interface()
continue
}
node = elem.Interface()
default:
return fmt.Errorf("invalid token reference %q", decodedToken)
}
}
return nil
}
// DecodedTokens returns the decoded tokens
func (p *Pointer) DecodedTokens() []string {
result := make([]string, 0, len(p.referenceTokens))
for _, t := range p.referenceTokens {
result = append(result, Unescape(t))
}
return result
}
// IsEmpty returns true if this is an empty json pointer
// this indicates that it points to the root document
func (p *Pointer) IsEmpty() bool {
return len(p.referenceTokens) == 0
}
// Pointer to string representation function
func (p *Pointer) String() string {
if len(p.referenceTokens) == 0 {
return emptyPointer
}
pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator)
return pointerString
}
// Specific JSON pointer encoding here
// ~0 => ~
// ~1 => /
// ... and vice versa
const (
encRefTok0 = `~0`
encRefTok1 = `~1`
decRefTok0 = `~`
decRefTok1 = `/`
)
// Unescape unescapes a json pointer reference token string to the original representation
func Unescape(token string) string {
step1 := strings.Replace(token, encRefTok1, decRefTok1, -1)
step2 := strings.Replace(step1, encRefTok0, decRefTok0, -1)
return step2
}
// Escape escapes a pointer reference token string
func Escape(token string) string {
step1 := strings.Replace(token, decRefTok0, encRefTok0, -1)
step2 := strings.Replace(step1, decRefTok1, encRefTok1, -1)
return step2
}

View File

@@ -1,573 +0,0 @@
// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
//
// 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.
// author sigu-399
// author-github https://github.com/sigu-399
// author-mail sigu.399@gmail.com
//
// repository-name jsonpointer
// repository-desc An implementation of JSON Pointer - Go language
//
// description Automated tests on package.
//
// created 03-03-2013
package jsonpointer
import (
"encoding/json"
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
const (
TestDocumentNBItems = 11
TestNodeObjNBItems = 4
TestDocumentString = `{
"foo": ["bar", "baz"],
"obj": { "a":1, "b":2, "c":[3,4], "d":[ {"e":9}, {"f":[50,51]} ] },
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}`
)
var testDocumentJSON interface{}
type testStructJSON struct {
Foo []string `json:"foo"`
Obj struct {
A int `json:"a"`
B int `json:"b"`
C []int `json:"c"`
D []struct {
E int `json:"e"`
F []int `json:"f"`
} `json:"d"`
} `json:"obj"`
}
type aliasedMap map[string]interface{}
var testStructJSONDoc testStructJSON
var testStructJSONPtr *testStructJSON
func init() {
json.Unmarshal([]byte(TestDocumentString), &testDocumentJSON)
json.Unmarshal([]byte(TestDocumentString), &testStructJSONDoc)
testStructJSONPtr = &testStructJSONDoc
}
func TestEscaping(t *testing.T) {
ins := []string{`/`, `/`, `/a~1b`, `/a~1b`, `/c%d`, `/e^f`, `/g|h`, `/i\j`, `/k"l`, `/ `, `/m~0n`}
outs := []float64{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8}
for i := range ins {
p, err := New(ins[i])
if assert.NoError(t, err, "input: %v", ins[i]) {
result, _, err := p.Get(testDocumentJSON)
if assert.NoError(t, err, "input: %v", ins[i]) {
assert.Equal(t, outs[i], result, "input: %v", ins[i])
}
}
}
}
func TestFullDocument(t *testing.T) {
in := ``
p, err := New(in)
if err != nil {
t.Errorf("New(%v) error %v", in, err.Error())
}
result, _, err := p.Get(testDocumentJSON)
if err != nil {
t.Errorf("Get(%v) error %v", in, err.Error())
}
if len(result.(map[string]interface{})) != TestDocumentNBItems {
t.Errorf("Get(%v) = %v, expect full document", in, result)
}
result, _, err = p.get(testDocumentJSON, nil)
if err != nil {
t.Errorf("Get(%v) error %v", in, err.Error())
}
if len(result.(map[string]interface{})) != TestDocumentNBItems {
t.Errorf("Get(%v) = %v, expect full document", in, result)
}
}
func TestDecodedTokens(t *testing.T) {
p, err := New("/obj/a~1b")
assert.NoError(t, err)
assert.Equal(t, []string{"obj", "a/b"}, p.DecodedTokens())
}
func TestIsEmpty(t *testing.T) {
p, err := New("")
assert.NoError(t, err)
assert.True(t, p.IsEmpty())
p, err = New("/obj")
assert.NoError(t, err)
assert.False(t, p.IsEmpty())
}
func TestGetSingle(t *testing.T) {
in := `/obj`
_, err := New(in)
assert.NoError(t, err)
result, _, err := GetForToken(testDocumentJSON, "obj")
assert.NoError(t, err)
assert.Len(t, result, TestNodeObjNBItems)
result, _, err = GetForToken(testStructJSONDoc, "Obj")
assert.Error(t, err)
assert.Nil(t, result)
result, _, err = GetForToken(testStructJSONDoc, "Obj2")
assert.Error(t, err)
assert.Nil(t, result)
}
type pointableImpl struct {
a string
}
func (p pointableImpl) JSONLookup(token string) (interface{}, error) {
if token == "some" {
return p.a, nil
}
return nil, fmt.Errorf("object has no field %q", token)
}
func TestPointableInterface(t *testing.T) {
p := &pointableImpl{"hello"}
result, _, err := GetForToken(p, "some")
assert.NoError(t, err)
assert.Equal(t, p.a, result)
result, _, err = GetForToken(p, "something")
assert.Error(t, err)
assert.Nil(t, result)
}
func TestGetNode(t *testing.T) {
in := `/obj`
p, err := New(in)
assert.NoError(t, err)
result, _, err := p.Get(testDocumentJSON)
assert.NoError(t, err)
assert.Len(t, result, TestNodeObjNBItems)
result, _, err = p.Get(aliasedMap(testDocumentJSON.(map[string]interface{})))
assert.NoError(t, err)
assert.Len(t, result, TestNodeObjNBItems)
result, _, err = p.Get(testStructJSONDoc)
assert.NoError(t, err)
assert.Equal(t, testStructJSONDoc.Obj, result)
result, _, err = p.Get(testStructJSONPtr)
assert.NoError(t, err)
assert.Equal(t, testStructJSONDoc.Obj, result)
}
func TestArray(t *testing.T) {
ins := []string{`/foo/0`, `/foo/0`, `/foo/1`}
outs := []string{"bar", "bar", "baz"}
for i := range ins {
p, err := New(ins[i])
assert.NoError(t, err)
result, _, err := p.Get(testStructJSONDoc)
assert.NoError(t, err)
assert.Equal(t, outs[i], result)
result, _, err = p.Get(testStructJSONPtr)
assert.NoError(t, err)
assert.Equal(t, outs[i], result)
result, _, err = p.Get(testDocumentJSON)
assert.NoError(t, err)
assert.Equal(t, outs[i], result)
}
}
func TestOtherThings(t *testing.T) {
_, err := New("abc")
assert.Error(t, err)
p, err := New("")
assert.NoError(t, err)
assert.Equal(t, "", p.String())
p, err = New("/obj/a")
assert.Equal(t, "/obj/a", p.String())
s := Escape("m~n")
assert.Equal(t, "m~0n", s)
s = Escape("m/n")
assert.Equal(t, "m~1n", s)
p, err = New("/foo/3")
assert.NoError(t, err)
_, _, err = p.Get(testDocumentJSON)
assert.Error(t, err)
p, err = New("/foo/a")
assert.NoError(t, err)
_, _, err = p.Get(testDocumentJSON)
assert.Error(t, err)
p, err = New("/notthere")
assert.NoError(t, err)
_, _, err = p.Get(testDocumentJSON)
assert.Error(t, err)
p, err = New("/invalid")
assert.NoError(t, err)
_, _, err = p.Get(1234)
assert.Error(t, err)
p, err = New("/foo/1")
assert.NoError(t, err)
expected := "hello"
bbb := testDocumentJSON.(map[string]interface{})["foo"]
bbb.([]interface{})[1] = "hello"
v, _, err := p.Get(testDocumentJSON)
assert.NoError(t, err)
assert.Equal(t, expected, v)
esc := Escape("a/")
assert.Equal(t, "a~1", esc)
unesc := Unescape(esc)
assert.Equal(t, "a/", unesc)
unesc = Unescape("~01")
assert.Equal(t, "~1", unesc)
assert.Equal(t, "~0~1", Escape("~/"))
assert.Equal(t, "~/", Unescape("~0~1"))
}
func TestObject(t *testing.T) {
ins := []string{`/obj/a`, `/obj/b`, `/obj/c/0`, `/obj/c/1`, `/obj/c/1`, `/obj/d/1/f/0`}
outs := []float64{1, 2, 3, 4, 4, 50}
for i := range ins {
p, err := New(ins[i])
assert.NoError(t, err)
result, _, err := p.Get(testDocumentJSON)
assert.NoError(t, err)
assert.Equal(t, outs[i], result)
result, _, err = p.Get(testStructJSONDoc)
assert.NoError(t, err)
assert.EqualValues(t, outs[i], result)
result, _, err = p.Get(testStructJSONPtr)
assert.NoError(t, err)
assert.EqualValues(t, outs[i], result)
}
}
type setJsonDocEle struct {
B int `json:"b"`
C int `json:"c"`
}
type setJsonDoc struct {
A []struct {
B int `json:"b"`
C int `json:"c"`
} `json:"a"`
D int `json:"d"`
}
type settableDoc struct {
Coll settableColl
Int settableInt
}
func (s settableDoc) MarshalJSON() ([]byte, error) {
var res struct {
A settableColl `json:"a"`
D settableInt `json:"d"`
}
res.A = s.Coll
res.D = s.Int
return json.Marshal(res)
}
func (s *settableDoc) UnmarshalJSON(data []byte) error {
var res struct {
A settableColl `json:"a"`
D settableInt `json:"d"`
}
if err := json.Unmarshal(data, &res); err != nil {
return err
}
s.Coll = res.A
s.Int = res.D
return nil
}
// JSONLookup implements an interface to customize json pointer lookup
func (s settableDoc) JSONLookup(token string) (interface{}, error) {
switch token {
case "a":
return &s.Coll, nil
case "d":
return &s.Int, nil
default:
return nil, fmt.Errorf("%s is not a known field", token)
}
}
// JSONLookup implements an interface to customize json pointer lookup
func (s *settableDoc) JSONSet(token string, data interface{}) error {
switch token {
case "a":
switch dt := data.(type) {
case settableColl:
s.Coll = dt
return nil
case *settableColl:
if dt != nil {
s.Coll = *dt
} else {
s.Coll = settableColl{}
}
return nil
case []settableCollItem:
s.Coll.Items = dt
return nil
}
case "d":
switch dt := data.(type) {
case settableInt:
s.Int = dt
return nil
case int:
s.Int.Value = dt
return nil
case int8:
s.Int.Value = int(dt)
return nil
case int16:
s.Int.Value = int(dt)
return nil
case int32:
s.Int.Value = int(dt)
return nil
case int64:
s.Int.Value = int(dt)
return nil
default:
return fmt.Errorf("invalid type %T for %s", data, token)
}
}
return fmt.Errorf("%s is not a known field", token)
}
type settableColl struct {
Items []settableCollItem
}
func (s settableColl) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Items)
}
func (s *settableColl) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &s.Items)
}
// JSONLookup implements an interface to customize json pointer lookup
func (s settableColl) JSONLookup(token string) (interface{}, error) {
if tok, err := strconv.Atoi(token); err == nil {
return &s.Items[tok], nil
}
return nil, fmt.Errorf("%s is not a valid index", token)
}
// JSONLookup implements an interface to customize json pointer lookup
func (s *settableColl) JSONSet(token string, data interface{}) error {
if _, err := strconv.Atoi(token); err == nil {
_, err := SetForToken(s.Items, token, data)
return err
}
return fmt.Errorf("%s is not a valid index", token)
}
type settableCollItem struct {
B int `json:"b"`
C int `json:"c"`
}
type settableInt struct {
Value int
}
func (s settableInt) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Value)
}
func (s *settableInt) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &s.Value)
}
func TestSetNode(t *testing.T) {
jsonText := `{"a":[{"b": 1, "c": 2}], "d": 3}`
var jsonDocument interface{}
if assert.NoError(t, json.Unmarshal([]byte(jsonText), &jsonDocument)) {
in := "/a/0/c"
p, err := New(in)
if assert.NoError(t, err) {
_, err = p.Set(jsonDocument, 999)
assert.NoError(t, err)
firstNode := jsonDocument.(map[string]interface{})
assert.Len(t, firstNode, 2)
sliceNode := firstNode["a"].([]interface{})
assert.Len(t, sliceNode, 1)
changedNode := sliceNode[0].(map[string]interface{})
chNodeVI := changedNode["c"]
if assert.IsType(t, 0, chNodeVI) {
changedNodeValue := chNodeVI.(int)
if assert.Equal(t, 999, changedNodeValue) {
assert.Len(t, sliceNode, 1)
}
}
}
v, err := New("/a/0")
if assert.NoError(t, err) {
_, err = v.Set(jsonDocument, map[string]interface{}{"b": 3, "c": 8})
if assert.NoError(t, err) {
firstNode := jsonDocument.(map[string]interface{})
assert.Len(t, firstNode, 2)
sliceNode := firstNode["a"].([]interface{})
assert.Len(t, sliceNode, 1)
changedNode := sliceNode[0].(map[string]interface{})
assert.Equal(t, 3, changedNode["b"])
assert.Equal(t, 8, changedNode["c"])
}
}
}
var structDoc setJsonDoc
if assert.NoError(t, json.Unmarshal([]byte(jsonText), &structDoc)) {
g, err := New("/a")
if assert.NoError(t, err) {
_, err = g.Set(&structDoc, []struct {
B int `json:"b"`
C int `json:"c"`
}{{B: 4, C: 7}})
if assert.NoError(t, err) {
assert.Len(t, structDoc.A, 1)
changedNode := structDoc.A[0]
assert.Equal(t, 4, changedNode.B)
assert.Equal(t, 7, changedNode.C)
}
}
v, err := New("/a/0")
if assert.NoError(t, err) {
_, err = v.Set(structDoc, struct {
B int `json:"b"`
C int `json:"c"`
}{B: 3, C: 8})
if assert.NoError(t, err) {
assert.Len(t, structDoc.A, 1)
changedNode := structDoc.A[0]
assert.Equal(t, 3, changedNode.B)
assert.Equal(t, 8, changedNode.C)
}
}
p, err := New("/a/0/c")
if assert.NoError(t, err) {
_, err = p.Set(&structDoc, 999)
assert.NoError(t, err)
if assert.Len(t, structDoc.A, 1) {
assert.Equal(t, 999, structDoc.A[0].C)
}
}
}
var setDoc settableDoc
if assert.NoError(t, json.Unmarshal([]byte(jsonText), &setDoc)) {
g, err := New("/a")
if assert.NoError(t, err) {
_, err = g.Set(&setDoc, []settableCollItem{{B: 4, C: 7}})
if assert.NoError(t, err) {
assert.Len(t, setDoc.Coll.Items, 1)
changedNode := setDoc.Coll.Items[0]
assert.Equal(t, 4, changedNode.B)
assert.Equal(t, 7, changedNode.C)
}
}
v, err := New("/a/0")
if assert.NoError(t, err) {
_, err = v.Set(setDoc, settableCollItem{B: 3, C: 8})
if assert.NoError(t, err) {
assert.Len(t, setDoc.Coll.Items, 1)
changedNode := setDoc.Coll.Items[0]
assert.Equal(t, 3, changedNode.B)
assert.Equal(t, 8, changedNode.C)
}
}
p, err := New("/a/0/c")
if assert.NoError(t, err) {
_, err = p.Set(setDoc, 999)
assert.NoError(t, err)
if assert.Len(t, setDoc.Coll.Items, 1) {
assert.Equal(t, 999, setDoc.Coll.Items[0].C)
}
}
}
}

View File

@@ -1,117 +0,0 @@
## Contribution Guidelines
### Pull requests are always welcome
We are always thrilled to receive pull requests, and do our best to
process them as fast as possible. Not sure if that typo is worth a pull
request? Do it! We will appreciate it.
If your pull request is not accepted on the first try, don't be
discouraged! If there's a problem with the implementation, hopefully you
received feedback on what to improve.
We're trying very hard to keep go-swagger lean and focused. We don't want it
to do everything for everybody. This means that we might decide against
incorporating a new feature. However, there might be a way to implement
that feature *on top of* go-swagger.
### Conventions
Fork the repo and make changes on your fork in a feature branch:
- If it's a bugfix branch, name it XXX-something where XXX is the number of the
issue
- If it's a feature branch, create an enhancement issue to announce your
intentions, and name it XXX-something where XXX is the number of the issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test suite on
your branch before submitting a pull request.
Update the documentation when creating or modifying features. Test
your documentation changes for clarity, concision, and correctness, as
well as a clean documentation build. See ``docs/README.md`` for more
information on building the docs and how docs get released.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plugins that do this automatically.
Pull requests descriptions should be as clear as possible and include a
reference to all the issues that they address.
Pull requests must not contain commits from other users or branches.
Commit messages must start with a capitalized and short summary (max. 50
chars) written in the imperative, followed by an optional, more detailed
explanatory text which is separated from the summary by an empty line.
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Be
sure to post a comment after pushing. The new commits will show up in the pull
request automatically, but the reviewers will not be notified unless you
comment.
Before the pull request is merged, make sure that you squash your commits into
logical units of work using `git rebase -i` and `git push -f`. After every
commit the test suite should be passing. Include documentation changes in the
same commit so that a revert would remove all traces of the feature or fix.
Commits that fix or close an issue should include a reference like `Closes #XXX`
or `Fixes #XXX`, which will automatically close the issue when merged.
### Sign your work
The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below (from
[developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
then you just add a line to every git commit message:
Signed-off-by: Joe Smith <joe@gmail.com>
using your real name (sorry, no pseudonyms or anonymous contributions.)
You can add the sign off when creating the git commit via `git commit -s`.

View File

@@ -1 +0,0 @@
secrets.yml

View File

@@ -1,16 +0,0 @@
after_success:
- bash <(curl -s https://codecov.io/bash)
go:
- '1.9'
- 1.10.x
- 1.11.x
install:
- go get -u github.com/stretchr/testify/assert
- go get -u github.com/PuerkitoBio/purell
- go get -u github.com/go-openapi/jsonpointer
language: go
notifications:
slack:
secure: OpQG/36F7DSF00HLm9WZMhyqFCYYyYTsVDObW226cWiR8PWYiNfLZiSEvIzT1Gx4dDjhigKTIqcLhG34CkL5iNXDjm9Yyo2RYhQPlK8NErNqUEXuBqn4RqYHW48VGhEhOyDd4Ei0E2FN5ZbgpvHgtpkdZ6XDi64r3Ac89isP9aPHXQTuv2Jog6b4/OKKiUTftLcTIst0p4Cp3gqOJWf1wnoj+IadWiECNVQT6zb47IYjtyw6+uV8iUjTzdKcRB6Zc6b4Dq7JAg1Zd7Jfxkql3hlKp4PNlRf9Cy7y5iA3G7MLyg3FcPX5z2kmcyPt2jOTRMBWUJ5zIQpOxizAcN8WsT3WWBL5KbuYK6k0PzujrIDLqdxGpNmjkkMfDBT9cKmZpm2FdW+oZgPFJP+oKmAo4u4KJz/vjiPTXgQlN5bmrLuRMCp+AwC5wkIohTqWZVPE2TK6ZSnMYcg/W39s+RP/9mJoyryAvPSpBOLTI+biCgaUCTOAZxNTWpMFc3tPYntc41WWkdKcooZ9JA5DwfcaVFyTGQ3YXz+HvX6G1z/gW0Q/A4dBi9mj2iE1xm7tRTT+4VQ2AXFvSEI1HJpfPgYnwAtwOD1v3Qm2EUHk9sCdtEDR4wVGEPIVn44GnwFMnGKx9JWppMPYwFu3SVDdHt+E+LOlhZUply11Aa+IVrT2KUQ=
script:
- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...

View File

@@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ivan+abuse@flanders.co.nz. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,202 +0,0 @@
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.

View File

@@ -1,15 +0,0 @@
# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io)
[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference)
An implementation of JSON Reference - Go language
## Status
Work in progress ( 90% done )
## Dependencies
https://github.com/go-openapi/jsonpointer
## References
http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03

View File

@@ -1,15 +0,0 @@
module github.com/go-openapi/jsonreference
require (
github.com/PuerkitoBio/purell v1.1.0
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-openapi/jsonpointer v0.17.0
github.com/go-openapi/swag v0.17.0 // indirect
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
golang.org/x/net v0.0.0-20181005035420-146acd28ed58 // indirect
golang.org/x/text v0.3.0 // indirect
gopkg.in/yaml.v2 v2.2.1 // indirect
)

View File

@@ -1,20 +0,0 @@
github.com/PuerkitoBio/purell v1.1.0 h1:rmGxhojJlM0tuKtfdvliR84CFHljx9ag64t2xmVkjK4=
github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/jsonpointer v0.17.0 h1:Bpl2DtZ6k7wKqfFs7e+4P08+M9I3FQgn09a1UsRUQbk=
github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/swag v0.17.0 h1:7wu+dZ5k83kvUWeAb+WUkFiUhDzwGqzTR/NhWzeo1JU=
github.com/go-openapi/swag v0.17.0/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/net v0.0.0-20181005035420-146acd28ed58 h1:otZG8yDCO4LVps5+9bxOeNiCvgmOyt96J3roHTYs7oE=
golang.org/x/net v0.0.0-20181005035420-146acd28ed58/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -1,156 +0,0 @@
// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
//
// 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.
// author sigu-399
// author-github https://github.com/sigu-399
// author-mail sigu.399@gmail.com
//
// repository-name jsonreference
// repository-desc An implementation of JSON Reference - Go language
//
// description Main and unique file.
//
// created 26-02-2013
package jsonreference
import (
"errors"
"net/url"
"strings"
"github.com/PuerkitoBio/purell"
"github.com/go-openapi/jsonpointer"
)
const (
fragmentRune = `#`
)
// New creates a new reference for the given string
func New(jsonReferenceString string) (Ref, error) {
var r Ref
err := r.parse(jsonReferenceString)
return r, err
}
// MustCreateRef parses the ref string and panics when it's invalid.
// Use the New method for a version that returns an error
func MustCreateRef(ref string) Ref {
r, err := New(ref)
if err != nil {
panic(err)
}
return r
}
// Ref represents a json reference object
type Ref struct {
referenceURL *url.URL
referencePointer jsonpointer.Pointer
HasFullURL bool
HasURLPathOnly bool
HasFragmentOnly bool
HasFileScheme bool
HasFullFilePath bool
}
// GetURL gets the URL for this reference
func (r *Ref) GetURL() *url.URL {
return r.referenceURL
}
// GetPointer gets the json pointer for this reference
func (r *Ref) GetPointer() *jsonpointer.Pointer {
return &r.referencePointer
}
// String returns the best version of the url for this reference
func (r *Ref) String() string {
if r.referenceURL != nil {
return r.referenceURL.String()
}
if r.HasFragmentOnly {
return fragmentRune + r.referencePointer.String()
}
return r.referencePointer.String()
}
// IsRoot returns true if this reference is a root document
func (r *Ref) IsRoot() bool {
return r.referenceURL != nil &&
!r.IsCanonical() &&
!r.HasURLPathOnly &&
r.referenceURL.Fragment == ""
}
// IsCanonical returns true when this pointer starts with http(s):// or file://
func (r *Ref) IsCanonical() bool {
return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL)
}
// "Constructor", parses the given string JSON reference
func (r *Ref) parse(jsonReferenceString string) error {
parsed, err := url.Parse(jsonReferenceString)
if err != nil {
return err
}
r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes))
refURL := r.referenceURL
if refURL.Scheme != "" && refURL.Host != "" {
r.HasFullURL = true
} else {
if refURL.Path != "" {
r.HasURLPathOnly = true
} else if refURL.RawQuery == "" && refURL.Fragment != "" {
r.HasFragmentOnly = true
}
}
r.HasFileScheme = refURL.Scheme == "file"
r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/")
// invalid json-pointer error means url has no json-pointer fragment. simply ignore error
r.referencePointer, _ = jsonpointer.New(refURL.Fragment)
return nil
}
// Inherits creates a new reference from a parent and a child
// If the child cannot inherit from the parent, an error is returned
func (r *Ref) Inherits(child Ref) (*Ref, error) {
childURL := child.GetURL()
parentURL := r.GetURL()
if childURL == nil {
return nil, errors.New("child url is nil")
}
if parentURL == nil {
return &child, nil
}
ref, err := New(parentURL.ResolveReference(childURL).String())
if err != nil {
return nil, err
}
return &ref, nil
}

View File

@@ -1,420 +0,0 @@
// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
//
// 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.
// author sigu-399
// author-github https://github.com/sigu-399
// author-mail sigu.399@gmail.com
//
// repository-name jsonreference
// repository-desc An implementation of JSON Reference - Go language
//
// description Automated tests on package.
//
// created 03-03-2013
package jsonreference
import (
"testing"
"github.com/go-openapi/jsonpointer"
"github.com/stretchr/testify/assert"
)
func TestIsRoot(t *testing.T) {
in := "#"
r1, err := New(in)
assert.NoError(t, err)
assert.True(t, r1.IsRoot())
in = "#/ok"
r1 = MustCreateRef(in)
assert.False(t, r1.IsRoot())
assert.Panics(t, assert.PanicTestFunc(func() {
MustCreateRef("%2")
}))
}
func TestFull(t *testing.T) {
in := "http://host/path/a/b/c#/f/a/b"
r1, err := New(in)
if err != nil {
t.Errorf("New(%v) error %s", in, err.Error())
}
if in != r1.String() {
t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in)
}
if r1.HasFragmentOnly != false {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false)
}
if r1.HasFullURL != true {
t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true)
}
if r1.HasURLPathOnly != false {
t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false)
}
if r1.HasFileScheme != false {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false)
}
if r1.GetPointer().String() != "/f/a/b" {
t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b")
}
}
func TestFullURL(t *testing.T) {
in := "http://host/path/a/b/c"
r1, err := New(in)
if err != nil {
t.Errorf("New(%v) error %s", in, err.Error())
}
if in != r1.String() {
t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in)
}
if r1.HasFragmentOnly != false {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false)
}
if r1.HasFullURL != true {
t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true)
}
if r1.HasURLPathOnly != false {
t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false)
}
if r1.HasFileScheme != false {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false)
}
if r1.GetPointer().String() != "" {
t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "")
}
}
func TestFragmentOnly(t *testing.T) {
in := "#/fragment/only"
r1, err := New(in)
if err != nil {
t.Errorf("New(%v) error %s", in, err.Error())
}
if in != r1.String() {
t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in)
}
if r1.HasFragmentOnly != true {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true)
}
if r1.HasFullURL != false {
t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false)
}
if r1.HasURLPathOnly != false {
t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false)
}
if r1.HasFileScheme != false {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false)
}
if r1.GetPointer().String() != "/fragment/only" {
t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only")
}
p, _ := jsonpointer.New(r1.referenceURL.Fragment)
r2 := Ref{referencePointer: p, HasFragmentOnly: true}
assert.Equal(t, r2.String(), in)
r3 := Ref{referencePointer: p, HasFragmentOnly: false}
assert.Equal(t, r3.String(), in[1:])
}
func TestURLPathOnly(t *testing.T) {
in := "/documents/document.json"
r1, err := New(in)
if err != nil {
t.Errorf("New(%v) error %s", in, err.Error())
}
if in != r1.String() {
t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in)
}
if r1.HasFragmentOnly != false {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false)
}
if r1.HasFullURL != false {
t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false)
}
if r1.HasURLPathOnly != true {
t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true)
}
if r1.HasFileScheme != false {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false)
}
if r1.GetPointer().String() != "" {
t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "")
}
}
func TestURLRelativePathOnly(t *testing.T) {
in := "document.json"
r1, err := New(in)
if err != nil {
t.Errorf("New(%v) error %s", in, err.Error())
}
if in != r1.String() {
t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in)
}
if r1.HasFragmentOnly != false {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false)
}
if r1.HasFullURL != false {
t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false)
}
if r1.HasURLPathOnly != true {
t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true)
}
if r1.HasFileScheme != false {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false)
}
if r1.GetPointer().String() != "" {
t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "")
}
}
func TestInheritsInValid(t *testing.T) {
in1 := "http://www.test.com/doc.json"
in2 := "#/a/b"
r1, _ := New(in1)
r2 := Ref{}
result, err := r1.Inherits(r2)
assert.Error(t, err)
assert.Nil(t, result)
r1 = Ref{}
r2, _ = New(in2)
result, err = r1.Inherits(r2)
assert.NoError(t, err)
assert.Equal(t, r2, *result)
}
func TestInheritsValid(t *testing.T) {
in1 := "http://www.test.com/doc.json"
in2 := "#/a/b"
out := in1 + in2
r1, _ := New(in1)
r2, _ := New(in2)
result, err := r1.Inherits(r2)
if err != nil {
t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error())
}
if result.String() != out {
t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out)
}
if result.GetPointer().String() != "/a/b" {
t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b")
}
}
func TestInheritsDifferentHost(t *testing.T) {
in1 := "http://www.test.com/doc.json"
in2 := "http://www.test2.com/doc.json#bla"
r1, _ := New(in1)
r2, _ := New(in2)
result, err := r1.Inherits(r2)
if err != nil {
t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error())
}
if result.String() != in2 {
t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result)
}
if result.GetPointer().String() != "" {
t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "")
}
}
func TestFileScheme(t *testing.T) {
in1 := "file:///Users/mac/1.json#a"
in2 := "file:///Users/mac/2.json#b"
r1, _ := New(in1)
r2, _ := New(in2)
if r1.HasFragmentOnly != false {
t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false)
}
if r1.HasFileScheme != true {
t.Errorf("New(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true)
}
if r1.HasFullFilePath != true {
t.Errorf("New(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true)
}
if r1.IsCanonical() != true {
t.Errorf("New(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical(), true)
}
result, err := r1.Inherits(r2)
if err != nil {
t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error())
}
if result.String() != in2 {
t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result)
}
if result.GetPointer().String() != "" {
t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "")
}
}
func TestReferenceResolution(t *testing.T) {
// 5.4. Reference Resolution Examples
// http://tools.ietf.org/html/rfc3986#section-5.4
base := "http://a/b/c/d;p?q"
baseRef, err := New(base)
if err != nil {
t.Errorf("New(%s) failed error: %s", base, err.Error())
}
if baseRef.String() != base {
t.Errorf("New(%s) %s expected %s", base, baseRef.String(), base)
}
checks := []string{
// 5.4.1. Normal Examples
// http://tools.ietf.org/html/rfc3986#section-5.4.1
"g:h", "g:h",
"g", "http://a/b/c/g",
"./g", "http://a/b/c/g",
"g/", "http://a/b/c/g/",
"/g", "http://a/g",
"//g", "http://g",
"?y", "http://a/b/c/d;p?y",
"g?y", "http://a/b/c/g?y",
"#s", "http://a/b/c/d;p?q#s",
"g#s", "http://a/b/c/g#s",
"g?y#s", "http://a/b/c/g?y#s",
";x", "http://a/b/c/;x",
"g;x", "http://a/b/c/g;x",
"g;x?y#s", "http://a/b/c/g;x?y#s",
"", "http://a/b/c/d;p?q",
".", "http://a/b/c/",
"./", "http://a/b/c/",
"..", "http://a/b/",
"../", "http://a/b/",
"../g", "http://a/b/g",
"../..", "http://a/",
"../../", "http://a/",
"../../g", "http://a/g",
// 5.4.2. Abnormal Examples
// http://tools.ietf.org/html/rfc3986#section-5.4.2
"../../../g", "http://a/g",
"../../../../g", "http://a/g",
"/./g", "http://a/g",
"/../g", "http://a/g",
"g.", "http://a/b/c/g.",
".g", "http://a/b/c/.g",
"g..", "http://a/b/c/g..",
"..g", "http://a/b/c/..g",
"./../g", "http://a/b/g",
"./g/.", "http://a/b/c/g/",
"g/./h", "http://a/b/c/g/h",
"g/../h", "http://a/b/c/h",
"g;x=1/./y", "http://a/b/c/g;x=1/y",
"g;x=1/../y", "http://a/b/c/y",
"g?y/./x", "http://a/b/c/g?y/./x",
"g?y/../x", "http://a/b/c/g?y/../x",
"g#s/./x", "http://a/b/c/g#s/./x",
"g#s/../x", "http://a/b/c/g#s/../x",
"http:g", "http:g", // for strict parsers
//"http:g", "http://a/b/c/g", // for backward compatibility
}
for i := 0; i < len(checks); i += 2 {
child := checks[i]
expected := checks[i+1]
// fmt.Printf("%d: %v -> %v\n", i/2, child, expected)
childRef, e := New(child)
if e != nil {
t.Errorf("%d: New(%s) failed error: %s", i/2, child, e.Error())
}
res, e := baseRef.Inherits(childRef)
if res == nil {
t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child)
}
if e != nil {
t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error())
}
if res.String() != expected {
t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected)
}
}
}

View File

@@ -1,26 +0,0 @@
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
# Set default charset
[*.{js,py,go,scala,rb,java,html,css,less,sass,md}]
charset = utf-8
# Tab indentation (no size specified)
[*.go]
indent_style = tab
[*.md]
trim_trailing_whitespace = false
# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

View File

@@ -1,117 +0,0 @@
## Contribution Guidelines
### Pull requests are always welcome
We are always thrilled to receive pull requests, and do our best to
process them as fast as possible. Not sure if that typo is worth a pull
request? Do it! We will appreciate it.
If your pull request is not accepted on the first try, don't be
discouraged! If there's a problem with the implementation, hopefully you
received feedback on what to improve.
We're trying very hard to keep go-swagger lean and focused. We don't want it
to do everything for everybody. This means that we might decide against
incorporating a new feature. However, there might be a way to implement
that feature *on top of* go-swagger.
### Conventions
Fork the repo and make changes on your fork in a feature branch:
- If it's a bugfix branch, name it XXX-something where XXX is the number of the
issue
- If it's a feature branch, create an enhancement issue to announce your
intentions, and name it XXX-something where XXX is the number of the issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test suite on
your branch before submitting a pull request.
Update the documentation when creating or modifying features. Test
your documentation changes for clarity, concision, and correctness, as
well as a clean documentation build. See ``docs/README.md`` for more
information on building the docs and how docs get released.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plugins that do this automatically.
Pull requests descriptions should be as clear as possible and include a
reference to all the issues that they address.
Pull requests must not contain commits from other users or branches.
Commit messages must start with a capitalized and short summary (max. 50
chars) written in the imperative, followed by an optional, more detailed
explanatory text which is separated from the summary by an empty line.
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Be
sure to post a comment after pushing. The new commits will show up in the pull
request automatically, but the reviewers will not be notified unless you
comment.
Before the pull request is merged, make sure that you squash your commits into
logical units of work using `git rebase -i` and `git push -f`. After every
commit the test suite should be passing. Include documentation changes in the
same commit so that a revert would remove all traces of the feature or fix.
Commits that fix or close an issue should include a reference like `Closes #XXX`
or `Fixes #XXX`, which will automatically close the issue when merged.
### Sign your work
The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below (from
[developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
then you just add a line to every git commit message:
Signed-off-by: Joe Smith <joe@gmail.com>
using your real name (sorry, no pseudonyms or anonymous contributions.)
You can add the sign off when creating the git commit via `git commit -s`.

View File

@@ -1,2 +0,0 @@
secrets.yml
coverage.out

View File

@@ -1,21 +0,0 @@
linters-settings:
govet:
check-shadowing: true
golint:
min-confidence: 0
gocyclo:
min-complexity: 25
maligned:
suggest-new: true
dupl:
threshold: 100
goconst:
min-len: 2
min-occurrences: 2
linters:
enable-all: true
disable:
- maligned
- unparam
- lll

View File

@@ -1,18 +0,0 @@
after_success:
- bash <(curl -s https://codecov.io/bash)
go:
- '1.9'
- 1.10.x
- 1.11.x
install:
- go get -u github.com/stretchr/testify
- go get -u github.com/go-openapi/swag
- go get -u gopkg.in/yaml.v2
- go get -u github.com/go-openapi/jsonpointer
- go get -u github.com/go-openapi/jsonreference
language: go
notifications:
slack:
secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E=
script:
- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...

View File

@@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ivan+abuse@flanders.co.nz. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,202 +0,0 @@
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.

View File

@@ -1,10 +0,0 @@
# OAI object model [![Build Status](https://travis-ci.org/go-openapi/spec.svg?branch=master)](https://travis-ci.org/go-openapi/spec) [![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io)
[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE)
[![GoDoc](https://godoc.org/github.com/go-openapi/spec?status.svg)](http://godoc.org/github.com/go-openapi/spec)
[![GolangCI](https://golangci.com/badges/github.com/go-openapi/spec.svg)](https://golangci.com)
[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/spec)](https://goreportcard.com/report/github.com/go-openapi/spec)
The object model for OpenAPI specification documents.
Currently supports Swagger 2.0.

View File

@@ -1,128 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"testing"
)
func TestSerialization_AuthSerialization(t *testing.T) {
assertSerializeJSON(t, BasicAuth(), `{"type":"basic"}`)
assertSerializeJSON(t, APIKeyAuth("api-key", "header"), `{"type":"apiKey","name":"api-key","in":"header"}`)
assertSerializeJSON(
t,
OAuth2Implicit("http://foo.com/authorization"),
`{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization"}`)
assertSerializeJSON(
t,
OAuth2Password("http://foo.com/token"),
`{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/token"}`)
assertSerializeJSON(t,
OAuth2Application("http://foo.com/token"),
`{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token"}`)
assertSerializeJSON(
t,
OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token"),
`{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token"}`)
auth1 := OAuth2Implicit("http://foo.com/authorization")
auth1.AddScope("email", "read your email")
assertSerializeJSON(
t,
auth1,
`{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`)
auth2 := OAuth2Password("http://foo.com/authorization")
auth2.AddScope("email", "read your email")
assertSerializeJSON(
t,
auth2,
`{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`)
auth3 := OAuth2Application("http://foo.com/token")
auth3.AddScope("email", "read your email")
assertSerializeJSON(
t,
auth3,
`{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`)
auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token")
auth4.AddScope("email", "read your email")
assertSerializeJSON(
t,
auth4,
`{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`)
}
func TestSerialization_AuthDeserialization(t *testing.T) {
assertParsesJSON(t, `{"type":"basic"}`, BasicAuth())
assertParsesJSON(
t,
`{"in":"header","name":"api-key","type":"apiKey"}`,
APIKeyAuth("api-key", "header"))
assertParsesJSON(
t,
`{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","type":"oauth2"}`,
OAuth2Implicit("http://foo.com/authorization"))
assertParsesJSON(
t,
`{"flow":"password","tokenUrl":"http://foo.com/token","type":"oauth2"}`,
OAuth2Password("http://foo.com/token"))
assertParsesJSON(
t,
`{"flow":"application","tokenUrl":"http://foo.com/token","type":"oauth2"}`,
OAuth2Application("http://foo.com/token"))
assertParsesJSON(
t,
`{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","tokenUrl":"http://foo.com/token","type":"oauth2"}`,
OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token"))
auth1 := OAuth2Implicit("http://foo.com/authorization")
auth1.AddScope("email", "read your email")
assertParsesJSON(t,
`{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","scopes":{"email":"read your email"},"type":"oauth2"}`,
auth1)
auth2 := OAuth2Password("http://foo.com/token")
auth2.AddScope("email", "read your email")
assertParsesJSON(t,
`{"flow":"password","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`,
auth2)
auth3 := OAuth2Application("http://foo.com/token")
auth3.AddScope("email", "read your email")
assertParsesJSON(t,
`{"flow":"application","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`,
auth3)
auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token")
auth4.AddScope("email", "read your email")
assertParsesJSON(
t,
`{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`,
auth4)
}

File diff suppressed because one or more lines are too long

View File

@@ -1,24 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
// ContactInfo contact information for the exposed API.
//
// For more information: http://goo.gl/8us55a#contactObject
type ContactInfo struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}

View File

@@ -1,37 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"testing"
)
var contactInfoJSON = `{"name":"wordnik api team","url":"http://developer.wordnik.com","email":"some@mailayada.dkdkd"}`
var contactInfoYAML = `name: wordnik api team
url: http://developer.wordnik.com
email: some@mailayada.dkdkd
`
var contactInfo = ContactInfo{
Name: "wordnik api team",
URL: "http://developer.wordnik.com",
Email: "some@mailayada.dkdkd",
}
func TestIntegrationContactInfo(t *testing.T) {
assertSerializeJSON(t, contactInfo, contactInfoJSON)
assertSerializeYAML(t, contactInfo, contactInfoYAML)
assertParsesJSON(t, contactInfoJSON, contactInfo)
assertParsesYAML(t, contactInfoYAML, contactInfo)
}

View File

@@ -1,47 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
)
var (
// Debug is true when the SWAGGER_DEBUG env var is not empty.
// It enables a more verbose logging of validators.
Debug = os.Getenv("SWAGGER_DEBUG") != ""
// validateLogger is a debug logger for this package
specLogger *log.Logger
)
func init() {
debugOptions()
}
func debugOptions() {
specLogger = log.New(os.Stdout, "spec:", log.LstdFlags)
}
func debugLog(msg string, args ...interface{}) {
// A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog()
if Debug {
_, file1, pos1, _ := runtime.Caller(1)
specLogger.Printf("%s:%d: %s", filepath.Base(file1), pos1, fmt.Sprintf(msg, args...))
}
}

View File

@@ -1,59 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"io/ioutil"
"os"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
var (
logMutex = &sync.Mutex{}
)
func TestDebug(t *testing.T) {
tmpFile, _ := ioutil.TempFile("", "debug-test")
tmpName := tmpFile.Name()
defer func() {
Debug = false
// mutex for -race
logMutex.Unlock()
_ = os.Remove(tmpName)
}()
// mutex for -race
logMutex.Lock()
Debug = true
debugOptions()
defer func() {
specLogger.SetOutput(os.Stdout)
}()
specLogger.SetOutput(tmpFile)
debugLog("A debug")
Debug = false
_ = tmpFile.Close()
flushed, _ := os.Open(tmpName)
buf := make([]byte, 500)
_, _ = flushed.Read(buf)
specLogger.SetOutput(os.Stdout)
assert.Contains(t, string(buf), "A debug")
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
// ExternalDocumentation allows referencing an external resource for
// extended documentation.
//
// For more information: http://goo.gl/8us55a#externalDocumentationObject
type ExternalDocumentation struct {
Description string `json:"description,omitempty"`
URL string `json:"url,omitempty"`
}

View File

@@ -1,29 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"testing"
)
func TestIntegrationExternalDocs(t *testing.T) {
var extDocs = ExternalDocumentation{"the name", "the url"}
const extDocsYAML = "description: the name\nurl: the url\n"
const extDocsJSON = `{"description":"the name","url":"the url"}`
assertSerializeJSON(t, extDocs, extDocsJSON)
assertSerializeYAML(t, extDocs, extDocsYAML)
assertParsesJSON(t, extDocsJSON, extDocs)
assertParsesYAML(t, extDocsYAML, extDocs)
}

View File

@@ -1,5 +0,0 @@
farFarAway:
type: object
properties:
farFarAwayProp:
type: integer

View File

@@ -1,11 +0,0 @@
aRemotePlace:
type: object
properties:
remoteProp:
type: integer
fartherProp:
$ref: './farther/farther.yaml#/farFarAway'
moreRemoteThanYouCanThink:
#$ref: './remote/remote.yaml#/farFarAway'
type: integer

View File

@@ -1,5 +0,0 @@
farFarAway:
type: object
properties:
farFarAwayProp:
type: integer

View File

@@ -1,104 +0,0 @@
swagger: '2.0'
info:
title: Responses
version: 0.1.0
definitions:
Error:
type: object
description: |
Contains all the properties any error response from the API will contain.
Some properties are optional so might be empty most of the time
required:
- code
- message
properties:
code:
description: the error code, this is not necessarily the http status code
type: integer
format: int32
message:
description: a human readable version of the error
type: string
helpUrl:
description: an optional url for getting more help about this error
type: string
format: uri
myArray:
type: array
items:
$ref: '#/definitions/myItems'
myItems:
type: object
properties:
propItems1:
type: integer
propItems2:
$ref: 'remote/remote.yaml#/aRemotePlace'
otherPlace:
Error:
type: object
properties:
message:
type: string
parameters:
BadRequest:
name: badRequest
in: body
schema:
$ref: '#/definitions/Error'
GoodRequest:
name: goodRequest
in: body
schema:
$ref: '#/otherPlace/Error'
PlainRequest:
name: plainRequest
in: body
schema:
type: integer
StrangeRequest:
name: stangeRequest
in: body
schema:
$ref: 'responses.yaml#/otherPlace/Error'
RemoteRequest:
name: remoteRequest
in: body
schema:
$ref: './remote/remote.yaml#/moreRemoteThanYouCanThink'
responses:
BadRequest:
description: Bad request
schema:
$ref: '#/definitions/Error'
GoodRequest:
description: good request
schema:
$ref: '#/otherPlace/Error'
PlainRequest:
description: plain request
schema:
type: integer
StrangeRequest:
description: strange request
schema:
$ref: 'responses.yaml#/otherPlace/Error'
RemoteRequest:
description: remote request
schema:
$ref: './remote/remote.yaml#/moreRemoteThanYouCanThink'
paths:
/:
get:
summary: GET
operationId: getAll
responses:
200:
description: Ok

View File

@@ -1,39 +0,0 @@
swagger: '2.0'
info:
title: Object
version: 0.1.0
paths:
/:
get:
summary: GET
operationId: getAll
parameters:
- $ref: 'responses.yaml#/parameters/BadRequest'
- $ref: 'responses.yaml#/parameters/GoodRequest'
- $ref: 'responses.yaml#/parameters/PlainRequest'
- $ref: 'responses.yaml#/parameters/StrangeRequest'
- $ref: 'responses.yaml#/parameters/RemoteRequest'
- name: nestedBody
in: body
schema:
$ref: '#/definitions/nestedRefDefinition'
responses:
200:
description: Ok
400:
$ref: 'responses.yaml#/responses/BadRequest'
403:
$ref: 'responses.yaml#/responses/GoodRequest'
404:
$ref: 'responses.yaml#/responses/PlainRequest'
304:
$ref: 'responses.yaml#/responses/StrangeRequest'
204:
$ref: 'responses.yaml#/responses/RemoteRequest'
definitions:
badDefinition:
$ref: 'responses.yaml#/definitions/Error'
nestedRefDefinition:
$ref: 'responses.yaml#/definitions/myArray'

File diff suppressed because it is too large Load Diff

View File

@@ -1,618 +0,0 @@
definitions:
# Generic response model
V4GenericResponse:
type: object
properties:
message:
type: string
description: A human readable message
code:
type: string
description: |
A machine readable [response code](https://github.com/giantswarm/api-spec/blob/master/details/RESPONSE_CODES.md) like e. g. `INVALID_CREDENTIALS`
# Info resposne
V4InfoResponse:
type: object
properties:
general:
description: General information
type: object
properties:
installation_name:
description: Unique name of the installation
type: string
provider:
description: The technical provider used in this installation. Either "kvm", "aws", or "azure".
type: string
datacenter:
description: Identifier of the datacenter or cloud provider region, e. g. "eu-west-1"
type: string
workers:
description: Information related to worker nodes
type: object
properties:
count_per_cluster:
description: Number of workers per cluster
type: object
properties:
max:
description: Maximum number of worker a cluster can have
type: number
default:
description: Default number of workers in a new cluster will have, if not specifiec otherwise
type: number
instance_type:
description: Instance types to be used for worker nodes. Only available for AWS clusters.
type: object
properties:
options:
description: List of available instance types
type: array
items:
type: string
default:
description: The instance type used in new cluster, if not specified
type: string
vm_size:
description: Azure Virtual Machine size to be used for worker nodes. Only available for Azure clusters.
type: object
properties:
options:
description: List of available instance types
type: array
items:
type: string
default:
description: The instance type used in new cluster, if not specified
type: string
# Request to create a new cluster
V4AddClusterRequest:
type: object
required:
- owner
description: Request model for creating a new cluster
properties:
owner:
type: string
description: Name of the organization owning the cluster
name:
type: string
description: Cluster name
release_version:
type: string
description: |
The [release](https://docs.giantswarm.io/api/#tag/releases) version
to use in the new cluster
kubernetes_version:
type: string
description: |
Kubernetes version number (deprecated). Doesn't have any effect.
This attribute is going to be removed in future API versions.
workers:
type: array
items:
$ref: '#/definitions/V4NodeDefinition'
V4ModifyClusterRequest:
type: object
required: []
description: Request body for cluster modification
properties:
name:
type: string
description: Name for the cluster
owner:
type: string
description: Name of the organization owning the cluster
release_version:
type: string
description: Release version to use after an upgrade
workers:
type: array
description: Worker node array
items:
$ref: '#/definitions/V4NodeDefinition'
# Details on existing cluster
V4ClusterDetailsResponse:
type: object
description: Response model showing details of a cluster
properties:
id:
type: string
description: Unique cluster identifier
api_endpoint:
type: string
description: URI of the Kubernetes API endpoint
create_date:
type: string
description: Date/time of cluster creation
owner:
type: string
description: Name of the organization owning the cluster
name:
type: string
description: Cluster name
release_version:
type: string
description: |
The [release](https://docs.giantswarm.io/api/#tag/releases) version
currently running this cluster.
kubernetes_version:
type: string
description: Deprecated. Will be removed in a future API version.
workers:
type: array
items:
$ref: '#/definitions/V4NodeDefinition'
kvm:
type: object
description: Attributes specific to clusters running on KVM (on-prem) installations.
properties:
port_mappings:
type: array
description: |
Reveals the ports on the host cluster that are mapped to this guest cluster's ingress
and which protocol that port supports. Only shown and relevant on our on-prem KVM clusters.
items:
type: object
properties:
port:
description: |
The port on the host cluster that will forward traffic to the guest cluster
type: integer
protocol:
description: |
The protocol this port mapping is made for.
type: string
# Definition of a cluster node
V4NodeDefinition:
type: object
properties:
aws:
type: object
description: |
Attributes specific to nodes running on Amazon Web Services (AWS)
properties:
instance_type:
type: string
description: |
EC2 instance type name. Must be the same for all worker nodes
of a cluster.
azure:
type: object
description: |
Attributes specific to nodes running on Microsoft Azure
properties:
vm_size:
type: string
description: |
Azure Virtual Machine size. Must be the same for all worker nodes
of a cluster.
memory:
type: object
properties:
size_gb:
type: number
description: RAM size in GB. Can be an integer or float.
storage:
type: object
properties:
size_gb:
type: number
description: Node storage size in GB. Can be an integer or float.
cpu:
type: object
properties:
cores:
type: integer
description: Number of CPU cores
labels:
type: object
additionalProperties: true
# List of key pairs
V4GetKeyPairsResponse:
type: array
description: Array of sparse key pair objects
items:
type: object
properties:
id:
type: string
description: Unique identifier of the key pair
description:
type: string
description: Free text information about the key pair
ttl_hours:
type: integer
description: Expiration time (from creation) in hours
create_date:
type: string
description: Date/time of creation
common_name:
type: string
description: The common name of the certificate subject.
certificate_organizations:
type: string
description: The certificate subject's `organization` fields.
# Add key pair request
V4AddKeyPairRequest:
type: object
required:
- description
properties:
description:
type: string
description: Free text information about the key pair
ttl_hours:
type: integer
format: int32
description: Expiration time (from creation) in hours
cn_prefix:
type: string
description: The common name prefix of the certificate subject. This only allows characters that are usable in domain names (`a-z`, `0-9`, and `.-`, where `.-` must not occur at either the start or the end).
certificate_organizations:
type: string
description: |
This will set the certificate subject's `organization` fields.
Use a comma seperated list of values.
V4AddKeyPairResponse:
type: object
properties:
id:
type: string
description: Unique identifier of the key pair
description:
type: string
description: Free text information about the key pair
ttl_hours:
type: integer
description: Expiration time (from creation) in hours
create_date:
type: string
description: Date/time of creation
certificate_authority_data:
type: string
description: PEM-encoded CA certificate of the cluster
client_key_data:
type: string
description: PEM-encoded RSA private key
client_certificate_data:
type: string
description: PEM-encoded certificate
# cluster metrics
V4GetClusterMetricsResponse:
description: Response for the getClusterMetrics operation
type: object
properties:
workers:
description: Group of metrics regarding workers
type: array
items:
$ref: '#/definitions/V4NodeMetrics'
V4NodeMetrics:
type: object
properties:
id:
description: String identifying the node
type: string
metrics:
description: Container object for all metrics available for the node
type: object
properties:
container_count:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
pod_count:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
cpu_used:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
ram_free:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
ram_available:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
ram_cached:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
ram_buffers:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
ram_mapped:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
node_storage_used:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
network_rx:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
network_tx:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
resource_cpu_requests:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
resource_cpu_limits:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
resource_ram_requests:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
resource_ram_limits:
type: object
properties:
timestamp:
description: Time when the given value has been recorded
type: string
value:
description: The value for the metric. Can be an integer or float.
type: number
# a complete organization object
V4Organization:
type: object
properties:
id:
type: string
description: Unique name/identifier of the organization
members:
type: array
description: List of members that belong to this organization
items:
$ref: '#/definitions/V4OrganizationMember'
# An organization as returned by getOrganizations as an array item
V4OrganizationListItem:
type: object
properties:
id:
type: string
description: Unique name/identifier of the organization
# A user that belongs to an organization
V4OrganizationMember:
type: object
properties:
email:
type: string
description: Email address of the user
# One of the users in the array as returned by getUsers
V4UserListItem:
type: object
properties:
email:
type: string
description: Email address of the user
created:
type: string
description: The date and time that this account was created
expiry:
type: string
description: The date and time when this account will expire
# A cluster array item, as return by getClusters
V4ClusterListItem:
type: object
properties:
id:
type: string
description: Unique cluster identifier
create_date:
type: string
description: Date/time of cluster creation
name:
type: string
description: Cluster name
owner:
type: string
description: Name of the organization owning the cluster
release_version:
type: string
description: The semantic version number of this cluster
# A cluster array item, as return by getClusters
V4ReleaseListItem:
type: object
required: ["version", "timestamp", "changelog", "components"]
properties:
version:
type: string
description: The semantic version number
timestamp:
type: string
description: Date and time of the release creation
active:
type: boolean
description: |
If true, the version is available for new clusters and cluster
upgrades. Older versions become unavailable and thus have the
value `false` here.
changelog:
description: |
Structured list of changes in this release, in comparison to the
previous version, with respect to the contained components.
type: array
items:
type: object
properties:
component:
type: string
description: |
If the changed item was a component, this attribute is the
name of the component.
description:
type: string
description: Human-friendly description of the change
components:
description: |
List of components and their version contained in the release
type: array
items:
type: object
required: ["name", "version"]
properties:
name:
type: string
description: Name of the component
version:
type: string
description: Version number of the component
V4CreateUserRequest:
type: object
required:
- password
description: Request model for creating a new user
properties:
password:
type: string
description: A Base64 encoded password
expiry:
type: string
description: The date and time when this account will expire
V4AddCredentialsRequest:
type: object
required:
- provider
description: Request model for adding a set of credentials
properties:
provider:
type: string
aws:
type: object
description: Credentials specific to an AWS account
required:
- roles
properties:
roles:
type: object
description: IAM roles to assume by certain entities
required:
- awsoperator
- admin
properties:
admin:
type: string
description: ARN of the IAM role to assume by Giant Swarm support staff
awsoperator:
type: string
description: ARN of the IAM role to assume by the software operating clusters
# A request for an auth token
V4CreateAuthTokenRequest:
type: object
properties:
email:
type: string
description: Your email address
password_base64:
type: string
description: Your password as a base64 encoded string
# A response to a successful auth token request
V4CreateAuthTokenResponse:
type: object
properties:
auth_token:
type: string
description: The newly created API token

File diff suppressed because it is too large Load Diff

View File

@@ -1,61 +0,0 @@
parameters:
RequiredGiantSwarmAuthorizationHeader:
name: Authorization
type: string
in: header
required: true
description: As described in the [authentication](#section/Authentication) section
ClusterIdPathParameter:
name: cluster_id
in: path
required: true
type: string
description: Cluster ID
UserEmailPathParameter:
name: email
in: path
required: true
type: string
description: The user's email address
OrganizationIdPathParameter:
name: organization_id
in: path
required: true
type: string
description: |
An ID for the organization.
This ID must be unique and match this regular
expression: ^[a-z0-9_]{4,30}$
XRequestIDHeader:
name: X-Request-ID
in: header
type: string
required: false
description: |
A randomly generated key that can be used to track a request throughout
services of Giant Swarm.
XGiantSwarmActivityHeader:
name: X-Giant-Swarm-Activity
in: header
type: string
required: false
description: |
Name of an activity to track, like "list-clusters". This allows to
analyze several API requests sent in context and gives an idea on
the purpose.
XGiantSwarmCmdLineHeader:
name: X-Giant-Swarm-CmdLine
in: header
type: string
required: false
description: |
If activity has been issued by a CLI, this header can contain the
command line

View File

@@ -1,13 +0,0 @@
responses:
V4Generic401Response:
description: Permission denied
schema:
$ref: "./definitions.yaml#/definitions/V4GenericResponse"
examples:
application/json:
{
"code": "PERMISSION_DENIED",
"message": "The requested resource cannot be accessed using the provided authentication details."
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,254 +0,0 @@
{
"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"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.wordnik.com",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": {
"idParam": {
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
},
"tag": {
"type": "string",
"in": "query",
"required": false
},
"query": {
"$ref": "#/parameters/tag"
}
},
"responses": {
"petResponse": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/pet"
}
},
"stringResponse": {
"descripion": "string response",
"schema": {
"type": "string"
}
},
"anotherPet": {
"$ref": "#/responses/petResponse"
}
},
"paths": {
"/": {
"get": {
"operationId": "indexStuff",
"responses": {
"default": {
"$ref": "#/responses/stringResponse"
},
"200": {
"$ref": "#/responses/anotherPet"
}
}
}
},
"/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/petInput"
}
}
],
"responses": {
"200": { "$ref": "#/responses/petResponse" },
"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": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"200": {
"$ref": "#/responses/petResponse"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"pet": {
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"petInput": {
"allOf": [
{
"$ref": "#/definitions/pet"
},
{
"required": [
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"errorModel": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View File

@@ -1,58 +0,0 @@
{
"swagger": "2.0",
"info": {
"version": "0.0.1"
},
"basePath": "/",
"paths": {
"/cycles": {
"get": {
"responses": {
"200": {
"description": "ok",
"schema": {
"$ref": "#/definitions/node0"
}
}
}
}
}
},
"definitions": {
"node0": {
"type": "object",
"properties": {
"p00": {
"$ref": "#/definitions/node1"
},
"p01": {
"$ref": "#/definitions/node3"
}
}
},
"node1": {
"type": "object",
"properties": {
"p1": {
"$ref": "#/definitions/node2"
}
}
},
"node2": {
"type": "object",
"properties": {
"p2": {
"$ref": "#/definitions/node0"
}
}
},
"node3": {
"type": "object",
"properties": {
"p3": {
"$ref": "#/definitions/node1"
}
}
}
}
}

View File

@@ -1,54 +0,0 @@
{
"definitions": {
"brand": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"category": {
"type": "object",
"properties": {
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/category"
}
}
}
},
"car": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"make": {
"type": "string"
},
"similar": {
"items": {
"$ref": "#/definitions/car"
}
},
"notSimilar": {
"additionalProperties": {
"$ref": "#/definitions/car"
}
},
"oneCar": {
"$ref": "#/definitions/car"
},
"category": {
"$ref": "#/definitions/category"
},
"brand": {
"$ref": "#/definitions/brand"
}
}
}
}
}

View File

@@ -1 +0,0 @@
{"swagger":"2.0","info":{"title":"Swagger Sample","description":"Sample API Playground.","version":"1.0.0"},"basePath":"/v1","schemes":["http"],"consumes":["application/vdn.sample.v1+json"],"produces":["application/vdn.sample.v1+json"],"paths":{"/books":{"get":{"summary":"List all books","operationId":"listBooks","tags":["books"],"responses":{"200":{"headers":{"Link":{"type":"string"}},"description":"An array of books","schema":{"type":"array","items":{"$ref":"#/definitions/Book"}}},"default":{"description":"generic error response","schema":{"$ref":"#/definitions/Error"}}}}}},"definitions":{"Book":{"type":"object","required":["title","summary"],"properties":{"title":{"type":"string","example":"Winnie the Pooh"},"summary":{"type":"string","example":"Famous children's book"},"related_books":{"type":"array","items":{"$ref":"#/definitions/Book"}}}},"Error":{"type":"object","readOnly":true,"properties":{"code":{"type":"integer","format":"int64","example":400},"message":{"type":"string","example":"Unexpected error"}},"required":["message"]}}}

View File

@@ -1,67 +0,0 @@
---
swagger: "2.0"
info:
title: Swagger Sample
description: Sample API Playground.
version: 1.0.0
basePath: /v1
schemes:
- http
consumes:
- application/vdn.sample.v1+json
produces:
- application/vdn.sample.v1+json
paths:
/books:
get:
summary: List all books
operationId: listBooks
tags:
- books
responses:
200:
headers:
Link:
type: string
description: An array of books
schema:
type: array
items:
$ref: "#/definitions/Book"
default:
description: generic error response
schema:
$ref: "#/definitions/Error"
definitions:
Book:
type: object
required:
- title
- summary
properties:
title:
type: string
example: Winnie the Pooh
summary:
type: string
example: Famous children's book
related_books:
type: array
items:
$ref: "#/definitions/Book"
Error:
type: object
readOnly: true
properties:
code:
type: integer
format: int64
example: 400
message:
type: string
example: Unexpected error
required:
- message

View File

@@ -1,330 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "swagger.yaml for investigating an issue with spec.expandSchema",
"version": "0.0.1",
"description": "expander.go test for issue analysis, the spec derived from ODataWebV3.Northwind.Model and simplified for the analysis"
},
"schemes": [
"http"
],
"host": "localhost",
"basePath": "/modified_from_Northwind.svc",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/Employees": {
"get": {
"summary": "Get entities from Employees",
"responses": {
"200": {
"description": "Retrieved entities",
"schema": {
"title": "Collection of Employee",
"type": "object",
"properties": {
"value": {
"type": "array",
"items": {
"$ref": "#/definitions/Employee"
}
}
}
}
},
"default": {
"$ref": "#/responses/error"
}
}
}
}
},
"definitions": {
"Category": {
"type": "object",
"properties": {
"CategoryID": {
"type": "integer",
"format": "int32"
},
"CategoryName": {
"type": "string",
"maxLength": 15
},
"Products": {
"type": "array",
"items": {
"$ref": "#/definitions/Product"
}
}
},
"title": "Category"
},
"CustomerDemographic": {
"type": "object",
"properties": {
"CustomerTypeID": {
"type": "string",
"maxLength": 10
},
"CustomerDesc": {
"type": "string",
"example": "string"
},
"Customers": {
"type": "array",
"items": {
"$ref": "#/definitions/Customer"
}
}
},
"title": "CustomerDemographic"
},
"Customer": {
"type": "object",
"properties": {
"CustomerID": {
"type": "string",
"maxLength": 5
},
"CompanyName": {
"type": "string",
"maxLength": 40
},
"Orders": {
"type": "array",
"items": {
"$ref": "#/definitions/Order"
}
},
"CustomerDemographics": {
"type": "array",
"items": {
"$ref": "#/definitions/CustomerDemographic"
}
}
},
"title": "Customer"
},
"Employee": {
"type": "object",
"properties": {
"EmployeeID": {
"type": "integer",
"format": "int32"
},
"LastName": {
"type": "string",
"maxLength": 20
},
"FirstName": {
"type": "string",
"maxLength": 10
},
"Employees1": {
"type": "array",
"items": {
"$ref": "#/definitions/Employee"
}
},
"Employee1": {
"$ref": "#/definitions/Employee"
},
"Orders": {
"type": "array",
"items": {
"$ref": "#/definitions/Order"
}
},
"Territories": {
"type": "array",
"items": {
"$ref": "#/definitions/Territory"
}
}
},
"title": "Employee"
},
"Order_Detail": {
"type": "object",
"properties": {
"OrderID": {
"type": "integer",
"format": "int32"
},
"ProductID": {
"type": "integer",
"format": "int32"
},
"UnitPrice": {
"type": "number",
"format": "decimal",
"multipleOf": 0.0001
},
"Quantity": {
"type": "integer",
"format": "int16"
},
"Order": {
"$ref": "#/definitions/Order"
},
"Product": {
"$ref": "#/definitions/Product"
}
},
"title": "Order_Detail"
},
"Order": {
"type": "object",
"properties": {
"OrderID": {
"type": "integer",
"format": "int32"
},
"CustomerID": {
"type": "string",
"maxLength": 5,
"example": "string"
},
"Customer": {
"$ref": "#/definitions/Customer"
},
"Employee": {
"$ref": "#/definitions/Employee"
},
"Order_Details": {
"type": "array",
"items": {
"$ref": "#/definitions/Order_Detail"
}
},
"Shipper": {
"$ref": "#/definitions/Shipper"
}
},
"title": "Order"
},
"Product": {
"type": "object",
"properties": {
"ProductID": {
"type": "integer",
"format": "int32"
},
"ProductName": {
"type": "string",
"maxLength": 40
},
"Category": {
"$ref": "#/definitions/Category"
},
"Order_Details": {
"type": "array",
"items": {
"$ref": "#/definitions/Order_Detail"
}
},
"Supplier": {
"$ref": "#/definitions/Supplier"
}
},
"title": "Product"
},
"Region": {
"type": "object",
"properties": {
"RegionID": {
"type": "integer",
"format": "int32"
},
"RegionDescription": {
"type": "string",
"maxLength": 50
},
"Territories": {
"type": "array",
"items": {
"$ref": "#/definitions/Territory"
}
}
},
"title": "Region"
},
"Shipper": {
"type": "object",
"properties": {
"ShipperID": {
"type": "integer",
"format": "int32"
},
"CompanyName": {
"type": "string",
"maxLength": 40
},
"Orders": {
"type": "array",
"items": {
"$ref": "#/definitions/Order"
}
}
},
"title": "Shipper"
},
"Supplier": {
"type": "object",
"properties": {
"SupplierID": {
"type": "integer",
"format": "int32"
},
"CompanyName": {
"type": "string",
"maxLength": 40
},
"Products": {
"type": "array",
"items": {
"$ref": "#/definitions/Product"
}
}
},
"title": "Supplier"
},
"Territory": {
"type": "object",
"properties": {
"TerritoryID": {
"type": "string",
"maxLength": 20
},
"TerritoryDescription": {
"type": "string",
"maxLength": 50
},
"RegionID": {
"type": "integer",
"format": "int32"
},
"Region": {
"$ref": "#/definitions/Region"
},
"Employees": {
"type": "array",
"items": {
"$ref": "#/definitions/Employee"
}
}
},
"title": "Territory"
}
},
"responses": {
"error": {
"description": "Error"
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,85 +0,0 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"contact": {
"name": "wordnik api team",
"url": "http://developer.wordnik.com"
},
"license": {
"name": "Creative Commons 4.0 International",
"url": "http://creativecommons.org/licenses/by/4.0/"
}
},
"host": "petstore.swagger.wordnik.com",
"basePath": "/api",
"schemes": [
"http"
],
"paths": {
"/pets": {
"get": {
"tags": [ "Pet Operations" ],
"summary": "finds pets in the system",
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "NotCorrectRef"
}
},
"headers": {
"x-expires": {
"type": "string"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "NotCorrectRef"
}
}
}
}
}
},
"definitions": {
"Pet": {
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"Error": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View File

@@ -1,31 +0,0 @@
{
"swagger": "2.0",
"info": {
"version": "2.1.0",
"title": "Missing Item API"
},
"host": "item.com",
"basePath": "/missing/ref",
"schemes": [
"http"
],
"paths": {
"/employees": {
"get": {
"operationId": "LIST-Employees",
"summary": "List Employee Types",
"responses": {
"200": {
"description": "",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/employees-output"
}
}
}
}
}
}
}
}

View File

@@ -1,165 +0,0 @@
{
"input": {
"swagger": "2.0",
"info": {
"version": "1.0",
"title": "Continue On Error"
},
"paths": {
"/todos": {
"get": {
"responses": {
"200": {
"description": "List Todos",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/todo-full"
}
}
},
"404": {
"$ref": "#/responses/404"
}
}
}
}
},
"definitions": {
"todo-partial": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"completed": {
"type": "boolean"
}
}
},
"todo-full": {
"allOf": [
{
"$ref": "#/definitions/todo-partial"
},
{
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"completed_at": {
"type": "string"
},
"created_at": {
"type": "string"
},
"updated_at": {
"type": "string"
}
}
}
]
}
}
},
"expected": {
"swagger": "2.0",
"info": {
"title": "Continue On Error",
"version": "1.0"
},
"paths": {
"/todos": {
"get": {
"responses": {
"200": {
"description": "List Todos",
"schema": {
"type": "array",
"items": {
"allOf": [
{
"type": "object",
"properties": {
"completed": {
"type": "boolean"
},
"name": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"completed_at": {
"type": "string"
},
"created_at": {
"type": "string"
},
"id": {
"type": "integer"
},
"updated_at": {
"type": "string"
}
}
}
]
}
}
},
"404": {}
}
}
}
},
"definitions": {
"todo-full": {
"allOf": [
{
"type": "object",
"properties": {
"completed": {
"type": "boolean"
},
"name": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"completed_at": {
"type": "string"
},
"created_at": {
"type": "string"
},
"id": {
"type": "integer"
},
"updated_at": {
"type": "string"
}
}
}
]
},
"todo-partial": {
"type": "object",
"properties": {
"completed": {
"type": "boolean"
},
"name": {
"type": "string"
}
}
}
}
}
}

View File

@@ -1,124 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "Swagger Sample",
"description": "Sample API Playground.",
"version": "1.0.0"
},
"basePath": "/v1",
"schemes": [
"http"
],
"consumes": [
"application/vdn.sample.v1+json"
],
"produces": [
"application/vdn.sample.v1+json"
],
"paths": {
"/books": {
"get": {
"summary": "List all books",
"operationId": "listBooks",
"tags": [
"books"
],
"responses": {
"200": {
"headers": {
"Link": {
"type": "string"
}
},
"description": "An array of books",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Book"
}
}
},
"default": {
"description": "generic error response",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
}
},
"definitions": {
"Store": {
"type": "object",
"properties": {
"title": {
"type": "string",
"example": "Book Shop"
},
"categories": {
"type": "array",
"items": {
"$ref": "#/definitions/Category"
}
}
}
},
"Category": {
"type": "object",
"properties": {
"title": {
"type": "string",
"example": "Drama"
},
"books": {
"type": "array",
"items": {
"$ref": "#/definitions/Book"
}
}
}
},
"Book": {
"type": "object",
"required": [
"title",
"summary"
],
"properties": {
"title": {
"type": "string",
"example": "Winnie the Pooh"
},
"summary": {
"type": "string",
"example": "Famous children's book"
},
"related_books": {
"type": "array",
"items": {
"$ref": "#/definitions/Book"
}
}
}
},
"Error": {
"type": "object",
"readOnly": true,
"properties": {
"code": {
"type": "integer",
"format": "int64",
"example": 400
},
"message": {
"type": "string",
"example": "Unexpected error"
}
},
"required": [
"message"
]
}
}
}

View File

@@ -1,25 +0,0 @@
{
"parameters": {
"id": {
"type": "integer",
"format": "int64",
"in": "path",
"required": true
},
"tag": {
"type": "string",
"in": "query",
"required": false
},
"query": {
"$ref": "#/parameters/tag"
}
},
"paths": {
"/cars/{id}": {
"parameters": [
{ "$ref": "#/parameters/id"}
]
}
}
}

View File

@@ -1,127 +0,0 @@
{
"definitions": {
"car": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"make": {
"type": "string"
},
"brand": {
"$ref": "#/definitions/brand"
}
}
},
"tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"value": {
"type": "string"
}
}
},
"brand": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
}
},
"truck": {
"$ref": "#/definitions/car"
},
"batch": {
"items": {
"$ref": "#/definitions/brand"
}
},
"batch2": {
"items": [
{
"$ref": "#/definitions/brand"
},
{
"$ref": "#/definitions/tag"
}
]
},
"allofBoth": {
"allOf": [
{
"$ref": "#/definitions/brand"
},
{
"$ref": "#/definitions/tag"
}
]
},
"anyofBoth": {
"anyOf": [
{
"$ref": "#/definitions/brand"
},
{
"$ref": "#/definitions/tag"
}
]
},
"oneofBoth": {
"oneOf": [
{
"$ref": "#/definitions/brand"
},
{
"$ref": "#/definitions/tag"
}
]
},
"notSomething": {
"not": {
"$ref": "#/definitions/tag"
}
},
"withAdditional": {
"additionalProperties": {
"$ref": "#/definitions/tag"
}
},
"withPattern": {
"patternProperties": {
"^x-ab": {
"$ref": "#/definitions/tag"
}
}
},
"withAdditionalItems": {
"additionalItems": {
"$ref": "#/definitions/tag"
}
},
"deps": {
"dependencies": {
"something": {
"$ref": "#/definitions/tag"
}
}
},
"defined": {
"definitions": {
"something": {
"$ref": "#/definitions/tag"
}
}
}
}
}

View File

@@ -1,161 +0,0 @@
{
"definitions": {
"car": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"make": {
"type": "string"
},
"brand": {
"items": {
"$ref": "#/definitions/brand"
}
}
}
},
"tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"value": {
"type": "string"
}
}
},
"brand": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
}
},
"truck": {
"items": {
"$ref": "#/definitions/car"
}
},
"batch": {
"items": {
"items": {
"$ref": "#/definitions/brand"
}
}
},
"batch2": {
"items": [
{
"items": {
"$ref": "#/definitions/brand"
}
},
{
"items": {
"$ref": "#/definitions/tag"
}
}
]
},
"allofBoth": {
"allOf": [
{
"items": {
"$ref": "#/definitions/brand"
}
},
{
"items": {
"$ref": "#/definitions/tag"
}
}
]
},
"anyofBoth": {
"anyOf": [
{
"items": {
"$ref": "#/definitions/brand"
}
},
{
"items": {
"$ref": "#/definitions/tag"
}
}
]
},
"oneofBoth": {
"oneOf": [
{
"items": {
"$ref": "#/definitions/brand"
}
},
{
"items": {
"$ref": "#/definitions/tag"
}
}
]
},
"notSomething": {
"not": {
"items": {
"$ref": "#/definitions/tag"
}
}
},
"withAdditional": {
"additionalProperties": {
"items": {
"$ref": "#/definitions/tag"
}
}
},
"withPattern": {
"patternProperties": {
"^x-ab": {
"items": {
"$ref": "#/definitions/tag"
}
}
}
},
"withAdditionalItems": {
"additionalItems": {
"items": {
"$ref": "#/definitions/tag"
}
}
},
"deps": {
"dependencies": {
"something": {
"items": {
"$ref": "#/definitions/tag"
}
}
}
},
"defined": {
"definitions": {
"something": {
"items": {
"$ref": "#/definitions/tag"
}
}
}
}
}
}

View File

@@ -1,18 +0,0 @@
{
"properties": {
"id": {
"format": "int64",
"readOnly": true,
"type": "integer"
},
"title": {
"maxLength": 80,
"minLength": 2,
"type": "string"
}
},
"required": [
"title"
],
"type": "object"
}

View File

@@ -1,12 +0,0 @@
type: object
required:
- title
properties:
id:
type: integer
format: uint64
readOnly: true
title:
type: string
minLength: 2
maxLength: 80

View File

@@ -1,46 +0,0 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "item.api.local",
"info": {
"description": "Item API",
"title": "Item API",
"version": "1.0.0"
},
"paths": {
"/item": {
"get": {
"operationId": "GetItem",
"responses": {
"200": {
"description": "item detail response",
"schema": {
"$ref": "item.json"
}
}
}
}
}
},
"produces": [
"application/json"
],
"schemes": [
"http"
],
"security": [
{
"key": []
}
],
"securityDefinitions": {
"key": {
"in": "header",
"name": "x-item-token",
"type": "apiKey"
}
},
"swagger": "2.0"
}

View File

@@ -1,30 +0,0 @@
---
swagger: "2.0"
info:
title: Item API
description: Item API
version: "1.0.0"
host: item.api.local
basePath: /v1
securityDefinitions:
key:
type: apiKey
name: x-item-token
in: header
security:
- key: []
consumes:
- application/json
produces:
- application/json
schemes:
- http
paths:
/item:
get:
operationId: GetItem
responses:
200:
description: item detail response
schema:
"$ref": "item2.yaml"

File diff suppressed because one or more lines are too long

View File

@@ -1,23 +0,0 @@
{
"item": {
"type": "object",
"required": [
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "uint64",
"readOnly": true
},
"title": {
"type": "string",
"minLength": 2,
"maxLength": 80
},
"subitem": {
"$ref": "item.json#/item"
}
}
}
}

View File

@@ -1,23 +0,0 @@
{
"item": {
"type": "object",
"required": [
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "uint64",
"readOnly": true
},
"title": {
"type": "string",
"minLength": 2,
"maxLength": 80
},
"subitem": {
"$ref": "#/item"
}
}
}
}

View File

@@ -1,23 +0,0 @@
{
"item": {
"type": "object",
"required": [
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "uint64",
"readOnly": true
},
"title": {
"type": "string",
"minLength": 2,
"maxLength": 80
},
"subitem": {
"$ref": "item4.json#/item"
}
}
}
}

View File

@@ -1,57 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "Item API",
"description": "Item API",
"version": "1.0.0"
},
"host": "item.api.local",
"basePath": "/v1",
"securityDefinitions": {
"key": {
"type": "apiKey",
"name": "x-item-token",
"in": "header"
}
},
"security": [
{
"key": []
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http"
],
"responses": {
"itemResponse": {
"description": "Item",
"schema": {
"$ref": "item.json#/item"
}
}
},
"paths": {
"/item": {
"get": {
"operationId": "GetItem",
"responses": {
"200": {
"description": "item detail response",
"schema": {
"$ref": "item.json#/item"
}
},
"default": {
"$ref": "#/responses/itemResponse"
}
}
}
}
}
}

View File

@@ -1,57 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "Item API",
"description": "Item API",
"version": "1.0.0"
},
"host": "item.api.local",
"basePath": "/v1",
"securityDefinitions": {
"key": {
"type": "apiKey",
"name": "x-item-token",
"in": "header"
}
},
"security": [
{
"key": []
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http"
],
"responses": {
"itemResponse": {
"description": "Item",
"schema": {
"$ref": "item2.json#/item"
}
}
},
"paths": {
"/item": {
"get": {
"operationId": "GetItem",
"responses": {
"200": {
"description": "item detail response",
"schema": {
"$ref": "item2.json#/item"
}
},
"default": {
"$ref": "#/responses/itemResponse"
}
}
}
}
}
}

View File

@@ -1,51 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "Item API",
"description": "Item API",
"version": "1.0.0"
},
"host": "item.api.local",
"basePath": "/v1",
"securityDefinitions": {
"key": {
"type": "apiKey",
"name": "x-item-token",
"in": "header"
}
},
"security": [
{
"key": []
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http"
],
"paths": {
"/item": {
"get": {
"operationId": "GetItem",
"responses": {
"200": {
"description": "item detail response",
"schema": {
"$ref": "#/definitions/myItems"
}
}
}
}
}
},
"definitions": {
"myItems": {
"$ref": "item.json#/item"
}
}
}

View File

@@ -1,59 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "Item API",
"description": "Item API",
"version": "1.0.0"
},
"host": "item.api.local",
"basePath": "/v1",
"securityDefinitions": {
"key": {
"type": "apiKey",
"name": "x-item-token",
"in": "header"
}
},
"security": [
{
"key": []
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http"
],
"parameters": {
"itemParameter": {
"description": "Item",
"schema": {
"$ref": "item4.json#/item"
}
}
},
"paths": {
"/item": {
"get": {
"operationId": "GetItem",
"parameters": [
{
"$ref": "#/parameters/itemParameter"
}
],
"responses": {
"200": {
"description": "item detail response",
"schema": {
"$ref": "item4.json#/item"
}
}
}
}
}
}
}

View File

@@ -1,245 +0,0 @@
{
"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"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.wordnik.com",
"basePath": "/api",
"schemes": ["http"],
"consumes": ["application/json"],
"produces": ["application/json"],
"parameters": {
"idParam": {
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
},
"tag": {
"type": "string",
"in": "query",
"required": false
},
"query": {
"$ref": "#/parameters/tag"
}
},
"responses": {
"petResponse": {
"description": "pet response",
"schema": {
"$ref": "pet/pet.json#/definitions/pet"
}
},
"stringResponse": {
"descripion": "string response",
"schema": {
"type": "string"
}
},
"anotherPet": {
"$ref": "pet/pet.json#/responses/anotherPet"
},
"circularA": {
"$ref": "pet/pet.json#/responses/circularB"
}
},
"paths": {
"/": {
"get": {
"operationId": "indexStuff",
"responses": {
"default": {
"$ref": "#/responses/stringResponse"
},
"200": {
"$ref": "#/responses/anotherPet"
}
}
}
},
"/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": "pet/pet.json#/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/petInput"
}
}
],
"responses": {
"200": { "$ref": "#/responses/petResponse" },
"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": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"200": {
"$ref": "#/responses/petResponse"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"pet": {
"required": ["id", "name"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"petInput": {
"allOf": [
{
"$ref": "pet/pet.json#/definitions/pet"
},
{
"required": ["name"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"errorModel": {
"required": ["code", "message"],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View File

@@ -1,42 +0,0 @@
{
"responses": {
"petResponse": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/pet"
}
},
"stringResponse": {
"descripion": "string response",
"schema": {
"type": "string"
}
},
"circularB": {
"$ref": "#/responses/circularC"
},
"circularC": {
"$ref": "../all-the-things.json#/responses/circularA"
},
"anotherPet": {
"$ref": "#/responses/petResponse"
}
},
"definitions": {
"pet": {
"required": ["id", "name"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
}
}
}

View File

@@ -1,6 +0,0 @@
{
"type":"array",
"items": {
"type": "string"
}
}

View File

@@ -1,3 +0,0 @@
{
"type": "string"
}

View File

@@ -1,224 +0,0 @@
{
"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"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.wordnik.com",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": {
"idParam": {
"name": "id",
"in": "path",
"description": "ID of pet to fetch",
"required": true,
"type": "integer",
"format": "int64"
}
},
"responses": {
"petResponse": {
"description": "pet response",
"schema": {
"$ref": "#/definitions/pet"
}
}
},
"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/petInput"
}
}
],
"responses": {
"200": { "$ref": "#/responses/petResponse" },
"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": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"200": {
"$ref": "#/responses/petResponse"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
},
"delete": {
"description": "deletes a single pet based on the ID supplied",
"operationId": "deletePet",
"parameters": [
{
"$ref": "#/parameters/idParam"
}
],
"responses": {
"204": {
"description": "pet deleted"
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"pet": {
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"petInput": {
"allOf": [
{
"$ref": "pet"
},
{
"required": [
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
}
}
]
},
"errorModel": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}

View File

@@ -1,14 +0,0 @@
{
"id": "http://localhost:1234",
"items": {
"id": "deeper/",
"items": {
"$ref": "stringProp.json"
}
},
"definitions": {
"bool": {
"$ref": "boolProp.json"
}
}
}

View File

@@ -1,9 +0,0 @@
{
"id": "http://localhost:1234",
"items": {
"id": "deeper/",
"items": {
"$ref": "arrayProp.json#/items"
}
}
}

View File

@@ -1,103 +0,0 @@
{
"swagger": "2.0",
"info": {
"version": "1.0",
"title": "To-do Demo",
"description":
"### Notes:\n\nThis OAS2 (Swagger 2) specification defines common models and responses, that other specifications may reference.\n\nFor example, check out the user poperty in the main.oas2 todo-partial model - it references the user model in this specification!\n\nLikewise, the main.oas2 operations reference the shared error responses in this common specification.",
"contact": {
"name": "Stoplight",
"url": "https://stoplight.io"
},
"license": {
"name": "MIT"
}
},
"host": "example.com",
"securityDefinitions": {},
"paths": {},
"responses": {
"401": {
"description": "",
"schema": {
"$ref": "#/definitions/error-response"
},
"examples": {
"application/json": {
"status": "401",
"error": "Not Authorized"
}
}
},
"403": {
"description": "",
"schema": {
"$ref": "#/definitions/error-response"
},
"examples": {
"application/json": {
"status": "403",
"error": "Forbbiden"
}
}
},
"404": {
"description": "",
"schema": {
"$ref": "#/definitions/error-response"
},
"examples": {
"application/json": {
"status": "404",
"error": "Not Found"
}
}
},
"500": {
"description": "",
"schema": {
"$ref": "#/definitions/error-response"
},
"examples": {
"application/json": {
"status": "500",
"error": "Server Error"
}
}
}
},
"definitions": {
"user": {
"title": "User",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The user's full name."
},
"age": {
"type": "number",
"minimum": 0,
"maximum": 150
},
"error": {
"$ref": "#/definitions/error-response"
}
},
"required": ["name", "age"]
},
"error-response": {
"type": "object",
"title": "Error Response",
"properties": {
"status": {
"type": "string"
},
"error": {
"type": "string"
}
},
"required": ["status", "error"]
}
}
}

View File

@@ -1,346 +0,0 @@
{
"swagger": "2.0",
"info": {
"version": "1.0",
"title": "To-do Demo",
"description": "This OAS2 (Swagger 2) file represents a real API that lives at http://todos.stoplight.io.\n\nFor authentication information, click the apikey security scheme in the editor sidebar.",
"contact": {
"name": "Stoplight",
"url": "https://stoplight.io"
},
"license": {
"name": "MIT"
}
},
"host": "todos.stoplight.io",
"schemes": ["http"],
"consumes": ["application/json"],
"produces": ["application/json"],
"securityDefinitions": {
"Basic": {
"type": "basic"
},
"API Key": {
"type": "apiKey",
"name": "apikey",
"in": "query"
}
},
"paths": {
"/todos/{todoId}": {
"parameters": [{
"name": "todoId",
"in": "path",
"required": true,
"type": "string"
}],
"get": {
"operationId": "GET_todo",
"summary": "Get Todo",
"tags": ["Todos"],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/todo-full"
},
"examples": {
"application/json": {
"id": 1,
"name": "get food",
"completed": false,
"completed_at": "1955-04-23T13:22:52.685Z",
"created_at": "1994-11-05T03:26:51.471Z",
"updated_at": "1989-07-29T11:30:06.701Z"
},
"/todos/foobar": "{\n\t\"foo\": \"bar\"\n}\n",
"/todos/chores": {
"id": 9000,
"name": "Do Chores",
"completed": false,
"created_at": "2014-08-28T14:14:28.494Z",
"updated_at": "2014-08-28T14:14:28.494Z"
},
"new": {
"name": "esse qui proident labore",
"completed": null,
"id": 920778,
"completed_at": "2014-01-07T07:49:55.123Z",
"created_at": "1948-04-21T12:04:21.282Z",
"updated_at": "1951-12-19T11:10:34.039Z",
"user": {
"name": "irure deserunt fugiat",
"age": 121.45395681110494
},
"float": -47990796.228164576
}
}
},
"404": {
"$ref": "./todos.common.json#/responses/404"
},
"500": {
"$ref": "./todos.common.json#/responses/500"
}
},
"parameters": [{
"in": "query",
"name": "",
"type": "string"
}]
},
"put": {
"operationId": "PUT_todos",
"summary": "Update Todo",
"tags": ["Todos"],
"parameters": [{
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/todo-partial",
"example": {
"name": "my todo's new name",
"completed": false
}
}
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/todo-full"
},
"examples": {
"application/json": {
"id": 9000,
"name": "It's Over 9000!!!",
"completed": true,
"completed_at": null,
"created_at": "2014-08-28T14:14:28.494Z",
"updated_at": "2015-08-28T14:14:28.494Z"
}
}
},
"401": {
"$ref": "./todos.common.json#/responses/401"
},
"404": {
"$ref": "./todos.common.json#/responses/404"
},
"500": {
"$ref": "./todos.common.json#/responses/500"
}
},
"security": [{
"Basic": []
},
{
"API Key": []
}
]
},
"delete": {
"operationId": "DELETE_todo",
"summary": "Delete Todo",
"tags": ["Todos"],
"responses": {
"204": {
"description": ""
},
"401": {
"$ref": "./todos.common.json#/responses/401"
},
"404": {
"$ref": "./todos.common.json#/responses/404"
},
"500": {
"$ref": "./todos.common.json#/responses/500"
}
},
"security": [{
"Basic": []
},
{
"API Key": []
}
]
}
},
"/todos": {
"post": {
"operationId": "POST_todos",
"summary": "Create Todo",
"tags": ["Todos"],
"parameters": [{
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/todo-partial",
"example": {
"name": "my todo's name",
"completed": false
}
}
}],
"responses": {
"201": {
"description": "",
"schema": {
"$ref": "#/definitions/todo-full"
},
"examples": {
"application/json": {
"id": 9000,
"name": "It's Over 9000!!!",
"completed": null,
"completed_at": null,
"created_at": "2014-08-28T14:14:28.494Z",
"updated_at": "2014-08-28T14:14:28.494Z"
},
"/todos/chores": {
"id": 9000,
"name": "Do Chores",
"completed": false,
"created_at": "2014-08-28T14:14:28.494Z",
"updated_at": "2014-08-28T14:14:28.494Z"
}
}
},
"401": {
"$ref": "./todos.common.json#/responses/401"
},
"500": {
"$ref": "./todos.common.json#/responses/500"
}
},
"security": [{
"API Key": []
},
{
"Basic": []
}
],
"description": "This creates a Todo object.\n\nTesting `inline code`."
},
"get": {
"operationId": "GET_todos",
"summary": "List Todos",
"tags": ["Todos"],
"parameters": [{
"$ref": "#/parameters/limit"
},
{
"$ref": "#/parameters/skip"
}
],
"responses": {
"200": {
"description": "",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/todo-full"
}
},
"examples": {
"application/json": [{
"id": 1,
"name": "design the thingz",
"completed": true
},
{
"id": 2,
"name": "mock the thingz",
"completed": true
},
{
"id": 3,
"name": "code the thingz",
"completed": false
}
],
"empty": []
},
"headers": {
"foo": {
"type": "string",
"default": "bar"
}
}
},
"500": {
"$ref": "./todos.common.json#/responses/500"
}
},
"description": ""
}
}
},
"parameters": {
"limit": {
"name": "limit",
"in": "query",
"description": "This is how it works.",
"required": false,
"type": "integer",
"maximum": 100
},
"skip": {
"name": "skip",
"in": "query",
"required": false,
"type": "string"
}
},
"definitions": {
"todo-partial": {
"title": "Todo Partial",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"completed": {
"type": ["boolean", "null"]
}
},
"required": ["name", "completed"]
},
"todo-full": {
"title": "Todo Full",
"allOf": [{
"$ref": "#/definitions/todo-partial"
},
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 0,
"maximum": 1000000
},
"completed_at": {
"type": ["string", "null"],
"format": "date-time"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
},
"user": {
"$ref": "./todos.common.json#/definitions/user"
}
},
"required": ["id", "user"]
}
]
}
},
"tags": [{
"name": "Todos"
}]
}

View File

@@ -1,16 +0,0 @@
module github.com/go-openapi/spec
require (
github.com/PuerkitoBio/purell v1.1.0 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-openapi/jsonpointer v0.17.0
github.com/go-openapi/jsonreference v0.17.0
github.com/go-openapi/swag v0.17.0
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
golang.org/x/net v0.0.0-20181005035420-146acd28ed58 // indirect
golang.org/x/text v0.3.0 // indirect
gopkg.in/yaml.v2 v2.2.1
)

View File

@@ -1,22 +0,0 @@
github.com/PuerkitoBio/purell v1.1.0 h1:rmGxhojJlM0tuKtfdvliR84CFHljx9ag64t2xmVkjK4=
github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/jsonpointer v0.17.0 h1:Bpl2DtZ6k7wKqfFs7e+4P08+M9I3FQgn09a1UsRUQbk=
github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonreference v0.17.0 h1:d/o7/fsLWWQZACbihvZxcyLQ59jfUVs7WOJv/ak7T7A=
github.com/go-openapi/jsonreference v0.17.0/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/swag v0.17.0 h1:7wu+dZ5k83kvUWeAb+WUkFiUhDzwGqzTR/NhWzeo1JU=
github.com/go-openapi/swag v0.17.0/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/net v0.0.0-20181005035420-146acd28ed58 h1:otZG8yDCO4LVps5+9bxOeNiCvgmOyt96J3roHTYs7oE=
golang.org/x/net v0.0.0-20181005035420-146acd28ed58/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -1,193 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/swag"
)
// HeaderProps describes a response header
type HeaderProps struct {
Description string `json:"description,omitempty"`
}
// Header describes a header for a response of the API
//
// For more information: http://goo.gl/8us55a#headerObject
type Header struct {
CommonValidations
SimpleSchema
VendorExtensible
HeaderProps
}
// ResponseHeader creates a new header instance for use in a response
func ResponseHeader() *Header {
return new(Header)
}
// WithDescription sets the description on this response, allows for chaining
func (h *Header) WithDescription(description string) *Header {
h.Description = description
return h
}
// Typed a fluent builder method for the type of parameter
func (h *Header) Typed(tpe, format string) *Header {
h.Type = tpe
h.Format = format
return h
}
// CollectionOf a fluent builder method for an array item
func (h *Header) CollectionOf(items *Items, format string) *Header {
h.Type = "array"
h.Items = items
h.CollectionFormat = format
return h
}
// WithDefault sets the default value on this item
func (h *Header) WithDefault(defaultValue interface{}) *Header {
h.Default = defaultValue
return h
}
// WithMaxLength sets a max length value
func (h *Header) WithMaxLength(max int64) *Header {
h.MaxLength = &max
return h
}
// WithMinLength sets a min length value
func (h *Header) WithMinLength(min int64) *Header {
h.MinLength = &min
return h
}
// WithPattern sets a pattern value
func (h *Header) WithPattern(pattern string) *Header {
h.Pattern = pattern
return h
}
// WithMultipleOf sets a multiple of value
func (h *Header) WithMultipleOf(number float64) *Header {
h.MultipleOf = &number
return h
}
// WithMaximum sets a maximum number value
func (h *Header) WithMaximum(max float64, exclusive bool) *Header {
h.Maximum = &max
h.ExclusiveMaximum = exclusive
return h
}
// WithMinimum sets a minimum number value
func (h *Header) WithMinimum(min float64, exclusive bool) *Header {
h.Minimum = &min
h.ExclusiveMinimum = exclusive
return h
}
// WithEnum sets a the enum values (replace)
func (h *Header) WithEnum(values ...interface{}) *Header {
h.Enum = append([]interface{}{}, values...)
return h
}
// WithMaxItems sets the max items
func (h *Header) WithMaxItems(size int64) *Header {
h.MaxItems = &size
return h
}
// WithMinItems sets the min items
func (h *Header) WithMinItems(size int64) *Header {
h.MinItems = &size
return h
}
// UniqueValues dictates that this array can only have unique items
func (h *Header) UniqueValues() *Header {
h.UniqueItems = true
return h
}
// AllowDuplicates this array can have duplicates
func (h *Header) AllowDuplicates() *Header {
h.UniqueItems = false
return h
}
// MarshalJSON marshal this to JSON
func (h Header) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(h.CommonValidations)
if err != nil {
return nil, err
}
b2, err := json.Marshal(h.SimpleSchema)
if err != nil {
return nil, err
}
b3, err := json.Marshal(h.HeaderProps)
if err != nil {
return nil, err
}
return swag.ConcatJSON(b1, b2, b3), nil
}
// UnmarshalJSON unmarshals this header from JSON
func (h *Header) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &h.CommonValidations); err != nil {
return err
}
if err := json.Unmarshal(data, &h.SimpleSchema); err != nil {
return err
}
if err := json.Unmarshal(data, &h.VendorExtensible); err != nil {
return err
}
return json.Unmarshal(data, &h.HeaderProps)
}
// JSONLookup look up a value by the json property name
func (h Header) JSONLookup(token string) (interface{}, error) {
if ex, ok := h.Extensions[token]; ok {
return &ex, nil
}
r, _, err := jsonpointer.GetForToken(h.CommonValidations, token)
if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
return nil, err
}
if r != nil {
return r, nil
}
r, _, err = jsonpointer.GetForToken(h.SimpleSchema, token)
if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
return nil, err
}
if r != nil {
return r, nil
}
r, _, err = jsonpointer.GetForToken(h.HeaderProps, token)
return r, err
}

View File

@@ -1,126 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func float64Ptr(f float64) *float64 {
return &f
}
func int64Ptr(f int64) *int64 {
return &f
}
var header = Header{
VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{
"x-framework": "swagger-go",
}},
HeaderProps: HeaderProps{Description: "the description of this header"},
SimpleSchema: SimpleSchema{
Items: &Items{
Refable: Refable{Ref: MustCreateRef("Cat")},
},
Type: "string",
Format: "date",
Default: "8",
},
CommonValidations: CommonValidations{
Maximum: float64Ptr(100),
ExclusiveMaximum: true,
ExclusiveMinimum: true,
Minimum: float64Ptr(5),
MaxLength: int64Ptr(100),
MinLength: int64Ptr(5),
Pattern: "\\w{1,5}\\w+",
MaxItems: int64Ptr(100),
MinItems: int64Ptr(5),
UniqueItems: true,
MultipleOf: float64Ptr(5),
Enum: []interface{}{"hello", "world"},
},
}
var headerJSON = `{
"items": {
"$ref": "Cat"
},
"x-framework": "swagger-go",
"description": "the description of this header",
"maximum": 100,
"minimum": 5,
"exclusiveMaximum": true,
"exclusiveMinimum": true,
"maxLength": 100,
"minLength": 5,
"pattern": "\\w{1,5}\\w+",
"maxItems": 100,
"minItems": 5,
"uniqueItems": true,
"multipleOf": 5,
"enum": ["hello", "world"],
"type": "string",
"format": "date",
"default": "8"
}`
func TestIntegrationHeader(t *testing.T) {
var actual Header
if assert.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) {
assert.EqualValues(t, actual, header)
}
assertParsesJSON(t, headerJSON, header)
}
func TestJSONLookupHeader(t *testing.T) {
var def string
res, err := header.JSONLookup("default")
if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, def, res) {
t.FailNow()
return
}
def = res.(string)
assert.Equal(t, "8", def)
var x *interface{}
res, err = header.JSONLookup("x-framework")
if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, x, res) {
t.FailNow()
return
}
x = res.(*interface{})
assert.EqualValues(t, "swagger-go", *x)
res, err = header.JSONLookup("unknown")
if !assert.Error(t, err) || !assert.Nil(t, res) {
t.FailNow()
return
}
var max *float64
res, err = header.JSONLookup("maximum")
if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, max, res) {
t.FailNow()
return
}
max = res.(*float64)
assert.Equal(t, float64(100), *max)
}

View File

@@ -1,168 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/swag"
)
// Extensions vendor specific extensions
type Extensions map[string]interface{}
// Add adds a value to these extensions
func (e Extensions) Add(key string, value interface{}) {
realKey := strings.ToLower(key)
e[realKey] = value
}
// GetString gets a string value from the extensions
func (e Extensions) GetString(key string) (string, bool) {
if v, ok := e[strings.ToLower(key)]; ok {
str, ok := v.(string)
return str, ok
}
return "", false
}
// GetBool gets a string value from the extensions
func (e Extensions) GetBool(key string) (bool, bool) {
if v, ok := e[strings.ToLower(key)]; ok {
str, ok := v.(bool)
return str, ok
}
return false, false
}
// GetStringSlice gets a string value from the extensions
func (e Extensions) GetStringSlice(key string) ([]string, bool) {
if v, ok := e[strings.ToLower(key)]; ok {
arr, isSlice := v.([]interface{})
if !isSlice {
return nil, false
}
var strs []string
for _, iface := range arr {
str, isString := iface.(string)
if !isString {
return nil, false
}
strs = append(strs, str)
}
return strs, ok
}
return nil, false
}
// VendorExtensible composition block.
type VendorExtensible struct {
Extensions Extensions
}
// AddExtension adds an extension to this extensible object
func (v *VendorExtensible) AddExtension(key string, value interface{}) {
if value == nil {
return
}
if v.Extensions == nil {
v.Extensions = make(map[string]interface{})
}
v.Extensions.Add(key, value)
}
// MarshalJSON marshals the extensions to json
func (v VendorExtensible) MarshalJSON() ([]byte, error) {
toser := make(map[string]interface{})
for k, v := range v.Extensions {
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-") {
toser[k] = v
}
}
return json.Marshal(toser)
}
// UnmarshalJSON for this extensible object
func (v *VendorExtensible) UnmarshalJSON(data []byte) error {
var d map[string]interface{}
if err := json.Unmarshal(data, &d); err != nil {
return err
}
for k, vv := range d {
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-") {
if v.Extensions == nil {
v.Extensions = map[string]interface{}{}
}
v.Extensions[k] = vv
}
}
return nil
}
// InfoProps the properties for an info definition
type InfoProps struct {
Description string `json:"description,omitempty"`
Title string `json:"title,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact *ContactInfo `json:"contact,omitempty"`
License *License `json:"license,omitempty"`
Version string `json:"version,omitempty"`
}
// Info object provides metadata about the API.
// The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience.
//
// For more information: http://goo.gl/8us55a#infoObject
type Info struct {
VendorExtensible
InfoProps
}
// JSONLookup look up a value by the json property name
func (i Info) JSONLookup(token string) (interface{}, error) {
if ex, ok := i.Extensions[token]; ok {
return &ex, nil
}
r, _, err := jsonpointer.GetForToken(i.InfoProps, token)
return r, err
}
// MarshalJSON marshal this to JSON
func (i Info) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(i.InfoProps)
if err != nil {
return nil, err
}
b2, err := json.Marshal(i.VendorExtensible)
if err != nil {
return nil, err
}
return swag.ConcatJSON(b1, b2), nil
}
// UnmarshalJSON marshal this from JSON
func (i *Info) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &i.InfoProps); err != nil {
return err
}
if err := json.Unmarshal(data, &i.VendorExtensible); err != nil {
return err
}
return nil
}

View File

@@ -1,65 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
var infoJSON = `{
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"title": "Swagger Sample API",
"termsOfService": "http://helloreverb.com/terms/",
"contact": {
"name": "wordnik api team",
"url": "http://developer.wordnik.com"
},
"license": {
"name": "Creative Commons 4.0 International",
"url": "http://creativecommons.org/licenses/by/4.0/"
},
"version": "1.0.9-abcd",
"x-framework": "go-swagger"
}`
var info = Info{
InfoProps: InfoProps{
Version: "1.0.9-abcd",
Title: "Swagger Sample API",
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: &ContactInfo{Name: "wordnik api team", URL: "http://developer.wordnik.com"},
License: &License{Name: "Creative Commons 4.0 International", URL: "http://creativecommons.org/licenses/by/4.0/"},
},
VendorExtensible: VendorExtensible{map[string]interface{}{"x-framework": "go-swagger"}},
}
func TestIntegrationInfo_Serialize(t *testing.T) {
b, err := json.MarshalIndent(info, "", "\t")
if assert.NoError(t, err) {
assert.Equal(t, infoJSON, string(b))
}
}
func TestIntegrationInfo_Deserialize(t *testing.T) {
actual := Info{}
err := json.Unmarshal([]byte(infoJSON), &actual)
if assert.NoError(t, err) {
assert.EqualValues(t, info, actual)
}
}

View File

@@ -1,233 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/swag"
)
// SimpleSchema describe swagger simple schemas for parameters and headers
type SimpleSchema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Items *Items `json:"items,omitempty"`
CollectionFormat string `json:"collectionFormat,omitempty"`
Default interface{} `json:"default,omitempty"`
Example interface{} `json:"example,omitempty"`
}
// TypeName return the type (or format) of a simple schema
func (s *SimpleSchema) TypeName() string {
if s.Format != "" {
return s.Format
}
return s.Type
}
// ItemsTypeName yields the type of items in a simple schema array
func (s *SimpleSchema) ItemsTypeName() string {
if s.Items == nil {
return ""
}
return s.Items.TypeName()
}
// CommonValidations describe common JSON-schema validations
type CommonValidations struct {
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
MaxLength *int64 `json:"maxLength,omitempty"`
MinLength *int64 `json:"minLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
MaxItems *int64 `json:"maxItems,omitempty"`
MinItems *int64 `json:"minItems,omitempty"`
UniqueItems bool `json:"uniqueItems,omitempty"`
MultipleOf *float64 `json:"multipleOf,omitempty"`
Enum []interface{} `json:"enum,omitempty"`
}
// Items a limited subset of JSON-Schema's items object.
// It is used by parameter definitions that are not located in "body".
//
// For more information: http://goo.gl/8us55a#items-object
type Items struct {
Refable
CommonValidations
SimpleSchema
VendorExtensible
}
// NewItems creates a new instance of items
func NewItems() *Items {
return &Items{}
}
// Typed a fluent builder method for the type of item
func (i *Items) Typed(tpe, format string) *Items {
i.Type = tpe
i.Format = format
return i
}
// CollectionOf a fluent builder method for an array item
func (i *Items) CollectionOf(items *Items, format string) *Items {
i.Type = "array"
i.Items = items
i.CollectionFormat = format
return i
}
// WithDefault sets the default value on this item
func (i *Items) WithDefault(defaultValue interface{}) *Items {
i.Default = defaultValue
return i
}
// WithMaxLength sets a max length value
func (i *Items) WithMaxLength(max int64) *Items {
i.MaxLength = &max
return i
}
// WithMinLength sets a min length value
func (i *Items) WithMinLength(min int64) *Items {
i.MinLength = &min
return i
}
// WithPattern sets a pattern value
func (i *Items) WithPattern(pattern string) *Items {
i.Pattern = pattern
return i
}
// WithMultipleOf sets a multiple of value
func (i *Items) WithMultipleOf(number float64) *Items {
i.MultipleOf = &number
return i
}
// WithMaximum sets a maximum number value
func (i *Items) WithMaximum(max float64, exclusive bool) *Items {
i.Maximum = &max
i.ExclusiveMaximum = exclusive
return i
}
// WithMinimum sets a minimum number value
func (i *Items) WithMinimum(min float64, exclusive bool) *Items {
i.Minimum = &min
i.ExclusiveMinimum = exclusive
return i
}
// WithEnum sets a the enum values (replace)
func (i *Items) WithEnum(values ...interface{}) *Items {
i.Enum = append([]interface{}{}, values...)
return i
}
// WithMaxItems sets the max items
func (i *Items) WithMaxItems(size int64) *Items {
i.MaxItems = &size
return i
}
// WithMinItems sets the min items
func (i *Items) WithMinItems(size int64) *Items {
i.MinItems = &size
return i
}
// UniqueValues dictates that this array can only have unique items
func (i *Items) UniqueValues() *Items {
i.UniqueItems = true
return i
}
// AllowDuplicates this array can have duplicates
func (i *Items) AllowDuplicates() *Items {
i.UniqueItems = false
return i
}
// UnmarshalJSON hydrates this items instance with the data from JSON
func (i *Items) UnmarshalJSON(data []byte) error {
var validations CommonValidations
if err := json.Unmarshal(data, &validations); err != nil {
return err
}
var ref Refable
if err := json.Unmarshal(data, &ref); err != nil {
return err
}
var simpleSchema SimpleSchema
if err := json.Unmarshal(data, &simpleSchema); err != nil {
return err
}
var vendorExtensible VendorExtensible
if err := json.Unmarshal(data, &vendorExtensible); err != nil {
return err
}
i.Refable = ref
i.CommonValidations = validations
i.SimpleSchema = simpleSchema
i.VendorExtensible = vendorExtensible
return nil
}
// MarshalJSON converts this items object to JSON
func (i Items) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(i.CommonValidations)
if err != nil {
return nil, err
}
b2, err := json.Marshal(i.SimpleSchema)
if err != nil {
return nil, err
}
b3, err := json.Marshal(i.Refable)
if err != nil {
return nil, err
}
b4, err := json.Marshal(i.VendorExtensible)
if err != nil {
return nil, err
}
return swag.ConcatJSON(b4, b3, b1, b2), nil
}
// JSONLookup look up a value by the json property name
func (i Items) JSONLookup(token string) (interface{}, error) {
if token == "$ref" {
return &i.Ref, nil
}
r, _, err := jsonpointer.GetForToken(i.CommonValidations, token)
if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
return nil, err
}
if r != nil {
return r, nil
}
r, _, err = jsonpointer.GetForToken(i.SimpleSchema, token)
return r, err
}

View File

@@ -1,141 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
var items = Items{
Refable: Refable{Ref: MustCreateRef("Dog")},
CommonValidations: CommonValidations{
Maximum: float64Ptr(100),
ExclusiveMaximum: true,
ExclusiveMinimum: true,
Minimum: float64Ptr(5),
MaxLength: int64Ptr(100),
MinLength: int64Ptr(5),
Pattern: "\\w{1,5}\\w+",
MaxItems: int64Ptr(100),
MinItems: int64Ptr(5),
UniqueItems: true,
MultipleOf: float64Ptr(5),
Enum: []interface{}{"hello", "world"},
},
SimpleSchema: SimpleSchema{
Type: "string",
Format: "date",
Items: &Items{
Refable: Refable{Ref: MustCreateRef("Cat")},
},
CollectionFormat: "csv",
Default: "8",
},
}
var itemsJSON = `{
"items": {
"$ref": "Cat"
},
"$ref": "Dog",
"maximum": 100,
"minimum": 5,
"exclusiveMaximum": true,
"exclusiveMinimum": true,
"maxLength": 100,
"minLength": 5,
"pattern": "\\w{1,5}\\w+",
"maxItems": 100,
"minItems": 5,
"uniqueItems": true,
"multipleOf": 5,
"enum": ["hello", "world"],
"type": "string",
"format": "date",
"collectionFormat": "csv",
"default": "8"
}`
func TestIntegrationItems(t *testing.T) {
var actual Items
if assert.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) {
assert.EqualValues(t, actual, items)
}
assertParsesJSON(t, itemsJSON, items)
}
func TestTypeNameItems(t *testing.T) {
var nilItems Items
assert.Equal(t, "", nilItems.TypeName())
assert.Equal(t, "date", items.TypeName())
assert.Equal(t, "", items.ItemsTypeName())
nested := Items{
SimpleSchema: SimpleSchema{
Type: "array",
Items: &Items{
SimpleSchema: SimpleSchema{
Type: "integer",
Format: "int32",
},
},
CollectionFormat: "csv",
},
}
assert.Equal(t, "array", nested.TypeName())
assert.Equal(t, "int32", nested.ItemsTypeName())
}
func TestJSONLookupItems(t *testing.T) {
res, err := items.JSONLookup("$ref")
if !assert.NoError(t, err) {
t.FailNow()
return
}
if assert.IsType(t, &Ref{}, res) {
ref := res.(*Ref)
assert.EqualValues(t, MustCreateRef("Dog"), *ref)
}
var max *float64
res, err = items.JSONLookup("maximum")
if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, max, res) {
t.FailNow()
return
}
max = res.(*float64)
assert.Equal(t, float64(100), *max)
var f string
res, err = items.JSONLookup("collectionFormat")
if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, f, res) {
t.FailNow()
return
}
f = res.(string)
assert.Equal(t, "csv", f)
res, err = items.JSONLookup("unknown")
if !assert.Error(t, err) || !assert.Nil(t, res) {
t.FailNow()
return
}
}

View File

@@ -1,23 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
// License information for the exposed API.
//
// For more information: http://goo.gl/8us55a#licenseObject
type License struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
}

View File

@@ -1,28 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import "testing"
func TestIntegrationLicense(t *testing.T) {
license := License{"the name", "the url"}
const licenseJSON = `{"name":"the name","url":"the url"}`
const licenseYAML = "name: the name\nurl: the url\n"
assertSerializeJSON(t, license, licenseJSON)
assertSerializeYAML(t, license, licenseYAML)
assertParsesJSON(t, licenseJSON, license)
assertParsesYAML(t, licenseYAML, license)
}

View File

@@ -1,259 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/swag"
)
// OperationProps describes an operation
type OperationProps struct {
Description string `json:"description,omitempty"`
Consumes []string `json:"consumes,omitempty"`
Produces []string `json:"produces,omitempty"`
Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss]
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
ID string `json:"operationId,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
Security []map[string][]string `json:"security,omitempty"` //Special case, see MarshalJSON function
Parameters []Parameter `json:"parameters,omitempty"`
Responses *Responses `json:"responses,omitempty"`
}
// MarshalJSON takes care of serializing operation properties to JSON
//
// We use a custom marhaller here to handle a special cases related to
// the Security field. We need to preserve zero length slice
// while omitting the field when the value is nil/unset.
func (op OperationProps) MarshalJSON() ([]byte, error) {
type Alias OperationProps
if op.Security == nil {
return json.Marshal(&struct {
Security []map[string][]string `json:"security,omitempty"`
*Alias
}{
Security: op.Security,
Alias: (*Alias)(&op),
})
}
return json.Marshal(&struct {
Security []map[string][]string `json:"security"`
*Alias
}{
Security: op.Security,
Alias: (*Alias)(&op),
})
}
// Operation describes a single API operation on a path.
//
// For more information: http://goo.gl/8us55a#operationObject
type Operation struct {
VendorExtensible
OperationProps
}
// SuccessResponse gets a success response model
func (o *Operation) SuccessResponse() (*Response, int, bool) {
if o.Responses == nil {
return nil, 0, false
}
for k, v := range o.Responses.StatusCodeResponses {
if k/100 == 2 {
return &v, k, true
}
}
return o.Responses.Default, 0, false
}
// JSONLookup look up a value by the json property name
func (o Operation) JSONLookup(token string) (interface{}, error) {
if ex, ok := o.Extensions[token]; ok {
return &ex, nil
}
r, _, err := jsonpointer.GetForToken(o.OperationProps, token)
return r, err
}
// UnmarshalJSON hydrates this items instance with the data from JSON
func (o *Operation) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &o.OperationProps); err != nil {
return err
}
if err := json.Unmarshal(data, &o.VendorExtensible); err != nil {
return err
}
return nil
}
// MarshalJSON converts this items object to JSON
func (o Operation) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(o.OperationProps)
if err != nil {
return nil, err
}
b2, err := json.Marshal(o.VendorExtensible)
if err != nil {
return nil, err
}
concated := swag.ConcatJSON(b1, b2)
return concated, nil
}
// NewOperation creates a new operation instance.
// It expects an ID as parameter but not passing an ID is also valid.
func NewOperation(id string) *Operation {
op := new(Operation)
op.ID = id
return op
}
// WithID sets the ID property on this operation, allows for chaining.
func (o *Operation) WithID(id string) *Operation {
o.ID = id
return o
}
// WithDescription sets the description on this operation, allows for chaining
func (o *Operation) WithDescription(description string) *Operation {
o.Description = description
return o
}
// WithSummary sets the summary on this operation, allows for chaining
func (o *Operation) WithSummary(summary string) *Operation {
o.Summary = summary
return o
}
// WithExternalDocs sets/removes the external docs for/from this operation.
// When you pass empty strings as params the external documents will be removed.
// When you pass non-empty string as one value then those values will be used on the external docs object.
// So when you pass a non-empty description, you should also pass the url and vice versa.
func (o *Operation) WithExternalDocs(description, url string) *Operation {
if description == "" && url == "" {
o.ExternalDocs = nil
return o
}
if o.ExternalDocs == nil {
o.ExternalDocs = &ExternalDocumentation{}
}
o.ExternalDocs.Description = description
o.ExternalDocs.URL = url
return o
}
// Deprecate marks the operation as deprecated
func (o *Operation) Deprecate() *Operation {
o.Deprecated = true
return o
}
// Undeprecate marks the operation as not deprected
func (o *Operation) Undeprecate() *Operation {
o.Deprecated = false
return o
}
// WithConsumes adds media types for incoming body values
func (o *Operation) WithConsumes(mediaTypes ...string) *Operation {
o.Consumes = append(o.Consumes, mediaTypes...)
return o
}
// WithProduces adds media types for outgoing body values
func (o *Operation) WithProduces(mediaTypes ...string) *Operation {
o.Produces = append(o.Produces, mediaTypes...)
return o
}
// WithTags adds tags for this operation
func (o *Operation) WithTags(tags ...string) *Operation {
o.Tags = append(o.Tags, tags...)
return o
}
// AddParam adds a parameter to this operation, when a parameter for that location
// and with that name already exists it will be replaced
func (o *Operation) AddParam(param *Parameter) *Operation {
if param == nil {
return o
}
for i, p := range o.Parameters {
if p.Name == param.Name && p.In == param.In {
params := append(o.Parameters[:i], *param)
params = append(params, o.Parameters[i+1:]...)
o.Parameters = params
return o
}
}
o.Parameters = append(o.Parameters, *param)
return o
}
// RemoveParam removes a parameter from the operation
func (o *Operation) RemoveParam(name, in string) *Operation {
for i, p := range o.Parameters {
if p.Name == name && p.In == name {
o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...)
return o
}
}
return o
}
// SecuredWith adds a security scope to this operation.
func (o *Operation) SecuredWith(name string, scopes ...string) *Operation {
o.Security = append(o.Security, map[string][]string{name: scopes})
return o
}
// WithDefaultResponse adds a default response to the operation.
// Passing a nil value will remove the response
func (o *Operation) WithDefaultResponse(response *Response) *Operation {
return o.RespondsWith(0, response)
}
// RespondsWith adds a status code response to the operation.
// When the code is 0 the value of the response will be used as default response value.
// When the value of the response is nil it will be removed from the operation
func (o *Operation) RespondsWith(code int, response *Response) *Operation {
if o.Responses == nil {
o.Responses = new(Responses)
}
if code == 0 {
o.Responses.Default = response
return o
}
if response == nil {
delete(o.Responses.StatusCodeResponses, code)
return o
}
if o.Responses.StatusCodeResponses == nil {
o.Responses.StatusCodeResponses = make(map[int]Response)
}
o.Responses.StatusCodeResponses[code] = *response
return o
}

View File

@@ -1,107 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
var operation = Operation{
VendorExtensible: VendorExtensible{
Extensions: map[string]interface{}{
"x-framework": "go-swagger",
},
},
OperationProps: OperationProps{
Description: "operation description",
Consumes: []string{"application/json", "application/x-yaml"},
Produces: []string{"application/json", "application/x-yaml"},
Schemes: []string{"http", "https"},
Tags: []string{"dogs"},
Summary: "the summary of the operation",
ID: "sendCat",
Deprecated: true,
Security: []map[string][]string{
{
"apiKey": {},
},
},
Parameters: []Parameter{
{Refable: Refable{Ref: MustCreateRef("Cat")}},
},
Responses: &Responses{
ResponsesProps: ResponsesProps{
Default: &Response{
ResponseProps: ResponseProps{
Description: "void response",
},
},
},
},
},
}
var operationJSON = `{
"description": "operation description",
"x-framework": "go-swagger",
"consumes": [ "application/json", "application/x-yaml" ],
"produces": [ "application/json", "application/x-yaml" ],
"schemes": ["http", "https"],
"tags": ["dogs"],
"summary": "the summary of the operation",
"operationId": "sendCat",
"deprecated": true,
"security": [ { "apiKey": [] } ],
"parameters": [{"$ref":"Cat"}],
"responses": {
"default": {
"description": "void response"
}
}
}`
func TestIntegrationOperation(t *testing.T) {
var actual Operation
if assert.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) {
assert.EqualValues(t, actual, operation)
}
assertParsesJSON(t, operationJSON, operation)
}
func TestSecurityProperty(t *testing.T) {
//Ensure we omit security key when unset
securityNotSet := OperationProps{}
jsonResult, err := json.Marshal(securityNotSet)
if assert.NoError(t, err) {
assert.NotContains(t, string(jsonResult), "security", "security key should be omitted when unset")
}
//Ensure we preseve the security key when it contains an empty (zero length) slice
securityContainsEmptyArray := OperationProps{
Security: []map[string][]string{},
}
jsonResult, err = json.Marshal(securityContainsEmptyArray)
if assert.NoError(t, err) {
var props OperationProps
if assert.NoError(t, json.Unmarshal(jsonResult, &props)) {
assert.Equal(t, securityContainsEmptyArray, props)
}
}
}

View File

@@ -1,302 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// 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 spec
import (
"encoding/json"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/swag"
)
// QueryParam creates a query parameter
func QueryParam(name string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}}
}
// HeaderParam creates a header parameter, this is always required by default
func HeaderParam(name string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}}
}
// PathParam creates a path parameter, this is always required
func PathParam(name string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}}
}
// BodyParam creates a body parameter
func BodyParam(name string, schema *Schema) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}, SimpleSchema: SimpleSchema{Type: "object"}}
}
// FormDataParam creates a body parameter
func FormDataParam(name string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}}
}
// FileParam creates a body parameter
func FileParam(name string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, SimpleSchema: SimpleSchema{Type: "file"}}
}
// SimpleArrayParam creates a param for a simple array (string, int, date etc)
func SimpleArrayParam(name, tpe, fmt string) *Parameter {
return &Parameter{ParamProps: ParamProps{Name: name}, SimpleSchema: SimpleSchema{Type: "array", CollectionFormat: "csv", Items: &Items{SimpleSchema: SimpleSchema{Type: "string", Format: fmt}}}}
}
// ParamRef creates a parameter that's a json reference
func ParamRef(uri string) *Parameter {
p := new(Parameter)
p.Ref = MustCreateRef(uri)
return p
}
// ParamProps describes the specific attributes of an operation parameter
type ParamProps struct {
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
Required bool `json:"required,omitempty"`
Schema *Schema `json:"schema,omitempty"` // when in == "body"
AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // when in == "query" || "formData"
}
// Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn).
//
// There are five possible parameter types.
// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`.
// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`.
// * Header - Custom headers that are expected as part of the request.
// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation.
// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or `multipart/form-data` are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4):
// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred.
// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers.
//
// For more information: http://goo.gl/8us55a#parameterObject
type Parameter struct {
Refable
CommonValidations
SimpleSchema
VendorExtensible
ParamProps
}
// JSONLookup look up a value by the json property name
func (p Parameter) JSONLookup(token string) (interface{}, error) {
if ex, ok := p.Extensions[token]; ok {
return &ex, nil
}
if token == "$ref" {
return &p.Ref, nil
}
r, _, err := jsonpointer.GetForToken(p.CommonValidations, token)
if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
return nil, err
}
if r != nil {
return r, nil
}
r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token)
if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
return nil, err
}
if r != nil {
return r, nil
}
r, _, err = jsonpointer.GetForToken(p.ParamProps, token)
return r, err
}
// WithDescription a fluent builder method for the description of the parameter
func (p *Parameter) WithDescription(description string) *Parameter {
p.Description = description
return p
}
// Named a fluent builder method to override the name of the parameter
func (p *Parameter) Named(name string) *Parameter {
p.Name = name
return p
}
// WithLocation a fluent builder method to override the location of the parameter
func (p *Parameter) WithLocation(in string) *Parameter {
p.In = in
return p
}
// Typed a fluent builder method for the type of the parameter value
func (p *Parameter) Typed(tpe, format string) *Parameter {
p.Type = tpe
p.Format = format
return p
}
// CollectionOf a fluent builder method for an array parameter
func (p *Parameter) CollectionOf(items *Items, format string) *Parameter {
p.Type = "array"
p.Items = items
p.CollectionFormat = format
return p
}
// WithDefault sets the default value on this parameter
func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter {
p.AsOptional() // with default implies optional
p.Default = defaultValue
return p
}
// AllowsEmptyValues flags this parameter as being ok with empty values
func (p *Parameter) AllowsEmptyValues() *Parameter {
p.AllowEmptyValue = true
return p
}
// NoEmptyValues flags this parameter as not liking empty values
func (p *Parameter) NoEmptyValues() *Parameter {
p.AllowEmptyValue = false
return p
}
// AsOptional flags this parameter as optional
func (p *Parameter) AsOptional() *Parameter {
p.Required = false
return p
}
// AsRequired flags this parameter as required
func (p *Parameter) AsRequired() *Parameter {
if p.Default != nil { // with a default required makes no sense
return p
}
p.Required = true
return p
}
// WithMaxLength sets a max length value
func (p *Parameter) WithMaxLength(max int64) *Parameter {
p.MaxLength = &max
return p
}
// WithMinLength sets a min length value
func (p *Parameter) WithMinLength(min int64) *Parameter {
p.MinLength = &min
return p
}
// WithPattern sets a pattern value
func (p *Parameter) WithPattern(pattern string) *Parameter {
p.Pattern = pattern
return p
}
// WithMultipleOf sets a multiple of value
func (p *Parameter) WithMultipleOf(number float64) *Parameter {
p.MultipleOf = &number
return p
}
// WithMaximum sets a maximum number value
func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter {
p.Maximum = &max
p.ExclusiveMaximum = exclusive
return p
}
// WithMinimum sets a minimum number value
func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter {
p.Minimum = &min
p.ExclusiveMinimum = exclusive
return p
}
// WithEnum sets a the enum values (replace)
func (p *Parameter) WithEnum(values ...interface{}) *Parameter {
p.Enum = append([]interface{}{}, values...)
return p
}
// WithMaxItems sets the max items
func (p *Parameter) WithMaxItems(size int64) *Parameter {
p.MaxItems = &size
return p
}
// WithMinItems sets the min items
func (p *Parameter) WithMinItems(size int64) *Parameter {
p.MinItems = &size
return p
}
// UniqueValues dictates that this array can only have unique items
func (p *Parameter) UniqueValues() *Parameter {
p.UniqueItems = true
return p
}
// AllowDuplicates this array can have duplicates
func (p *Parameter) AllowDuplicates() *Parameter {
p.UniqueItems = false
return p
}
// UnmarshalJSON hydrates this items instance with the data from JSON
func (p *Parameter) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &p.CommonValidations); err != nil {
return err
}
if err := json.Unmarshal(data, &p.Refable); err != nil {
return err
}
if err := json.Unmarshal(data, &p.SimpleSchema); err != nil {
return err
}
if err := json.Unmarshal(data, &p.VendorExtensible); err != nil {
return err
}
if err := json.Unmarshal(data, &p.ParamProps); err != nil {
return err
}
return nil
}
// MarshalJSON converts this items object to JSON
func (p Parameter) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(p.CommonValidations)
if err != nil {
return nil, err
}
b2, err := json.Marshal(p.SimpleSchema)
if err != nil {
return nil, err
}
b3, err := json.Marshal(p.Refable)
if err != nil {
return nil, err
}
b4, err := json.Marshal(p.VendorExtensible)
if err != nil {
return nil, err
}
b5, err := json.Marshal(p.ParamProps)
if err != nil {
return nil, err
}
return swag.ConcatJSON(b3, b1, b2, b4, b5), nil
}

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