Vendor dependencies for GCS

This commit is contained in:
Alexander Neumann 2017-08-05 20:17:15 +02:00
parent ba75a3884c
commit 8ca6a9a240
1228 changed files with 1769186 additions and 1 deletions

406
vendor/google.golang.org/api/googleapi/googleapi.go generated vendored Normal file
View file

@ -0,0 +1,406 @@
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package googleapi contains the common code shared by all Google API
// libraries.
package googleapi // import "google.golang.org/api/googleapi"
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"google.golang.org/api/googleapi/internal/uritemplates"
)
// ContentTyper is an interface for Readers which know (or would like
// to override) their Content-Type. If a media body doesn't implement
// ContentTyper, the type is sniffed from the content using
// http.DetectContentType.
type ContentTyper interface {
ContentType() string
}
// A SizeReaderAt is a ReaderAt with a Size method.
// An io.SectionReader implements SizeReaderAt.
type SizeReaderAt interface {
io.ReaderAt
Size() int64
}
// ServerResponse is embedded in each Do response and
// provides the HTTP status code and header sent by the server.
type ServerResponse struct {
// HTTPStatusCode is the server's response status code.
// When using a resource method's Do call, this will always be in the 2xx range.
HTTPStatusCode int
// Header contains the response header fields from the server.
Header http.Header
}
const (
Version = "0.5"
// UserAgent is the header string used to identify this package.
UserAgent = "google-api-go-client/" + Version
// The default chunk size to use for resumable uploads if not specified by the user.
DefaultUploadChunkSize = 8 * 1024 * 1024
// The minimum chunk size that can be used for resumable uploads. All
// user-specified chunk sizes must be multiple of this value.
MinUploadChunkSize = 256 * 1024
)
// Error contains an error response from the server.
type Error struct {
// Code is the HTTP response status code and will always be populated.
Code int `json:"code"`
// Message is the server response message and is only populated when
// explicitly referenced by the JSON server response.
Message string `json:"message"`
// Body is the raw response returned by the server.
// It is often but not always JSON, depending on how the request fails.
Body string
// Header contains the response header fields from the server.
Header http.Header
Errors []ErrorItem
}
// ErrorItem is a detailed error code & message from the Google API frontend.
type ErrorItem struct {
// Reason is the typed error code. For example: "some_example".
Reason string `json:"reason"`
// Message is the human-readable description of the error.
Message string `json:"message"`
}
func (e *Error) Error() string {
if len(e.Errors) == 0 && e.Message == "" {
return fmt.Sprintf("googleapi: got HTTP response code %d with body: %v", e.Code, e.Body)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "googleapi: Error %d: ", e.Code)
if e.Message != "" {
fmt.Fprintf(&buf, "%s", e.Message)
}
if len(e.Errors) == 0 {
return strings.TrimSpace(buf.String())
}
if len(e.Errors) == 1 && e.Errors[0].Message == e.Message {
fmt.Fprintf(&buf, ", %s", e.Errors[0].Reason)
return buf.String()
}
fmt.Fprintln(&buf, "\nMore details:")
for _, v := range e.Errors {
fmt.Fprintf(&buf, "Reason: %s, Message: %s\n", v.Reason, v.Message)
}
return buf.String()
}
type errorReply struct {
Error *Error `json:"error"`
}
// CheckResponse returns an error (of type *Error) if the response
// status code is not 2xx.
func CheckResponse(res *http.Response) error {
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
slurp, err := ioutil.ReadAll(res.Body)
if err == nil {
jerr := new(errorReply)
err = json.Unmarshal(slurp, jerr)
if err == nil && jerr.Error != nil {
if jerr.Error.Code == 0 {
jerr.Error.Code = res.StatusCode
}
jerr.Error.Body = string(slurp)
return jerr.Error
}
}
return &Error{
Code: res.StatusCode,
Body: string(slurp),
Header: res.Header,
}
}
// IsNotModified reports whether err is the result of the
// server replying with http.StatusNotModified.
// Such error values are sometimes returned by "Do" methods
// on calls when If-None-Match is used.
func IsNotModified(err error) bool {
if err == nil {
return false
}
ae, ok := err.(*Error)
return ok && ae.Code == http.StatusNotModified
}
// CheckMediaResponse returns an error (of type *Error) if the response
// status code is not 2xx. Unlike CheckResponse it does not assume the
// body is a JSON error document.
// It is the caller's responsibility to close res.Body.
func CheckMediaResponse(res *http.Response) error {
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
slurp, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20))
return &Error{
Code: res.StatusCode,
Body: string(slurp),
}
}
type MarshalStyle bool
var WithDataWrapper = MarshalStyle(true)
var WithoutDataWrapper = MarshalStyle(false)
func (wrap MarshalStyle) JSONReader(v interface{}) (io.Reader, error) {
buf := new(bytes.Buffer)
if wrap {
buf.Write([]byte(`{"data": `))
}
err := json.NewEncoder(buf).Encode(v)
if err != nil {
return nil, err
}
if wrap {
buf.Write([]byte(`}`))
}
return buf, nil
}
// endingWithErrorReader from r until it returns an error. If the
// final error from r is io.EOF and e is non-nil, e is used instead.
type endingWithErrorReader struct {
r io.Reader
e error
}
func (er endingWithErrorReader) Read(p []byte) (n int, err error) {
n, err = er.r.Read(p)
if err == io.EOF && er.e != nil {
err = er.e
}
return
}
// countingWriter counts the number of bytes it receives to write, but
// discards them.
type countingWriter struct {
n *int64
}
func (w countingWriter) Write(p []byte) (int, error) {
*w.n += int64(len(p))
return len(p), nil
}
// ProgressUpdater is a function that is called upon every progress update of a resumable upload.
// This is the only part of a resumable upload (from googleapi) that is usable by the developer.
// The remaining usable pieces of resumable uploads is exposed in each auto-generated API.
type ProgressUpdater func(current, total int64)
type MediaOption interface {
setOptions(o *MediaOptions)
}
type contentTypeOption string
func (ct contentTypeOption) setOptions(o *MediaOptions) {
o.ContentType = string(ct)
if o.ContentType == "" {
o.ForceEmptyContentType = true
}
}
// ContentType returns a MediaOption which sets the Content-Type header for media uploads.
// If ctype is empty, the Content-Type header will be omitted.
func ContentType(ctype string) MediaOption {
return contentTypeOption(ctype)
}
type chunkSizeOption int
func (cs chunkSizeOption) setOptions(o *MediaOptions) {
size := int(cs)
if size%MinUploadChunkSize != 0 {
size += MinUploadChunkSize - (size % MinUploadChunkSize)
}
o.ChunkSize = size
}
// ChunkSize returns a MediaOption which sets the chunk size for media uploads.
// size will be rounded up to the nearest multiple of 256K.
// Media which contains fewer than size bytes will be uploaded in a single request.
// Media which contains size bytes or more will be uploaded in separate chunks.
// If size is zero, media will be uploaded in a single request.
func ChunkSize(size int) MediaOption {
return chunkSizeOption(size)
}
// MediaOptions stores options for customizing media upload. It is not used by developers directly.
type MediaOptions struct {
ContentType string
ForceEmptyContentType bool
ChunkSize int
}
// ProcessMediaOptions stores options from opts in a MediaOptions.
// It is not used by developers directly.
func ProcessMediaOptions(opts []MediaOption) *MediaOptions {
mo := &MediaOptions{ChunkSize: DefaultUploadChunkSize}
for _, o := range opts {
o.setOptions(mo)
}
return mo
}
func ResolveRelative(basestr, relstr string) string {
u, _ := url.Parse(basestr)
rel, _ := url.Parse(relstr)
u = u.ResolveReference(rel)
us := u.String()
us = strings.Replace(us, "%7B", "{", -1)
us = strings.Replace(us, "%7D", "}", -1)
return us
}
// Expand subsitutes any {encoded} strings in the URL passed in using
// the map supplied.
//
// This calls SetOpaque to avoid encoding of the parameters in the URL path.
func Expand(u *url.URL, expansions map[string]string) {
escaped, unescaped, err := uritemplates.Expand(u.Path, expansions)
if err == nil {
u.Path = unescaped
u.RawPath = escaped
}
}
// CloseBody is used to close res.Body.
// Prior to calling Close, it also tries to Read a small amount to see an EOF.
// Not seeing an EOF can prevent HTTP Transports from reusing connections.
func CloseBody(res *http.Response) {
if res == nil || res.Body == nil {
return
}
// Justification for 3 byte reads: two for up to "\r\n" after
// a JSON/XML document, and then 1 to see EOF if we haven't yet.
// TODO(bradfitz): detect Go 1.3+ and skip these reads.
// See https://codereview.appspot.com/58240043
// and https://codereview.appspot.com/49570044
buf := make([]byte, 1)
for i := 0; i < 3; i++ {
_, err := res.Body.Read(buf)
if err != nil {
break
}
}
res.Body.Close()
}
// VariantType returns the type name of the given variant.
// If the map doesn't contain the named key or the value is not a []interface{}, "" is returned.
// This is used to support "variant" APIs that can return one of a number of different types.
func VariantType(t map[string]interface{}) string {
s, _ := t["type"].(string)
return s
}
// ConvertVariant uses the JSON encoder/decoder to fill in the struct 'dst' with the fields found in variant 'v'.
// This is used to support "variant" APIs that can return one of a number of different types.
// It reports whether the conversion was successful.
func ConvertVariant(v map[string]interface{}, dst interface{}) bool {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(v)
if err != nil {
return false
}
return json.Unmarshal(buf.Bytes(), dst) == nil
}
// A Field names a field to be retrieved with a partial response.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
//
// Partial responses can dramatically reduce the amount of data that must be sent to your application.
// In order to request partial responses, you can specify the full list of fields
// that your application needs by adding the Fields option to your request.
//
// Field strings use camelCase with leading lower-case characters to identify fields within the response.
//
// For example, if your response has a "NextPageToken" and a slice of "Items" with "Id" fields,
// you could request just those fields like this:
//
// svc.Events.List().Fields("nextPageToken", "items/id").Do()
//
// or if you were also interested in each Item's "Updated" field, you can combine them like this:
//
// svc.Events.List().Fields("nextPageToken", "items(id,updated)").Do()
//
// More information about field formatting can be found here:
// https://developers.google.com/+/api/#fields-syntax
//
// Another way to find field names is through the Google API explorer:
// https://developers.google.com/apis-explorer/#p/
type Field string
// CombineFields combines fields into a single string.
func CombineFields(s []Field) string {
r := make([]string, len(s))
for i, v := range s {
r[i] = string(v)
}
return strings.Join(r, ",")
}
// A CallOption is an optional argument to an API call.
// It should be treated as an opaque value by users of Google APIs.
//
// A CallOption is something that configures an API call in a way that is
// not specific to that API; for instance, controlling the quota user for
// an API call is common across many APIs, and is thus a CallOption.
type CallOption interface {
Get() (key, value string)
}
// QuotaUser returns a CallOption that will set the quota user for a call.
// The quota user can be used by server-side applications to control accounting.
// It can be an arbitrary string up to 40 characters, and will override UserIP
// if both are provided.
func QuotaUser(u string) CallOption { return quotaUser(u) }
type quotaUser string
func (q quotaUser) Get() (string, string) { return "quotaUser", string(q) }
// UserIP returns a CallOption that will set the "userIp" parameter of a call.
// This should be the IP address of the originating request.
func UserIP(ip string) CallOption { return userIP(ip) }
type userIP string
func (i userIP) Get() (string, string) { return "userIp", string(i) }
// Trace returns a CallOption that enables diagnostic tracing for a call.
// traceToken is an ID supplied by Google support.
func Trace(traceToken string) CallOption { return traceTok(traceToken) }
type traceTok string
func (t traceTok) Get() (string, string) { return "trace", "token:" + string(t) }
// TODO: Fields too

View file

@ -0,0 +1,291 @@
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package googleapi
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
"testing"
)
type ExpandTest struct {
in string
expansions map[string]string
want string
}
var expandTests = []ExpandTest{
// no expansions
{
"http://www.golang.org/",
map[string]string{},
"http://www.golang.org/",
},
// one expansion, no escaping
{
"http://www.golang.org/{bucket}/delete",
map[string]string{
"bucket": "red",
},
"http://www.golang.org/red/delete",
},
// one expansion, with hex escapes
{
"http://www.golang.org/{bucket}/delete",
map[string]string{
"bucket": "red/blue",
},
"http://www.golang.org/red%2Fblue/delete",
},
// one expansion, with space
{
"http://www.golang.org/{bucket}/delete",
map[string]string{
"bucket": "red or blue",
},
"http://www.golang.org/red%20or%20blue/delete",
},
// expansion not found
{
"http://www.golang.org/{object}/delete",
map[string]string{
"bucket": "red or blue",
},
"http://www.golang.org//delete",
},
// multiple expansions
{
"http://www.golang.org/{one}/{two}/{three}/get",
map[string]string{
"one": "ONE",
"two": "TWO",
"three": "THREE",
},
"http://www.golang.org/ONE/TWO/THREE/get",
},
// utf-8 characters
{
"http://www.golang.org/{bucket}/get",
map[string]string{
"bucket": "£100",
},
"http://www.golang.org/%C2%A3100/get",
},
// punctuations
{
"http://www.golang.org/{bucket}/get",
map[string]string{
"bucket": `/\@:,.`,
},
"http://www.golang.org/%2F%5C%40%3A%2C./get",
},
// mis-matched brackets
{
"http://www.golang.org/{bucket/get",
map[string]string{
"bucket": "red",
},
"http://www.golang.org/%7Bbucket/get",
},
// "+" prefix for suppressing escape
// See also: http://tools.ietf.org/html/rfc6570#section-3.2.3
{
"http://www.golang.org/{+topic}",
map[string]string{
"topic": "/topics/myproject/mytopic",
},
// The double slashes here look weird, but it's intentional
"http://www.golang.org//topics/myproject/mytopic",
},
}
func TestExpand(t *testing.T) {
for i, test := range expandTests {
u := url.URL{
Path: test.in,
}
Expand(&u, test.expansions)
got := u.EscapedPath()
if got != test.want {
t.Errorf("got %q expected %q in test %d", got, test.want, i+1)
}
}
}
type CheckResponseTest struct {
in *http.Response
bodyText string
want error
errText string
}
var checkResponseTests = []CheckResponseTest{
{
&http.Response{
StatusCode: http.StatusOK,
},
"",
nil,
"",
},
{
&http.Response{
StatusCode: http.StatusInternalServerError,
},
`{"error":{}}`,
&Error{
Code: http.StatusInternalServerError,
Body: `{"error":{}}`,
},
`googleapi: got HTTP response code 500 with body: {"error":{}}`,
},
{
&http.Response{
StatusCode: http.StatusNotFound,
},
`{"error":{"message":"Error message for StatusNotFound."}}`,
&Error{
Code: http.StatusNotFound,
Message: "Error message for StatusNotFound.",
Body: `{"error":{"message":"Error message for StatusNotFound."}}`,
},
"googleapi: Error 404: Error message for StatusNotFound.",
},
{
&http.Response{
StatusCode: http.StatusBadRequest,
},
`{"error":"invalid_token","error_description":"Invalid Value"}`,
&Error{
Code: http.StatusBadRequest,
Body: `{"error":"invalid_token","error_description":"Invalid Value"}`,
},
`googleapi: got HTTP response code 400 with body: {"error":"invalid_token","error_description":"Invalid Value"}`,
},
{
&http.Response{
StatusCode: http.StatusBadRequest,
},
`{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`,
&Error{
Code: http.StatusBadRequest,
Errors: []ErrorItem{
{
Reason: "keyInvalid",
Message: "Bad Request",
},
},
Body: `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`,
Message: "Bad Request",
},
"googleapi: Error 400: Bad Request, keyInvalid",
},
}
func TestCheckResponse(t *testing.T) {
for _, test := range checkResponseTests {
res := test.in
if test.bodyText != "" {
res.Body = ioutil.NopCloser(strings.NewReader(test.bodyText))
}
g := CheckResponse(res)
if !reflect.DeepEqual(g, test.want) {
t.Errorf("CheckResponse: got %v, want %v", g, test.want)
gotJson, err := json.Marshal(g)
if err != nil {
t.Error(err)
}
wantJson, err := json.Marshal(test.want)
if err != nil {
t.Error(err)
}
t.Errorf("json(got): %q\njson(want): %q", string(gotJson), string(wantJson))
}
if g != nil && g.Error() != test.errText {
t.Errorf("CheckResponse: unexpected error message.\nGot: %q\nwant: %q", g, test.errText)
}
}
}
type VariantPoint struct {
Type string
Coordinates []float64
}
type VariantTest struct {
in map[string]interface{}
result bool
want VariantPoint
}
var coords = []interface{}{1.0, 2.0}
var variantTests = []VariantTest{
{
in: map[string]interface{}{
"type": "Point",
"coordinates": coords,
},
result: true,
want: VariantPoint{
Type: "Point",
Coordinates: []float64{1.0, 2.0},
},
},
{
in: map[string]interface{}{
"type": "Point",
"bogus": coords,
},
result: true,
want: VariantPoint{
Type: "Point",
},
},
}
func TestVariantType(t *testing.T) {
for _, test := range variantTests {
if g := VariantType(test.in); g != test.want.Type {
t.Errorf("VariantType(%v): got %v, want %v", test.in, g, test.want.Type)
}
}
}
func TestConvertVariant(t *testing.T) {
for _, test := range variantTests {
g := VariantPoint{}
r := ConvertVariant(test.in, &g)
if r != test.result {
t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, r, test.result)
}
if !reflect.DeepEqual(g, test.want) {
t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, g, test.want)
}
}
}
func TestRoundChunkSize(t *testing.T) {
type testCase struct {
in int
want int
}
for _, tc := range []testCase{
{0, 0},
{256*1024 - 1, 256 * 1024},
{256 * 1024, 256 * 1024},
{256*1024 + 1, 2 * 256 * 1024},
} {
mo := &MediaOptions{}
ChunkSize(tc.in).setOptions(mo)
if got := mo.ChunkSize; got != tc.want {
t.Errorf("rounding chunk size: got: %v; want %v", got, tc.want)
}
}
}

View file

@ -0,0 +1,18 @@
Copyright (c) 2013 Joshua Tacoma
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,248 @@
// Copyright 2013 Joshua Tacoma. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package uritemplates is a level 3 implementation of RFC 6570 (URI
// Template, http://tools.ietf.org/html/rfc6570).
// uritemplates does not support composite values (in Go: slices or maps)
// and so does not qualify as a level 4 implementation.
package uritemplates
import (
"bytes"
"errors"
"regexp"
"strconv"
"strings"
)
var (
unreserved = regexp.MustCompile("[^A-Za-z0-9\\-._~]")
reserved = regexp.MustCompile("[^A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]")
validname = regexp.MustCompile("^([A-Za-z0-9_\\.]|%[0-9A-Fa-f][0-9A-Fa-f])+$")
hex = []byte("0123456789ABCDEF")
)
func pctEncode(src []byte) []byte {
dst := make([]byte, len(src)*3)
for i, b := range src {
buf := dst[i*3 : i*3+3]
buf[0] = 0x25
buf[1] = hex[b/16]
buf[2] = hex[b%16]
}
return dst
}
// pairWriter is a convenience struct which allows escaped and unescaped
// versions of the template to be written in parallel.
type pairWriter struct {
escaped, unescaped bytes.Buffer
}
// Write writes the provided string directly without any escaping.
func (w *pairWriter) Write(s string) {
w.escaped.WriteString(s)
w.unescaped.WriteString(s)
}
// Escape writes the provided string, escaping the string for the
// escaped output.
func (w *pairWriter) Escape(s string, allowReserved bool) {
w.unescaped.WriteString(s)
if allowReserved {
w.escaped.Write(reserved.ReplaceAllFunc([]byte(s), pctEncode))
} else {
w.escaped.Write(unreserved.ReplaceAllFunc([]byte(s), pctEncode))
}
}
// Escaped returns the escaped string.
func (w *pairWriter) Escaped() string {
return w.escaped.String()
}
// Unescaped returns the unescaped string.
func (w *pairWriter) Unescaped() string {
return w.unescaped.String()
}
// A uriTemplate is a parsed representation of a URI template.
type uriTemplate struct {
raw string
parts []templatePart
}
// parse parses a URI template string into a uriTemplate object.
func parse(rawTemplate string) (*uriTemplate, error) {
split := strings.Split(rawTemplate, "{")
parts := make([]templatePart, len(split)*2-1)
for i, s := range split {
if i == 0 {
if strings.Contains(s, "}") {
return nil, errors.New("unexpected }")
}
parts[i].raw = s
continue
}
subsplit := strings.Split(s, "}")
if len(subsplit) != 2 {
return nil, errors.New("malformed template")
}
expression := subsplit[0]
var err error
parts[i*2-1], err = parseExpression(expression)
if err != nil {
return nil, err
}
parts[i*2].raw = subsplit[1]
}
return &uriTemplate{
raw: rawTemplate,
parts: parts,
}, nil
}
type templatePart struct {
raw string
terms []templateTerm
first string
sep string
named bool
ifemp string
allowReserved bool
}
type templateTerm struct {
name string
explode bool
truncate int
}
func parseExpression(expression string) (result templatePart, err error) {
switch expression[0] {
case '+':
result.sep = ","
result.allowReserved = true
expression = expression[1:]
case '.':
result.first = "."
result.sep = "."
expression = expression[1:]
case '/':
result.first = "/"
result.sep = "/"
expression = expression[1:]
case ';':
result.first = ";"
result.sep = ";"
result.named = true
expression = expression[1:]
case '?':
result.first = "?"
result.sep = "&"
result.named = true
result.ifemp = "="
expression = expression[1:]
case '&':
result.first = "&"
result.sep = "&"
result.named = true
result.ifemp = "="
expression = expression[1:]
case '#':
result.first = "#"
result.sep = ","
result.allowReserved = true
expression = expression[1:]
default:
result.sep = ","
}
rawterms := strings.Split(expression, ",")
result.terms = make([]templateTerm, len(rawterms))
for i, raw := range rawterms {
result.terms[i], err = parseTerm(raw)
if err != nil {
break
}
}
return result, err
}
func parseTerm(term string) (result templateTerm, err error) {
// TODO(djd): Remove "*" suffix parsing once we check that no APIs have
// mistakenly used that attribute.
if strings.HasSuffix(term, "*") {
result.explode = true
term = term[:len(term)-1]
}
split := strings.Split(term, ":")
if len(split) == 1 {
result.name = term
} else if len(split) == 2 {
result.name = split[0]
var parsed int64
parsed, err = strconv.ParseInt(split[1], 10, 0)
result.truncate = int(parsed)
} else {
err = errors.New("multiple colons in same term")
}
if !validname.MatchString(result.name) {
err = errors.New("not a valid name: " + result.name)
}
if result.explode && result.truncate > 0 {
err = errors.New("both explode and prefix modifers on same term")
}
return result, err
}
// Expand expands a URI template with a set of values to produce the
// resultant URI. Two forms of the result are returned: one with all the
// elements escaped, and one with the elements unescaped.
func (t *uriTemplate) Expand(values map[string]string) (escaped, unescaped string) {
var w pairWriter
for _, p := range t.parts {
p.expand(&w, values)
}
return w.Escaped(), w.Unescaped()
}
func (tp *templatePart) expand(w *pairWriter, values map[string]string) {
if len(tp.raw) > 0 {
w.Write(tp.raw)
return
}
var first = true
for _, term := range tp.terms {
value, exists := values[term.name]
if !exists {
continue
}
if first {
w.Write(tp.first)
first = false
} else {
w.Write(tp.sep)
}
tp.expandString(w, term, value)
}
}
func (tp *templatePart) expandName(w *pairWriter, name string, empty bool) {
if tp.named {
w.Write(name)
if empty {
w.Write(tp.ifemp)
} else {
w.Write("=")
}
}
}
func (tp *templatePart) expandString(w *pairWriter, t templateTerm, s string) {
if len(s) > t.truncate && t.truncate > 0 {
s = s[:t.truncate]
}
tp.expandName(w, t.name, len(s) == 0)
w.Escape(s, tp.allowReserved)
}

View file

@ -0,0 +1,280 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uritemplates
import (
"fmt"
"log"
"net/url"
"testing"
)
func ExampleExpand() {
values := map[string]string{
"user": "golang",
"repo": "go",
}
expanded, _, err := Expand("https://api.github.com/repos{/user,repo}", values)
if err != nil {
log.Fatalf("Error expanding template: %v", err)
}
fmt.Println(expanded)
// Output:
// https://api.github.com/repos/golang/go
}
func TestExpand(t *testing.T) {
testCases := []struct {
tmpl string
values map[string]string
want string
}{
// These examples come from the RFC:
// http://tools.ietf.org/html/rfc6570
{
tmpl: "http://www.example.com/foo{?query,number}",
values: map[string]string{"query": "mycelium", "number": "100"},
want: "http://www.example.com/foo?query=mycelium&number=100",
},
{
tmpl: "http://www.example.com/foo{?query,number}",
values: map[string]string{"query": "mycelium"},
want: "http://www.example.com/foo?query=mycelium",
},
{
tmpl: "http://www.example.com/foo{?query,number}",
values: map[string]string{},
want: "http://www.example.com/foo",
},
}
for _, tt := range testCases {
exp, _, err := Expand(tt.tmpl, tt.values)
if err != nil {
t.Errorf("Expand(%q, %v) error: %v", tt.tmpl, tt.values, err)
continue
}
if exp != tt.want {
t.Errorf("Expand(%q, %v)\ngot %q\nwant %q", tt.tmpl, tt.values, exp, tt.want)
}
}
}
func TestExpandRFCLevels(t *testing.T) {
values := map[string]string{
"dub": "me/too",
"hello": "Hello World!",
"half": "50%",
"var": "value",
"who": "fred",
"base": "http://example.com/home/",
"path": "/foo/bar",
"semi": ";",
"v": "6",
"x": "1024",
"y": "768",
"empty": "",
// undef not mapped.
}
testCases := []struct {
tmpl, want string
}{
// These examples come from the RFC levels specification.
// http://tools.ietf.org/html/rfc6570
// Level 1 examples.
{tmpl: "{var}", want: "value"},
{tmpl: "{hello}", want: "Hello%20World%21"},
// Level 2 examples.
{tmpl: "{+var}", want: "value"},
{tmpl: "{+hello}", want: "Hello%20World!"},
{tmpl: "{+path}/here", want: "/foo/bar/here"},
{tmpl: "here?ref={+path}", want: "here?ref=/foo/bar"},
{tmpl: "X{#var}", want: "X#value"},
{tmpl: "X{#hello}", want: "X#Hello%20World!"},
// Level 3 examples.
{tmpl: "map?{x,y}", want: "map?1024,768"},
{tmpl: "{x,hello,y}", want: "1024,Hello%20World%21,768"},
{tmpl: "{+x,hello,y}", want: "1024,Hello%20World!,768"},
{tmpl: "{+path,x}/here", want: "/foo/bar,1024/here"},
{tmpl: "{#x,hello,y}", want: "#1024,Hello%20World!,768"},
{tmpl: "{#path,x}/here", want: "#/foo/bar,1024/here"},
{tmpl: "X{.var}", want: "X.value"},
{tmpl: "X{.x,y}", want: "X.1024.768"},
{tmpl: "{/var}", want: "/value"},
{tmpl: "{/var,x}/here", want: "/value/1024/here"},
{tmpl: "{;x,y}", want: ";x=1024;y=768"},
{tmpl: "{;x,y,empty}", want: ";x=1024;y=768;empty"},
{tmpl: "{?x,y}", want: "?x=1024&y=768"},
{tmpl: "{?x,y,empty}", want: "?x=1024&y=768&empty="},
{tmpl: "?fixed=yes{&x}", want: "?fixed=yes&x=1024"},
{tmpl: "{&x,y,empty}", want: "&x=1024&y=768&empty="},
{tmpl: "{var:3}", want: "val"},
{tmpl: "{var:30}", want: "value"},
{tmpl: "{+path:6}/here", want: "/foo/b/here"},
{tmpl: "{#path:6}/here", want: "#/foo/b/here"},
{tmpl: "X{.var:3}", want: "X.val"},
{tmpl: "{/var:1,var}", want: "/v/value"},
{tmpl: "{;hello:5}", want: ";hello=Hello"},
{tmpl: "{?var:3}", want: "?var=val"},
{tmpl: "{&var:3}", want: "&var=val"},
// 2.4.1 Prefix values.
{tmpl: "{var}", want: "value"},
{tmpl: "{var:20}", want: "value"},
{tmpl: "{var:3}", want: "val"},
{tmpl: "{semi}", want: "%3B"},
{tmpl: "{semi:2}", want: "%3B"},
// 3.2.2. Simple String Expansion: {var}
{tmpl: "{var}", want: "value"},
{tmpl: "{hello}", want: "Hello%20World%21"},
{tmpl: "{half}", want: "50%25"},
{tmpl: "O{empty}X", want: "OX"},
{tmpl: "O{undef}X", want: "OX"},
{tmpl: "{x,y}", want: "1024,768"},
{tmpl: "{x,hello,y}", want: "1024,Hello%20World%21,768"},
{tmpl: "?{x,empty}", want: "?1024,"},
{tmpl: "?{x,undef}", want: "?1024"},
{tmpl: "?{undef,y}", want: "?768"},
{tmpl: "{var:3}", want: "val"},
{tmpl: "{var:30}", want: "value"},
// 3.2.3. Reserved Expansion: {+var}
{tmpl: "{+var}", want: "value"},
{tmpl: "{+hello}", want: "Hello%20World!"},
{tmpl: "{+half}", want: "50%25"},
{tmpl: "{base}index", want: "http%3A%2F%2Fexample.com%2Fhome%2Findex"},
{tmpl: "{+base}index", want: "http://example.com/home/index"},
{tmpl: "O{+empty}X", want: "OX"},
{tmpl: "O{+undef}X", want: "OX"},
{tmpl: "{+path}/here", want: "/foo/bar/here"},
{tmpl: "here?ref={+path}", want: "here?ref=/foo/bar"},
{tmpl: "up{+path}{var}/here", want: "up/foo/barvalue/here"},
{tmpl: "{+x,hello,y}", want: "1024,Hello%20World!,768"},
{tmpl: "{+path,x}/here", want: "/foo/bar,1024/here"},
{tmpl: "{+path:6}/here", want: "/foo/b/here"},
// 3.2.4. Fragment Expansion: {#var}
{tmpl: "{#var}", want: "#value"},
{tmpl: "{#hello}", want: "#Hello%20World!"},
{tmpl: "{#half}", want: "#50%25"},
{tmpl: "foo{#empty}", want: "foo#"},
{tmpl: "foo{#undef}", want: "foo"},
{tmpl: "{#x,hello,y}", want: "#1024,Hello%20World!,768"},
{tmpl: "{#path,x}/here", want: "#/foo/bar,1024/here"},
{tmpl: "{#path:6}/here", want: "#/foo/b/here"},
// 3.2.5. Label Expansion with Dot-Prefix: {.var}
{tmpl: "{.who}", want: ".fred"},
{tmpl: "{.who,who}", want: ".fred.fred"},
{tmpl: "{.half,who}", want: ".50%25.fred"},
{tmpl: "X{.var}", want: "X.value"},
{tmpl: "X{.empty}", want: "X."},
{tmpl: "X{.undef}", want: "X"},
{tmpl: "X{.var:3}", want: "X.val"},
// 3.2.6. Path Segment Expansion: {/var}
{tmpl: "{/who}", want: "/fred"},
{tmpl: "{/who,who}", want: "/fred/fred"},
{tmpl: "{/half,who}", want: "/50%25/fred"},
{tmpl: "{/who,dub}", want: "/fred/me%2Ftoo"},
{tmpl: "{/var}", want: "/value"},
{tmpl: "{/var,empty}", want: "/value/"},
{tmpl: "{/var,undef}", want: "/value"},
{tmpl: "{/var,x}/here", want: "/value/1024/here"},
{tmpl: "{/var:1,var}", want: "/v/value"},
// 3.2.7. Path-Style Parameter Expansion: {;var}
{tmpl: "{;who}", want: ";who=fred"},
{tmpl: "{;half}", want: ";half=50%25"},
{tmpl: "{;empty}", want: ";empty"},
{tmpl: "{;v,empty,who}", want: ";v=6;empty;who=fred"},
{tmpl: "{;v,bar,who}", want: ";v=6;who=fred"},
{tmpl: "{;x,y}", want: ";x=1024;y=768"},
{tmpl: "{;x,y,empty}", want: ";x=1024;y=768;empty"},
{tmpl: "{;x,y,undef}", want: ";x=1024;y=768"},
{tmpl: "{;hello:5}", want: ";hello=Hello"},
// 3.2.8. Form-Style Query Expansion: {?var}
{tmpl: "{?who}", want: "?who=fred"},
{tmpl: "{?half}", want: "?half=50%25"},
{tmpl: "{?x,y}", want: "?x=1024&y=768"},
{tmpl: "{?x,y,empty}", want: "?x=1024&y=768&empty="},
{tmpl: "{?x,y,undef}", want: "?x=1024&y=768"},
{tmpl: "{?var:3}", want: "?var=val"},
// 3.2.9. Form-Style Query Continuation: {&var}
{tmpl: "{&who}", want: "&who=fred"},
{tmpl: "{&half}", want: "&half=50%25"},
{tmpl: "?fixed=yes{&x}", want: "?fixed=yes&x=1024"},
{tmpl: "{&x,y,empty}", want: "&x=1024&y=768&empty="},
{tmpl: "{&x,y,undef}", want: "&x=1024&y=768"},
{tmpl: "{&var:3}", want: "&var=val"},
}
for _, tt := range testCases {
esc, unesc, err := Expand(tt.tmpl, values)
if err != nil {
t.Errorf("Expand(%q) error: %v", tt.tmpl, err)
continue
}
if esc != tt.want {
t.Errorf("Expand(%q)\ngot %q\nwant %q", tt.tmpl, esc, tt.want)
}
// Check that the escaped form is equivalent to unescaped.
urlUnesc, err := url.QueryUnescape(esc)
if err != nil {
t.Errorf("Expand(%q) gave invalid escaping %q: %v", tt.tmpl, esc, err)
continue
}
if urlUnesc != unesc {
t.Errorf("Expand(%q) gave inconsistent escaped/unescaped\nunescaped %q\nescaped %q\nwhich is %q", tt.tmpl, unesc, esc, urlUnesc)
}
}
}
func TestExpandUnescaped(t *testing.T) {
testCases := []struct {
tmpl, wantEsc, wantUnesc string
values map[string]string
}{
{
tmpl: "/foo/{bucket}/bar",
values: map[string]string{
"bucket": "simple",
},
wantEsc: "/foo/simple/bar",
wantUnesc: "/foo/simple/bar",
},
{
tmpl: "/foo/{bucket}/bar",
values: map[string]string{
"bucket": "path/with/slash",
},
wantEsc: "/foo/path%2Fwith%2Fslash/bar",
wantUnesc: "/foo/path/with/slash/bar",
},
{
tmpl: "/foo/{+bucket}/bar",
values: map[string]string{
"bucket": "path/with/slash",
},
wantEsc: "/foo/path/with/slash/bar",
wantUnesc: "/foo/path/with/slash/bar",
},
{
tmpl: "/foo/{bucket}/bar",
values: map[string]string{
"bucket": "double%2Fescaped",
},
wantEsc: "/foo/double%252Fescaped/bar",
wantUnesc: "/foo/double%2Fescaped/bar",
},
}
for _, tt := range testCases {
esc, unesc, err := Expand(tt.tmpl, tt.values)
if err != nil {
t.Errorf("Expand(%q) error: %v", tt.tmpl, err)
continue
}
if esc != tt.wantEsc || unesc != tt.wantUnesc {
t.Errorf("Expand(%q)\ngot esc=%q, unesc=%q\nwant esc=%q, unesc=%q", tt.tmpl, esc, unesc, tt.wantEsc, tt.wantUnesc)
}
}
}

View file

@ -0,0 +1,17 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uritemplates
// Expand parses then expands a URI template with a set of values to produce
// the resultant URI. Two forms of the result are returned: one with all the
// elements escaped, and one with the elements unescaped.
func Expand(path string, values map[string]string) (escaped, unescaped string, err error) {
template, err := parse(path)
if err != nil {
return "", "", err
}
escaped, unescaped = template.Expand(values)
return escaped, unescaped, nil
}

View file

@ -0,0 +1,38 @@
// Copyright 2012 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package transport contains HTTP transports used to make
// authenticated API requests.
package transport
import (
"errors"
"net/http"
)
// APIKey is an HTTP Transport which wraps an underlying transport and
// appends an API Key "key" parameter to the URL of outgoing requests.
type APIKey struct {
// Key is the API Key to set on requests.
Key string
// Transport is the underlying HTTP transport.
// If nil, http.DefaultTransport is used.
Transport http.RoundTripper
}
func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) {
rt := t.Transport
if rt == nil {
rt = http.DefaultTransport
if rt == nil {
return nil, errors.New("googleapi/transport: no Transport specified or available")
}
}
newReq := *req
args := newReq.URL.Query()
args.Set("key", t.Key)
newReq.URL.RawQuery = args.Encode()
return rt.RoundTrip(&newReq)
}

202
vendor/google.golang.org/api/googleapi/types.go generated vendored Normal file
View file

@ -0,0 +1,202 @@
// Copyright 2013 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package googleapi
import (
"encoding/json"
"errors"
"strconv"
)
// Int64s is a slice of int64s that marshal as quoted strings in JSON.
type Int64s []int64
func (q *Int64s) UnmarshalJSON(raw []byte) error {
*q = (*q)[:0]
var ss []string
if err := json.Unmarshal(raw, &ss); err != nil {
return err
}
for _, s := range ss {
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*q = append(*q, int64(v))
}
return nil
}
// Int32s is a slice of int32s that marshal as quoted strings in JSON.
type Int32s []int32
func (q *Int32s) UnmarshalJSON(raw []byte) error {
*q = (*q)[:0]
var ss []string
if err := json.Unmarshal(raw, &ss); err != nil {
return err
}
for _, s := range ss {
v, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return err
}
*q = append(*q, int32(v))
}
return nil
}
// Uint64s is a slice of uint64s that marshal as quoted strings in JSON.
type Uint64s []uint64
func (q *Uint64s) UnmarshalJSON(raw []byte) error {
*q = (*q)[:0]
var ss []string
if err := json.Unmarshal(raw, &ss); err != nil {
return err
}
for _, s := range ss {
v, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return err
}
*q = append(*q, uint64(v))
}
return nil
}
// Uint32s is a slice of uint32s that marshal as quoted strings in JSON.
type Uint32s []uint32
func (q *Uint32s) UnmarshalJSON(raw []byte) error {
*q = (*q)[:0]
var ss []string
if err := json.Unmarshal(raw, &ss); err != nil {
return err
}
for _, s := range ss {
v, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return err
}
*q = append(*q, uint32(v))
}
return nil
}
// Float64s is a slice of float64s that marshal as quoted strings in JSON.
type Float64s []float64
func (q *Float64s) UnmarshalJSON(raw []byte) error {
*q = (*q)[:0]
var ss []string
if err := json.Unmarshal(raw, &ss); err != nil {
return err
}
for _, s := range ss {
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
*q = append(*q, float64(v))
}
return nil
}
func quotedList(n int, fn func(dst []byte, i int) []byte) ([]byte, error) {
dst := make([]byte, 0, 2+n*10) // somewhat arbitrary
dst = append(dst, '[')
for i := 0; i < n; i++ {
if i > 0 {
dst = append(dst, ',')
}
dst = append(dst, '"')
dst = fn(dst, i)
dst = append(dst, '"')
}
dst = append(dst, ']')
return dst, nil
}
func (s Int64s) MarshalJSON() ([]byte, error) {
return quotedList(len(s), func(dst []byte, i int) []byte {
return strconv.AppendInt(dst, s[i], 10)
})
}
func (s Int32s) MarshalJSON() ([]byte, error) {
return quotedList(len(s), func(dst []byte, i int) []byte {
return strconv.AppendInt(dst, int64(s[i]), 10)
})
}
func (s Uint64s) MarshalJSON() ([]byte, error) {
return quotedList(len(s), func(dst []byte, i int) []byte {
return strconv.AppendUint(dst, s[i], 10)
})
}
func (s Uint32s) MarshalJSON() ([]byte, error) {
return quotedList(len(s), func(dst []byte, i int) []byte {
return strconv.AppendUint(dst, uint64(s[i]), 10)
})
}
func (s Float64s) MarshalJSON() ([]byte, error) {
return quotedList(len(s), func(dst []byte, i int) []byte {
return strconv.AppendFloat(dst, s[i], 'g', -1, 64)
})
}
// RawMessage is a raw encoded JSON value.
// It is identical to json.RawMessage, except it does not suffer from
// https://golang.org/issue/14493.
type RawMessage []byte
// MarshalJSON returns m.
func (m RawMessage) MarshalJSON() ([]byte, error) {
return m, nil
}
// UnmarshalJSON sets *m to a copy of data.
func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("googleapi.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[:0], data...)
return nil
}
/*
* Helper routines for simplifying the creation of optional fields of basic type.
*/
// Bool is a helper routine that allocates a new bool value
// to store v and returns a pointer to it.
func Bool(v bool) *bool { return &v }
// Int32 is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it.
func Int32(v int32) *int32 { return &v }
// Int64 is a helper routine that allocates a new int64 value
// to store v and returns a pointer to it.
func Int64(v int64) *int64 { return &v }
// Float64 is a helper routine that allocates a new float64 value
// to store v and returns a pointer to it.
func Float64(v float64) *float64 { return &v }
// Uint32 is a helper routine that allocates a new uint32 value
// to store v and returns a pointer to it.
func Uint32(v uint32) *uint32 { return &v }
// Uint64 is a helper routine that allocates a new uint64 value
// to store v and returns a pointer to it.
func Uint64(v uint64) *uint64 { return &v }
// String is a helper routine that allocates a new string value
// to store v and returns a pointer to it.
func String(v string) *string { return &v }

68
vendor/google.golang.org/api/googleapi/types_test.go generated vendored Normal file
View file

@ -0,0 +1,68 @@
// Copyright 2013 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package googleapi
import (
"bytes"
"encoding/json"
"reflect"
"testing"
)
func TestTypes(t *testing.T) {
type T struct {
I32 Int32s
I64 Int64s
U32 Uint32s
U64 Uint64s
F64 Float64s
}
v := &T{
I32: Int32s{-1, 2, 3},
I64: Int64s{-1, 2, 1 << 33},
U32: Uint32s{1, 2},
U64: Uint64s{1, 2, 1 << 33},
F64: Float64s{1.5, 3.33},
}
got, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
want := `{"I32":["-1","2","3"],"I64":["-1","2","8589934592"],"U32":["1","2"],"U64":["1","2","8589934592"],"F64":["1.5","3.33"]}`
if string(got) != want {
t.Fatalf("Marshal mismatch.\n got: %s\nwant: %s\n", got, want)
}
v2 := new(T)
if err := json.Unmarshal(got, v2); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if !reflect.DeepEqual(v, v2) {
t.Fatalf("Unmarshal didn't produce same results.\n got: %#v\nwant: %#v\n", v, v2)
}
}
func TestRawMessageMarshal(t *testing.T) {
// https://golang.org/issue/14493
const want = "{}"
b, err := json.Marshal(RawMessage(want))
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if !bytes.Equal(b, []byte(want)) {
t.Errorf("Marshal(RawMessage(%q)) = %q; want %q", want, b, want)
}
}
func TestRawMessageUnmarshal(t *testing.T) {
const want = "{}"
var m RawMessage
if err := json.Unmarshal([]byte(want), &m); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if !bytes.Equal([]byte(m), []byte(want)) {
t.Errorf("Unmarshal([]byte(%q), &m); m = %q; want %q", want, string(m), want)
}
}